multiuser

This commit is contained in:
2026-03-12 01:08:16 +11:00
parent 30a7725769
commit 7cf6b4e6ae
12 changed files with 939 additions and 247 deletions

View File

@@ -67,7 +67,7 @@ import { HomeCreateRoom } from './client/home/CreateRoom';
import { Create } from './client/create';
import { CreateSpaceModalRenderer } from '../features/create-space';
import { SearchModalRenderer } from '../features/search';
import { getFallbackSession } from '../state/sessions';
import { getCurrentSession } from '../state/sessions';
export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize) => {
const { hashRouter } = clientConfig;
@@ -85,15 +85,37 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize)
<Route
index
loader={() => {
if (getFallbackSession()) return redirect(getHomePath());
if (getCurrentSession()) return redirect(getHomePath());
const afterLoginPath = getAppPathFromHref(getOriginBaseUrl(), window.location.href);
if (afterLoginPath) setAfterLoginRedirectPath(afterLoginPath);
return redirect(getLoginPath());
}}
/>
<Route
loader={() => {
if (getFallbackSession()) {
loader={({ request }) => {
const url = new URL(request.url);
const addingAccount = url.searchParams.get('add-account') === 'true';
const hasSession = !!getCurrentSession();
// Log to localStorage for persistence across reloads
const debugInfo = {
timestamp: new Date().toISOString(),
url: url.toString(),
pathname: url.pathname,
search: url.search,
hash: url.hash,
addingAccount,
hasSession,
willRedirect: hasSession && !addingAccount
};
console.log('[Router] Auth loader:', debugInfo);
const debugLog = JSON.parse(localStorage.getItem('debug-router-logs') || '[]');
debugLog.push(debugInfo);
if (debugLog.length > 10) debugLog.shift(); // Keep last 10
localStorage.setItem('debug-router-logs', JSON.stringify(debugLog));
if (hasSession && !addingAccount) {
console.log('[Router] Redirecting to home because session exists and not adding account');
return redirect(getHomePath());
}
@@ -113,7 +135,7 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize)
<Route
loader={() => {
if (!getFallbackSession()) {
if (!getCurrentSession()) {
const afterLoginPath = getAppPathFromHref(
getOriginBaseUrl(hashRouter),
window.location.href

View File

@@ -100,7 +100,7 @@ export function AuthLayout() {
navigate(
generatePath(currentAuthPath(location.pathname), {
server: encodeURIComponent(server),
}),
}) + location.search,
{ replace: true }
);
}
@@ -114,7 +114,7 @@ export function AuthLayout() {
return;
}
navigate(
generatePath(currentAuthPath(location.pathname), { server: encodeURIComponent(newServer) })
generatePath(currentAuthPath(location.pathname), { server: encodeURIComponent(newServer) }) + location.search
);
},
[navigate, location, discoveryState, server, discoverServer]

View File

@@ -11,6 +11,7 @@ import {
} from '../../afterLoginRedirectPath';
import { getHomePath } from '../../pathUtils';
import { setFallbackSession } from '../../../state/sessions';
import { getLocalStorageItem, setLocalStorageItem } from '../../../state/utils/atomWithLocalStorage';
export enum GetBaseUrlError {
NotAllow = 'NotAllow',
@@ -114,17 +115,51 @@ export const useLoginComplete = (data?: CustomLoginResponse) => {
useEffect(() => {
if (data) {
const { response: loginRes, baseUrl: loginBaseUrl } = data;
setFallbackSession(loginRes.access_token, loginRes.device_id, loginRes.user_id, loginBaseUrl);
// Add session to sessions list
const sessions = getLocalStorageItem('matrixSessions', []);
const newSession = {
baseUrl: loginBaseUrl,
userId: loginRes.user_id,
deviceId: loginRes.device_id,
accessToken: loginRes.access_token,
expiresInMs: loginRes.expires_in_ms,
refreshToken: loginRes.refresh_token,
fallbackSdkStores: false,
};
// Check if session already exists (by userId AND deviceId to avoid conflicts)
const existingIndex = sessions.findIndex(
(s: any) => s.userId === loginRes.user_id && s.deviceId === loginRes.device_id
);
if (existingIndex >= 0) {
// Preserve fallbackSdkStores if it was set, but never enable it for new logins
const oldSession = sessions[existingIndex];
sessions[existingIndex] = {
...newSession,
fallbackSdkStores: oldSession.fallbackSdkStores === true ? true : false,
};
} else {
sessions.push(newSession);
}
setLocalStorageItem('matrixSessions', sessions);
setLocalStorageItem('currentSessionUserId', loginRes.user_id);
const afterLoginRedirectUrl = getAfterLoginRedirectPath();
deleteAfterLoginRedirectPath();
const targetPath = afterLoginRedirectUrl ?? getHomePath();
console.log('[Login] Navigating after login:', {
console.log('[Login] Login complete, reloading to initialize client:', {
targetPath,
afterLoginRedirectUrl,
homePath: getHomePath(),
currentLocation: window.location.href,
userId: loginRes.user_id,
deviceId: loginRes.device_id,
isMultiAccount: sessions.length > 1,
});
navigate(targetPath, { replace: true });
// Reload to the target path
// For hash router, we need to use just the origin without /login pathname
window.location.href = window.location.origin + '/#' + targetPath;
}
}, [data, navigate]);
};

View File

@@ -33,11 +33,13 @@ import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
import { useSyncState } from '../../hooks/useSyncState';
import { stopPropagation } from '../../utils/keyboard';
import { AuthMetadataProvider } from '../../hooks/useAuthMetadata';
import { getFallbackSession } from '../../state/sessions';
import { getCurrentSession } from '../../state/sessions';
import { CallProviderWrapper } from '../../features/call/CallProviderWrapper';
import { isTauriMobile, startBackgroundSync, stopBackgroundSync } from '../../utils/tauri';
import { TitleBar } from '../../components/title-bar';
import { initPaarrotAPI } from '../../paarrot-api';
import { AccountSwitcher } from '../../components/account-switcher';
import { getLoginPath, withSearchParam } from '../pathUtils';
function ClientRootLoading() {
return (
@@ -50,81 +52,6 @@ function ClientRootLoading() {
);
}
function ClientRootOptions({ mx }: { mx?: MatrixClient }) {
const [menuAnchor, setMenuAnchor] = useState<RectCords>();
const handleToggle: MouseEventHandler<HTMLButtonElement> = (evt) => {
const cords = evt.currentTarget.getBoundingClientRect();
setMenuAnchor((currentState) => {
if (currentState) return undefined;
return cords;
});
};
return (
<IconButton
style={{
position: 'absolute',
top: config.space.S100,
right: config.space.S100,
}}
variant="Background"
fill="None"
onClick={handleToggle}
>
<Icon size="200" src={Icons.VerticalDots} />
<PopOut
anchor={menuAnchor}
position="Bottom"
align="End"
offset={6}
content={
<FocusTrap
focusTrapOptions={{
initialFocus: false,
returnFocusOnDeactivate: false,
onDeactivate: () => setMenuAnchor(undefined),
clickOutsideDeactivates: true,
isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown',
isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp',
escapeDeactivates: stopPropagation,
}}
>
<Menu>
<Box direction="Column" gap="100" style={{ padding: config.space.S100 }}>
{mx && (
<MenuItem onClick={() => clearCacheAndReload(mx)} size="300" radii="300">
<Text as="span" size="T300" truncate>
Clear Cache and Reload
</Text>
</MenuItem>
)}
<MenuItem
onClick={() => {
if (mx) {
logoutClient(mx);
return;
}
clearLoginData();
}}
size="300"
radii="300"
variant="Critical"
fill="None"
>
<Text as="span" size="T300" truncate>
Logout
</Text>
</MenuItem>
</Box>
</Menu>
</FocusTrap>
}
/>
</IconButton>
);
}
const useLogoutListener = (mx?: MatrixClient) => {
useEffect(() => {
const handleLogout: HttpApiEventHandlerMap[HttpApiEvent.SessionLoggedOut] = async () => {
@@ -230,11 +157,12 @@ type ClientRootProps = {
};
export function ClientRoot({ children }: ClientRootProps) {
const [loading, setLoading] = useState(true);
const { baseUrl } = getFallbackSession() ?? {};
const [syncError, setSyncError] = useState<Error | null>(null);
const { baseUrl } = getCurrentSession() ?? {};
const [loadState, loadMatrix] = useAsyncCallback<MatrixClient, Error, []>(
useCallback(() => {
const session = getFallbackSession();
const session = getCurrentSession();
if (!session) {
throw new Error('No session Found!');
}
@@ -269,11 +197,29 @@ export function ClientRoot({ children }: ClientRootProps) {
}
}, [mx, startMatrix]);
// Timeout if sync takes too long
useEffect(() => {
if (!mx || !loading) return;
const timeout = setTimeout(() => {
console.error('[ClientRoot] Sync timeout - client failed to reach PREPARED state');
setSyncError(new Error('Sync timeout - failed to connect to homeserver'));
}, 30000); // 30 second timeout
return () => clearTimeout(timeout);
}, [mx, loading]);
useSyncState(
mx,
useCallback((state) => {
useCallback((state, prevState, data) => {
console.log('[ClientRoot] Sync state changed:', state, 'Error:', data);
if (state === 'PREPARED') {
setLoading(false);
setSyncError(null);
} else if (state === 'ERROR') {
const error = data instanceof Error ? data : new Error('Sync failed');
console.error('[ClientRoot] Sync error:', error);
setSyncError(error);
}
}, [])
);
@@ -281,7 +227,6 @@ export function ClientRoot({ children }: ClientRootProps) {
return (
<SpecVersions baseUrl={baseUrl!}>
<TitleBar mx={mx} />
{loading && <ClientRootOptions mx={mx} />}
{(loadState.status === AsyncStatus.Error || startState.status === AsyncStatus.Error) && (
<SplashScreen>
<Box direction="Column" grow="Yes" alignItems="Center" justifyContent="Center" gap="400">
@@ -303,6 +248,23 @@ export function ClientRoot({ children }: ClientRootProps) {
</Box>
</SplashScreen>
)}
{syncError && (
<SplashScreen>
<Box direction="Column" grow="Yes" alignItems="Center" justifyContent="Center" gap="400">
<Dialog>
<Box direction="Column" gap="400" style={{ padding: config.space.S400 }}>
<Text>{`Sync failed: ${syncError.message}`}</Text>
<Text size="T300">Check your internet connection and homeserver status.</Text>
<Button variant="Critical" onClick={() => window.location.reload()}>
<Text as="span" size="B400">
Retry
</Text>
</Button>
</Box>
</Dialog>
</Box>
</SplashScreen>
)}
{loading || !mx ? (
<ClientRootLoading />
) : (

View File

@@ -1,5 +1,7 @@
import React, { useState } from 'react';
import { Text } from 'folds';
import React, { MouseEventHandler, useState } from 'react';
import { Box, config, Icon, Icons, Menu, MenuItem, PopOut, RectCords, Text } from 'folds';
import FocusTrap from 'focus-trap-react';
import { useNavigate } from 'react-router-dom';
import { SidebarItem, SidebarItemTooltip, SidebarAvatar } from '../../../components/sidebar';
import { UserAvatar } from '../../../components/user-avatar';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
@@ -9,14 +11,20 @@ import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication';
import { Settings } from '../../../features/settings';
import { useUserProfile } from '../../../hooks/useUserProfile';
import { Modal500 } from '../../../components/Modal500';
import { AccountSwitcher } from '../../../components/account-switcher';
import { stopPropagation } from '../../../utils/keyboard';
import { getLoginPath, withSearchParam } from '../../pathUtils';
import { logoutClient } from '../../../../client/initMatrix';
export function SettingsTab() {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
const userId = mx.getUserId()!;
const profile = useUserProfile(userId);
const navigate = useNavigate();
const [settings, setSettings] = useState(false);
const [menuAnchor, setMenuAnchor] = useState<RectCords>();
const displayName = profile.displayName ?? getMxIdLocalPart(userId) ?? userId;
const avatarUrl = profile.avatarUrl
@@ -26,11 +34,22 @@ export function SettingsTab() {
const openSettings = () => setSettings(true);
const closeSettings = () => setSettings(false);
const handleContextMenu: MouseEventHandler<HTMLButtonElement> = (evt) => {
evt.preventDefault();
const cords = evt.currentTarget.getBoundingClientRect();
setMenuAnchor(cords);
};
return (
<SidebarItem active={settings}>
<SidebarItemTooltip tooltip="User Settings">
{(triggerRef) => (
<SidebarAvatar as="button" ref={triggerRef} onClick={openSettings}>
<SidebarAvatar
as="button"
ref={triggerRef}
onClick={openSettings}
onContextMenu={handleContextMenu}
>
<UserAvatar
userId={userId}
src={avatarUrl}
@@ -39,6 +58,69 @@ export function SettingsTab() {
</SidebarAvatar>
)}
</SidebarItemTooltip>
<PopOut
anchor={menuAnchor}
position="Right"
align="Start"
offset={6}
content={
<FocusTrap
focusTrapOptions={{
initialFocus: false,
returnFocusOnDeactivate: false,
onDeactivate: () => setMenuAnchor(undefined),
clickOutsideDeactivates: true,
isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown',
isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp',
escapeDeactivates: stopPropagation,
}}
>
<Menu>
<Box direction="Column" gap="100" style={{ padding: config.space.S100 }}>
<AccountSwitcher currentUserId={userId} />
<MenuItem
onClick={() => {
setMenuAnchor(undefined);
const loginPath = getLoginPath() + '?add-account=true';
console.log('[SettingsTab] Navigating to add account:', loginPath);
localStorage.setItem('debug-add-account-nav', JSON.stringify({
timestamp: new Date().toISOString(),
loginPath,
currentUrl: window.location.href
}));
navigate(loginPath);
}}
size="300"
radii="300"
>
<Box gap="200" alignItems="Center">
<Icon size="100" src={Icons.Plus} />
<Text as="span" size="T300" truncate>
Add Account
</Text>
</Box>
</MenuItem>
<MenuItem
onClick={() => {
setMenuAnchor(undefined);
logoutClient(mx);
}}
size="300"
radii="300"
variant="Critical"
fill="None"
>
<Text as="span" size="T300" truncate>
Logout
</Text>
</MenuItem>
</Box>
</Menu>
</FocusTrap>
}
/>
{settings && (
<Modal500 requestClose={closeSettings}>
<Settings requestClose={closeSettings} />