mirror of
https://github.com/SableClient/Sable.git
synced 2026-12-06 00:32:26 -08:00
refactor(call): remove native lifecycle integration
This commit is contained in:
53 files changed
+37
-4737
No files matched your search
@@ -1,171 +0,0 @@
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { SecretStorageKeyContent } from '$types/matrix/accountData';
|
||||
import { SecretStorageRecoveryKey, SecretStorageRecoveryPassphrase } from './SecretStorage';
|
||||
|
||||
const decodeRecoveryKey = vi.hoisted(() =>
|
||||
vi.fn<(key: string) => Uint8Array>(() => new Uint8Array([1, 2, 3]))
|
||||
);
|
||||
const deriveRecoveryKeyFromPassphrase = vi.hoisted(() =>
|
||||
vi.fn<() => Promise<Uint8Array>>(async () => new Uint8Array([4, 5, 6]))
|
||||
);
|
||||
const checkKey = vi.hoisted(() => vi.fn<() => Promise<boolean>>());
|
||||
|
||||
vi.mock('$types/matrix-sdk', () => ({ decodeRecoveryKey, deriveRecoveryKeyFromPassphrase }));
|
||||
vi.mock('$hooks/useMatrixClient', () => ({
|
||||
useMatrixClient: () => ({ secretStorage: { checkKey } }),
|
||||
}));
|
||||
|
||||
const KEY_CONTENT = { algorithm: 'm.secret_storage.v1.aes-hmac-sha2' } as SecretStorageKeyContent;
|
||||
const PASSPHRASE_CONTENT = {
|
||||
algorithm: 'm.pbkdf2',
|
||||
salt: 'salt',
|
||||
iterations: 10000,
|
||||
bits: 256,
|
||||
};
|
||||
|
||||
const validKey = new Uint8Array([1, 2, 3]);
|
||||
|
||||
const submitRecoveryKey = (value: string) => {
|
||||
const input = document.querySelector('form input') as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value } });
|
||||
const form = input.closest('form') as HTMLFormElement;
|
||||
// jsdom lacks named form-element properties (form.recoveryKeyInput), which
|
||||
// the component relies on in real browsers.
|
||||
Object.defineProperty(form, input.name, { value: input, configurable: true });
|
||||
fireEvent.submit(form);
|
||||
};
|
||||
|
||||
describe('SecretStorageRecoveryKey', () => {
|
||||
beforeEach(() => {
|
||||
decodeRecoveryKey.mockReset();
|
||||
decodeRecoveryKey.mockReturnValue(validKey);
|
||||
checkKey.mockReset();
|
||||
});
|
||||
|
||||
it('does not forward a key when decoding fails and shows the original error', async () => {
|
||||
const onDecodedRecoveryKey = vi.fn<(key: Uint8Array) => void>();
|
||||
decodeRecoveryKey.mockImplementation(() => {
|
||||
throw new Error('Malformed recovery key');
|
||||
});
|
||||
render(
|
||||
<SecretStorageRecoveryKey
|
||||
keyContent={KEY_CONTENT}
|
||||
onDecodedRecoveryKey={onDecodedRecoveryKey}
|
||||
/>
|
||||
);
|
||||
|
||||
submitRecoveryKey('not-a-key');
|
||||
|
||||
expect(await screen.findByText('Malformed recovery key')).toBeInTheDocument();
|
||||
expect(onDecodedRecoveryKey).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not forward a key rejected by checkKey', async () => {
|
||||
const onDecodedRecoveryKey = vi.fn<(key: Uint8Array) => void>();
|
||||
checkKey.mockResolvedValue(false);
|
||||
render(
|
||||
<SecretStorageRecoveryKey
|
||||
keyContent={KEY_CONTENT}
|
||||
onDecodedRecoveryKey={onDecodedRecoveryKey}
|
||||
/>
|
||||
);
|
||||
|
||||
submitRecoveryKey('stale-key');
|
||||
|
||||
expect(await screen.findByText('Invalid recovery key.')).toBeInTheDocument();
|
||||
expect(onDecodedRecoveryKey).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not forward a key when checkKey rejects', async () => {
|
||||
const onDecodedRecoveryKey = vi.fn<(key: Uint8Array) => void>();
|
||||
checkKey.mockRejectedValue(new Error('network gone'));
|
||||
render(
|
||||
<SecretStorageRecoveryKey
|
||||
keyContent={KEY_CONTENT}
|
||||
onDecodedRecoveryKey={onDecodedRecoveryKey}
|
||||
/>
|
||||
);
|
||||
|
||||
submitRecoveryKey('some-key');
|
||||
|
||||
expect(await screen.findByText('network gone')).toBeInTheDocument();
|
||||
expect(onDecodedRecoveryKey).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not forward a non-Uint8Array result even when checkKey passes', async () => {
|
||||
const onDecodedRecoveryKey = vi.fn<(key: Uint8Array) => void>();
|
||||
decodeRecoveryKey.mockReturnValue('not-bytes' as unknown as Uint8Array);
|
||||
checkKey.mockResolvedValue(true);
|
||||
render(
|
||||
<SecretStorageRecoveryKey
|
||||
keyContent={KEY_CONTENT}
|
||||
onDecodedRecoveryKey={onDecodedRecoveryKey}
|
||||
/>
|
||||
);
|
||||
|
||||
submitRecoveryKey('some-key');
|
||||
|
||||
await waitFor(() => expect(checkKey).toHaveBeenCalled());
|
||||
await waitFor(() => expect(screen.queryByText('Verify')).toBeInTheDocument());
|
||||
expect(onDecodedRecoveryKey).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('forwards a valid decoded key exactly once', async () => {
|
||||
const onDecodedRecoveryKey = vi.fn<(key: Uint8Array) => void>();
|
||||
checkKey.mockResolvedValue(true);
|
||||
render(
|
||||
<SecretStorageRecoveryKey
|
||||
keyContent={KEY_CONTENT}
|
||||
onDecodedRecoveryKey={onDecodedRecoveryKey}
|
||||
/>
|
||||
);
|
||||
|
||||
submitRecoveryKey('valid-key');
|
||||
|
||||
await waitFor(() => expect(onDecodedRecoveryKey).toHaveBeenCalledTimes(1));
|
||||
expect(onDecodedRecoveryKey).toHaveBeenCalledWith(validKey);
|
||||
expect(screen.queryByText('Invalid recovery key.')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('SecretStorageRecoveryPassphrase', () => {
|
||||
beforeEach(() => {
|
||||
deriveRecoveryKeyFromPassphrase.mockReset();
|
||||
deriveRecoveryKeyFromPassphrase.mockResolvedValue(validKey);
|
||||
checkKey.mockReset();
|
||||
});
|
||||
|
||||
it('does not forward a key for an invalid passphrase', async () => {
|
||||
const onDecodedRecoveryKey = vi.fn<(key: Uint8Array) => void>();
|
||||
checkKey.mockResolvedValue(false);
|
||||
render(
|
||||
<SecretStorageRecoveryPassphrase
|
||||
keyContent={KEY_CONTENT}
|
||||
passphraseContent={PASSPHRASE_CONTENT}
|
||||
onDecodedRecoveryKey={onDecodedRecoveryKey}
|
||||
/>
|
||||
);
|
||||
|
||||
submitRecoveryKey('wrong passphrase');
|
||||
expect(await screen.findByText('Invalid recovery passphrase.')).toBeInTheDocument();
|
||||
expect(onDecodedRecoveryKey).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('forwards a valid passphrase-derived key exactly once', async () => {
|
||||
const onDecodedRecoveryKey = vi.fn<(key: Uint8Array) => void>();
|
||||
checkKey.mockResolvedValue(true);
|
||||
render(
|
||||
<SecretStorageRecoveryPassphrase
|
||||
keyContent={KEY_CONTENT}
|
||||
passphraseContent={PASSPHRASE_CONTENT}
|
||||
onDecodedRecoveryKey={onDecodedRecoveryKey}
|
||||
/>
|
||||
);
|
||||
|
||||
submitRecoveryKey('correct passphrase');
|
||||
|
||||
await waitFor(() => expect(onDecodedRecoveryKey).toHaveBeenCalledTimes(1));
|
||||
expect(onDecodedRecoveryKey).toHaveBeenCalledWith(validKey);
|
||||
});
|
||||
});
|
||||
@@ -74,7 +74,7 @@ export function SecretStorageRecoveryPassphrase({
|
||||
|
||||
const { salt, iterations, bits } = passphraseContent;
|
||||
submitPassphrase(recoveryPassphrase, salt, iterations, bits).then((decodedRecoveryKey) => {
|
||||
if (alive() && decodedRecoveryKey instanceof Uint8Array) {
|
||||
if (alive()) {
|
||||
recoveryPassphraseInput.value = '';
|
||||
onDecodedRecoveryKey(decodedRecoveryKey);
|
||||
}
|
||||
@@ -193,7 +193,7 @@ export function SecretStorageRecoveryKey({
|
||||
if (!recoveryKey) return;
|
||||
|
||||
submitRecoveryKey(recoveryKey).then((decodedRecoveryKey) => {
|
||||
if (alive() && decodedRecoveryKey instanceof Uint8Array) {
|
||||
if (alive()) {
|
||||
recoveryKeyInput.value = '';
|
||||
onDecodedRecoveryKey(decodedRecoveryKey);
|
||||
}
|
||||
|
||||
@@ -183,23 +183,6 @@ describe('LiveKit JS manual media test', () => {
|
||||
expect(screen.queryByText(/do-not-show|secret/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('maps the platform lifecycle failure to a safe bounded message', async () => {
|
||||
const session = makeSession();
|
||||
session.media!.setMicrophoneEnabled = vi
|
||||
.fn<() => Promise<void>>()
|
||||
.mockRejectedValue({ code: 'platform-lifecycle-failed', message: 'raw native detail' });
|
||||
render(
|
||||
<LivekitJsMediaTestSurface room={session.room!} media={session.media!} onHangup={() => {}} />
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Turn on microphone' }));
|
||||
|
||||
expect(
|
||||
await screen.findByText('Mobile call media is unavailable on this device.')
|
||||
).toBeInTheDocument();
|
||||
expect(screen.queryByText(/raw native detail/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps End as the only teardown action', () => {
|
||||
const onHangup = vi.fn<() => void>();
|
||||
const session = makeSession();
|
||||
|
||||
@@ -47,7 +47,6 @@ const mediaFailureMessages: Record<LivekitJsMediaFailure, string> = {
|
||||
'e2ee-key-not-ready': 'Waiting for encrypted media keys.',
|
||||
'e2ee-key-failed': 'Encrypted media setup failed.',
|
||||
'room-not-active': 'The LiveKit room is not active.',
|
||||
'platform-lifecycle-failed': 'Mobile call media is unavailable on this device.',
|
||||
'media-operation-failed': 'The media operation failed.',
|
||||
};
|
||||
|
||||
|
||||
@@ -1,17 +1,5 @@
|
||||
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
|
||||
|
||||
const tauriRuntime = vi.hoisted(() => vi.fn<() => boolean>());
|
||||
const pluginPlatform = vi.hoisted(() => ({
|
||||
getPlatformCapabilities: vi.fn<() => Promise<unknown>>(),
|
||||
getPlatformState: vi.fn<() => Promise<unknown>>(),
|
||||
onPlatformCallEvent: vi.fn<() => Promise<unknown>>(),
|
||||
startPlatformLifecycle: vi.fn<() => Promise<unknown>>(),
|
||||
stopPlatformLifecycle: vi.fn<() => Promise<unknown>>(),
|
||||
}));
|
||||
|
||||
vi.mock('@tauri-apps/api/core', () => ({ isTauri: tauriRuntime }));
|
||||
vi.mock('$plugins/call/platformCallLifecycle', () => pluginPlatform);
|
||||
|
||||
import {
|
||||
MatrixRTCSessionEvent,
|
||||
type CallMembership,
|
||||
@@ -22,10 +10,7 @@ import type { Room as LivekitRoom, RoomOptions } from 'livekit-client';
|
||||
import {
|
||||
createLivekitJsController,
|
||||
type LivekitJsControllerDependencies,
|
||||
type LivekitJsPlatformBridge,
|
||||
type LivekitJsPlatformStartRequest,
|
||||
} from './livekitJsController';
|
||||
import type { PlatformCallEvent } from '$plugins/call/platformCallLifecycle';
|
||||
import type {
|
||||
LivekitMatrixKeyProvider,
|
||||
LivekitMatrixKeyProviderState,
|
||||
@@ -222,52 +207,9 @@ const connectToActive = async (
|
||||
await connectPromise;
|
||||
};
|
||||
|
||||
type FakePlatform = {
|
||||
bridge: LivekitJsPlatformBridge;
|
||||
getCapabilities: Mock<() => Promise<unknown>>;
|
||||
start: Mock<(request: LivekitJsPlatformStartRequest) => Promise<unknown>>;
|
||||
stop: Mock<(request: { sessionId: string }) => Promise<unknown>>;
|
||||
emit: (event: PlatformCallEvent) => void;
|
||||
};
|
||||
|
||||
const makePlatform = (supported: boolean, order: string[]): FakePlatform => {
|
||||
let handler: ((event: PlatformCallEvent) => void) | undefined;
|
||||
const getCapabilities = vi.fn<() => Promise<unknown>>().mockImplementation(async () => {
|
||||
order.push('platform-caps');
|
||||
return { supported, microphone: supported, playback: supported };
|
||||
});
|
||||
const start = vi
|
||||
.fn<(request: LivekitJsPlatformStartRequest) => Promise<unknown>>()
|
||||
.mockImplementation(async (request) => {
|
||||
order.push(`platform-start:${request.microphone}:${request.playback}`);
|
||||
return { sessionId: request.sessionId };
|
||||
});
|
||||
const stop = vi
|
||||
.fn<(request: { sessionId: string }) => Promise<unknown>>()
|
||||
.mockImplementation(async () => {
|
||||
order.push('platform-stop');
|
||||
return {};
|
||||
});
|
||||
const bridge: LivekitJsPlatformBridge = {
|
||||
getCapabilities: getCapabilities as LivekitJsPlatformBridge['getCapabilities'],
|
||||
start: start as LivekitJsPlatformBridge['start'],
|
||||
stop: stop as LivekitJsPlatformBridge['stop'],
|
||||
onEvent: async (nextHandler) => {
|
||||
handler = nextHandler;
|
||||
return () => {
|
||||
order.push('platform-unlisten');
|
||||
};
|
||||
},
|
||||
};
|
||||
return { bridge, getCapabilities, start, stop, emit: (event) => handler?.(event) };
|
||||
};
|
||||
|
||||
describe('livekit JS controller', () => {
|
||||
beforeEach(() => {
|
||||
resetCallOwnerForTests();
|
||||
tauriRuntime.mockReset();
|
||||
tauriRuntime.mockReturnValue(false);
|
||||
Object.values(pluginPlatform).forEach((mock) => mock.mockReset());
|
||||
});
|
||||
|
||||
it('attaches E2EE before joining and provisions before connecting one no-media Room', async () => {
|
||||
@@ -555,452 +497,28 @@ describe('livekit JS controller', () => {
|
||||
});
|
||||
expect(controller.getState().mediaFailure).toBe('e2ee-unsupported');
|
||||
});
|
||||
|
||||
it('treats unsupported desktop platform capabilities as a no-op', async () => {
|
||||
const order: string[] = [];
|
||||
const session = makeSession(order);
|
||||
const platform = makePlatform(false, order);
|
||||
it('reports media-operation-failed when a media operation rejects', async () => {
|
||||
const session = makeSession();
|
||||
const provider = makeProvider({
|
||||
ready: true,
|
||||
localOutboundIdentity: 'local-backend-identity',
|
||||
keyIndex: 1,
|
||||
});
|
||||
const { dependencies, mediaParticipant } = makeDependencies(session, order, provider);
|
||||
dependencies.platformBridge = platform.bridge;
|
||||
const controller = createLivekitJsController(dependencies, { manualMediaTest: true });
|
||||
|
||||
await connectToActive(controller, session);
|
||||
await controller.setMicrophoneEnabled(true);
|
||||
|
||||
expect(platform.getCapabilities).toHaveBeenCalledOnce();
|
||||
expect(platform.start).not.toHaveBeenCalled();
|
||||
expect(platform.stop).not.toHaveBeenCalled();
|
||||
expect(mediaParticipant.setMicrophoneEnabled).toHaveBeenCalledWith(true);
|
||||
expect(controller.getState().platform).toBeUndefined();
|
||||
});
|
||||
|
||||
it('starts the platform lifecycle before enabling the local microphone', async () => {
|
||||
const order: string[] = [];
|
||||
const session = makeSession(order);
|
||||
const platform = makePlatform(true, order);
|
||||
const provider = makeProvider({
|
||||
ready: true,
|
||||
localOutboundIdentity: 'local-backend-identity',
|
||||
keyIndex: 1,
|
||||
});
|
||||
const { dependencies, mediaParticipant } = makeDependencies(session, order, provider);
|
||||
dependencies.platformBridge = platform.bridge;
|
||||
dependencies.createPlatformSessionId = () => 'opaque-session-1';
|
||||
mediaParticipant.setMicrophoneEnabled.mockImplementation(async () => {
|
||||
order.push('mic');
|
||||
return undefined;
|
||||
});
|
||||
const controller = createLivekitJsController(dependencies, { manualMediaTest: true });
|
||||
|
||||
await connectToActive(controller, session);
|
||||
expect(platform.start).not.toHaveBeenCalled();
|
||||
await controller.setMicrophoneEnabled(true);
|
||||
|
||||
expect(order.indexOf('platform-caps')).toBeGreaterThan(order.indexOf('connect'));
|
||||
expect(order.indexOf('platform-start:true:true')).toBeGreaterThan(order.indexOf('connect'));
|
||||
expect(order.indexOf('platform-start:true:true')).toBeLessThan(order.indexOf('mic'));
|
||||
expect(platform.start).toHaveBeenCalledWith({
|
||||
sessionId: 'opaque-session-1',
|
||||
microphone: true,
|
||||
playback: true,
|
||||
});
|
||||
expect(controller.getState().platform?.active).toBe(true);
|
||||
});
|
||||
|
||||
it('stops the platform lifecycle after Room disconnect and before MatrixRTC leave', async () => {
|
||||
const order: string[] = [];
|
||||
const session = makeSession(order);
|
||||
const platform = makePlatform(true, order);
|
||||
const provider = makeProvider({
|
||||
ready: true,
|
||||
localOutboundIdentity: 'local-backend-identity',
|
||||
keyIndex: 1,
|
||||
});
|
||||
const { dependencies, mediaParticipant } = makeDependencies(session, order, provider);
|
||||
dependencies.platformBridge = platform.bridge;
|
||||
mediaParticipant.setMicrophoneEnabled.mockImplementation(async () => {
|
||||
order.push('mic');
|
||||
return undefined;
|
||||
});
|
||||
const { dependencies, mediaParticipant } = makeDependencies(session, [], provider);
|
||||
const controller = createLivekitJsController(dependencies, { manualMediaTest: true });
|
||||
await connectToActive(controller, session);
|
||||
await controller.setMicrophoneEnabled(true);
|
||||
|
||||
await controller.disconnect();
|
||||
|
||||
expect(order.lastIndexOf('mic')).toBeLessThan(order.indexOf('disconnect'));
|
||||
expect(order.indexOf('disconnect')).toBeLessThan(order.indexOf('platform-stop'));
|
||||
expect(order.indexOf('platform-stop')).toBeLessThan(order.indexOf('detach'));
|
||||
expect(order.indexOf('platform-stop')).toBeLessThan(order.indexOf('leave'));
|
||||
expect(platform.stop).toHaveBeenCalledOnce();
|
||||
expect(controller.getState().platform).toBeUndefined();
|
||||
expect(controller.getState().lifecycle).toBe('idle');
|
||||
});
|
||||
|
||||
it('refuses the media operation and skips platform stop when platform start fails', async () => {
|
||||
const order: string[] = [];
|
||||
const session = makeSession(order);
|
||||
const platform = makePlatform(true, order);
|
||||
platform.start.mockRejectedValue(new Error('native start failed'));
|
||||
const provider = makeProvider({
|
||||
ready: true,
|
||||
localOutboundIdentity: 'local-backend-identity',
|
||||
keyIndex: 1,
|
||||
});
|
||||
const { dependencies, mediaParticipant } = makeDependencies(session, order, provider);
|
||||
dependencies.platformBridge = platform.bridge;
|
||||
const controller = createLivekitJsController(dependencies, { manualMediaTest: true });
|
||||
await connectToActive(controller, session);
|
||||
|
||||
await expect(controller.setMicrophoneEnabled(true)).rejects.toMatchObject({
|
||||
code: 'platform-lifecycle-failed',
|
||||
});
|
||||
|
||||
expect(mediaParticipant.setMicrophoneEnabled).not.toHaveBeenCalled();
|
||||
expect(controller.getState().mediaFailure).toBe('platform-lifecycle-failed');
|
||||
expect(controller.getState().platform?.active).toBe(false);
|
||||
|
||||
await controller.disconnect();
|
||||
expect(platform.stop).not.toHaveBeenCalled();
|
||||
expect(provider.detach).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('restarts platform lifecycle with the same session when flags change', async () => {
|
||||
const order: string[] = [];
|
||||
const session = makeSession(order);
|
||||
const platform = makePlatform(true, order);
|
||||
const provider = makeProvider({
|
||||
ready: true,
|
||||
localOutboundIdentity: 'local-backend-identity',
|
||||
keyIndex: 1,
|
||||
});
|
||||
const { dependencies } = makeDependencies(session, order, provider);
|
||||
dependencies.platformBridge = platform.bridge;
|
||||
dependencies.createPlatformSessionId = () => 'opaque-session-1';
|
||||
const controller = createLivekitJsController(dependencies, { manualMediaTest: true });
|
||||
await connectToActive(controller, session);
|
||||
|
||||
await controller.setCameraEnabled(true);
|
||||
expect(platform.start).toHaveBeenLastCalledWith({
|
||||
sessionId: 'opaque-session-1',
|
||||
microphone: false,
|
||||
playback: true,
|
||||
});
|
||||
expect(platform.stop).not.toHaveBeenCalled();
|
||||
|
||||
await controller.setMicrophoneEnabled(true);
|
||||
expect(platform.stop).toHaveBeenCalledWith({ sessionId: 'opaque-session-1' });
|
||||
expect(platform.start).toHaveBeenLastCalledWith({
|
||||
sessionId: 'opaque-session-1',
|
||||
microphone: true,
|
||||
playback: true,
|
||||
});
|
||||
expect(platform.start).toHaveBeenCalledTimes(2);
|
||||
|
||||
const stopsBefore = platform.stop.mock.calls.length;
|
||||
await controller.setMicrophoneEnabled(true);
|
||||
expect(platform.stop.mock.calls.length).toBe(stopsBefore);
|
||||
expect(platform.start).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('filters stale session and revision platform events', async () => {
|
||||
const order: string[] = [];
|
||||
const session = makeSession(order);
|
||||
const platform = makePlatform(true, order);
|
||||
const provider = makeProvider({
|
||||
ready: true,
|
||||
localOutboundIdentity: 'local-backend-identity',
|
||||
keyIndex: 1,
|
||||
});
|
||||
const { dependencies } = makeDependencies(session, order, provider);
|
||||
dependencies.platformBridge = platform.bridge;
|
||||
dependencies.createPlatformSessionId = () => 'opaque-session-1';
|
||||
const controller = createLivekitJsController(dependencies, { manualMediaTest: true });
|
||||
await connectToActive(controller, session);
|
||||
await controller.setCameraEnabled(true);
|
||||
|
||||
platform.emit({ revision: 2, sessionId: 'other-session', type: 'media_reset' });
|
||||
platform.emit({ revision: 3, sessionId: 'opaque-session-1', type: 'media_reset' });
|
||||
platform.emit({
|
||||
revision: 3,
|
||||
sessionId: 'opaque-session-1',
|
||||
type: 'focus_changed',
|
||||
focused: false,
|
||||
});
|
||||
platform.emit({
|
||||
revision: 4,
|
||||
sessionId: 'opaque-session-1',
|
||||
type: 'focus_changed',
|
||||
focused: false,
|
||||
});
|
||||
await vi.waitFor(() => expect(controller.getState().platform?.focused).toBe(false));
|
||||
|
||||
const snapshot = controller.getState().platform;
|
||||
expect(snapshot?.mediaReset).toBe(true);
|
||||
expect(snapshot?.focused).toBe(false);
|
||||
expect(snapshot?.active).toBe(true);
|
||||
expect(controller.getState().mediaFailure).toBeNull();
|
||||
});
|
||||
|
||||
it('refuses manual media when the platform capability lookup fails', async () => {
|
||||
const order: string[] = [];
|
||||
const session = makeSession(order);
|
||||
const platform = makePlatform(false, order);
|
||||
platform.getCapabilities.mockReset();
|
||||
platform.getCapabilities.mockRejectedValue(new Error('capability bridge unavailable'));
|
||||
const provider = makeProvider({
|
||||
ready: true,
|
||||
localOutboundIdentity: 'local-backend-identity',
|
||||
keyIndex: 1,
|
||||
});
|
||||
const { dependencies, mediaParticipant } = makeDependencies(session, order, provider);
|
||||
dependencies.platformBridge = platform.bridge;
|
||||
const controller = createLivekitJsController(dependencies, { manualMediaTest: true });
|
||||
await connectToActive(controller, session);
|
||||
|
||||
await expect(controller.setMicrophoneEnabled(true)).rejects.toMatchObject({
|
||||
code: 'platform-lifecycle-failed',
|
||||
});
|
||||
|
||||
expect(mediaParticipant.setMicrophoneEnabled).not.toHaveBeenCalled();
|
||||
expect(platform.start).not.toHaveBeenCalled();
|
||||
expect(controller.getState().mediaFailure).toBe('platform-lifecycle-failed');
|
||||
expect(controller.getState().platform).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['malformed supported', { supported: 'yes', microphone: true, playback: true }],
|
||||
['missing microphone', { supported: true, playback: true }],
|
||||
['malformed microphone', { supported: true, microphone: 1, playback: true }],
|
||||
['missing playback', { supported: true, microphone: true }],
|
||||
['malformed playback', { supported: true, microphone: true, playback: null }],
|
||||
['missing everything', {}],
|
||||
['a null result', null],
|
||||
['an undefined result', undefined],
|
||||
])(
|
||||
'refuses manual media without calling media methods on %s capability result',
|
||||
async (_label, capabilities) => {
|
||||
const order: string[] = [];
|
||||
const session = makeSession(order);
|
||||
const platform = makePlatform(false, order);
|
||||
platform.getCapabilities.mockReset();
|
||||
platform.getCapabilities.mockResolvedValue(capabilities);
|
||||
const provider = makeProvider({
|
||||
ready: true,
|
||||
localOutboundIdentity: 'local-backend-identity',
|
||||
keyIndex: 1,
|
||||
});
|
||||
const { dependencies, mediaParticipant } = makeDependencies(session, order, provider);
|
||||
dependencies.platformBridge = platform.bridge;
|
||||
const controller = createLivekitJsController(dependencies, { manualMediaTest: true });
|
||||
await connectToActive(controller, session);
|
||||
|
||||
await expect(controller.setMicrophoneEnabled(true)).rejects.toMatchObject({
|
||||
code: 'platform-lifecycle-failed',
|
||||
});
|
||||
await expect(controller.setCameraEnabled(true)).rejects.toMatchObject({
|
||||
code: 'platform-lifecycle-failed',
|
||||
});
|
||||
|
||||
expect(mediaParticipant.setMicrophoneEnabled).not.toHaveBeenCalled();
|
||||
expect(mediaParticipant.setCameraEnabled).not.toHaveBeenCalled();
|
||||
expect(mediaParticipant.setScreenShareEnabled).not.toHaveBeenCalled();
|
||||
expect(platform.start).not.toHaveBeenCalled();
|
||||
expect(controller.getState().mediaFailure).toBe('platform-lifecycle-failed');
|
||||
expect(controller.getState().platform).toBeUndefined();
|
||||
}
|
||||
);
|
||||
|
||||
it('disables the LiveKit microphone track before downgrading the platform lifecycle', async () => {
|
||||
const order: string[] = [];
|
||||
const session = makeSession(order);
|
||||
const platform = makePlatform(true, order);
|
||||
const provider = makeProvider({
|
||||
ready: true,
|
||||
localOutboundIdentity: 'local-backend-identity',
|
||||
keyIndex: 1,
|
||||
});
|
||||
const { dependencies, mediaParticipant } = makeDependencies(session, order, provider);
|
||||
dependencies.platformBridge = platform.bridge;
|
||||
dependencies.createPlatformSessionId = () => 'opaque-session-1';
|
||||
mediaParticipant.setMicrophoneEnabled.mockImplementation(async (enabled) => {
|
||||
order.push(enabled ? 'mic-on' : 'mic-off');
|
||||
return undefined;
|
||||
});
|
||||
const controller = createLivekitJsController(dependencies, { manualMediaTest: true });
|
||||
await connectToActive(controller, session);
|
||||
await controller.setMicrophoneEnabled(true);
|
||||
expect(platform.start).toHaveBeenLastCalledWith({
|
||||
sessionId: 'opaque-session-1',
|
||||
microphone: true,
|
||||
playback: true,
|
||||
});
|
||||
|
||||
await controller.setMicrophoneEnabled(false);
|
||||
|
||||
expect(order.indexOf('mic-on')).toBeLessThan(order.indexOf('mic-off'));
|
||||
expect(order.indexOf('mic-off')).toBeLessThan(order.indexOf('platform-stop'));
|
||||
expect(order.indexOf('platform-stop')).toBeLessThan(order.indexOf('platform-start:false:true'));
|
||||
expect(platform.start).toHaveBeenLastCalledWith({
|
||||
sessionId: 'opaque-session-1',
|
||||
microphone: false,
|
||||
playback: true,
|
||||
});
|
||||
expect(controller.getState().platform?.active).toBe(true);
|
||||
expect(controller.getState().mediaFailure).toBeNull();
|
||||
});
|
||||
|
||||
it('retains the microphone lifecycle when the JS microphone disable fails', async () => {
|
||||
const order: string[] = [];
|
||||
const session = makeSession(order);
|
||||
const platform = makePlatform(true, order);
|
||||
const provider = makeProvider({
|
||||
ready: true,
|
||||
localOutboundIdentity: 'local-backend-identity',
|
||||
keyIndex: 1,
|
||||
});
|
||||
const { dependencies, mediaParticipant } = makeDependencies(session, order, provider);
|
||||
dependencies.platformBridge = platform.bridge;
|
||||
dependencies.createPlatformSessionId = () => 'opaque-session-1';
|
||||
mediaParticipant.setMicrophoneEnabled.mockImplementation(async (enabled) => {
|
||||
order.push(enabled ? 'mic-on' : 'mic-off');
|
||||
return undefined;
|
||||
});
|
||||
const controller = createLivekitJsController(dependencies, { manualMediaTest: true });
|
||||
await connectToActive(controller, session);
|
||||
await controller.setMicrophoneEnabled(true);
|
||||
|
||||
mediaParticipant.setMicrophoneEnabled.mockRejectedValueOnce(new Error('track stuck'));
|
||||
await expect(controller.setMicrophoneEnabled(false)).rejects.toMatchObject({
|
||||
code: 'media-operation-failed',
|
||||
});
|
||||
|
||||
expect(platform.stop).not.toHaveBeenCalled();
|
||||
expect(platform.start).toHaveBeenCalledTimes(1);
|
||||
expect(controller.getState().mediaFailure).toBe('media-operation-failed');
|
||||
expect(controller.getState().platform?.active).toBe(true);
|
||||
|
||||
// A later media operation must not downgrade the microphone lifecycle.
|
||||
await controller.setCameraEnabled(true);
|
||||
expect(platform.stop).not.toHaveBeenCalled();
|
||||
expect(platform.start).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Teardown still stops the retained microphone lifecycle.
|
||||
// Teardown still unpublishes the retained microphone before disconnect.
|
||||
await controller.disconnect();
|
||||
expect(platform.stop).toHaveBeenCalledWith({ sessionId: 'opaque-session-1' });
|
||||
expect(order.lastIndexOf('platform-stop')).toBeLessThan(order.indexOf('leave'));
|
||||
expect(mediaParticipant.setMicrophoneEnabled).toHaveBeenLastCalledWith(false);
|
||||
expect(controller.getState().lifecycle).toBe('idle');
|
||||
});
|
||||
|
||||
it('uses an explicit unsupported browser bridge without calling Tauri invoke', async () => {
|
||||
// tauriRuntime is false: no platform bridge dependency is injected.
|
||||
const order: string[] = [];
|
||||
const session = makeSession(order);
|
||||
const provider = makeProvider({
|
||||
ready: true,
|
||||
localOutboundIdentity: 'local-backend-identity',
|
||||
keyIndex: 1,
|
||||
});
|
||||
const { dependencies, mediaParticipant } = makeDependencies(session, order, provider);
|
||||
const controller = createLivekitJsController(dependencies, { manualMediaTest: true });
|
||||
|
||||
await connectToActive(controller, session);
|
||||
await controller.setMicrophoneEnabled(true);
|
||||
await controller.setCameraEnabled(true);
|
||||
|
||||
expect(mediaParticipant.setMicrophoneEnabled).toHaveBeenCalledWith(true);
|
||||
expect(mediaParticipant.setCameraEnabled).toHaveBeenCalledWith(true);
|
||||
expect(controller.getState().mediaFailure).toBeNull();
|
||||
expect(pluginPlatform.getPlatformCapabilities).not.toHaveBeenCalled();
|
||||
expect(pluginPlatform.startPlatformLifecycle).not.toHaveBeenCalled();
|
||||
expect(pluginPlatform.stopPlatformLifecycle).not.toHaveBeenCalled();
|
||||
expect(pluginPlatform.onPlatformCallEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps the Tauri default bridge: desktop capability response stays a no-op', async () => {
|
||||
tauriRuntime.mockReturnValue(true);
|
||||
pluginPlatform.getPlatformCapabilities.mockResolvedValue({
|
||||
supported: false,
|
||||
microphone: false,
|
||||
playback: false,
|
||||
});
|
||||
const order: string[] = [];
|
||||
const session = makeSession(order);
|
||||
const provider = makeProvider({
|
||||
ready: true,
|
||||
localOutboundIdentity: 'local-backend-identity',
|
||||
keyIndex: 1,
|
||||
});
|
||||
const { dependencies, mediaParticipant } = makeDependencies(session, order, provider);
|
||||
const controller = createLivekitJsController(dependencies, { manualMediaTest: true });
|
||||
|
||||
await connectToActive(controller, session);
|
||||
await controller.setMicrophoneEnabled(true);
|
||||
|
||||
expect(pluginPlatform.getPlatformCapabilities).toHaveBeenCalledOnce();
|
||||
expect(pluginPlatform.startPlatformLifecycle).not.toHaveBeenCalled();
|
||||
expect(mediaParticipant.setMicrophoneEnabled).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('still fails closed on Tauri when the capability lookup rejects', async () => {
|
||||
tauriRuntime.mockReturnValue(true);
|
||||
pluginPlatform.getPlatformCapabilities.mockRejectedValue(new Error('invoke failed'));
|
||||
const order: string[] = [];
|
||||
const session = makeSession(order);
|
||||
const provider = makeProvider({
|
||||
ready: true,
|
||||
localOutboundIdentity: 'local-backend-identity',
|
||||
keyIndex: 1,
|
||||
});
|
||||
const { dependencies, mediaParticipant } = makeDependencies(session, order, provider);
|
||||
const controller = createLivekitJsController(dependencies, { manualMediaTest: true });
|
||||
|
||||
await connectToActive(controller, session);
|
||||
await expect(controller.setMicrophoneEnabled(true)).rejects.toMatchObject({
|
||||
code: 'platform-lifecycle-failed',
|
||||
});
|
||||
|
||||
expect(mediaParticipant.setMicrophoneEnabled).not.toHaveBeenCalled();
|
||||
expect(pluginPlatform.startPlatformLifecycle).not.toHaveBeenCalled();
|
||||
expect(controller.getState().mediaFailure).toBe('platform-lifecycle-failed');
|
||||
});
|
||||
|
||||
it('stops manual media safely on a platform failure event', async () => {
|
||||
const order: string[] = [];
|
||||
const session = makeSession(order);
|
||||
const platform = makePlatform(true, order);
|
||||
const provider = makeProvider({
|
||||
ready: true,
|
||||
localOutboundIdentity: 'local-backend-identity',
|
||||
keyIndex: 1,
|
||||
});
|
||||
const { dependencies, mediaParticipant } = makeDependencies(session, order, provider);
|
||||
dependencies.platformBridge = platform.bridge;
|
||||
dependencies.createPlatformSessionId = () => 'opaque-session-1';
|
||||
const controller = createLivekitJsController(dependencies, { manualMediaTest: true });
|
||||
await connectToActive(controller, session);
|
||||
await controller.setMicrophoneEnabled(true);
|
||||
|
||||
platform.emit({
|
||||
revision: 1,
|
||||
sessionId: 'opaque-session-1',
|
||||
type: 'failed',
|
||||
code: 'audio_unavailable',
|
||||
});
|
||||
await vi.waitFor(() =>
|
||||
expect(controller.getState().mediaFailure).toBe('platform-lifecycle-failed')
|
||||
);
|
||||
|
||||
expect(controller.getState().platform).toMatchObject({
|
||||
active: false,
|
||||
failure: 'audio_unavailable',
|
||||
});
|
||||
expect(mediaParticipant.setMicrophoneEnabled).toHaveBeenLastCalledWith(false);
|
||||
expect(controller.getState().lifecycle).toBe('active');
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,3 @@
|
||||
import { isTauri } from '@tauri-apps/api/core';
|
||||
import { Room as LivekitRoom, type RoomOptions } from 'livekit-client';
|
||||
import type { AutoDiscoveryInfo } from '../../cs-api';
|
||||
import type { MatrixClient, MatrixRTCSession, Room as MatrixRoom } from '$types/matrix-sdk';
|
||||
@@ -13,16 +12,6 @@ import {
|
||||
} from './livekitMatrixKeyProvider';
|
||||
import { getPreferredLivekitTransport, provisionLivekitToken } from './livekitProvisioning';
|
||||
import { acquireCallOwner, type CallOwnerLease } from '$state/callOwner';
|
||||
import {
|
||||
getPlatformCapabilities as getPluginPlatformCapabilities,
|
||||
onPlatformCallEvent,
|
||||
startPlatformLifecycle,
|
||||
stopPlatformLifecycle,
|
||||
type PlatformCallCapabilities,
|
||||
type PlatformCallEvent,
|
||||
type PlatformCallFailureCode,
|
||||
type PlatformCallRoute,
|
||||
} from '$plugins/call/platformCallLifecycle';
|
||||
|
||||
export type LivekitJsControllerLifecycle =
|
||||
| 'idle'
|
||||
@@ -41,7 +30,6 @@ export type LivekitJsMediaFailure =
|
||||
| 'e2ee-key-not-ready'
|
||||
| 'e2ee-key-failed'
|
||||
| 'room-not-active'
|
||||
| 'platform-lifecycle-failed'
|
||||
| 'media-operation-failed';
|
||||
|
||||
export class LivekitJsMediaError extends Error {
|
||||
@@ -57,35 +45,12 @@ export type LivekitJsMediaFacade = {
|
||||
setScreenShareEnabled: (enabled: boolean) => Promise<void>;
|
||||
};
|
||||
|
||||
export type LivekitJsPlatformStartRequest = {
|
||||
sessionId: string;
|
||||
microphone: boolean;
|
||||
playback: boolean;
|
||||
};
|
||||
|
||||
export type LivekitJsPlatformBridge = {
|
||||
getCapabilities: () => Promise<PlatformCallCapabilities>;
|
||||
start: (request: LivekitJsPlatformStartRequest) => Promise<unknown>;
|
||||
stop: (request: { sessionId: string }) => Promise<unknown>;
|
||||
onEvent: (handler: (event: PlatformCallEvent) => void) => Promise<() => void>;
|
||||
};
|
||||
|
||||
export type LivekitJsPlatformState = {
|
||||
active: boolean;
|
||||
focused: boolean;
|
||||
route: PlatformCallRoute | null;
|
||||
interrupted: boolean;
|
||||
mediaReset: boolean;
|
||||
failure: PlatformCallFailureCode | null;
|
||||
};
|
||||
|
||||
export type LivekitJsControllerState = {
|
||||
lifecycle: LivekitJsControllerLifecycle;
|
||||
failure: LivekitJsControllerFailure | null;
|
||||
mediaFailure: LivekitJsMediaFailure | null;
|
||||
room?: LivekitRoom;
|
||||
media?: LivekitJsMediaFacade;
|
||||
platform?: LivekitJsPlatformState;
|
||||
e2ee: Readonly<LivekitMatrixKeyProviderState>;
|
||||
};
|
||||
|
||||
@@ -131,8 +96,6 @@ export type LivekitJsControllerDependencies = {
|
||||
isE2EESupported?: () => boolean;
|
||||
getPreferredTransport?: typeof getPreferredLivekitTransport;
|
||||
provisionToken?: typeof provisionLivekitToken;
|
||||
platformBridge?: LivekitJsPlatformBridge;
|
||||
createPlatformSessionId?: () => string;
|
||||
};
|
||||
|
||||
type ControllerRecord = {
|
||||
@@ -147,14 +110,6 @@ type ControllerRecord = {
|
||||
e2eeFailure: boolean;
|
||||
cancelMembershipWait?: () => void;
|
||||
removeKeyStateListener?: () => void;
|
||||
platformSessionId?: string;
|
||||
platformCaps?: Promise<PlatformCallCapabilities>;
|
||||
platformActive: boolean;
|
||||
platformFlags: { microphone: boolean; playback: boolean };
|
||||
platformDesired: { microphone: boolean; playback: boolean };
|
||||
platformRevision: number;
|
||||
platformUnlisten?: () => void;
|
||||
platformEventOp?: Promise<void>;
|
||||
mediaPublished: boolean;
|
||||
cleanupPromise?: Promise<void>;
|
||||
resourcesReady: Promise<void>;
|
||||
@@ -173,36 +128,6 @@ const defaultCreateRoom = (options: RoomOptions): LivekitRoomLike => new Livekit
|
||||
const defaultCreateWorker = (): Worker =>
|
||||
new Worker(new URL('livekit-client/e2ee-worker', import.meta.url), { type: 'module' });
|
||||
|
||||
const tauriPlatformBridge: LivekitJsPlatformBridge = {
|
||||
getCapabilities: getPluginPlatformCapabilities,
|
||||
start: startPlatformLifecycle,
|
||||
stop: stopPlatformLifecycle,
|
||||
onEvent: onPlatformCallEvent,
|
||||
};
|
||||
|
||||
// Browser builds have no platform lifecycle plugin: manual media uses browser
|
||||
// getUserMedia directly and the bridge reports explicit unsupported without
|
||||
// touching Tauri invoke.
|
||||
const browserPlatformBridge: LivekitJsPlatformBridge = {
|
||||
getCapabilities: async () => ({ supported: false, microphone: false, playback: false }),
|
||||
start: async () => Promise.reject(new Error('platform lifecycle is unavailable in browser')),
|
||||
stop: async () => Promise.reject(new Error('platform lifecycle is unavailable in browser')),
|
||||
onEvent: async () => () => undefined,
|
||||
};
|
||||
|
||||
const createDefaultPlatformBridge = (): LivekitJsPlatformBridge =>
|
||||
isTauri() ? tauriPlatformBridge : browserPlatformBridge;
|
||||
|
||||
let platformSessionCounter = 0;
|
||||
const defaultCreatePlatformSessionId = (): string => {
|
||||
platformSessionCounter += 1;
|
||||
const random =
|
||||
typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
|
||||
? crypto.randomUUID()
|
||||
: `${Date.now().toString(36)}-${platformSessionCounter.toString(36)}`;
|
||||
return `livekit-js-platform-${random}`;
|
||||
};
|
||||
|
||||
export function createLivekitJsController(
|
||||
dependencies: LivekitJsControllerDependencies | undefined,
|
||||
options: { manualMediaTest: true }
|
||||
@@ -222,9 +147,6 @@ export function createLivekitJsController(
|
||||
const supportsE2EE = dependencies.isE2EESupported ?? isLivekitE2EESupported;
|
||||
const getPreferredTransport = dependencies.getPreferredTransport ?? getPreferredLivekitTransport;
|
||||
const provisionToken = dependencies.provisionToken ?? provisionLivekitToken;
|
||||
const platformBridge = dependencies.platformBridge ?? createDefaultPlatformBridge();
|
||||
const createPlatformSessionId =
|
||||
dependencies.createPlatformSessionId ?? defaultCreatePlatformSessionId;
|
||||
const manualMediaTest = controllerOptions.manualMediaTest === true;
|
||||
|
||||
let state: LivekitJsControllerState = {
|
||||
@@ -286,32 +208,11 @@ export function createLivekitJsController(
|
||||
}
|
||||
await current.room?.disconnect();
|
||||
};
|
||||
const stopPlatform = async (): Promise<void> => {
|
||||
if (current.platformEventOp) {
|
||||
try {
|
||||
await current.platformEventOp;
|
||||
} catch {
|
||||
// Event settling must not block platform stop.
|
||||
}
|
||||
}
|
||||
if (current.platformActive && current.platformSessionId) {
|
||||
try {
|
||||
await platformBridge.stop({ sessionId: current.platformSessionId });
|
||||
} catch {
|
||||
// Platform stop failures never block room/provider cleanup.
|
||||
}
|
||||
current.platformActive = false;
|
||||
}
|
||||
current.platformUnlisten?.();
|
||||
current.platformUnlisten = undefined;
|
||||
publish({ platform: undefined });
|
||||
};
|
||||
if (current.matrixJoinStarted) {
|
||||
await disconnectLivekitThenLeaveMatrixRTC(async () => {
|
||||
try {
|
||||
await stopRoom();
|
||||
} finally {
|
||||
await stopPlatform();
|
||||
detachProvider();
|
||||
}
|
||||
}, current.session);
|
||||
@@ -321,7 +222,6 @@ export function createLivekitJsController(
|
||||
} catch {
|
||||
// Cleanup continues even when a setup room rejects disconnect.
|
||||
} finally {
|
||||
await stopPlatform();
|
||||
detachProvider();
|
||||
}
|
||||
}
|
||||
@@ -436,142 +336,12 @@ export function createLivekitJsController(
|
||||
return record.room.localParticipant;
|
||||
};
|
||||
|
||||
const publishPlatform = (current: ControllerRecord, patch: Partial<LivekitJsPlatformState>) => {
|
||||
if (record !== current) return;
|
||||
const base: LivekitJsPlatformState = state.platform ?? {
|
||||
active: current.platformActive,
|
||||
focused: true,
|
||||
route: null,
|
||||
interrupted: false,
|
||||
mediaReset: false,
|
||||
failure: null,
|
||||
};
|
||||
publish({ platform: { ...base, ...patch } });
|
||||
};
|
||||
|
||||
const getPlatformCapabilities = (
|
||||
current: ControllerRecord
|
||||
): Promise<PlatformCallCapabilities> => {
|
||||
if (!current.platformCaps) {
|
||||
current.platformCaps = platformBridge.getCapabilities();
|
||||
}
|
||||
return current.platformCaps;
|
||||
};
|
||||
|
||||
const applyPlatformEvent = async (
|
||||
current: ControllerRecord,
|
||||
event: PlatformCallEvent
|
||||
): Promise<void> => {
|
||||
if (current.cancelled || event.sessionId !== current.platformSessionId) return;
|
||||
if (event.revision <= current.platformRevision) return;
|
||||
current.platformRevision = event.revision;
|
||||
switch (event.type) {
|
||||
case 'focus_changed':
|
||||
publishPlatform(current, { focused: event.focused });
|
||||
break;
|
||||
case 'route_changed':
|
||||
publishPlatform(current, { route: event.route });
|
||||
break;
|
||||
case 'interrupted':
|
||||
publishPlatform(current, { interrupted: event.state === 'began' });
|
||||
break;
|
||||
case 'media_reset':
|
||||
publishPlatform(current, { mediaReset: true });
|
||||
break;
|
||||
case 'failed': {
|
||||
// Native code never controls tracks; JS fails the manual test safely.
|
||||
current.platformActive = false;
|
||||
publishPlatform(current, { active: false, failure: event.code });
|
||||
publish({ mediaFailure: 'platform-lifecycle-failed' });
|
||||
const participant = current.room?.localParticipant;
|
||||
if (participant && current.mediaPublished) {
|
||||
try {
|
||||
await participant.setMicrophoneEnabled(false);
|
||||
await participant.setCameraEnabled(false);
|
||||
await participant.setScreenShareEnabled(false);
|
||||
} catch {
|
||||
// Disconnect cleanup unpublishes any remaining tracks.
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
const ensurePlatformListener = async (current: ControllerRecord): Promise<void> => {
|
||||
if (current.platformUnlisten) return;
|
||||
const unlisten = await platformBridge.onEvent((event) => {
|
||||
current.platformEventOp = applyPlatformEvent(current, event).finally(() => {
|
||||
current.platformEventOp = undefined;
|
||||
});
|
||||
});
|
||||
if (current.cancelled || !current.platformActive) {
|
||||
unlisten();
|
||||
return;
|
||||
}
|
||||
current.platformUnlisten = unlisten;
|
||||
};
|
||||
|
||||
const ensurePlatformLifecycle = async (current: ControllerRecord): Promise<void> => {
|
||||
let capabilities: PlatformCallCapabilities;
|
||||
try {
|
||||
capabilities = await getPlatformCapabilities(current);
|
||||
} catch {
|
||||
// A rejected capability request is not the desktop no-op case.
|
||||
throw new LivekitJsMediaError('platform-lifecycle-failed');
|
||||
}
|
||||
if (
|
||||
!capabilities ||
|
||||
typeof capabilities.supported !== 'boolean' ||
|
||||
typeof capabilities.microphone !== 'boolean' ||
|
||||
typeof capabilities.playback !== 'boolean'
|
||||
) {
|
||||
// A malformed capability result fails closed like a rejection.
|
||||
throw new LivekitJsMediaError('platform-lifecycle-failed');
|
||||
}
|
||||
if (!capabilities.supported || current.cancelled) return;
|
||||
|
||||
const desired = { ...current.platformDesired };
|
||||
if (
|
||||
current.platformActive &&
|
||||
current.platformFlags.microphone === desired.microphone &&
|
||||
current.platformFlags.playback === desired.playback
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (current.platformActive && current.platformSessionId) {
|
||||
await platformBridge.stop({ sessionId: current.platformSessionId });
|
||||
current.platformActive = false;
|
||||
}
|
||||
if (!current.platformSessionId) current.platformSessionId = createPlatformSessionId();
|
||||
await platformBridge.start({ sessionId: current.platformSessionId, ...desired });
|
||||
current.platformFlags = desired;
|
||||
current.platformActive = true;
|
||||
publishPlatform(current, { active: true, failure: null });
|
||||
await ensurePlatformListener(current);
|
||||
} catch {
|
||||
current.platformActive = false;
|
||||
publishPlatform(current, { active: false });
|
||||
throw new LivekitJsMediaError('platform-lifecycle-failed');
|
||||
}
|
||||
};
|
||||
|
||||
const runMediaAction = async (
|
||||
action: (participant: LivekitLocalParticipantLike) => Promise<unknown>,
|
||||
platformOrder: 'platform-first' | 'platform-after' = 'platform-first'
|
||||
action: (participant: LivekitLocalParticipantLike) => Promise<unknown>
|
||||
): Promise<void> => {
|
||||
let current: ControllerRecord;
|
||||
let participant: LivekitLocalParticipantLike;
|
||||
try {
|
||||
participant = requireMediaParticipant();
|
||||
// requireMediaParticipant guarantees an active record; narrow for TS.
|
||||
if (!record) throw new LivekitJsMediaError('room-not-active');
|
||||
current = record;
|
||||
if (platformOrder === 'platform-first') await ensurePlatformLifecycle(current);
|
||||
} catch (error) {
|
||||
if (error instanceof LivekitJsMediaError) publish({ mediaFailure: error.code });
|
||||
throw error;
|
||||
@@ -584,14 +354,6 @@ export function createLivekitJsController(
|
||||
publish({ mediaFailure: error.code });
|
||||
throw error;
|
||||
}
|
||||
if (platformOrder === 'platform-after') {
|
||||
try {
|
||||
await ensurePlatformLifecycle(current);
|
||||
} catch (error) {
|
||||
if (error instanceof LivekitJsMediaError) publish({ mediaFailure: error.code });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
publish({ mediaFailure: null });
|
||||
};
|
||||
|
||||
@@ -600,31 +362,11 @@ export function createLivekitJsController(
|
||||
if (published && record) record.mediaPublished = true;
|
||||
});
|
||||
|
||||
const setMicrophoneEnabled = (enabled: boolean): Promise<void> => {
|
||||
if (record) record.platformDesired.microphone = enabled;
|
||||
const promise = markMediaPublished(
|
||||
// A microphone disable must unpublish the JS track before the platform
|
||||
// lifecycle is stopped or downgraded.
|
||||
runMediaAction(
|
||||
(participant) => participant.setMicrophoneEnabled(enabled),
|
||||
enabled ? 'platform-first' : 'platform-after'
|
||||
),
|
||||
const setMicrophoneEnabled = (enabled: boolean): Promise<void> =>
|
||||
markMediaPublished(
|
||||
runMediaAction((participant) => participant.setMicrophoneEnabled(enabled)),
|
||||
enabled
|
||||
);
|
||||
if (enabled) return promise;
|
||||
return promise.catch((error) => {
|
||||
// The JS track failed to disable, so the microphone may still be
|
||||
// live: retain the microphone platform lifecycle.
|
||||
if (
|
||||
record &&
|
||||
error instanceof LivekitJsMediaError &&
|
||||
error.code === 'media-operation-failed'
|
||||
) {
|
||||
record.platformDesired.microphone = true;
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
};
|
||||
|
||||
const setCameraEnabled = (enabled: boolean): Promise<void> =>
|
||||
markMediaPublished(
|
||||
@@ -695,10 +437,6 @@ export function createLivekitJsController(
|
||||
ownerLease,
|
||||
resourcesReady,
|
||||
resolveResources,
|
||||
platformActive: false,
|
||||
platformFlags: { microphone: false, playback: false },
|
||||
platformDesired: { microphone: false, playback: true },
|
||||
platformRevision: -1,
|
||||
mediaPublished: false,
|
||||
};
|
||||
record = current;
|
||||
|
||||
@@ -106,18 +106,10 @@ export async function showSnapOverlay(): Promise<void> {
|
||||
return invoke('show_snap_overlay');
|
||||
}
|
||||
|
||||
export async function startCallForegroundService(): Promise<void> {
|
||||
return invoke('start_call_foreground_service');
|
||||
}
|
||||
|
||||
export async function startWindowTrackingWithTarget(params: types.StartWindowTrackingWithTargetParams): Promise<void> {
|
||||
return invoke('start_window_tracking_with_target', params);
|
||||
}
|
||||
|
||||
export async function stopCallForegroundService(): Promise<void> {
|
||||
return invoke('stop_call_foreground_service');
|
||||
}
|
||||
|
||||
export async function stopWindowTracking(): Promise<void> {
|
||||
return invoke('stop_window_tracking');
|
||||
}
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const pluginGetCapabilities = vi.hoisted(() => vi.fn<() => Promise<unknown>>());
|
||||
const pluginGetState = vi.hoisted(() => vi.fn<() => Promise<unknown>>());
|
||||
const pluginListenEvent = vi.hoisted(() =>
|
||||
vi.fn<(handler: (event: unknown) => void) => Promise<unknown>>()
|
||||
);
|
||||
const pluginStart = vi.hoisted(() => vi.fn<(request: unknown) => Promise<unknown>>());
|
||||
const pluginStop = vi.hoisted(() => vi.fn<(request: unknown) => Promise<unknown>>());
|
||||
|
||||
vi.mock('tauri-plugin-call-lifecycle-api', () => ({
|
||||
getPlatformCallCapabilities: pluginGetCapabilities,
|
||||
getPlatformCallState: pluginGetState,
|
||||
listenPlatformCallEvent: pluginListenEvent,
|
||||
startPlatformCallLifecycle: pluginStart,
|
||||
stopPlatformCallLifecycle: pluginStop,
|
||||
}));
|
||||
|
||||
import {
|
||||
getPlatformCapabilities,
|
||||
getPlatformState,
|
||||
onPlatformCallEvent,
|
||||
startPlatformLifecycle,
|
||||
stopPlatformLifecycle,
|
||||
type PlatformCallEvent,
|
||||
type PlatformCallState,
|
||||
} from './platformCallLifecycle';
|
||||
|
||||
describe('platform call lifecycle wrapper', () => {
|
||||
beforeEach(() => {
|
||||
pluginGetCapabilities.mockReset();
|
||||
pluginGetState.mockReset();
|
||||
pluginListenEvent.mockReset();
|
||||
pluginStart.mockReset();
|
||||
pluginStop.mockReset();
|
||||
pluginListenEvent.mockResolvedValue(vi.fn());
|
||||
});
|
||||
|
||||
it('delegates capabilities/start/stop/state commands with opaque session payloads', async () => {
|
||||
const capabilities = { supported: true, microphone: true, playback: true };
|
||||
const state = {
|
||||
revision: 2,
|
||||
state: 'active',
|
||||
sessionId: 'opaque-session',
|
||||
microphone: true,
|
||||
playback: true,
|
||||
capabilities,
|
||||
} satisfies PlatformCallState;
|
||||
pluginGetCapabilities.mockResolvedValue(capabilities);
|
||||
pluginStart.mockResolvedValue(state);
|
||||
pluginStop.mockResolvedValue(state);
|
||||
pluginGetState.mockResolvedValue(state);
|
||||
|
||||
await expect(getPlatformCapabilities()).resolves.toEqual(capabilities);
|
||||
await expect(
|
||||
startPlatformLifecycle({ sessionId: 'opaque-session', microphone: true, playback: true })
|
||||
).resolves.toEqual(state);
|
||||
await expect(stopPlatformLifecycle({ sessionId: 'opaque-session' })).resolves.toEqual(state);
|
||||
await expect(getPlatformState()).resolves.toEqual(state);
|
||||
|
||||
expect(pluginStart).toHaveBeenCalledWith({
|
||||
sessionId: 'opaque-session',
|
||||
microphone: true,
|
||||
playback: true,
|
||||
});
|
||||
expect(pluginStop).toHaveBeenCalledWith({ sessionId: 'opaque-session' });
|
||||
});
|
||||
|
||||
it('forwards bounded platform events and drops malformed payloads', async () => {
|
||||
const handler = vi.fn<(event: PlatformCallEvent) => void>();
|
||||
await onPlatformCallEvent(handler);
|
||||
const listener = pluginListenEvent.mock.calls[0]?.[0] as (event: unknown) => void;
|
||||
|
||||
const routeEvent: PlatformCallEvent = {
|
||||
revision: 4,
|
||||
sessionId: 'opaque-session',
|
||||
type: 'route_changed',
|
||||
route: 'speaker',
|
||||
};
|
||||
listener(routeEvent);
|
||||
listener({ revision: 5, sessionId: 'opaque-session', type: 'media_reset' });
|
||||
listener({
|
||||
revision: 6,
|
||||
sessionId: 'opaque-session',
|
||||
type: 'failed',
|
||||
code: 'audio_unavailable',
|
||||
});
|
||||
|
||||
// Malformed or out-of-contract payloads never reach the handler.
|
||||
listener({ revision: 7, sessionId: 'opaque-session', type: 'route_changed', route: 'eth0' });
|
||||
listener({ revision: 8, sessionId: 'opaque-session', type: 'publish_track' });
|
||||
listener({ revision: '9', sessionId: 'opaque-session', type: 'media_reset' });
|
||||
listener({ revision: 10, type: 'media_reset' });
|
||||
listener({ revision: 11, sessionId: 'opaque-session', type: 'failed', code: 'raw-native' });
|
||||
|
||||
expect(handler).toHaveBeenCalledTimes(3);
|
||||
expect(handler).toHaveBeenNthCalledWith(1, routeEvent);
|
||||
});
|
||||
});
|
||||
@@ -1,81 +0,0 @@
|
||||
import {
|
||||
getPlatformCallCapabilities as pluginGetCapabilities,
|
||||
getPlatformCallState as pluginGetState,
|
||||
listenPlatformCallEvent as pluginListenEvent,
|
||||
startPlatformCallLifecycle as pluginStart,
|
||||
stopPlatformCallLifecycle as pluginStop,
|
||||
type PlatformCallCapabilities,
|
||||
type PlatformCallEvent,
|
||||
type PlatformCallFailureCode,
|
||||
type PlatformCallRoute,
|
||||
type PlatformCallState,
|
||||
type StartPlatformCallLifecycleRequest,
|
||||
type StopPlatformCallLifecycleRequest,
|
||||
} from 'tauri-plugin-call-lifecycle-api';
|
||||
import type { UnlistenFn } from '@tauri-apps/api/event';
|
||||
|
||||
export type {
|
||||
PlatformCallCapabilities,
|
||||
PlatformCallEvent,
|
||||
PlatformCallFailureCode,
|
||||
PlatformCallRoute,
|
||||
PlatformCallState,
|
||||
StartPlatformCallLifecycleRequest,
|
||||
StopPlatformCallLifecycleRequest,
|
||||
};
|
||||
|
||||
const EVENT_TYPES = new Set([
|
||||
'focus_changed',
|
||||
'route_changed',
|
||||
'interrupted',
|
||||
'media_reset',
|
||||
'failed',
|
||||
]);
|
||||
|
||||
const ROUTES = new Set<PlatformCallRoute>(['earpiece', 'speaker', 'wired', 'bluetooth', 'unknown']);
|
||||
|
||||
const FAILURE_CODES = new Set<PlatformCallFailureCode>([
|
||||
'unsupported',
|
||||
'permission_denied',
|
||||
'audio_unavailable',
|
||||
'start_failed',
|
||||
'stop_failed',
|
||||
'stale_session',
|
||||
'busy',
|
||||
]);
|
||||
|
||||
const isBoundedEvent = (payload: unknown): payload is PlatformCallEvent => {
|
||||
if (!payload || typeof payload !== 'object') return false;
|
||||
const event = payload as Record<string, unknown>;
|
||||
if (typeof event.revision !== 'number' || typeof event.sessionId !== 'string') return false;
|
||||
if (typeof event.type !== 'string' || !EVENT_TYPES.has(event.type)) return false;
|
||||
switch (event.type) {
|
||||
case 'focus_changed':
|
||||
return typeof event.focused === 'boolean';
|
||||
case 'route_changed':
|
||||
return typeof event.route === 'string' && ROUTES.has(event.route as PlatformCallRoute);
|
||||
case 'interrupted':
|
||||
return event.state === 'began' || event.state === 'ended';
|
||||
case 'media_reset':
|
||||
return true;
|
||||
case 'failed':
|
||||
return (
|
||||
typeof event.code === 'string' && FAILURE_CODES.has(event.code as PlatformCallFailureCode)
|
||||
);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const getPlatformCapabilities = pluginGetCapabilities;
|
||||
export const startPlatformLifecycle = pluginStart;
|
||||
export const stopPlatformLifecycle = pluginStop;
|
||||
export const getPlatformState = pluginGetState;
|
||||
|
||||
export function onPlatformCallEvent(
|
||||
handler: (event: PlatformCallEvent) => void
|
||||
): Promise<UnlistenFn> {
|
||||
return pluginListenEvent((payload) => {
|
||||
if (isBoundedEvent(payload)) handler(payload);
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user