Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e8fd0a1112 |
@@ -80,7 +80,7 @@ import {
|
||||
setRoomNotificationPreference,
|
||||
} from '../../hooks/useRoomsNotificationPreferences';
|
||||
import { RoomNotificationModeSwitcher } from '../../components/RoomNotificationSwitcher';
|
||||
import { clearMuteTimer, scheduleMuteTimer } from './muteTimers';
|
||||
import { scheduleMuteTimer, unmuteRoom } from './muteTimers';
|
||||
import { getRoomCreatorsForRoomId, useRoomCreators } from '../../hooks/useRoomCreators';
|
||||
import { getRoomPermissionsAPI, useRoomPermissions } from '../../hooks/useRoomPermissions';
|
||||
import { InviteUserPrompt } from '../../components/invite-user-prompt';
|
||||
@@ -381,10 +381,9 @@ const RoomNavItemMenu = forwardRef<HTMLDivElement, RoomNavItemMenuProps>(
|
||||
prevMode,
|
||||
).catch(() => {});
|
||||
if (durationMs !== null) {
|
||||
await scheduleMuteTimer(mx, room.roomId, durationMs).catch(() => {});
|
||||
} else {
|
||||
// An indefinite mute replaces any timed one.
|
||||
await clearMuteTimer(mx, room.roomId);
|
||||
scheduleMuteTimer(room.roomId, durationMs, () => {
|
||||
unmuteRoom(mx, room.roomId);
|
||||
});
|
||||
}
|
||||
requestClose();
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { RoomNotificationMode } from '../../hooks/useRoomsNotificationPreferences';
|
||||
import { muteTimersContent, parseMuteTimers, shouldResetMuteOnUnmute } from './muteTimers';
|
||||
import { shouldResetMuteOnUnmute } from './muteTimers';
|
||||
|
||||
test('resets to Unset when the room is still Mute at expiry', () => {
|
||||
assert.equal(shouldResetMuteOnUnmute(RoomNotificationMode.Mute), true);
|
||||
@@ -18,16 +18,3 @@ test('does not reset when the user switched to Special messages during the mute
|
||||
test('does not reset when the mode is already Unset', () => {
|
||||
assert.equal(shouldResetMuteOnUnmute(RoomNotificationMode.Unset), false);
|
||||
});
|
||||
|
||||
test('parseMuteTimers / muteTimersContent round-trip and tolerate garbage (#333)', () => {
|
||||
const entries = [
|
||||
{ roomId: '!a:x', unmuteAt: 1000 },
|
||||
{ roomId: '!b:x', unmuteAt: 2000 },
|
||||
];
|
||||
assert.deepEqual(parseMuteTimers(muteTimersContent(entries)), entries);
|
||||
assert.deepEqual(parseMuteTimers({ timers: { '!a:x': 'soon', '!b:x': 5 } }), [
|
||||
{ roomId: '!b:x', unmuteAt: 5 },
|
||||
]);
|
||||
assert.deepEqual(parseMuteTimers(undefined), []);
|
||||
assert.deepEqual(parseMuteTimers({ timers: null }), []);
|
||||
});
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
setRoomNotificationPreference,
|
||||
} from '../../hooks/useRoomsNotificationPreferences';
|
||||
|
||||
// Legacy localStorage key (before #333); migrated into account data once.
|
||||
// localStorage key for timed mute timers
|
||||
export const MUTE_TIMERS_KEY = 'io.lotus.mute_timers';
|
||||
|
||||
// setTimeout's delay is a signed 32-bit int; larger values overflow and fire
|
||||
@@ -16,62 +16,19 @@ export const MAX_MUTE_TIMEOUT_MS = 2_147_483_647;
|
||||
|
||||
export type MuteTimerEntry = { roomId: string; unmuteAt: number };
|
||||
|
||||
/** Pure: the timers in an `io.lotus.mute_timers` account data content. */
|
||||
export function parseMuteTimers(content: unknown): MuteTimerEntry[] {
|
||||
const timers = (content as { timers?: unknown } | undefined)?.timers;
|
||||
if (!timers || typeof timers !== 'object') return [];
|
||||
return Object.entries(timers as Record<string, unknown>)
|
||||
.filter((e): e is [string, number] => typeof e[1] === 'number' && Number.isFinite(e[1]))
|
||||
.map(([roomId, unmuteAt]) => ({ roomId, unmuteAt }));
|
||||
}
|
||||
|
||||
/** Pure: account data content for `entries`. */
|
||||
export const muteTimersContent = (entries: MuteTimerEntry[]) => ({
|
||||
timers: Object.fromEntries(entries.map((e) => [e.roomId, e.unmuteAt])),
|
||||
});
|
||||
|
||||
/**
|
||||
* [Gitea #333] Timed mutes live in account data: the mute itself is a
|
||||
* server-side push rule on every device, so the timer must be too — kept in one
|
||||
* browser's localStorage, only that device ever unmuted (and never after a
|
||||
* logout there).
|
||||
*/
|
||||
export function loadMuteTimers(mx: MatrixClient): MuteTimerEntry[] {
|
||||
return parseMuteTimers(getAccountData(mx, AccountDataEvent.LotusMuteTimers)?.getContent());
|
||||
}
|
||||
|
||||
async function saveMuteTimers(mx: MatrixClient, entries: MuteTimerEntry[]): Promise<void> {
|
||||
await mx.setAccountData(
|
||||
AccountDataEvent.LotusMuteTimers as never,
|
||||
muteTimersContent(entries) as never,
|
||||
);
|
||||
}
|
||||
|
||||
/** Move timers kept in this browser's localStorage (pre-#333) into account data. */
|
||||
export async function migrateLocalMuteTimers(mx: MatrixClient): Promise<void> {
|
||||
let legacy: MuteTimerEntry[] = [];
|
||||
export function loadMuteTimers(): MuteTimerEntry[] {
|
||||
try {
|
||||
const parsed = JSON.parse(localStorage.getItem(MUTE_TIMERS_KEY) ?? '[]');
|
||||
legacy = Array.isArray(parsed)
|
||||
? parsed.filter(
|
||||
(e): e is MuteTimerEntry =>
|
||||
!!e && typeof e.roomId === 'string' && typeof e.unmuteAt === 'number',
|
||||
)
|
||||
: [];
|
||||
return Array.isArray(parsed) ? parsed : [];
|
||||
} catch {
|
||||
legacy = [];
|
||||
}
|
||||
if (legacy.length === 0) return;
|
||||
const current = loadMuteTimers(mx);
|
||||
const merged = [...current, ...legacy.filter((l) => !current.some((c) => c.roomId === l.roomId))];
|
||||
await saveMuteTimers(mx, merged);
|
||||
try {
|
||||
localStorage.removeItem(MUTE_TIMERS_KEY);
|
||||
} catch {
|
||||
/* ignore */
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function saveMuteTimers(timers: MuteTimerEntry[]): void {
|
||||
localStorage.setItem(MUTE_TIMERS_KEY, JSON.stringify(timers));
|
||||
}
|
||||
|
||||
// Pure decision for the unmute guard: a timed mute should only be reset back to
|
||||
// Unset if the room's notification mode is still Mute at expiry time. If the user
|
||||
// manually changed it (e.g. to All messages) while the timer was pending, leave
|
||||
@@ -120,30 +77,12 @@ export async function unmuteRoom(mx: MatrixClient, roomId: string): Promise<void
|
||||
RoomNotificationMode.Mute,
|
||||
).catch(() => {});
|
||||
}
|
||||
await clearMuteTimer(mx, roomId);
|
||||
saveMuteTimers(loadMuteTimers().filter((e) => e.roomId !== roomId));
|
||||
}
|
||||
|
||||
/** Drop a room's timer (e.g. it was muted indefinitely or unmuted by hand). */
|
||||
export async function clearMuteTimer(mx: MatrixClient, roomId: string): Promise<void> {
|
||||
const timers = loadMuteTimers(mx);
|
||||
if (!timers.some((e) => e.roomId === roomId)) return;
|
||||
await saveMuteTimers(
|
||||
mx,
|
||||
timers.filter((e) => e.roomId !== roomId),
|
||||
).catch(() => {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Record when a timed mute ends. MuteTimerRestore (on every Lotus device)
|
||||
* schedules the unmute from account data, so whichever is online at expiry
|
||||
* lifts it.
|
||||
*/
|
||||
export async function scheduleMuteTimer(
|
||||
mx: MatrixClient,
|
||||
roomId: string,
|
||||
durationMs: number,
|
||||
): Promise<void> {
|
||||
export function scheduleMuteTimer(roomId: string, durationMs: number, onUnmute: () => void): void {
|
||||
const unmuteAt = Date.now() + durationMs;
|
||||
const existing = loadMuteTimers(mx).filter((e) => e.roomId !== roomId);
|
||||
await saveMuteTimers(mx, [...existing, { roomId, unmuteAt }]);
|
||||
const existing = loadMuteTimers().filter((e) => e.roomId !== roomId);
|
||||
saveMuteTimers([...existing, { roomId, unmuteAt }]);
|
||||
setTimeout(onUnmute, Math.min(durationMs, MAX_MUTE_TIMEOUT_MS));
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { useServerStatus } from '../../hooks/useServerStatus';
|
||||
import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize';
|
||||
import { serverStatusAtom } from '../../state/serverStatus';
|
||||
import { pickBanner, resolveStatusPage, StatusBanner } from '../../utils/kumaStatus';
|
||||
import { homeserverStalledAtom, useHomeserverStall } from '../../hooks/useHomeserverStall';
|
||||
|
||||
const DISMISS_KEY = 'lotus-status-banner-dismissed';
|
||||
const DISMISS_MAX = 50;
|
||||
@@ -163,7 +164,12 @@ export function ServerStatusFeature({ mx }: { mx: MatrixClient }) {
|
||||
});
|
||||
}, []),
|
||||
);
|
||||
const syncLost = lostAt !== null;
|
||||
// [Gitea #317] A hung server keeps sync "SYNCING" for up to 110 s; the stall
|
||||
// watchdog flags it sooner, and Kuma is asked at once.
|
||||
const stalled = useHomeserverStall(mx);
|
||||
const setStalled = useSetAtom(homeserverStalledAtom);
|
||||
useEffect(() => setStalled(stalled), [setStalled, stalled]);
|
||||
const syncLost = lostAt !== null || stalled;
|
||||
const status = useServerStatus(page, syncLost);
|
||||
const setAtom = useSetAtom(serverStatusAtom);
|
||||
useEffect(() => setAtom({ status, syncLost, lostAt }), [setAtom, status, syncLost, lostAt]);
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { SyncState } from 'matrix-js-sdk';
|
||||
import { STALL_AFTER_MS, syncOverdue } from './useHomeserverStall';
|
||||
|
||||
test('syncOverdue: only while SYNCING and past the stall threshold (#317)', () => {
|
||||
const now = 1_000_000;
|
||||
assert.equal(syncOverdue(now - STALL_AFTER_MS - 1, now, SyncState.Syncing), true);
|
||||
assert.equal(syncOverdue(now - 20_000, now, SyncState.Syncing), false, 'a normal long-poll');
|
||||
assert.equal(
|
||||
syncOverdue(now - 120_000, now, SyncState.Reconnecting),
|
||||
false,
|
||||
'SyncStatus already shows that',
|
||||
);
|
||||
assert.equal(syncOverdue(now - 120_000, now, null), false);
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { atom } from 'jotai';
|
||||
import { ClientEvent, MatrixClient, SyncState } from 'matrix-js-sdk';
|
||||
|
||||
/**
|
||||
* [Gitea #317] A hung homeserver (accepts connections, never answers) went
|
||||
* unnoticed for up to 110 s: the SDK only gives up on a /sync long-poll after
|
||||
* pollTimeout (30 s) + an 80 s buffer, and until then the sync state stays
|
||||
* SYNCING, so no strip showed and Kuma wasn't asked. This watchdog notices a
|
||||
* /sync that's overdue and confirms with a short probe of /versions.
|
||||
*/
|
||||
export const STALL_AFTER_MS = 45_000; // a healthy long-poll returns within ~30 s
|
||||
const CHECK_EVERY_MS = 10_000;
|
||||
const PROBE_TIMEOUT_MS = 5_000;
|
||||
|
||||
export const homeserverStalledAtom = atom(false);
|
||||
|
||||
/** Pure: should we probe, given the last sync response time? */
|
||||
export const syncOverdue = (lastSyncAt: number, now: number, state: SyncState | null): boolean =>
|
||||
state === SyncState.Syncing && now - lastSyncAt > STALL_AFTER_MS;
|
||||
|
||||
export function useHomeserverStall(mx: MatrixClient): boolean {
|
||||
const [stalled, setStalled] = useState(false);
|
||||
useEffect(() => {
|
||||
let lastSyncAt = Date.now();
|
||||
let probing = false;
|
||||
const onSync = () => {
|
||||
lastSyncAt = Date.now();
|
||||
setStalled(false);
|
||||
};
|
||||
const check = async () => {
|
||||
if (probing || !syncOverdue(lastSyncAt, Date.now(), mx.getSyncState())) return;
|
||||
probing = true;
|
||||
let answered = false;
|
||||
try {
|
||||
const res = await fetch(`${mx.getHomeserverUrl()}/_matrix/client/versions`, {
|
||||
cache: 'no-store',
|
||||
signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),
|
||||
});
|
||||
answered = res.ok;
|
||||
} catch {
|
||||
answered = false;
|
||||
}
|
||||
probing = false;
|
||||
// Still overdue and the server didn't answer a trivial request: stalled.
|
||||
if (!answered && syncOverdue(lastSyncAt, Date.now(), mx.getSyncState())) setStalled(true);
|
||||
if (answered) setStalled(false);
|
||||
};
|
||||
mx.on(ClientEvent.Sync, onSync);
|
||||
const id = setInterval(check, CHECK_EVERY_MS);
|
||||
return () => {
|
||||
mx.removeListener(ClientEvent.Sync, onSync);
|
||||
clearInterval(id);
|
||||
};
|
||||
}, [mx]);
|
||||
return stalled;
|
||||
}
|
||||
@@ -58,8 +58,8 @@ import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
|
||||
import { presenceStateFromSetting, usePresenceUpdater } from '../../hooks/usePresenceUpdater';
|
||||
import {
|
||||
MAX_MUTE_TIMEOUT_MS,
|
||||
MuteTimerEntry,
|
||||
loadMuteTimers,
|
||||
migrateLocalMuteTimers,
|
||||
unmuteRoom,
|
||||
} from '../../features/room-nav/muteTimers';
|
||||
import { STATUS_EXPIRY_KEY, STATUS_MSG_KEY } from '../../features/settings/account/Profile';
|
||||
@@ -91,7 +91,6 @@ import {
|
||||
shouldNotifyThreadReply,
|
||||
THREAD_NOTIFICATIONS_FALLBACK_BEHAVIOR,
|
||||
} from '../../utils/threadNotifications';
|
||||
import { AccountDataEvent } from '../../../types/matrix/accountData';
|
||||
|
||||
// Grace period after the initial sync settles before invite notifications arm, so
|
||||
// the async invite-atom population lands first and isn't mistaken for new invites.
|
||||
@@ -370,35 +369,30 @@ function PresenceUpdater() {
|
||||
function MuteTimerRestore() {
|
||||
const mx = useMatrixClient();
|
||||
|
||||
// [Gitea #333] Timers are in account data, so a mute set on another device
|
||||
// is lifted here too, and changes there (a new mute, a manual unmute)
|
||||
// reschedule. Moves any timers this browser kept locally (pre-#333) first.
|
||||
useEffect(() => {
|
||||
migrateLocalMuteTimers(mx).catch(() => {});
|
||||
}, [mx]);
|
||||
const timers = loadMuteTimers();
|
||||
if (timers.length === 0) return undefined;
|
||||
|
||||
const now = Date.now();
|
||||
const pastDue: MuteTimerEntry[] = [];
|
||||
const future: MuteTimerEntry[] = [];
|
||||
timers.forEach((entry) => (entry.unmuteAt <= now ? pastDue : future).push(entry));
|
||||
|
||||
pastDue.forEach((entry) => {
|
||||
unmuteRoom(mx, entry.roomId);
|
||||
});
|
||||
|
||||
const handles = future.map((entry) =>
|
||||
setTimeout(
|
||||
() => {
|
||||
unmuteRoom(mx, entry.roomId);
|
||||
},
|
||||
Math.min(entry.unmuteAt - now, MAX_MUTE_TIMEOUT_MS),
|
||||
),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
let handles: ReturnType<typeof setTimeout>[] = [];
|
||||
const schedule = () => {
|
||||
handles.forEach(clearTimeout);
|
||||
const now = Date.now();
|
||||
handles = loadMuteTimers(mx).map((entry) =>
|
||||
setTimeout(
|
||||
() => {
|
||||
unmuteRoom(mx, entry.roomId);
|
||||
},
|
||||
Math.max(0, Math.min(entry.unmuteAt - now, MAX_MUTE_TIMEOUT_MS)),
|
||||
),
|
||||
);
|
||||
};
|
||||
const onAccountData = (event: MatrixEvent) => {
|
||||
if (event.getType() === AccountDataEvent.LotusMuteTimers) schedule();
|
||||
};
|
||||
schedule();
|
||||
mx.on(ClientEvent.AccountData, onAccountData);
|
||||
return () => {
|
||||
handles.forEach(clearTimeout);
|
||||
mx.removeListener(ClientEvent.AccountData, onAccountData);
|
||||
};
|
||||
}, [mx]);
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useSyncState } from '../../hooks/useSyncState';
|
||||
import { ContainerColor } from '../../styles/ContainerColor.css';
|
||||
import { serverStatusAtom } from '../../state/serverStatus';
|
||||
import { serverConfirmedUpSince } from '../../utils/kumaStatus';
|
||||
import { homeserverStalledAtom } from '../../hooks/useHomeserverStall';
|
||||
|
||||
type StateData = {
|
||||
current: SyncState | null;
|
||||
@@ -17,6 +18,7 @@ type SyncStatusProps = {
|
||||
};
|
||||
export function SyncStatus({ mx }: SyncStatusProps) {
|
||||
const serverStatus = useAtomValue(serverStatusAtom);
|
||||
const stalled = useAtomValue(homeserverStalledAtom);
|
||||
const [stateData, setStateData] = useState<StateData>({
|
||||
current: null,
|
||||
previous: undefined,
|
||||
@@ -34,6 +36,35 @@ export function SyncStatus({ mx }: SyncStatusProps) {
|
||||
}, []),
|
||||
);
|
||||
|
||||
// [Gitea #124] When Kuma confirms the homeserver is down, the status banner
|
||||
// says so ("Lotus Chat's server is down…") instead of "Connection Lost!".
|
||||
const serverDown = serverStatus.status?.homeserver === 'down';
|
||||
// Only blame the user's connection when Kuma has checked the server since
|
||||
// the drop and it was fine (a stale "up" from before proves nothing).
|
||||
const serverUp = serverConfirmedUpSince(serverStatus.status, serverStatus.lostAt);
|
||||
|
||||
// [Gitea #317] Sync still says SYNCING, but the server has stopped answering.
|
||||
if (stalled && stateData.current === SyncState.Syncing && !serverDown) {
|
||||
return (
|
||||
<Box direction="Column" shrink="No">
|
||||
<Box
|
||||
className={ContainerColor({ variant: 'Warning' })}
|
||||
style={{ padding: `${config.space.S100} 0` }}
|
||||
alignItems="Center"
|
||||
justifyContent="Center"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
>
|
||||
<Text size="L400">
|
||||
Lotus Chat's server isn't responding. Messages will send when it's back.
|
||||
Still trying…
|
||||
</Text>
|
||||
</Box>
|
||||
<Line variant="Warning" size="300" />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
(stateData.current === SyncState.Prepared ||
|
||||
stateData.current === SyncState.Syncing ||
|
||||
@@ -57,13 +88,6 @@ export function SyncStatus({ mx }: SyncStatusProps) {
|
||||
);
|
||||
}
|
||||
|
||||
// [Gitea #124] When Kuma confirms the homeserver is down, the status banner
|
||||
// says so ("Lotus Chat's server is down…") instead of "Connection Lost!".
|
||||
const serverDown = serverStatus.status?.homeserver === 'down';
|
||||
// Only blame the user's connection when Kuma has checked the server since
|
||||
// the drop and it was fine (a stale "up" from before proves nothing).
|
||||
const serverUp = serverConfirmedUpSince(serverStatus.status, serverStatus.lostAt);
|
||||
|
||||
if (stateData.current === SyncState.Reconnecting && !serverDown) {
|
||||
return (
|
||||
<Box direction="Column" shrink="No">
|
||||
|
||||
@@ -64,10 +64,9 @@ const clearMsgDrafts = (): void => {
|
||||
* `lotus-status-expiry-*`, used to be preserved; since [Gitea #204] they are
|
||||
* swept with the rest — the server-side presence status survives, so a
|
||||
* re-login loses nothing)
|
||||
* - low-sensitivity UI/metadata residue (collapsed nav/space categories,
|
||||
* `cinny_oidc_dynamic_clients`) is treated as preferences, not swept here.
|
||||
* Timed mutes moved to account data in [Gitea #333]; a leftover local
|
||||
* `io.lotus.mute_timers` is migrated there on the next start.
|
||||
* - low-sensitivity UI/metadata residue (`io.lotus.mute_timers`, collapsed
|
||||
* nav/space categories, `cinny_oidc_dynamic_clients`) is treated as
|
||||
* preferences, not swept here
|
||||
*/
|
||||
/**
|
||||
* [Gitea #204] The local mirror of the user's status message (+ its expiry) is
|
||||
|
||||
@@ -26,10 +26,6 @@ export enum AccountDataEvent {
|
||||
// [Gitea #104] Synced subset of the Lotus Settings object (utils/settingsSync).
|
||||
LotusSettings = 'io.lotus.settings',
|
||||
|
||||
// [Gitea #333] Timed mutes: { timers: { [roomId]: unmuteAt } }, so any Lotus
|
||||
// device can lift a mute set on another.
|
||||
LotusMuteTimers = 'io.lotus.mute_timers',
|
||||
|
||||
SecretStorageDefaultKey = 'm.secret_storage.default_key',
|
||||
|
||||
CrossSigningMaster = 'm.cross_signing.master',
|
||||
|
||||
Reference in New Issue
Block a user