(fix): call being getting initialised even on the login screen
All checks were successful
/ build-web (push) Successful in 1m13s
/ build-desktop (push) Successful in 11m50s
/ build-mobile (push) Successful in 16m27s
/ release (push) Successful in 24s

This commit is contained in:
Alois 2026-05-23 21:43:11 +02:00
commit a0e3e85467
6 changed files with 73 additions and 55 deletions

View file

@ -1,5 +1,5 @@
import { Lock, LockOpen } from "lucide-react"; import { Lock, LockOpen } from "lucide-react";
import { openCallPage, useCall } from "../store"; import { openCallPage, useCall, getRoom } from "../store";
import { import {
Button, Button,
Card, Card,
@ -78,7 +78,7 @@ function ConnectionBar() {
} }
export function TinyPingGraph() { export function TinyPingGraph() {
const room = useCall((store) => store.room); const room = getRoom();
const [mapData, setMapData] = useState<Map<number, number>>(() => new Map()); const [mapData, setMapData] = useState<Map<number, number>>(() => new Map());

View file

@ -1,5 +1,5 @@
import { useUser, type User } from "@tensamin/user/context"; import { useUser, type User } from "@tensamin/user/context";
import { useCall } from "../store"; import { useCall, getRoom } from "../store";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useStorage } from "@tensamin/storage/context"; import { useStorage } from "@tensamin/storage/context";
import { import {
@ -14,7 +14,7 @@ import {
export default function TopBar() { export default function TopBar() {
const { get } = useUser(); const { get } = useUser();
const { load } = useStorage(); const { load } = useStorage();
const room = useCall((state) => state.room); const room = getRoom();
const screenRef = useCall((state) => state.screenRef); const screenRef = useCall((state) => state.screenRef);
const [portalContainer, setPortalContainer] = useState<HTMLElement>(); const [portalContainer, setPortalContainer] = useState<HTMLElement>();

View file

@ -1,6 +1,6 @@
import { VideoTrack, useParticipantTracks } from "@livekit/components-react"; import { VideoTrack, useParticipantTracks } from "@livekit/components-react";
import { TrackPublication } from "livekit-client"; import { TrackPublication } from "livekit-client";
import { useCall } from "../store"; import { getRoom } from "../store";
import { cn } from "@tensamin/ui"; import { cn } from "@tensamin/ui";
import { Loader2 } from "lucide-react"; import { Loader2 } from "lucide-react";
@ -17,7 +17,7 @@ export default function VideoViewer({
publication: TrackPublication; publication: TrackPublication;
participantId: string; participantId: string;
}) { }) {
const room = useCall((state) => state.room); const room = getRoom();
const tracks = useParticipantTracks([publication.source], { const tracks = useParticipantTracks([publication.source], {
participantIdentity: participantId, participantIdentity: participantId,
room, room,

View file

@ -101,27 +101,46 @@ type CallStore = {
callIsPopout: boolean; callIsPopout: boolean;
layoutVersion: number; layoutVersion: number;
screenRef: React.RefObject<HTMLDivElement | null> | null; screenRef: React.RefObject<HTMLDivElement | null> | null;
room: Room;
keyProvider: ExternalE2EEKeyProvider;
e2eeWorker: Worker;
runtime: Runtime | null; runtime: Runtime | null;
speakingParticipantIds: Set<number>; speakingParticipantIds: Set<number>;
micGated: boolean; micGated: boolean;
}; };
const keyProvider = new ExternalE2EEKeyProvider(); let _keyProvider: ExternalE2EEKeyProvider | null = null;
const e2eeWorker = new Worker( let _e2eeWorker: Worker | null = null;
let _room: Room | null = null;
function getKeyProvider(): ExternalE2EEKeyProvider {
if (!_keyProvider) {
_keyProvider = new ExternalE2EEKeyProvider();
}
return _keyProvider;
}
function getE2EEWorker(): Worker {
if (!_e2eeWorker) {
_e2eeWorker = new Worker(
new URL("livekit-client/e2ee-worker", import.meta.url), new URL("livekit-client/e2ee-worker", import.meta.url),
); );
const room = new Room({ }
return _e2eeWorker;
}
export function getRoom(): Room {
if (!_room) {
_room = new Room({
dynacast: true, dynacast: true,
adaptiveStream: true, adaptiveStream: true,
loggerName: "tensamin", loggerName: "tensamin",
encryption: { encryption: {
keyProvider, keyProvider: getKeyProvider(),
worker: e2eeWorker, worker: getE2EEWorker(),
}, },
}); });
}
return _room;
}
const remoteAudioElements = new Map<string, HTMLMediaElement>(); const remoteAudioElements = new Map<string, HTMLMediaElement>();
const SCREEN_SHARE_PREVIEW_MAX_WIDTH = 320; const SCREEN_SHARE_PREVIEW_MAX_WIDTH = 320;
@ -170,6 +189,7 @@ export function getParticipantId(identity: string | undefined): number | null {
} }
function getAllParticipants(): Participant[] { function getAllParticipants(): Participant[] {
const room = getRoom();
return [...room.remoteParticipants.values(), room.localParticipant]; return [...room.remoteParticipants.values(), room.localParticipant];
} }
@ -187,7 +207,7 @@ function getTrackPublicationBySource(
} }
function getRemoteParticipant(participantId: number) { function getRemoteParticipant(participantId: number) {
return [...room.remoteParticipants.values()].find( return [...getRoom().remoteParticipants.values()].find(
(participant) => getParticipantId(participant.identity) === participantId, (participant) => getParticipantId(participant.identity) === participantId,
); );
} }
@ -215,7 +235,7 @@ function syncRemoteParticipantTrackSubscriptions(participantId: number) {
} }
function syncAllRemoteTrackSubscriptions() { function syncAllRemoteTrackSubscriptions() {
for (const participant of room.remoteParticipants.values()) { for (const participant of getRoom().remoteParticipants.values()) {
const participantId = getParticipantId(participant.identity); const participantId = getParticipantId(participant.identity);
if (participantId != null) { if (participantId != null) {
@ -256,7 +276,7 @@ function hasParticipant(participantId: number) {
function getLocalScreenShareTrack(): MediaStreamTrack | null { function getLocalScreenShareTrack(): MediaStreamTrack | null {
const track = getTrackPublicationBySource( const track = getTrackPublicationBySource(
room.localParticipant, getRoom().localParticipant,
Track.Source.ScreenShare, Track.Source.ScreenShare,
)?.track; )?.track;
@ -275,7 +295,7 @@ async function updateLocalParticipantAttributes(
screenSharePreviewLength: attributes.screenSharePreview?.length ?? 0, screenSharePreviewLength: attributes.screenSharePreview?.length ?? 0,
}); });
await room.localParticipant.setAttributes(attributes).catch((error) => { await getRoom().localParticipant.setAttributes(attributes).catch((error) => {
log(1, "call", "red", "Failed to update local participant attributes", { log(1, "call", "red", "Failed to update local participant attributes", {
attributes: Object.keys(attributes), attributes: Object.keys(attributes),
error, error,
@ -487,7 +507,7 @@ function requireRuntime(runtime: Runtime | null): Runtime {
} }
export function getRoomMetadata() { export function getRoomMetadata() {
const roomMetadata = room.metadata; const roomMetadata = getRoom().metadata;
try { try {
const data = JSON.parse(roomMetadata || '{"admins": []}'); const data = JSON.parse(roomMetadata || '{"admins": []}');
return data as { admins: number[] }; return data as { admins: number[] };
@ -498,7 +518,8 @@ export function getRoomMetadata() {
// Sync local participant flags and screen-share derived state for the active call UI. // Sync local participant flags and screen-share derived state for the active call UI.
export function syncParticipantState() { export function syncParticipantState() {
const { room, screenShareSession } = useCall.getState(); const { screenShareSession } = useCall.getState();
const room = getRoom();
useCall.setState({ useCall.setState({
micEnabled: room.localParticipant.isMicrophoneEnabled, micEnabled: room.localParticipant.isMicrophoneEnabled,
@ -721,7 +742,7 @@ let screenShareController: ReturnType<
function getScreenShareController() { function getScreenShareController() {
if (!screenShareController) { if (!screenShareController) {
screenShareController = createScreenShareController({ screenShareController = createScreenShareController({
room, room: getRoom(),
getState: () => ({ getState: () => ({
screenShareSession: useCall.getState().screenShareSession, screenShareSession: useCall.getState().screenShareSession,
}), }),
@ -733,7 +754,7 @@ function getScreenShareController() {
); );
}, },
getLocalParticipantId: () => getLocalParticipantId: () =>
getParticipantId(room.localParticipant.identity), getParticipantId(getRoom().localParticipant.identity),
startWatching: startWatchingStream, startWatching: startWatchingStream,
stopWatching: stopWatchingStream, stopWatching: stopWatchingStream,
syncParticipantState, syncParticipantState,
@ -758,7 +779,7 @@ export async function connect(callId: string) {
callSecret: useCall.getState().callSecret, callSecret: useCall.getState().callSecret,
}); });
await room await getRoom()
.connect("wss://call.tensamin.net", token, { .connect("wss://call.tensamin.net", token, {
autoSubscribe: false, autoSubscribe: false,
}) })
@ -774,7 +795,7 @@ export async function connect(callId: string) {
syncAllRemoteTrackSubscriptions(); syncAllRemoteTrackSubscriptions();
await room.localParticipant.setMicrophoneEnabled(true).catch((error) => { await getRoom().localParticipant.setMicrophoneEnabled(true).catch((error) => {
log(1, "call", "red", "Failed to enable microphone", error); log(1, "call", "red", "Failed to enable microphone", error);
toast("error", "Failed to enable microphone."); toast("error", "Failed to enable microphone.");
throw error; throw error;
@ -819,12 +840,12 @@ export async function disconnect() {
micGated: false, micGated: false,
}); });
room.remoteParticipants.forEach((participant) => { getRoom().remoteParticipants.forEach((participant) => {
participant.setVolume(1); participant.setVolume(1);
}); });
try { try {
await room.disconnect(); await getRoom().disconnect();
} catch (error) { } catch (error) {
log(1, "call", "red", "Failed to disconnect from room", error); log(1, "call", "red", "Failed to disconnect from room", error);
} finally { } finally {
@ -867,8 +888,8 @@ export async function joinCall(
callSecret, callSecret,
); );
await keyProvider.setKey(decryptedSecret); await getKeyProvider().setKey(decryptedSecret);
await room.setE2EEEnabled(true); await getRoom().setE2EEEnabled(true);
useCall.setState({ callSecret: decryptedSecret }); useCall.setState({ callSecret: decryptedSecret });
} catch (err) { } catch (err) {
log(1, "call", "red", "Failed getting call secret", err); log(1, "call", "red", "Failed getting call secret", err);
@ -878,8 +899,8 @@ export async function joinCall(
} else { } else {
const random = crypto.randomUUID(); const random = crypto.randomUUID();
await keyProvider.setKey(random); await getKeyProvider().setKey(random);
await room.setE2EEEnabled(true); await getRoom().setE2EEEnabled(true);
useCall.setState({ callSecret: random }); useCall.setState({ callSecret: random });
} }
@ -898,11 +919,11 @@ export async function joinCall(
export async function toggleDeaf() { export async function toggleDeaf() {
const nextDeaf = !useCall.getState().deaf; const nextDeaf = !useCall.getState().deaf;
room.remoteParticipants.forEach((participant) => { getRoom().remoteParticipants.forEach((participant) => {
participant.setVolume(nextDeaf ? 0 : 1); participant.setVolume(nextDeaf ? 0 : 1);
}); });
if (nextDeaf && room.localParticipant.isMicrophoneEnabled) { if (nextDeaf && getRoom().localParticipant.isMicrophoneEnabled) {
await toggleMute(); await toggleMute();
} }
@ -922,7 +943,7 @@ export async function toggleMute() {
await toggleDeaf(); await toggleDeaf();
} }
await room.localParticipant.setMicrophoneEnabled(!micEnabled); await getRoom().localParticipant.setMicrophoneEnabled(!micEnabled);
syncParticipantState(); syncParticipantState();
} }
@ -986,7 +1007,7 @@ export function resetCallState() {
async function ensureNoiseFilter( async function ensureNoiseFilter(
noiseFilter: DeepFilterNoiseFilterProcessor, noiseFilter: DeepFilterNoiseFilterProcessor,
): Promise<void> { ): Promise<void> {
const microphoneTrack = room.localParticipant.getTrackPublication( const microphoneTrack = getRoom().localParticipant.getTrackPublication(
Track.Source.Microphone, Track.Source.Microphone,
)?.track; )?.track;
@ -1001,7 +1022,7 @@ async function ensureNoiseFilter(
log(1, "call", "red", "Failed to enable noise filter", err); log(1, "call", "red", "Failed to enable noise filter", err);
}); });
const participantId = getParticipantId(room.localParticipant.identity); const participantId = getParticipantId(getRoom().localParticipant.identity);
if (participantId != null) { if (participantId != null) {
const processedTrack = microphoneTrack.mediaStreamTrack; const processedTrack = microphoneTrack.mediaStreamTrack;
getSpeakingDetector().addTrack( getSpeakingDetector().addTrack(
@ -1021,8 +1042,8 @@ export const useCall = create<CallStore>(() => ({
livekitToken: null, livekitToken: null,
currentCallData: null, currentCallData: null,
deaf: false, deaf: false,
micEnabled: room.localParticipant.isMicrophoneEnabled, micEnabled: false,
screenShareEnabled: room.localParticipant.isScreenShareEnabled, screenShareEnabled: false,
screenShareSession: null, screenShareSession: null,
focusedParticipantId: null, focusedParticipantId: null,
focusedParticipantType: null, focusedParticipantType: null,
@ -1030,15 +1051,11 @@ export const useCall = create<CallStore>(() => ({
watchedStreamParticipantIds: [], watchedStreamParticipantIds: [],
pendingWatchedParticipantIds: [], pendingWatchedParticipantIds: [],
activeScreenShareParticipantIds: [], activeScreenShareParticipantIds: [],
isEncrypted: isEncrypted: false,
room.localParticipant.isE2EEEnabled && room.localParticipant.isEncrypted,
callIsFullscreen: false, callIsFullscreen: false,
callIsPopout: false, callIsPopout: false,
layoutVersion: 0, layoutVersion: 0,
screenRef: null, screenRef: null,
room,
keyProvider,
e2eeWorker,
runtime: null, runtime: null,
speakingParticipantIds: new Set(), speakingParticipantIds: new Set(),
micGated: false, micGated: false,
@ -1384,6 +1401,7 @@ export function useInitializeCall() {
syncParticipantState(); syncParticipantState();
}; };
const room = getRoom();
room.on(RoomEvent.Connected, onConnected); room.on(RoomEvent.Connected, onConnected);
room.on(RoomEvent.Reconnected, onConnected); room.on(RoomEvent.Reconnected, onConnected);
room.on(RoomEvent.Disconnected, onDisconnected); room.on(RoomEvent.Disconnected, onDisconnected);
@ -1424,7 +1442,7 @@ export function useInitializeCall() {
clearRemoteAudio(); clearRemoteAudio();
listenersRegistered.current = false; listenersRegistered.current = false;
room.disconnect(); room.disconnect();
e2eeWorker.terminate(); if (_e2eeWorker) _e2eeWorker.terminate();
}; };
}, [noiseFilter, load]); }, [noiseFilter, load]);

View file

@ -1,13 +1,13 @@
import { RoomEvent } from "livekit-client"; import { RoomEvent } from "livekit-client";
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useCall } from "../../store"; import { useCall, getRoom } from "../../store";
import Base from "../../components/modals/base"; import Base from "../../components/modals/base";
const SECONDARY_ROW_HEIGHT_PX = 180; const SECONDARY_ROW_HEIGHT_PX = 180;
const STACK_GAP_PX = 12; const STACK_GAP_PX = 12;
export default function View() { export default function View() {
const room = useCall((state) => state.room); const room = getRoom();
const layoutVersion = useCall((state) => state.layoutVersion); const layoutVersion = useCall((state) => state.layoutVersion);
const usersInFocusedViewHidden = useCall( const usersInFocusedViewHidden = useCall(

View file

@ -1,6 +1,6 @@
import { RoomEvent } from "livekit-client"; import { RoomEvent } from "livekit-client";
import { useEffect, useMemo, useRef, useState } from "react"; import { useEffect, useMemo, useRef, useState } from "react";
import { useCall } from "../../store"; import { useCall, getRoom } from "../../store";
import Base from "../../components/modals/base"; import Base from "../../components/modals/base";
const TILE_ASPECT_RATIO = 16 / 9; const TILE_ASPECT_RATIO = 16 / 9;
@ -82,7 +82,7 @@ function calculateOptimalGridLayout(
} }
export default function View() { export default function View() {
const room = useCall((state) => state.room); const room = getRoom();
const layoutVersion = useCall((state) => state.layoutVersion); const layoutVersion = useCall((state) => state.layoutVersion);
const activeScreenShareParticipantIds = useCall( const activeScreenShareParticipantIds = useCall(
(state) => state.activeScreenShareParticipantIds, (state) => state.activeScreenShareParticipantIds,