feat(call): add native transport probe

This commit is contained in:
Erwan Leboucher committed 2026-07-30 14:06:14 +02:00
1 parent 8d16da8560
commit 09d074d19f
14 files changed
+1078 -22

No files matched your search

+3
View File
@@ -69,3 +69,6 @@ result
.direnv
## auto-generated pre-commit config
.pre-commit-config.yaml
# Local deepwork state
.slim/deepwork/
+8
View File
@@ -3748,6 +3748,7 @@ dependencies = [
"prost",
"rand 0.9.5",
"reqwest 0.12.28",
"rustls-native-certs",
"scopeguard",
"serde",
"serde_json",
@@ -3755,6 +3756,7 @@ dependencies = [
"signature",
"thiserror 2.0.19",
"tokio",
"tokio-rustls",
"tokio-tungstenite",
"url",
]
@@ -7903,7 +7905,11 @@ checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c"
dependencies = [
"futures-util",
"log",
"rustls",
"rustls-native-certs",
"rustls-pki-types",
"tokio",
"tokio-rustls",
"tungstenite",
]
@@ -8325,6 +8331,8 @@ dependencies = [
"httparse",
"log",
"rand 0.9.5",
"rustls",
"rustls-pki-types",
"sha1",
"thiserror 2.0.19",
"url",
@@ -9,8 +9,8 @@ exclude = ["/examples", "/dist-js", "/guest-js", "/node_modules"]
links = "tauri-plugin-call-lifecycle"
[dependencies]
tauri = { version = "2.11.3" }
livekit = "0.7"
tauri = { version = "2.11.3", default-features = false }
livekit = { version = "0.7", features = ["rustls-tls-native-roots"] }
secrecy = { version = "0.10", features = ["serde"] }
serde = "1.0"
thiserror = "2"
+46 -4
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useRef, useState, type RefObject } from 'react';
import { Badge, Box, color, Header, Scroll, Text, toRem } from 'folds';
import { Badge, Box, Button, color, Header, Scroll, Text, toRem } from 'folds';
import { useAtomValue } from 'jotai';
import { ContainerColor } from '$styles/ContainerColor.css';
import { useRoom } from '$hooks/useRoom';
@@ -13,6 +13,8 @@ import { CallMemberRenderer } from './CallMemberCard';
import { PrescreenControls } from './PrescreenControls';
import { callEmbedAtom, callEmbedStartErrorAtom } from '$state/callEmbed';
import { canJoinCall } from './callStartCapabilities';
import { nativeCallAtom } from '$state/nativeCall';
import { isDesktopTauri } from '$utils/platform';
function LivekitServerMissingMessage() {
return (
@@ -80,6 +82,35 @@ function WidgetPreparationErrorMessage({ message }: { message: string }) {
);
}
function NativeCallProbe({
lifecycle,
error,
onHangup,
}: {
lifecycle: string;
error?: string;
onHangup: () => void;
}) {
return (
<Box alignItems="Center" justifyContent="Center" direction="Column" gap="200" grow="Yes">
<Text size="L400">Native call: {lifecycle}</Text>
<Text size="T300" align="Center">
Media is not implemented.
</Text>
{error && (
<Text style={{ color: color.Critical.Main }} size="T300" align="Center">
{error}
</Text>
)}
<Button size="300" variant="Critical" fill="Soft" radii="300" onClick={onHangup}>
<Text as="span" size="B300">
End
</Text>
</Button>
</Box>
);
}
function CallPrescreen() {
const room = useRoom();
const callEmbed = useAtomValue(callEmbedAtom);
@@ -168,8 +199,11 @@ export function CallView({ resizable }: CallViewProps) {
const callEmbed = useCallEmbed();
const callJoined = useCallJoined(callEmbed);
const nativeCall = useAtomValue(nativeCallAtom);
const currentJoined = callEmbed?.roomId === room.roomId && callJoined;
const nativeCallForRoom =
isDesktopTauri() && nativeCall?.roomId === room.roomId ? nativeCall : undefined;
const currentJoined = !nativeCallForRoom && callEmbed?.roomId === room.roomId && callJoined;
const [heightRatio, setHeightRatio] = useState(isMobile ? 0.3 : 0.72);
const [availableHeight, setAvailableHeight] = useState(0);
@@ -284,8 +318,16 @@ export function CallView({ resizable }: CallViewProps) {
/>
)}
{!currentJoined && <CallPrescreen />}
<CallJoined containerRef={callContainerRef} />
{!currentJoined && !nativeCallForRoom && <CallPrescreen />}
{nativeCallForRoom ? (
<NativeCallProbe
lifecycle={nativeCallForRoom.lifecycle}
error={nativeCallForRoom.error}
onHangup={() => void nativeCallForRoom.hangup()}
/>
) : (
<CallJoined containerRef={callContainerRef} />
)}
{resizable && (
<button
@@ -69,6 +69,7 @@ describe('provisionLivekitToken', () => {
const options = {
mx: client(),
roomId: '!room:example.org',
slotId: 'm.call#real-slot',
deviceId: 'DEVICE',
serviceUrl: 'https://sfu.example///',
memberId: 'member-id',
@@ -90,7 +91,7 @@ describe('provisionLivekitToken', () => {
expect(url).toBe('https://sfu.example/get_token');
expect(JSON.parse(request.body as string)).toEqual({
room_id: '!room:example.org',
slot_id: 'm.call#!room:example.org',
slot_id: 'm.call#real-slot',
openid_token: openidToken,
member: {
id: 'member-id',
+3 -1
View File
@@ -12,6 +12,7 @@ import type {
export type LivekitProvisioningOptions = {
mx: Pick<MatrixClient, 'getOpenIdToken'>;
roomId: string;
slotId: string;
deviceId: string;
serviceUrl: string;
memberId?: string;
@@ -90,6 +91,7 @@ const requestLivekitToken = async (
export const provisionLivekitToken = async ({
mx,
roomId,
slotId,
deviceId,
serviceUrl,
memberId,
@@ -105,7 +107,7 @@ export const provisionLivekitToken = async ({
const endpoint = trimTrailingSlash(serviceUrl);
const modernRequest: ModernProvisioningRequest = {
room_id: roomId,
slot_id: `m.call#${roomId}`,
slot_id: slotId,
openid_token: openidToken,
};
@@ -0,0 +1,483 @@
import { describe, expect, it, vi } from 'vitest';
import { MatrixRTCSessionEvent, type CallMembership } from '$types/matrix-sdk';
import type { MatrixClient, MatrixRTCSession, Room } from '$types/matrix-sdk';
import { createNativeCallController } from './nativeCallController';
import type { NativeCallSession } from '$state/nativeCall';
import type { CallLifecycleError, CallState } from '$plugins/call/callLifecycle';
const room = { roomId: '!room:example.org' } as Room;
const makeSession = (slotId = 'm.call#real-slot') =>
({
slotId,
joinRTCSession:
vi.fn<
(identity: unknown, transports: unknown[], multiSfu?: unknown, config?: unknown) => void
>(),
leaveRoomSession: vi.fn<MatrixRTCSession['leaveRoomSession']>().mockResolvedValue(true),
on: vi.fn<(...args: unknown[]) => void>(),
removeListener: vi.fn<(...args: unknown[]) => void>(),
}) as unknown as MatrixRTCSession;
const makeClient = (session: MatrixRTCSession) =>
({
getDeviceId: () => 'DEVICE',
getSafeUserId: () => '@alice:example.org',
matrixRTC: { getRoomSession: () => session },
}) as unknown as MatrixClient;
const transport = { type: 'livekit' as const, livekit_service_url: 'https://sfu.example' };
const ownMembership = { userId: '@alice:example.org', deviceId: 'DEVICE' } as CallMembership;
const waitForMembershipListener = async (session: MatrixRTCSession): Promise<void> => {
await vi.waitFor(() =>
expect(session.on).toHaveBeenCalledWith(
MatrixRTCSessionEvent.MembershipsChanged,
expect.any(Function)
)
);
};
const emitOwnMembership = (session: MatrixRTCSession): void => {
const handler = vi
.mocked(session.on)
.mock.calls.find(([event]) => event === MatrixRTCSessionEvent.MembershipsChanged)?.[1] as
| ((oldMemberships: CallMembership[], memberships: CallMembership[]) => void)
| undefined;
handler?.([], [ownMembership]);
};
const emitMembershipManagerError = (session: MatrixRTCSession): void => {
const handler = vi
.mocked(session.on)
.mock.calls.find(([event]) => event === MatrixRTCSessionEvent.MembershipManagerError)?.[1] as
| ((error: unknown) => void)
| undefined;
handler?.(new Error('secret-membership-error'));
};
const waitForMembershipErrorListener = async (session: MatrixRTCSession): Promise<void> => {
await vi.waitFor(() =>
expect(session.on).toHaveBeenCalledWith(
MatrixRTCSessionEvent.MembershipManagerError,
expect.any(Function)
)
);
};
describe('native call controller', () => {
it('joins with one identity, provisions the session slot, then connects', async () => {
const session = makeSession();
const setSession = vi.fn<(session: NativeCallSession | undefined) => void>();
const order: string[] = [];
vi.mocked(session.joinRTCSession).mockImplementation(() => order.push('join'));
const controller = createNativeCallController({
setSession,
connectionId: () => 'connection-id',
onState: async () => vi.fn<() => void>(),
onError: async () => vi.fn<() => void>(),
getPreferredTransport: async () => transport,
provisionToken: async (options) => {
order.push('provision');
expect(options.slotId).toBe('m.call#real-slot');
expect(options.memberId).toBe('@alice:example.org:DEVICE');
return { url: 'wss://livekit.example', jwt: 'jwt' };
},
connect: async () => {
order.push('connect');
return { revision: 1, state: 'connected', connectionId: 'connection-id' };
},
});
const startPromise = controller.start({
mx: makeClient(session),
room,
elementCallActive: false,
dm: false,
video: false,
ongoing: false,
});
await waitForMembershipListener(session);
expect(order).toEqual(['join']);
emitOwnMembership(session);
await startPromise;
expect(session.joinRTCSession).toHaveBeenCalledWith(
{
userId: '@alice:example.org',
deviceId: 'DEVICE',
memberId: '@alice:example.org:DEVICE',
},
[transport],
undefined,
{
callIntent: 'audio',
notificationType: 'notification',
}
);
expect(order).toEqual(['join', 'provision', 'connect']);
expect(setSession).toHaveBeenLastCalledWith(
expect.objectContaining({
roomId: room.roomId,
connectionId: 'connection-id',
lifecycle: 'connected',
})
);
});
it('disconnects and leaves when provisioning fails without exposing the failure', async () => {
const session = makeSession();
const disconnect = vi.fn<(request: { connectionId: string }) => Promise<CallState>>();
disconnect.mockResolvedValue({ revision: 1, state: 'idle', connectionId: null });
const stateUnlisten = vi.fn<() => void>();
const errorUnlisten = vi.fn<() => void>();
const setSession = vi.fn<(session: NativeCallSession | undefined) => void>();
const controller = createNativeCallController({
setSession,
connectionId: () => 'connection-id',
disconnect,
onState: async (handler: (state: CallState) => void) => {
void handler;
return stateUnlisten;
},
onError: async (handler: (error: CallLifecycleError) => void) => {
void handler;
return errorUnlisten;
},
getPreferredTransport: async () => transport,
provisionToken: async () => {
throw new Error('openid-secret jwt-secret');
},
});
const startPromise = controller.start({
mx: makeClient(session),
room,
elementCallActive: false,
dm: false,
video: false,
ongoing: false,
});
await waitForMembershipListener(session);
emitOwnMembership(session);
await startPromise;
expect(disconnect).toHaveBeenCalledWith({ connectionId: 'connection-id' });
expect(session.leaveRoomSession).toHaveBeenCalledWith(5000);
expect(stateUnlisten).toHaveBeenCalled();
expect(errorUnlisten).toHaveBeenCalled();
expect(session.removeListener).toHaveBeenCalledWith(
MatrixRTCSessionEvent.MembershipsChanged,
expect.any(Function)
);
expect(session.removeListener).toHaveBeenCalledWith(
MatrixRTCSessionEvent.MembershipManagerError,
expect.any(Function)
);
expect(setSession).toHaveBeenLastCalledWith(
expect.objectContaining({
lifecycle: 'error',
error: 'Native call setup failed during token provisioning.',
})
);
expect(setSession.mock.calls.flat()).not.toContain('openid-secret');
expect(setSession.mock.calls.flat()).not.toContain('jwt-secret');
});
it('cleans up when the membership manager fails before publication', async () => {
const session = makeSession();
const disconnect = vi.fn<(request: { connectionId: string }) => Promise<CallState>>();
disconnect.mockResolvedValue({ revision: 1, state: 'idle', connectionId: null });
const stateUnlisten = vi.fn<() => void>();
const errorUnlisten = vi.fn<() => void>();
const setSession = vi.fn<(session: NativeCallSession | undefined) => void>();
const provisionToken = vi.fn<() => Promise<{ url: string; jwt: string }>>(async () => ({
url: 'wss://livekit.example',
jwt: 'jwt',
}));
const connect = vi.fn<
() => Promise<{ revision: number; state: 'connected'; connectionId: string }>
>(async () => ({
revision: 1,
state: 'connected' as const,
connectionId: 'connection-id',
}));
const controller = createNativeCallController({
setSession,
connectionId: () => 'connection-id',
disconnect,
onState: async () => stateUnlisten,
onError: async () => errorUnlisten,
getPreferredTransport: async () => transport,
provisionToken,
connect,
});
const startPromise = controller.start({
mx: makeClient(session),
room,
elementCallActive: false,
dm: false,
video: false,
ongoing: false,
});
await waitForMembershipListener(session);
await waitForMembershipErrorListener(session);
emitMembershipManagerError(session);
await startPromise;
expect(provisionToken).not.toHaveBeenCalled();
expect(connect).not.toHaveBeenCalled();
expect(disconnect).toHaveBeenCalledWith({ connectionId: 'connection-id' });
expect(session.leaveRoomSession).toHaveBeenCalledWith(5000);
expect(stateUnlisten).toHaveBeenCalled();
expect(errorUnlisten).toHaveBeenCalled();
expect(setSession).toHaveBeenLastCalledWith(
expect.objectContaining({
lifecycle: 'error',
error: 'Native call setup failed during MatrixRTC.',
})
);
expect(setSession.mock.calls.flat()).not.toContain('secret-membership-error');
});
it('cleans up when local membership publication times out', async () => {
vi.useFakeTimers();
try {
const session = makeSession();
const disconnect = vi.fn<(request: { connectionId: string }) => Promise<CallState>>();
disconnect.mockResolvedValue({ revision: 1, state: 'idle', connectionId: null });
const setSession = vi.fn<(session: NativeCallSession | undefined) => void>();
const provisionToken = vi.fn<() => Promise<{ url: string; jwt: string }>>(async () => ({
url: 'wss://livekit.example',
jwt: 'jwt',
}));
const connect = vi.fn<
() => Promise<{ revision: number; state: 'connected'; connectionId: string }>
>(async () => ({
revision: 1,
state: 'connected' as const,
connectionId: 'connection-id',
}));
const controller = createNativeCallController({
setSession,
connectionId: () => 'connection-id',
disconnect,
onState: async () => vi.fn<() => void>(),
onError: async () => vi.fn<() => void>(),
getPreferredTransport: async () => transport,
provisionToken,
connect,
});
const startPromise = controller.start({
mx: makeClient(session),
room,
elementCallActive: false,
dm: false,
video: false,
ongoing: false,
});
await waitForMembershipListener(session);
await vi.advanceTimersByTimeAsync(10_000);
await startPromise;
expect(provisionToken).not.toHaveBeenCalled();
expect(connect).not.toHaveBeenCalled();
expect(disconnect).toHaveBeenCalledWith({ connectionId: 'connection-id' });
expect(session.leaveRoomSession).toHaveBeenCalledWith(5000);
expect(session.removeListener).toHaveBeenCalledWith(
MatrixRTCSessionEvent.MembershipsChanged,
expect.any(Function)
);
expect(session.removeListener).toHaveBeenCalledWith(
MatrixRTCSessionEvent.MembershipManagerError,
expect.any(Function)
);
expect(setSession).toHaveBeenLastCalledWith(
expect.objectContaining({
lifecycle: 'error',
error: 'Native call setup failed during MatrixRTC.',
})
);
} finally {
vi.useRealTimers();
}
});
it.each(['device lookup', 'connection id generation', 'session lookup'])(
'publishes a safe error when %s fails before record creation',
async (operation) => {
const session = makeSession();
const setSession = vi.fn<(session: NativeCallSession | undefined) => void>();
const mx = makeClient(session);
if (operation === 'device lookup') {
vi.spyOn(mx, 'getDeviceId').mockImplementation(() => {
throw new Error('secret-device');
});
}
if (operation === 'session lookup') {
vi.spyOn(mx.matrixRTC, 'getRoomSession').mockImplementation(() => {
throw new Error('secret-session');
});
}
const controller = createNativeCallController({
setSession,
connectionId:
operation === 'connection id generation'
? () => {
throw new Error('secret-connection');
}
: () => 'connection-id',
});
await controller.start({
mx,
room,
elementCallActive: false,
dm: false,
video: false,
ongoing: false,
});
expect(setSession).toHaveBeenLastCalledWith(
expect.objectContaining({
lifecycle: 'error',
error: 'Native call setup failed during MatrixRTC.',
})
);
expect(setSession.mock.calls.flat()).not.toContain('secret-device');
expect(setSession.mock.calls.flat()).not.toContain('secret-connection');
expect(setSession.mock.calls.flat()).not.toContain('secret-session');
}
);
it('attempts both sides of cleanup when hangup operations fail', async () => {
const session = makeSession();
session.leaveRoomSession = vi
.fn<MatrixRTCSession['leaveRoomSession']>()
.mockRejectedValue(new Error('leave failed'));
const disconnect = vi.fn<(request: { connectionId: string }) => Promise<CallState>>();
disconnect.mockRejectedValue(new Error('disconnect failed'));
const setSession = vi.fn<(session: NativeCallSession | undefined) => void>();
const controller = createNativeCallController({
setSession,
connectionId: () => 'connection-id',
disconnect,
onState: async () => vi.fn<() => void>(),
onError: async () => vi.fn<() => void>(),
getPreferredTransport: async () => transport,
provisionToken: async () => ({ url: 'wss://livekit.example', jwt: 'jwt' }),
connect: async () => ({ revision: 1, state: 'connected', connectionId: 'connection-id' }),
});
const startPromise = controller.start({
mx: makeClient(session),
room,
elementCallActive: false,
dm: false,
video: false,
ongoing: false,
});
await waitForMembershipListener(session);
emitOwnMembership(session);
await startPromise;
await setSession.mock.lastCall?.[0]?.hangup();
expect(disconnect).toHaveBeenCalledWith({ connectionId: 'connection-id' });
expect(session.leaveRoomSession).toHaveBeenCalledWith(5000);
expect(setSession).toHaveBeenLastCalledWith(undefined);
});
it('uses a ring notification for a new DM and no notification when joining', async () => {
const start = async (dm: boolean, ongoing: boolean) => {
const session = makeSession();
const setSession = vi.fn<(session: NativeCallSession | undefined) => void>();
const controller = createNativeCallController({
setSession,
connectionId: () => `${dm}-${ongoing}`,
onState: async () => vi.fn<() => void>(),
onError: async () => vi.fn<() => void>(),
getPreferredTransport: async () => transport,
provisionToken: async () => ({ url: 'wss://livekit.example', jwt: 'jwt' }),
connect: async () => ({
revision: 1,
state: 'connected',
connectionId: `${dm}-${ongoing}`,
}),
});
const startPromise = controller.start({
mx: makeClient(session),
room,
elementCallActive: false,
dm,
video: true,
ongoing,
});
await waitForMembershipListener(session);
emitOwnMembership(session);
await startPromise;
return session;
};
const newDmSession = await start(true, false);
expect(newDmSession.joinRTCSession).toHaveBeenCalledWith(
expect.any(Object),
[transport],
undefined,
{
callIntent: 'video',
notificationType: 'ring',
}
);
const joinedSession = await start(false, true);
expect(joinedSession.joinRTCSession).toHaveBeenCalledWith(
expect.any(Object),
[transport],
undefined,
{ callIntent: 'video' }
);
});
it('accepts an anonymous idle only after its own connection state was observed', async () => {
const session = makeSession();
const setSession = vi.fn<(session: NativeCallSession | undefined) => void>();
let stateHandler: ((state: CallState) => void) | undefined;
const disconnect = vi.fn<(request: { connectionId: string }) => Promise<CallState>>();
disconnect.mockResolvedValue({ revision: 3, state: 'idle', connectionId: null });
const controller = createNativeCallController({
setSession,
connectionId: () => 'connection-id',
disconnect,
onState: async (handler: (state: CallState) => void) => {
stateHandler = handler;
return vi.fn<() => void>();
},
onError: async () => vi.fn<() => void>(),
getPreferredTransport: async () => transport,
provisionToken: async () => ({ url: 'wss://livekit.example', jwt: 'jwt' }),
connect: async () => ({ revision: 2, state: 'connected', connectionId: 'connection-id' }),
});
const startPromise = controller.start({
mx: makeClient(session),
room,
elementCallActive: false,
dm: false,
video: false,
ongoing: false,
});
await waitForMembershipListener(session);
emitOwnMembership(session);
await startPromise;
stateHandler?.({ revision: 3, state: 'idle', connectionId: null });
await vi.waitFor(() => expect(session.leaveRoomSession).toHaveBeenCalledWith(5000));
expect(disconnect).toHaveBeenCalledWith({ connectionId: 'connection-id' });
expect(setSession).toHaveBeenLastCalledWith(
expect.objectContaining({ lifecycle: 'error', error: 'Native call ended.' })
);
});
});
@@ -0,0 +1,387 @@
import type { AutoDiscoveryInfo } from '../../cs-api';
import {
MatrixRTCSessionEvent,
type CallMembership,
type JoinSessionConfig,
type MatrixClient,
type MatrixRTCSession,
type Room,
} from '$types/matrix-sdk';
import {
connect,
disconnect,
onError,
onState,
type CallLifecycleError,
type CallState,
type ConnectionState,
} from '$plugins/call/callLifecycle';
import { getPreferredLivekitTransport, provisionLivekitToken } from './livekitProvisioning';
import type { NativeCallLifecycle, NativeCallSession } from '$state/nativeCall';
type SetNativeCall = (session: NativeCallSession | undefined) => void;
type NativeCallControllerDependencies = {
setSession: SetNativeCall;
connect: typeof connect;
disconnect: typeof disconnect;
onState: typeof onState;
onError: typeof onError;
getPreferredTransport: typeof getPreferredLivekitTransport;
provisionToken: typeof provisionLivekitToken;
connectionId?: () => string;
};
type NativeCallStartOptions = {
mx: MatrixClient;
room: Room;
discovery?: Pick<AutoDiscoveryInfo, 'org.matrix.msc4143.rtc_foci'>;
elementCallActive: boolean;
dm: boolean;
video: boolean;
ongoing: boolean;
};
type NativeCallRecord = {
roomId: string;
connectionId: string;
session: MatrixRTCSession;
cancelled: boolean;
observedActiveState: boolean;
stateUnlistenPromise?: ReturnType<NativeCallControllerDependencies['onState']>;
errorUnlistenPromise?: ReturnType<NativeCallControllerDependencies['onError']>;
cancelMembershipWait?: () => void;
cleanupPromise?: Promise<void>;
};
const errorMessage = 'Native call setup failed.';
const endedMessage = 'Native call ended.';
type SetupStage = 'MatrixRTC' | 'LiveKit transport' | 'token provisioning' | 'LiveKit connection';
const membershipWaitTimeoutMs = 10_000;
type MembershipWait = {
promise: Promise<void>;
cancel: () => void;
};
const waitForOwnMembership = (
session: MatrixRTCSession,
userId: string,
deviceId: string
): MembershipWait => {
let resolveWait!: () => void;
let rejectWait!: (reason?: unknown) => void;
let settled = false;
let timeout: ReturnType<typeof setTimeout> | undefined;
let membershipsListenerInstalled = false;
let membershipErrorListenerInstalled = false;
const removeListeners = (): void => {
if (membershipsListenerInstalled) {
try {
session.removeListener(MatrixRTCSessionEvent.MembershipsChanged, handleMembershipsChanged);
} catch {}
membershipsListenerInstalled = false;
}
if (membershipErrorListenerInstalled) {
try {
session.removeListener(
MatrixRTCSessionEvent.MembershipManagerError,
handleMembershipManagerError
);
} catch {}
membershipErrorListenerInstalled = false;
}
};
const settle = (settlePromise: () => void): void => {
if (settled) return;
settled = true;
if (timeout !== undefined) clearTimeout(timeout);
removeListeners();
settlePromise();
};
const handleMembershipsChanged = (
_oldMemberships: CallMembership[],
memberships: CallMembership[]
): void => {
if (
memberships.some(
(membership) => membership.userId === userId && membership.deviceId === deviceId
)
) {
settle(resolveWait);
}
};
const handleMembershipManagerError = (): void => {
settle(() => rejectWait(new Error('MatrixRTC membership publication failed')));
};
const promise = new Promise<void>((resolve, reject) => {
resolveWait = resolve;
rejectWait = reject;
});
try {
session.on(MatrixRTCSessionEvent.MembershipsChanged, handleMembershipsChanged);
membershipsListenerInstalled = true;
session.on(MatrixRTCSessionEvent.MembershipManagerError, handleMembershipManagerError);
membershipErrorListenerInstalled = true;
timeout = setTimeout(
() => settle(() => rejectWait(new Error('MatrixRTC membership publication timed out'))),
membershipWaitTimeoutMs
);
} catch {
settle(() => rejectWait(new Error('MatrixRTC membership listener setup failed')));
}
return {
promise,
cancel: () => settle(() => rejectWait(new Error('MatrixRTC membership wait cancelled'))),
};
};
const setupErrorMessage = (stage: SetupStage): string =>
`Native call setup failed during ${stage}.`;
const isTerminalState = (state: ConnectionState): boolean => state === 'idle';
const isMatchingConnection = (connectionId: string | null, record: NativeCallRecord): boolean =>
connectionId === record.connectionId;
const toLifecycle = (state: ConnectionState): NativeCallLifecycle | undefined => {
if (state === 'connecting' || state === 'connected' || state === 'reconnecting') return state;
return undefined;
};
export const createNativeCallController = (
dependencies: Pick<NativeCallControllerDependencies, 'setSession'> &
Partial<
Pick<
NativeCallControllerDependencies,
| 'connect'
| 'disconnect'
| 'onState'
| 'onError'
| 'getPreferredTransport'
| 'provisionToken'
| 'connectionId'
>
>
) => {
const deps: NativeCallControllerDependencies = {
...dependencies,
connect: dependencies.connect ?? connect,
disconnect: dependencies.disconnect ?? disconnect,
onState: dependencies.onState ?? onState,
onError: dependencies.onError ?? onError,
getPreferredTransport: dependencies.getPreferredTransport ?? getPreferredLivekitTransport,
provisionToken: dependencies.provisionToken ?? provisionLivekitToken,
connectionId: dependencies.connectionId ?? (() => crypto.randomUUID()),
};
let activeRecord: NativeCallRecord | undefined;
let displayedRecord: NativeCallRecord | undefined;
const isCurrent = (record: NativeCallRecord): boolean =>
activeRecord === record && !record.cancelled;
const setSetupError = (roomId: string, error = errorMessage, connectionId = ''): void => {
try {
deps.setSession({
roomId,
connectionId,
lifecycle: 'error',
error,
hangup: async () => {
try {
deps.setSession(undefined);
} catch {}
},
});
} catch {}
};
const publish = (
record: NativeCallRecord,
lifecycle: NativeCallLifecycle,
error?: string
): void => {
if (!isCurrent(record)) return;
deps.setSession({
roomId: record.roomId,
connectionId: record.connectionId,
lifecycle,
...(error ? { error } : {}),
hangup: () => cleanup(record, undefined, true),
});
displayedRecord = record;
};
const cleanup = async (
record: NativeCallRecord,
failure: string | undefined,
clear: boolean
): Promise<void> => {
if (record.cleanupPromise) {
await record.cleanupPromise;
if (clear && displayedRecord === record) {
displayedRecord = undefined;
try {
deps.setSession(undefined);
} catch {}
}
return;
}
record.cancelled = true;
record.cancelMembershipWait?.();
record.cancelMembershipWait = undefined;
if (failure && activeRecord === record) {
try {
deps.setSession({
roomId: record.roomId,
connectionId: record.connectionId,
lifecycle: 'error',
error: failure,
hangup: () => cleanup(record, undefined, true),
});
} catch {}
displayedRecord = record;
}
record.cleanupPromise = (async () => {
try {
await deps.disconnect({ connectionId: record.connectionId });
} catch {}
try {
await record.session.leaveRoomSession(5000);
} catch {}
await Promise.allSettled([
record.stateUnlistenPromise?.then((unlisten) => unlisten()) ?? Promise.resolve(),
record.errorUnlistenPromise?.then((unlisten) => unlisten()) ?? Promise.resolve(),
]);
if (activeRecord === record) {
activeRecord = undefined;
}
if (clear && displayedRecord === record) {
displayedRecord = undefined;
try {
deps.setSession(undefined);
} catch {}
}
})();
await record.cleanupPromise;
};
const handleState = (record: NativeCallRecord, state: CallState): void => {
if (!isCurrent(record)) return;
if (isTerminalState(state.state)) {
if (state.connectionId !== record.connectionId && !record.observedActiveState) return;
if (state.connectionId !== null && !isMatchingConnection(state.connectionId, record)) return;
void cleanup(record, endedMessage, false);
return;
}
if (!isMatchingConnection(state.connectionId, record)) return;
const lifecycle = toLifecycle(state.state);
if (!lifecycle) return;
record.observedActiveState = true;
publish(record, lifecycle);
};
const handleError = (record: NativeCallRecord, error: CallLifecycleError): void => {
if (!isCurrent(record)) return;
if (!isMatchingConnection(error.connectionId, record)) return;
void cleanup(record, errorMessage, false);
};
const start = async ({
mx,
room,
discovery,
elementCallActive,
dm,
video,
ongoing,
}: NativeCallStartOptions) => {
if (activeRecord || elementCallActive) return;
let record: NativeCallRecord | undefined;
let stage: SetupStage = 'MatrixRTC';
try {
const deviceId = mx.getDeviceId();
if (!deviceId) {
setSetupError(room.roomId, setupErrorMessage(stage));
return;
}
const connectionId = deps.connectionId!();
const session = mx.matrixRTC.getRoomSession(room);
record = {
roomId: room.roomId,
connectionId,
session,
cancelled: false,
observedActiveState: false,
};
const currentRecord = record;
activeRecord = record;
publish(record, 'starting');
record.stateUnlistenPromise = deps.onState((state) => handleState(currentRecord, state));
record.errorUnlistenPromise = deps.onError((error) => handleError(currentRecord, error));
await Promise.all([record.stateUnlistenPromise, record.errorUnlistenPromise]);
stage = 'LiveKit transport';
const transport = await deps.getPreferredTransport(mx, discovery);
if (!transport) throw new Error('No LiveKit transport available');
const userId = mx.getSafeUserId();
const identity = { userId, deviceId, memberId: `${userId}:${deviceId}` };
const joinConfig: JoinSessionConfig = {
callIntent: video ? 'video' : 'audio',
...(ongoing ? {} : { notificationType: dm ? 'ring' : 'notification' }),
};
stage = 'MatrixRTC';
const membershipWait = waitForOwnMembership(session, identity.userId, identity.deviceId);
record.cancelMembershipWait = membershipWait.cancel;
session.joinRTCSession(identity, [transport], undefined, joinConfig);
await membershipWait.promise;
record.cancelMembershipWait = undefined;
const slotId = session.slotId;
if (!slotId) throw new Error('MatrixRTC slot was not assigned');
if (!isCurrent(record)) return;
stage = 'token provisioning';
const provisioned = await deps.provisionToken({
mx,
roomId: room.roomId,
slotId,
deviceId,
serviceUrl: transport.livekit_service_url,
memberId: identity.memberId,
userId: identity.userId,
});
if (!isCurrent(record)) return;
stage = 'LiveKit connection';
const state = await deps.connect({
connectionId,
serverUrl: provisioned.url,
participantToken: provisioned.jwt,
});
handleState(record, state);
} catch {
if (record) {
await cleanup(record, setupErrorMessage(stage), false);
} else {
setSetupError(room.roomId, setupErrorMessage(stage));
}
}
};
return { start };
};
@@ -0,0 +1,41 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const desktop = vi.hoisted(() => vi.fn<() => boolean>());
vi.mock('$utils/platform', () => ({ isDesktopTauri: desktop }));
import { isNativeCallProbeEnabled, NATIVE_CALL_PROBE_STORAGE_KEY } from './nativeCallProbe';
describe('native call probe gate', () => {
beforeEach(() => {
desktop.mockReset();
localStorage.clear();
});
afterEach(() => {
vi.unstubAllEnvs();
});
it('is disabled by default and enabled only by the documented desktop key', () => {
desktop.mockReturnValue(true);
vi.stubEnv('VITE_ENABLE_NATIVE_CALL_PROBE', 'false');
expect(isNativeCallProbeEnabled()).toBe(false);
localStorage.setItem(NATIVE_CALL_PROBE_STORAGE_KEY, '1');
expect(isNativeCallProbeEnabled()).toBe(true);
});
it('is enabled by the environment flag on desktop Tauri', () => {
desktop.mockReturnValue(true);
vi.stubEnv('VITE_ENABLE_NATIVE_CALL_PROBE', 'true');
expect(isNativeCallProbeEnabled()).toBe(true);
});
it('is disabled outside desktop Tauri', () => {
desktop.mockReturnValue(false);
vi.stubEnv('VITE_ENABLE_NATIVE_CALL_PROBE', 'true');
localStorage.setItem(NATIVE_CALL_PROBE_STORAGE_KEY, '1');
expect(isNativeCallProbeEnabled()).toBe(false);
});
});
+17
View File
@@ -0,0 +1,17 @@
import { isDesktopTauri } from '$utils/platform';
// Enable the desktop transport probe with VITE_ENABLE_NATIVE_CALL_PROBE=true or manually:
// localStorage.setItem('sable.nativeCallProbe', '1').
export const NATIVE_CALL_PROBE_STORAGE_KEY = 'sable.nativeCallProbe';
export const isNativeCallProbeEnabled = (): boolean => {
if (typeof window === 'undefined' || !isDesktopTauri()) return false;
if (import.meta.env.VITE_ENABLE_NATIVE_CALL_PROBE === 'true') return true;
try {
return window.localStorage.getItem(NATIVE_CALL_PROBE_STORAGE_KEY) === '1';
} catch {
return false;
}
};
+20 -11
View File
@@ -11,6 +11,7 @@ import {
mutedCallRoomIdAtom,
type IncomingCall,
} from '$state/callEmbed';
import { nativeCallAtom } from '$state/nativeCall';
import { settingsAtom } from '$state/settings';
import {
parseIncomingRtcNotification,
@@ -52,6 +53,7 @@ export function useIncomingCallSignaling() {
const mx = useMatrixClient();
const store = useStore();
const callEmbed = useAtomValue(callEmbedAtom);
const nativeCall = useAtomValue(nativeCallAtom);
const mDirects = useAtomValue(mDirectAtom);
const settings = useAtomValue(settingsAtom);
const incomingCall = useAtomValue(incomingCallAtom);
@@ -89,6 +91,7 @@ export function useIncomingCallSignaling() {
type SignalingHandlerRefs = {
callEmbed: typeof callEmbed;
nativeCall: typeof nativeCall;
mDirects: typeof mDirects;
outgoingRingbackAllowed: boolean;
handleIncomingCall: (incoming: IncomingCall) => void;
@@ -117,7 +120,7 @@ export function useIncomingCallSignaling() {
hasCallBeenActiveRef.current = false;
outgoingRingRoomIdRef.current = null;
outgoingStartRef.current = null;
}, [callEmbed]);
}, [callEmbed?.roomId, nativeCall?.connectionId]);
useEffect(() => {
ringtoneManager.syncSources(
@@ -147,7 +150,8 @@ export function useIncomingCallSignaling() {
const handleOutgoingDecline = useCallback(
(decline: OutgoingDeclineEvent) => {
if (!callEmbed || callEmbed.roomId !== decline.roomId) {
const activeCall = callEmbed ?? nativeCall;
if (!activeCall || activeCall.roomId !== decline.roomId) {
return;
}
@@ -207,8 +211,8 @@ export function useIncomingCallSignaling() {
Sentry.metrics.count('sable.call.outgoing.declined', 1);
stopOutgoingRing();
void callEmbed
.hangup()
const hangup = callEmbed?.hangup() ?? nativeCall?.hangup() ?? Promise.resolve();
void hangup
.catch((error) => {
debugLog.warn('call', 'Failed to hang up after outgoing decline', {
roomId: decline.roomId,
@@ -219,12 +223,11 @@ export function useIncomingCallSignaling() {
.finally(() => {
window.setTimeout(() => {
const activeEmbed = store.get(callEmbedAtom);
if (activeEmbed !== callEmbed) return;
setCallEmbed(undefined);
if (activeEmbed === callEmbed) setCallEmbed(undefined);
}, OUTGOING_DECLINE_EMBED_CLEAR_MS);
});
},
[callEmbed, mDirects, mx, setCallEmbed, stopOutgoingRing, store]
[callEmbed, mDirects, mx, nativeCall, setCallEmbed, stopOutgoingRing, store]
);
const callAudioAllowed = canPlayCallAudio({
@@ -283,6 +286,7 @@ export function useIncomingCallSignaling() {
signalingHandlerRefs.current = {
callEmbed,
nativeCall,
mDirects,
outgoingRingbackAllowed,
handleIncomingCall,
@@ -421,7 +425,11 @@ export function useIncomingCallSignaling() {
if (!senderId || !eventId) return;
if (senderId === myUserId) {
if (type === RTC_NOTIFICATION_EVENT_TYPE && handlers().callEmbed?.roomId === room.roomId) {
if (
type === RTC_NOTIFICATION_EVENT_TYPE &&
(handlers().callEmbed?.roomId === room.roomId ||
handlers().nativeCall?.roomId === room.roomId)
) {
activeOutgoingNotificationIdRef.current = eventId;
}
return;
@@ -436,8 +444,8 @@ export function useIncomingCallSignaling() {
// Only inspect declines for the active outgoing call room. Cleartext declines are
// cheap; encrypted events are decrypted only when they might be RTC declines.
const activeEmbed = handlers().callEmbed;
if (!activeEmbed || activeEmbed.roomId !== room.roomId) {
const activeCall = handlers().callEmbed ?? handlers().nativeCall;
if (!activeCall || activeCall.roomId !== room.roomId) {
return;
}
if (event.isDecryptionFailure()) {
@@ -496,7 +504,8 @@ export function useIncomingCallSignaling() {
let outgoingRingTimeoutId: number | undefined;
const evaluateOutgoingFallback = () => {
const activeCallRoomId = handlers().callEmbed?.roomId;
const activeCallRoomId =
handlers().callEmbed?.roomId ?? handlers().nativeCall?.roomId;
const stop = () => {
handlers().stopOutgoingRing();
+5 -1
View File
@@ -28,6 +28,7 @@ import { useDelayedEventsSupport } from '$hooks/useDelayedEventsSupport';
import { delayedEventsSupportedAtom } from '$state/scheduledMessages';
import { useCallMembers, useCallSession } from '$hooks/useCall';
import { callEmbedAtom } from '$state/callEmbed';
import { nativeCallAtom } from '$state/nativeCall';
import { useCallJoined } from '$hooks/useCallEmbed';
import { CallView } from '$features/call/CallView';
import { useRoom } from '$hooks/useRoom';
@@ -143,8 +144,11 @@ export function RoomView({ eventId }: { eventId?: string }) {
const callSession = useCallSession(room);
const callMembers = useCallMembers(room, callSession);
const callEmbed = useAtomValue(callEmbedAtom);
const nativeCall = useAtomValue(nativeCallAtom);
const isJoinedInThisRoom = useCallJoined(callEmbed) && callEmbed?.roomId === room.roomId;
const showCallView = !room.isCallRoom() && (callMembers.length > 0 || isJoinedInThisRoom);
const isNativeCallInThisRoom = nativeCall?.roomId === room.roomId;
const showCallView =
!room.isCallRoom() && (callMembers.length > 0 || isJoinedInThisRoom || isNativeCallInThisRoom);
return (
<Page
+45 -2
View File
@@ -1,5 +1,5 @@
import type { RefObject } from 'react';
import { createContext, useCallback, useContext, useEffect, useState } from 'react';
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import type { MatrixClient, Room } from '$types/matrix-sdk';
import { useSetAtom } from 'jotai';
import * as Sentry from '@sentry/react';
@@ -15,6 +15,12 @@ import type { CallPreferences } from '../state/callPreferences';
import { createDebugLogger } from '../utils/debugLogger';
import { useClientConfig } from './useClientConfig';
import { callEmbedStartErrorAtom } from '$state/callEmbed';
import { isNativeCallActive, nativeCallAtom } from '$state/nativeCall';
import { createNativeCallController } from '$features/call/nativeCallController';
import { isNativeCallProbeEnabled } from '$features/call/nativeCallProbe';
import { useAutoDiscoveryInfo } from './useAutoDiscoveryInfo';
import { isDesktopTauri } from '$utils/platform';
import { useStore } from 'jotai';
const debugLog = createDebugLogger('useCallEmbed');
@@ -65,10 +71,36 @@ export const useCallStart = (dm = false) => {
const clientConfig = useClientConfig();
const setCallEmbed = useSetAtom(callEmbedAtom);
const setCallEmbedStartError = useSetAtom(callEmbedStartErrorAtom);
const setNativeCall = useSetAtom(nativeCallAtom);
const callEmbedRef = useCallEmbedRef();
const store = useStore();
const discovery = useAutoDiscoveryInfo();
const nativeCallController = useMemo(
() =>
createNativeCallController({
setSession: setNativeCall,
}),
[setNativeCall]
);
const startCall = useCallback(
(room: Room, pref?: CallPreferences) => {
if (isDesktopTauri() && isNativeCallProbeEnabled()) {
if (store.get(callEmbedAtom) || isNativeCallActive(store.get(nativeCallAtom))) return;
const ongoing = mx.matrixRTC.getRoomSession(room).memberships.length > 0;
void nativeCallController
.start({
mx,
room,
discovery,
elementCallActive: Boolean(store.get(callEmbedAtom)),
dm,
video: pref?.video ?? false,
ongoing,
})
.catch(() => undefined);
return;
}
const container = callEmbedRef.current;
if (!container) {
debugLog.error('call', 'Failed to start call — no embed container', {
@@ -106,7 +138,18 @@ export const useCallStart = (dm = false) => {
throw err;
}
},
[mx, dm, theme, setCallEmbed, callEmbedRef, clientConfig.elementCallUrl, setCallEmbedStartError]
[
mx,
dm,
theme,
setCallEmbed,
callEmbedRef,
clientConfig.elementCallUrl,
setCallEmbedStartError,
store,
discovery,
nativeCallController,
]
);
return startCall;
+16
View File
@@ -0,0 +1,16 @@
import { atom } from 'jotai';
export type NativeCallLifecycle = 'starting' | 'connecting' | 'connected' | 'reconnecting' | 'error';
export type NativeCallSession = {
roomId: string;
connectionId: string;
lifecycle: NativeCallLifecycle;
error?: string;
hangup: () => Promise<void>;
};
export const nativeCallAtom = atom<NativeCallSession | undefined>(undefined);
export const isNativeCallActive = (session: NativeCallSession | undefined): boolean =>
session?.lifecycle !== undefined && session.lifecycle !== 'error';