Files
cinny/src/app/hooks/usePresenceUpdater.ts
T
jaredandClaude Opus 4.8 dcd8201e16 fix(wave-3): audit fixes — ACL guards, presence, moderation, theming perf
Wave-3 bug-hunt fixes (findings in LOTUS_TODO), reviewed + gate-green:
- 🔴 ACL editor [H1–H4]: block saving an empty allow-list (was a one-click
  federation brick), warn on self-ban (case-insensitive glob match of
  mx.getDomain() vs allow/deny), accept real globs (1.2.3.*, *.evil.*), and
  gate Save behind a confirm dialog.
- 🔴 [P1] room context menu no longer acts on the wrong room after a live
  reorder (key by roomId, not list index). 🔴 [P2] status writes no longer
  force presence to online over Invisible/DND (shared presenceStateFromSetting).
- 🟠 [P3] timed mutes restored on boot; [P4] custom-status auto-clear now fires
  (always-mounted StatusExpiryMonitor); [P5] timezone also PUT to the m.tz
  profile field so it's visible to others; [H6] RoomInsights single-pass
  min/max (was Math.min(...spread) stack overflow); [H7/H8] mod-log labels.
- 🟡 [P6/P7] favorites collapse+filter, [P8] charCount reset, [P9] DM preview
  refresh on decrypt; theming [T-P1] lazy decorations, [T-P2] drop the redundant
  always-on body animation, [T-P4] live useReducedMotion, [T-P5] decoration key.
- NATIVE-CINNY LAW: notification presets + Powers permissions use folds icons.

DEFERRED: [H5] invite-QR is fetched from api.qrserver.com (third-party leak);
local generation needs a bundled QR lib (not added). tsc/eslint/prettier clean,
build OK, 677 tests.

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

163 lines
5.8 KiB
TypeScript

import { useEffect, useRef } from 'react';
import { useMatrixClient } from './useMatrixClient';
import { useSetting } from '../state/hooks/settings';
import { settingsAtom } from '../state/settings';
const IDLE_TIMEOUT_MS = 10 * 60 * 1000;
const ACTIVITY_THROTTLE_MS = 1000;
export type PresenceSetting = 'auto' | 'online' | 'idle' | 'dnd' | 'invisible';
export type PresenceState = 'online' | 'unavailable' | 'offline';
/**
* Single source of truth for mapping the user's presence preference to the
* Matrix presence value: auto/online → 'online', idle/dnd → 'unavailable',
* invisible (or the hidePresence override) → 'offline'. Shared with the Profile
* status writer so setting/clearing a status message never overrides the user's
* chosen presence (e.g. outing an Invisible user as online).
*/
export function presenceStateFromSetting(
presenceStatus: PresenceSetting,
hidePresence: boolean,
): PresenceState {
if (hidePresence || presenceStatus === 'invisible') return 'offline';
if (presenceStatus === 'idle' || presenceStatus === 'dnd') return 'unavailable';
return 'online';
}
export function usePresenceUpdater() {
const mx = useMatrixClient();
const [hidePresence] = useSetting(settingsAtom, 'hidePresence');
const [presenceStatus] = useSetting(settingsAtom, 'presenceStatus');
const idleTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const isIdleRef = useRef(false);
const lastActivityRef = useRef(0);
useEffect(() => {
const userId = mx.getUserId();
// Read status from localStorage at call time so manual updates from the
// Profile settings are never overwritten by a stale closure value.
const readStatus = () =>
userId ? (localStorage.getItem(`lotus-status-msg-${userId}`) ?? '') : '';
// Log presence failures without leaking PII (user id, token, status message).
const warnPresenceFailure = (presence: string, err: unknown) => {
const reason =
err instanceof Error ? err.message : typeof err === 'string' ? err : 'unknown error';
console.warn(`Failed to set presence to "${presence}":`, reason);
};
const setOnline = () => {
const status = readStatus();
return mx
.setPresence({
presence: 'online',
...(status ? { status_msg: status } : {}),
})
.catch((err) => warnPresenceFailure('online', err));
};
const setUnavailable = (statusMsg?: string) => {
const status = readStatus();
return mx
.setPresence({
presence: 'unavailable',
...(statusMsg ? { status_msg: statusMsg } : status ? { status_msg: status } : {}),
})
.catch((err) => warnPresenceFailure('unavailable', err));
};
const setOffline = () =>
mx
.setPresence({ presence: 'offline', status_msg: '' })
.catch((err) => warnPresenceFailure('offline', err));
// Manual presence overrides — no activity tracking needed.
if (hidePresence || presenceStatus === 'invisible') {
setOffline();
return undefined;
}
if (presenceStatus === 'online') {
setOnline();
return undefined;
}
if (presenceStatus === 'idle') {
setUnavailable();
return undefined;
}
if (presenceStatus === 'dnd') {
setUnavailable('dnd');
return undefined;
}
// presenceStatus === 'auto' — original activity-tracking behavior.
const startIdleTimer = () => {
clearTimeout(idleTimerRef.current);
idleTimerRef.current = setTimeout(() => {
isIdleRef.current = true;
setUnavailable();
}, IDLE_TIMEOUT_MS);
};
const handleActivity = () => {
const now = Date.now();
if (now - lastActivityRef.current < ACTIVITY_THROTTLE_MS) return;
lastActivityRef.current = now;
if (isIdleRef.current && !document.hidden) {
isIdleRef.current = false;
setOnline();
}
startIdleTimer();
};
const handleVisibilityChange = () => {
if (document.hidden) {
clearTimeout(idleTimerRef.current);
setUnavailable();
} else {
isIdleRef.current = false;
lastActivityRef.current = Date.now();
setOnline();
startIdleTimer();
}
};
const handlePageHide = () => {
const token = mx.getAccessToken();
const baseUrl = mx.getHomeserverUrl();
if (!userId || !token || !baseUrl) return;
// Reliable delivery during page teardown: navigator.sendBeacon cannot set the
// Authorization header required by the authenticated Matrix presence endpoint, so
// it isn't usable here. fetch(..., { keepalive: true }) lets the request outlive the
// page and is the correct mechanism for an authed endpoint. (keepalive bodies are
// capped at 64KB, which this tiny payload is well under.)
fetch(`${baseUrl}/_matrix/client/v3/presence/${encodeURIComponent(userId)}/status`, {
method: 'PUT',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ presence: 'offline' }),
keepalive: true,
}).catch((err) => warnPresenceFailure('offline (pagehide)', err));
};
setOnline();
startIdleTimer();
const activityEvents = ['mousemove', 'keydown', 'touchstart', 'click', 'scroll'] as const;
activityEvents.forEach((e) => window.addEventListener(e, handleActivity, { passive: true }));
document.addEventListener('visibilitychange', handleVisibilityChange);
window.addEventListener('pagehide', handlePageHide);
return () => {
clearTimeout(idleTimerRef.current);
activityEvents.forEach((e) => window.removeEventListener(e, handleActivity));
document.removeEventListener('visibilitychange', handleVisibilityChange);
window.removeEventListener('pagehide', handlePageHide);
};
}, [mx, hidePresence, presenceStatus]);
}