refactor(call): remove native lifecycle integration

This commit is contained in:
Erwan Leboucher committed 2026-07-30 14:11:19 +02:00
1 parent 9b9776d66e
commit 12e24a3c0e
53 files changed
+37 -4737

No files matched your search

-2
View File
@@ -1,2 +0,0 @@
[env]
MACOSX_DEPLOYMENT_TARGET = { value = "13.0", force = true }
-3
View File
@@ -69,6 +69,3 @@ result
.direnv
## auto-generated pre-commit config
.pre-commit-config.yaml
# Local deepwork state
.slim/deepwork/
+1 -1
View File
@@ -77,7 +77,7 @@ run = [
[tasks."tauri:setup:macos"]
description = "Install Xcode"
confirm = { message = "Install Xcode? (required for Tauri)", default = "no" }
run = '''developer_dir="${DEVELOPER_DIR:-$(xcode-select --print-path 2>/dev/null)}" && test -d "$developer_dir/Platforms/MacOSX.platform/Developer/SDKs" || { echo "Full Xcode with the macOS SDK is required. Install Xcode or set DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer (no sudo required)." >&2; exit 1; }'''
run = "xcode-select --print-path >/dev/null 2>&1 || xcode-select --install"
[tasks."tauri:setup:ios"]
description = "Set up iOS Xcode project"
+1 -2
View File
@@ -15,7 +15,7 @@
"fmt": "oxfmt .",
"fmt:check": "oxfmt --check .",
"typecheck": "tsc",
"tauri": "node scripts/tauri.js",
"tauri": "tauri",
"tauri:cef": "node scripts/tauri.js cef",
"tauri:wry": "node scripts/tauri.js wry",
"test": "vitest",
@@ -118,7 +118,6 @@
"slate-history": "^0.113.1",
"slate-react": "^0.125.1",
"tauri-plugin-android-fs-api": "28.4.0",
"tauri-plugin-call-lifecycle-api": "file:src-tauri/plugins/tauri-plugin-call-lifecycle",
"ua-parser-js": "^2.0.10",
"virtua": "^0.49.2",
"workbox-precaching": "^7.4.1"
-10
View File
@@ -259,9 +259,6 @@ importers:
tauri-plugin-android-fs-api:
specifier: 28.4.0
version: 28.4.0
tauri-plugin-call-lifecycle-api:
specifier: file:src-tauri/plugins/tauri-plugin-call-lifecycle
version: file:src-tauri/plugins/tauri-plugin-call-lifecycle
ua-parser-js:
specifier: ^2.0.10
version: 2.0.10
@@ -5410,9 +5407,6 @@ packages:
[email protected]:
resolution: {integrity: sha512-YOo1P+cRjuaoPbTNZprMhr56ruKO4hIDq7kJOum91NqkN+VWY9F+UPAdjZokhzJSsbkeY0nsb1VDLXb2/h3f3w==}
tauri-plugin-call-lifecycle-api@file:src-tauri/plugins/tauri-plugin-call-lifecycle:
resolution: {directory: src-tauri/plugins/tauri-plugin-call-lifecycle, type: directory}
[email protected]:
resolution: {integrity: sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==}
@@ -10924,10 +10918,6 @@ snapshots:
'@tauri-apps/api': 2.11.1
create-web-stream: 1.1.3
tauri-plugin-call-lifecycle-api@file:src-tauri/plugins/tauri-plugin-call-lifecycle:
dependencies:
'@tauri-apps/api': 2.11.1
[email protected]:
dependencies:
streamx: 2.28.0
+1 -1
View File
@@ -1,3 +1,3 @@
[toolchain]
channel = "1.97"
channel = "1.97.1"
components = ["clippy", "rustfmt"]
-10
View File
@@ -1,10 +0,0 @@
#!/bin/sh
case "${1:-}" in
-p|--print-path)
printf '%s\n' "${DEVELOPER_DIR:-}"
exit 0
;;
esac
exec /usr/bin/xcode-select "$@"
+3 -126
View File
@@ -20,10 +20,8 @@
*/
import { run } from '@tauri-apps/cli';
import { execFileSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { fileURLToPath } from 'url';
import { delimiter, dirname, join, resolve } from 'path';
import { dirname, join } from 'path';
import process from 'node:process';
import { PrefixedLogger, createTextHelpers } from './utils/console-style.js';
@@ -37,125 +35,6 @@ const cmdlineArgs = process.argv.slice(2);
process.chdir(join(__dirname, '..'));
const DESKTOP = new Set(['wry', 'cef']);
const DEFAULT_XCODE_DEVELOPER_DIR = '/Applications/Xcode.app/Contents/Developer';
function normalizeDeveloperDir(value) {
const path = resolve(value);
return path.endsWith('.app') ? join(path, 'Contents', 'Developer') : path;
}
function isFullXcodeDeveloperDir(developerDir) {
return (
existsSync(join(developerDir, 'usr', 'bin', 'xcodebuild')) &&
existsSync(join(developerDir, 'Platforms', 'MacOSX.platform', 'Developer', 'SDKs'))
);
}
function failMacOSToolchain(reason) {
logger.error(
`${reason} Install full Xcode or set DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer.`,
);
process.exit(1);
}
function configureMacOSToolchain() {
if (process.platform !== 'darwin') {
return;
}
const configuredDeveloperDir = process.env.DEVELOPER_DIR?.trim();
let developerDir;
if (configuredDeveloperDir) {
developerDir = normalizeDeveloperDir(configuredDeveloperDir);
if (!isFullXcodeDeveloperDir(developerDir)) {
failMacOSToolchain(`Full Xcode was not found at DEVELOPER_DIR=${configuredDeveloperDir}.`);
}
} else {
let selectedDeveloperDir;
try {
selectedDeveloperDir = execFileSync(
'/usr/bin/xcode-select',
['--print-path'],
{ encoding: 'utf8' },
).trim();
} catch {
selectedDeveloperDir = '';
}
const candidates = [selectedDeveloperDir, DEFAULT_XCODE_DEVELOPER_DIR]
.filter(Boolean)
.map(normalizeDeveloperDir);
developerDir = candidates.find(isFullXcodeDeveloperDir);
if (!developerDir) {
failMacOSToolchain(
'Full Xcode was not found at the selected developer directory or /Applications/Xcode.app.',
);
}
}
let sdkRoot;
try {
sdkRoot = execFileSync(
'/usr/bin/xcrun',
['--sdk', 'macosx', '--show-sdk-path'],
{
encoding: 'utf8',
env: { ...process.env, DEVELOPER_DIR: developerDir },
},
).trim();
} catch {
failMacOSToolchain(`Unable to resolve the macOS SDK from DEVELOPER_DIR=${developerDir}.`);
}
if (!sdkRoot || !existsSync(sdkRoot)) {
failMacOSToolchain(`The macOS SDK was not found from DEVELOPER_DIR=${developerDir}.`);
}
process.env.DEVELOPER_DIR = developerDir;
process.env.SDKROOT = sdkRoot;
process.env.PATH = [join(__dirname, 'macos-bin'), process.env.PATH]
.filter(Boolean)
.join(delimiter);
}
function injectMacOSDevFeature(args) {
if (process.platform !== 'darwin' || args[0] !== 'dev') {
return args;
}
const feature = 'notifications-dev';
const separatorIndex = args.indexOf('--');
const featureArgsEnd = separatorIndex === -1 ? args.length : separatorIndex;
const appendFeature = (value) =>
value.split(',').includes(feature) ? value : value ? `${value},${feature}` : feature;
for (let index = 0; index < featureArgsEnd; index += 1) {
if (args[index] === '--features' && index + 1 < featureArgsEnd) {
const featureValue = args[index + 1];
if (featureValue.split(',').includes(feature)) {
return args;
}
return [...args.slice(0, index + 1), appendFeature(featureValue), ...args.slice(index + 2)];
}
if (args[index].startsWith('--features=')) {
const featureValue = args[index].slice('--features='.length);
if (featureValue.split(',').includes(feature)) {
return args;
}
return [
...args.slice(0, index),
`--features=${appendFeature(featureValue)}`,
...args.slice(index + 1),
];
}
}
return [
...args.slice(0, featureArgsEnd),
'--features',
feature,
...args.slice(featureArgsEnd),
];
}
async function runTauri(args) {
logger.info(`${dim('Running:')} tauri ${args.join(' ')}`);
@@ -168,10 +47,8 @@ async function runTauri(args) {
}
async function main() {
configureMacOSToolchain();
if (cmdlineArgs.length === 0 || !DESKTOP.has(cmdlineArgs[0])) {
return runTauri(injectMacOSDevFeature(cmdlineArgs));
return runTauri(cmdlineArgs);
}
const [platform, cmd, ...rawTauriArgs] = cmdlineArgs;
@@ -207,7 +84,7 @@ async function main() {
args.splice(1, 0, '--no-bundle');
}
return runTauri(injectMacOSDevFeature(args));
return runTauri(args);
}
main();
+18 -30
View File
@@ -168,7 +168,7 @@ version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -179,7 +179,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -1011,7 +1011,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c"
dependencies = [
"lazy_static",
"windows-sys 0.59.0",
"windows-sys 0.48.0",
]
[[package]]
@@ -1553,7 +1553,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -1585,7 +1585,7 @@ version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a"
dependencies = [
"libloading 0.8.9",
"libloading 0.7.4",
]
[[package]]
@@ -1855,7 +1855,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -3653,7 +3653,7 @@ dependencies = [
"png 0.18.1",
"serde",
"thiserror 2.0.19",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -3777,7 +3777,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -4205,7 +4205,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.48.0",
]
[[package]]
@@ -4863,7 +4863,7 @@ dependencies = [
"once_cell",
"socket2 0.5.10",
"tracing",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -5282,7 +5282,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -5340,7 +5340,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -5403,7 +5403,6 @@ dependencies = [
"tauri",
"tauri-build",
"tauri-plugin-android-fs",
"tauri-plugin-call-lifecycle",
"tauri-plugin-clipboard-manager",
"tauri-plugin-deep-link",
"tauri-plugin-devtools",
@@ -6039,7 +6038,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -6563,17 +6562,6 @@ dependencies = [
"thiserror 2.0.19",
]
[[package]]
name = "tauri-plugin-call-lifecycle"
version = "0.1.0"
dependencies = [
"serde",
"tauri",
"tauri-plugin",
"thiserror 2.0.19",
"tokio",
]
[[package]]
name = "tauri-plugin-clipboard-manager"
version = "2.3.2"
@@ -7069,7 +7057,7 @@ dependencies = [
"serde_with",
"swift-rs",
"thiserror 2.0.19",
"toml 1.1.3+spec-1.1.0",
"toml 0.9.12+spec-1.1.0",
"url",
"urlpattern",
"uuid",
@@ -7108,7 +7096,7 @@ dependencies = [
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -7733,7 +7721,7 @@ dependencies = [
"png 0.18.1",
"serde",
"thiserror 2.0.19",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -7807,7 +7795,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
dependencies = [
"memoffset",
"tempfile",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -8437,7 +8425,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.48.0",
]
[[package]]
-2
View File
@@ -67,7 +67,6 @@ tauri-plugin-http = "2.5.9"
tauri-plugin-store = "2.4.4"
tauri-plugin-clipboard-manager = "2.3.2"
tauri-plugin-dialog = "2"
tauri-plugin-call-lifecycle = { path = "plugins/tauri-plugin-call-lifecycle" }
# Debug-only in practice: only initialized under #[cfg(debug_assertions)] in
# lib.rs, so the release build never calls into it.
@@ -158,7 +157,6 @@ custom-protocol = ["tauri/custom-protocol"]
wry = ["tauri/wry", "dep:webkit2gtk"]
# Tauri auto-updater. Disable with --no-default-features --features wry,cef.
updater = ["dep:tauri-plugin-updater"]
notifications-dev = ["tauri-plugin-notifications/notify-rust"]
# CEF (Chromium) runtime. Build with --no-default-features --features cef.
cef = ["dep:tauri-runtime-cef", "dep:cef"]
# CrabNebula devtools. Off by default: its aggregator retains every metadata record for the
+1 -2
View File
@@ -9,7 +9,6 @@
"store:default",
"notifications:default",
"process:default",
"dialog:default",
"call-lifecycle:default"
"dialog:default"
]
}
+1 -2
View File
@@ -8,7 +8,6 @@
"deep-link:default",
"edge-to-edge:default",
"notifications:default",
"sharekit:default",
"call-lifecycle:default"
"sharekit:default"
]
}
@@ -1,20 +0,0 @@
/.vs
.DS_Store
.Thumbs.db
*.sublime*
.idea/
debug.log
package-lock.json
.vscode/settings.json
yarn.lock
/.tauri
/target
Cargo.lock
node_modules/
dist
# The guest package is consumed directly by Sable's local file dependency.
!dist-js/
!dist-js/**
@@ -1,22 +0,0 @@
[package]
name = "tauri-plugin-call-lifecycle"
version = "0.1.0"
authors = [ "Sable Contributors" ]
description = ""
edition = "2021"
rust-version = "1.97"
exclude = ["/examples", "/dist-js", "/guest-js", "/node_modules"]
links = "tauri-plugin-call-lifecycle"
[dependencies]
tauri = { version = "2.11.3", default-features = false }
serde = "1.0"
thiserror = "2"
tokio = { version = "1", features = ["macros", "rt", "sync", "time"] }
[build-dependencies]
tauri-plugin = { version = "2.6.3", features = ["build"] }
[dev-dependencies]
serde_json = "1.0"
tauri = { version = "2.11.3", default-features = false, features = ["test"] }
@@ -1,33 +0,0 @@
plugins {
id("com.android.library")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "app.tauri.call_lifecycle"
compileSdk = 36
defaultConfig {
minSdk = 21
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"))
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
}
dependencies {
implementation(project(":tauri-android"))
implementation("androidx.core:core-ktx:1.16.0")
implementation("androidx.appcompat:appcompat:1.7.0")
}
@@ -1,30 +0,0 @@
pluginManagement {
repositories {
mavenCentral()
gradlePluginPortal()
google()
}
resolutionStrategy {
eachPlugin {
switch (requested.id.id) {
case "com.android.library":
useVersion("8.0.2")
break
case "org.jetbrains.kotlin.android":
useVersion("1.8.20")
break
}
}
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
mavenCentral()
google()
}
}
include ':tauri-android'
project(':tauri-android').projectDir = new File('./.tauri/tauri-api')
@@ -1,17 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application>
<service
android:name="app.tauri.call_lifecycle.CallLifecycleForegroundService"
android:exported="false"
android:foregroundServiceType="microphone|mediaPlayback" />
</application>
</manifest>
@@ -1,103 +0,0 @@
package app.tauri.call_lifecycle
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
/**
* Owns only the Android foreground-service notification for a JS-owned room.
* The WebView and LiveKit JS remain the owners of the room and its tracks.
*/
class CallLifecycleForegroundService : Service() {
/** Positive acknowledgement of foreground promotion for the owning plugin. */
interface StartListener {
fun onServiceStarted()
fun onServiceStartFailed()
}
override fun onCreate() {
super.onCreate()
createNotificationChannel()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val wantsMicrophone = intent?.getBooleanExtra(EXTRA_MICROPHONE, false) ?: false
val wantsPlayback = intent?.getBooleanExtra(EXTRA_PLAYBACK, false) ?: false
val started = try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
var types = 0
if (wantsMicrophone) types = types or ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
if (wantsPlayback) types = types or ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
if (types != 0) {
startForeground(NOTIFICATION_ID, buildNotification(), types)
} else {
startForeground(NOTIFICATION_ID, buildNotification())
}
} else {
startForeground(NOTIFICATION_ID, buildNotification())
}
true
} catch (_: SecurityException) {
false
} catch (_: IllegalArgumentException) {
false
} catch (_: IllegalStateException) {
false
}
if (started) {
activeStartListener?.onServiceStarted()
} else {
stopSelfResult(startId)
activeStartListener?.onServiceStartFailed()
}
return START_NOT_STICKY
}
override fun onBind(intent: Intent?): IBinder? = null
override fun onDestroy() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
stopForeground(STOP_FOREGROUND_REMOVE)
} else {
@Suppress("DEPRECATION")
stopForeground(true)
}
super.onDestroy()
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val channel = NotificationChannel(
CHANNEL_ID,
"Call audio",
NotificationManager.IMPORTANCE_LOW,
)
getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
}
private fun buildNotification(): Notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle("Call in progress")
.setContentText("Microphone and call audio are active")
.setCategory(Notification.CATEGORY_CALL)
.setOngoing(true)
.setOnlyAlertOnce(true)
.build()
companion object {
const val EXTRA_MICROPHONE = "app.tauri.call_lifecycle.extra.MICROPHONE"
const val EXTRA_PLAYBACK = "app.tauri.call_lifecycle.extra.PLAYBACK"
@Volatile
var activeStartListener: StartListener? = null
private const val CHANNEL_ID = "call_lifecycle_audio"
private const val NOTIFICATION_ID = 1396
}
}
@@ -1,469 +0,0 @@
package app.tauri.call_lifecycle
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.media.AudioAttributes
import android.media.AudioDeviceCallback
import android.media.AudioDeviceInfo
import android.media.AudioFocusRequest
import android.media.AudioManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import androidx.core.content.ContextCompat
import app.tauri.annotation.TauriPlugin
import app.tauri.annotation.Command
import app.tauri.annotation.InvokeArg
import app.tauri.annotation.Permission
import app.tauri.annotation.PermissionCallback
import app.tauri.plugin.Channel
import app.tauri.plugin.Invoke
import app.tauri.plugin.JSObject
import app.tauri.plugin.Plugin
@InvokeArg
internal class PlatformLifecycleStartArgs {
var sessionId: String = ""
var microphone: Boolean = false
var playback: Boolean = false
lateinit var channel: Channel
}
@InvokeArg
internal class PlatformLifecycleStopArgs {
var sessionId: String = ""
}
@TauriPlugin(
permissions = [
Permission(
strings = ["android.permission.RECORD_AUDIO"],
alias = "microphone",
),
],
)
class CallLifecyclePlugin(private val activity: Activity) : Plugin(activity) {
private var previousAudioMode: Int? = null
private val lastPlatformEventAt = mutableMapOf<String, Long>()
private var platformSessionId: String? = null
private var platformRevision = 0L
private var platformState = PLATFORM_IDLE
private var platformChannel: Channel? = null
private var platformFocus = PLATFORM_FOCUS_NONE
private var platformRoute = PLATFORM_ROUTE_UNKNOWN
private var platformMicrophone = false
private var platformPlayback = false
private var platformFocusRequest: AudioFocusRequest? = null
private var platformAudioManager: AudioManager? = null
private var platformAudioCallback: AudioDeviceCallback? = null
private var pendingPlatformStart: PendingPlatformStart? = null
private data class PendingPlatformStart(
val invoke: Invoke,
val args: PlatformLifecycleStartArgs,
)
@Command
fun getPlatformLifecycleCapabilities(invoke: Invoke) {
invoke.resolve(
JSObject()
.put("platform", "android")
.put("microphone", true)
.put("audioPlayback", true)
.put("audioFocus", true)
.put("routeEvents", true)
.put("foregroundService", true)
.put("backgroundJavascript", false)
.put("camera", false)
.put("screenShare", false),
)
}
@Command
fun startPlatformLifecycle(invoke: Invoke) {
val args = runCatching { invoke.parseArgs(PlatformLifecycleStartArgs::class.java) }.getOrNull()
if (args == null || args.sessionId.isBlank() || !hasChannel(args)) {
invoke.reject("platform lifecycle start failed", "invalid_request")
return
}
if (platformSessionId != null && platformSessionId != args.sessionId) {
invoke.reject("platform lifecycle is busy", "busy")
return
}
if (platformSessionId == args.sessionId) {
invoke.resolve(platformLifecycleState())
return
}
if (!isActivityVisible()) {
invoke.reject("platform lifecycle requires a visible activity", "not_visible")
return
}
platformSessionId = args.sessionId
platformChannel = args.channel
platformMicrophone = args.microphone
platformPlayback = args.playback
platformState = PLATFORM_STARTING
bumpPlatformRevision()
if (args.microphone && !hasPermission(android.Manifest.permission.RECORD_AUDIO)) {
val pending = PendingPlatformStart(invoke, args)
pendingPlatformStart = pending
try {
requestPermissionForAliases(arrayOf("microphone"), invoke, "permissionResult")
} catch (_: Exception) {
pendingPlatformStart = null
failPlatformStart(pending, "permission_denied")
}
return
}
beginPlatformLifecycle(invoke, args)
}
@Command
fun stopPlatformLifecycle(invoke: Invoke) {
val args = runCatching { invoke.parseArgs(PlatformLifecycleStopArgs::class.java) }.getOrNull()
if (args == null || args.sessionId.isBlank()) {
invoke.reject("platform lifecycle stop failed", "invalid_request")
return
}
if (platformSessionId != args.sessionId) {
// A stale stop must never tear down a replacement session.
invoke.resolve(platformLifecycleState())
return
}
pendingPlatformStart = null
releasePlatformLifecycle()
invoke.resolve(platformLifecycleState())
}
@Command
fun getPlatformLifecycleState(invoke: Invoke) {
invoke.resolve(platformLifecycleState())
}
@PermissionCallback
private fun permissionResult(invoke: Invoke) {
val pending = pendingPlatformStart ?: return
if (pending.invoke.id != invoke.id) return
pendingPlatformStart = null
if (hasPermission(android.Manifest.permission.RECORD_AUDIO)) {
beginPlatformLifecycle(pending.invoke, pending.args)
} else {
failPlatformStart(pending, "permission_denied")
}
}
override fun onDestroy(activity: androidx.appcompat.app.AppCompatActivity) {
pendingPlatformStart = null
releasePlatformLifecycle()
super.onDestroy(activity)
}
private fun beginPlatformLifecycle(invoke: Invoke, args: PlatformLifecycleStartArgs) {
if (platformSessionId != args.sessionId || !isActivityVisible()) {
failPlatformStart(PendingPlatformStart(invoke, args), "not_visible")
return
}
val audioManager = activity.getSystemService(Context.AUDIO_SERVICE) as AudioManager
platformAudioManager = audioManager
try {
if (args.microphone) {
if (previousAudioMode == null) previousAudioMode = audioManager.mode
audioManager.mode = AudioManager.MODE_IN_COMMUNICATION
if (!requestPlatformAudioFocus(audioManager)) {
failPlatformStart(PendingPlatformStart(invoke, args), "audio_focus_failed")
return
}
}
// The platform lifecycle only reports active once the foreground
// service positively acknowledges its promotion.
registerServiceStartAck(PendingPlatformStart(invoke, args))
startPlatformService(args)
} catch (_: SecurityException) {
CallLifecycleForegroundService.activeStartListener = null
failPlatformStart(PendingPlatformStart(invoke, args), "service_start_failed")
} catch (_: IllegalStateException) {
CallLifecycleForegroundService.activeStartListener = null
failPlatformStart(PendingPlatformStart(invoke, args), "service_start_failed")
} catch (_: RuntimeException) {
CallLifecycleForegroundService.activeStartListener = null
failPlatformStart(PendingPlatformStart(invoke, args), "service_start_failed")
}
}
private fun registerServiceStartAck(pending: PendingPlatformStart) {
val mainHandler = Handler(Looper.getMainLooper())
val sessionId = pending.args.sessionId
CallLifecycleForegroundService.activeStartListener =
object : CallLifecycleForegroundService.StartListener {
override fun onServiceStarted() {
mainHandler.post { completeServiceStart(pending, failed = false) }
}
override fun onServiceStartFailed() {
mainHandler.post { completeServiceStart(pending, failed = true) }
}
}
mainHandler.postDelayed({ completeServiceStartTimeout(pending, sessionId) }, SERVICE_START_TIMEOUT_MS)
}
private fun completeServiceStart(pending: PendingPlatformStart, failed: Boolean) {
CallLifecycleForegroundService.activeStartListener = null
if (platformSessionId != pending.args.sessionId || platformState != PLATFORM_STARTING) return
if (failed) {
failPlatformStart(pending, "service_start_failed")
return
}
val audioManager = platformAudioManager ?: return
registerPlatformAudioRoutes(audioManager)
platformState = PLATFORM_ACTIVE
bumpPlatformRevision()
pending.invoke.resolve(platformLifecycleState())
if (pending.args.microphone) emitPlatformFocus(PLATFORM_FOCUS_GAINED)
emitPlatformRoute(platformRoute)
}
private fun completeServiceStartTimeout(pending: PendingPlatformStart, sessionId: String) {
if (platformSessionId != sessionId || platformState != PLATFORM_STARTING) return
CallLifecycleForegroundService.activeStartListener = null
failPlatformStart(pending, "service_start_failed")
}
private fun requestPlatformAudioFocus(audioManager: AudioManager): Boolean {
val attributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build()
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val request = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
.setAudioAttributes(attributes)
.setOnAudioFocusChangeListener(platformFocusListener, Handler(Looper.getMainLooper()))
.setWillPauseWhenDucked(false)
.build()
platformFocusRequest = request
audioManager.requestAudioFocus(request) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
} else {
@Suppress("DEPRECATION")
audioManager.requestAudioFocus(
platformFocusListener,
AudioManager.STREAM_VOICE_CALL,
AudioManager.AUDIOFOCUS_GAIN,
) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
}
}
private fun startPlatformService(args: PlatformLifecycleStartArgs) {
val intent = Intent(activity, CallLifecycleForegroundService::class.java)
.putExtra(CallLifecycleForegroundService.EXTRA_MICROPHONE, args.microphone)
.putExtra(CallLifecycleForegroundService.EXTRA_PLAYBACK, args.playback)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ContextCompat.startForegroundService(activity, intent)
} else {
@Suppress("DEPRECATION")
activity.startService(intent)
}
}
private fun registerPlatformAudioRoutes(audioManager: AudioManager) {
platformRoute = currentPlatformRoute(audioManager)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return
val callback = object : AudioDeviceCallback() {
override fun onAudioDevicesAdded(addedDevices: Array<out AudioDeviceInfo>) {
handlePlatformRouteChanged()
}
override fun onAudioDevicesRemoved(removedDevices: Array<out AudioDeviceInfo>) {
handlePlatformRouteChanged()
}
}
platformAudioCallback = callback
audioManager.registerAudioDeviceCallback(callback, Handler(Looper.getMainLooper()))
}
private fun handlePlatformRouteChanged() {
val audioManager = platformAudioManager ?: return
val route = currentPlatformRoute(audioManager)
if (route != platformRoute) {
platformRoute = route
emitPlatformRoute(route)
}
}
private fun currentPlatformRoute(audioManager: AudioManager): String {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val types = audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS).map { it.type }.toSet()
return when {
types.any { it == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP || it == AudioDeviceInfo.TYPE_BLUETOOTH_SCO ||
(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && it == AudioDeviceInfo.TYPE_BLE_HEADSET) } ->
PLATFORM_ROUTE_BLUETOOTH
types.any { it == AudioDeviceInfo.TYPE_WIRED_HEADSET || it == AudioDeviceInfo.TYPE_WIRED_HEADPHONES } ->
PLATFORM_ROUTE_WIRED
types.any { it == AudioDeviceInfo.TYPE_USB_DEVICE || it == AudioDeviceInfo.TYPE_USB_HEADSET } ->
PLATFORM_ROUTE_USB
types.any { it == AudioDeviceInfo.TYPE_BUILTIN_EARPIECE } -> PLATFORM_ROUTE_EARPIECE
types.any { it == AudioDeviceInfo.TYPE_BUILTIN_SPEAKER } -> PLATFORM_ROUTE_SPEAKER
else -> PLATFORM_ROUTE_UNKNOWN
}
}
@Suppress("DEPRECATION")
return when {
audioManager.isBluetoothA2dpOn || audioManager.isBluetoothScoOn -> PLATFORM_ROUTE_BLUETOOTH
audioManager.isWiredHeadsetOn -> PLATFORM_ROUTE_WIRED
audioManager.isSpeakerphoneOn -> PLATFORM_ROUTE_SPEAKER
else -> PLATFORM_ROUTE_UNKNOWN
}
}
private fun emitPlatformFocus(focus: String) {
platformFocus = focus
emitPlatformEvent("focus", focus = focus)
}
private fun emitPlatformRoute(route: String) {
emitPlatformEvent("route", route = route)
}
private fun emitPlatformEvent(
event: String,
focus: String? = null,
route: String? = null,
code: String? = null,
) {
val channel = platformChannel ?: return
val now = SystemClock.elapsedRealtime()
val previous = lastPlatformEventAt[event]
if (event != "failure" && previous != null && now - previous < PLATFORM_EVENT_INTERVAL_MS) return
lastPlatformEventAt[event] = now
bumpPlatformRevision()
val payload = JSObject()
.put("sessionId", platformSessionId)
.put("revision", platformRevision)
.put("event", event)
focus?.let { payload.put("focus", it) }
route?.let { payload.put("route", it) }
code?.let { payload.put("code", it) }
channel.send(payload)
}
private fun emitPlatformFailure(code: String) {
val safeCode = if (code in PLATFORM_FAILURE_CODES) code else "service_start_failed"
emitPlatformEvent("failure", code = safeCode)
}
private fun failPlatformStart(pending: PendingPlatformStart, code: String) {
emitPlatformFailure(code)
pending.invoke.reject("platform lifecycle start failed", if (code in PLATFORM_FAILURE_CODES) code else "service_start_failed")
releasePlatformLifecycle()
}
private fun releasePlatformLifecycle() {
CallLifecycleForegroundService.activeStartListener = null
platformAudioCallback?.let { callback ->
platformAudioManager?.let { manager ->
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
manager.unregisterAudioDeviceCallback(callback)
}
}
}
platformAudioCallback = null
platformAudioManager?.let { manager ->
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
platformFocusRequest?.let { manager.abandonAudioFocusRequest(it) }
} else {
@Suppress("DEPRECATION")
manager.abandonAudioFocus(platformFocusListener)
}
}
platformFocusRequest = null
platformAudioManager = null
activity.stopService(Intent(activity, CallLifecycleForegroundService::class.java))
restoreAudio()
val hadState = platformSessionId != null || platformState != PLATFORM_IDLE
platformSessionId = null
platformChannel = null
platformFocus = PLATFORM_FOCUS_NONE
platformRoute = PLATFORM_ROUTE_UNKNOWN
platformMicrophone = false
platformPlayback = false
lastPlatformEventAt.clear()
platformState = PLATFORM_IDLE
if (hadState) bumpPlatformRevision()
}
private fun platformLifecycleState(): JSObject = JSObject()
.put("sessionId", platformSessionId)
.put("revision", platformRevision)
.put("state", platformState)
.put("focus", platformFocus)
.put("route", platformRoute)
.put("microphone", platformMicrophone)
.put("playback", platformPlayback)
.put("backgroundJavascript", false)
private fun bumpPlatformRevision() {
platformRevision = if (platformRevision == Long.MAX_VALUE) 1L else platformRevision + 1L
}
private fun hasChannel(args: PlatformLifecycleStartArgs): Boolean =
runCatching { args.channel }.isSuccess
private fun isActivityVisible(): Boolean =
!activity.isFinishing &&
(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1 || !activity.isDestroyed) &&
activity.window.decorView.isShown &&
activity.hasWindowFocus()
private val platformFocusListener = AudioManager.OnAudioFocusChangeListener { change ->
val update = {
when (change) {
AudioManager.AUDIOFOCUS_GAIN -> emitPlatformFocus(PLATFORM_FOCUS_GAINED)
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> emitPlatformFocus(PLATFORM_FOCUS_DUCKED)
AudioManager.AUDIOFOCUS_LOSS,
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> emitPlatformFocus(PLATFORM_FOCUS_LOST)
else -> Unit
}
}
if (Looper.myLooper() == Looper.getMainLooper()) update() else activity.runOnUiThread(update)
}
private fun hasPermission(permission: String): Boolean =
ContextCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_GRANTED
private fun restoreAudio() {
val audioManager = activity.getSystemService(Context.AUDIO_SERVICE) as AudioManager
previousAudioMode?.let { audioManager.mode = it }
previousAudioMode = null
}
companion object {
private const val PLATFORM_EVENT_INTERVAL_MS = 1_000L
private const val SERVICE_START_TIMEOUT_MS = 1_500L
private const val PLATFORM_IDLE = "idle"
private const val PLATFORM_STARTING = "starting"
private const val PLATFORM_ACTIVE = "active"
private const val PLATFORM_FOCUS_NONE = "none"
private const val PLATFORM_FOCUS_GAINED = "gained"
private const val PLATFORM_FOCUS_LOST = "lost"
private const val PLATFORM_FOCUS_DUCKED = "ducked"
private const val PLATFORM_ROUTE_UNKNOWN = "unknown"
private const val PLATFORM_ROUTE_EARPIECE = "earpiece"
private const val PLATFORM_ROUTE_SPEAKER = "speaker"
private const val PLATFORM_ROUTE_WIRED = "wired"
private const val PLATFORM_ROUTE_BLUETOOTH = "bluetooth"
private const val PLATFORM_ROUTE_USB = "usb"
private val PLATFORM_FAILURE_CODES = setOf(
"invalid_request",
"busy",
"not_visible",
"permission_denied",
"audio_focus_failed",
"service_start_failed",
)
}
}
@@ -1,13 +0,0 @@
const COMMANDS: &[&str] = &[
"getPlatformCallCapabilities",
"startPlatformCallLifecycle",
"stopPlatformCallLifecycle",
"getPlatformCallState",
];
fn main() {
tauri_plugin::Builder::new(COMMANDS)
.android_path("android")
.ios_path("ios")
.build();
}
@@ -1,32 +0,0 @@
'use strict';
var core = require('@tauri-apps/api/core');
var event = require('@tauri-apps/api/event');
const PLATFORM_CALL_EVENT = 'plugin:call-lifecycle://platform-event';
async function getPlatformCallCapabilities() {
return await core.invoke('plugin:call-lifecycle|getPlatformCallCapabilities');
}
async function startPlatformCallLifecycle(request) {
return await core.invoke('plugin:call-lifecycle|startPlatformCallLifecycle', {
payload: request,
});
}
async function stopPlatformCallLifecycle(request) {
return await core.invoke('plugin:call-lifecycle|stopPlatformCallLifecycle', {
payload: request,
});
}
async function getPlatformCallState() {
return await core.invoke('plugin:call-lifecycle|getPlatformCallState');
}
async function listenPlatformCallEvent(handler) {
return await event.listen(PLATFORM_CALL_EVENT, ({ payload }) => handler(payload));
}
exports.PLATFORM_CALL_EVENT = PLATFORM_CALL_EVENT;
exports.getPlatformCallCapabilities = getPlatformCallCapabilities;
exports.getPlatformCallState = getPlatformCallState;
exports.listenPlatformCallEvent = listenPlatformCallEvent;
exports.startPlatformCallLifecycle = startPlatformCallLifecycle;
exports.stopPlatformCallLifecycle = stopPlatformCallLifecycle;
@@ -1,51 +0,0 @@
import { type UnlistenFn } from '@tauri-apps/api/event';
export type PlatformCallStateKind = 'idle' | 'starting' | 'active' | 'stopping';
export type PlatformCallRoute = 'earpiece' | 'speaker' | 'wired' | 'bluetooth' | 'unknown';
export type PlatformCallInterruption = 'began' | 'ended';
export type PlatformCallFailureCode = 'unsupported' | 'permission_denied' | 'audio_unavailable' | 'start_failed' | 'stop_failed' | 'stale_session' | 'busy';
export interface PlatformCallCapabilities {
supported: boolean;
microphone: boolean;
playback: boolean;
}
export interface StartPlatformCallLifecycleRequest {
sessionId: string;
microphone: boolean;
playback: boolean;
}
export interface StopPlatformCallLifecycleRequest {
sessionId: string;
}
export interface PlatformCallState {
revision: number;
state: PlatformCallStateKind;
sessionId: string | null;
microphone: boolean;
playback: boolean;
capabilities: PlatformCallCapabilities;
}
export type PlatformCallEventKind = {
type: 'focus_changed';
focused: boolean;
} | {
type: 'route_changed';
route: PlatformCallRoute;
} | {
type: 'interrupted';
state: PlatformCallInterruption;
} | {
type: 'media_reset';
} | {
type: 'failed';
code: PlatformCallFailureCode;
};
export type PlatformCallEvent = {
revision: number;
sessionId: string;
} & PlatformCallEventKind;
export declare const PLATFORM_CALL_EVENT = "plugin:call-lifecycle://platform-event";
export declare function getPlatformCallCapabilities(): Promise<PlatformCallCapabilities>;
export declare function startPlatformCallLifecycle(request: StartPlatformCallLifecycleRequest): Promise<PlatformCallState>;
export declare function stopPlatformCallLifecycle(request: StopPlatformCallLifecycleRequest): Promise<PlatformCallState>;
export declare function getPlatformCallState(): Promise<PlatformCallState>;
export declare function listenPlatformCallEvent(handler: (event: PlatformCallEvent) => void): Promise<UnlistenFn>;
@@ -1,25 +0,0 @@
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
const PLATFORM_CALL_EVENT = 'plugin:call-lifecycle://platform-event';
async function getPlatformCallCapabilities() {
return await invoke('plugin:call-lifecycle|getPlatformCallCapabilities');
}
async function startPlatformCallLifecycle(request) {
return await invoke('plugin:call-lifecycle|startPlatformCallLifecycle', {
payload: request,
});
}
async function stopPlatformCallLifecycle(request) {
return await invoke('plugin:call-lifecycle|stopPlatformCallLifecycle', {
payload: request,
});
}
async function getPlatformCallState() {
return await invoke('plugin:call-lifecycle|getPlatformCallState');
}
async function listenPlatformCallEvent(handler) {
return await listen(PLATFORM_CALL_EVENT, ({ payload }) => handler(payload));
}
export { PLATFORM_CALL_EVENT, getPlatformCallCapabilities, getPlatformCallState, listenPlatformCallEvent, startPlatformCallLifecycle, stopPlatformCallLifecycle };
@@ -1,85 +0,0 @@
import { invoke } from '@tauri-apps/api/core';
import { listen, type UnlistenFn } from '@tauri-apps/api/event';
export type PlatformCallStateKind = 'idle' | 'starting' | 'active' | 'stopping';
export type PlatformCallRoute = 'earpiece' | 'speaker' | 'wired' | 'bluetooth' | 'unknown';
export type PlatformCallInterruption = 'began' | 'ended';
export type PlatformCallFailureCode =
| 'unsupported'
| 'permission_denied'
| 'audio_unavailable'
| 'start_failed'
| 'stop_failed'
| 'stale_session'
| 'busy';
export interface PlatformCallCapabilities {
supported: boolean;
microphone: boolean;
playback: boolean;
}
export interface StartPlatformCallLifecycleRequest {
sessionId: string;
microphone: boolean;
playback: boolean;
}
export interface StopPlatformCallLifecycleRequest {
sessionId: string;
}
export interface PlatformCallState {
revision: number;
state: PlatformCallStateKind;
sessionId: string | null;
microphone: boolean;
playback: boolean;
capabilities: PlatformCallCapabilities;
}
export type PlatformCallEventKind =
| { type: 'focus_changed'; focused: boolean }
| { type: 'route_changed'; route: PlatformCallRoute }
| { type: 'interrupted'; state: PlatformCallInterruption }
| { type: 'media_reset' }
| { type: 'failed'; code: PlatformCallFailureCode };
export type PlatformCallEvent = {
revision: number;
sessionId: string;
} & PlatformCallEventKind;
export const PLATFORM_CALL_EVENT = 'plugin:call-lifecycle://platform-event';
export async function getPlatformCallCapabilities(): Promise<PlatformCallCapabilities> {
return await invoke<PlatformCallCapabilities>(
'plugin:call-lifecycle|getPlatformCallCapabilities'
);
}
export async function startPlatformCallLifecycle(
request: StartPlatformCallLifecycleRequest
): Promise<PlatformCallState> {
return await invoke<PlatformCallState>('plugin:call-lifecycle|startPlatformCallLifecycle', {
payload: request,
});
}
export async function stopPlatformCallLifecycle(
request: StopPlatformCallLifecycleRequest
): Promise<PlatformCallState> {
return await invoke<PlatformCallState>('plugin:call-lifecycle|stopPlatformCallLifecycle', {
payload: request,
});
}
export async function getPlatformCallState(): Promise<PlatformCallState> {
return await invoke<PlatformCallState>('plugin:call-lifecycle|getPlatformCallState');
}
export async function listenPlatformCallEvent(
handler: (event: PlatformCallEvent) => void
): Promise<UnlistenFn> {
return await listen<PlatformCallEvent>(PLATFORM_CALL_EVENT, ({ payload }) => handler(payload));
}
@@ -1,28 +0,0 @@
// swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "tauri-plugin-call-lifecycle",
platforms: [
.macOS(.v10_13),
.iOS(.v13),
],
products: [
.library(
name: "tauri-plugin-call-lifecycle",
type: .static,
targets: ["tauri-plugin-call-lifecycle"])
],
dependencies: [
.package(name: "Tauri", path: "../.tauri/tauri-api")
],
targets: [
.target(
name: "tauri-plugin-call-lifecycle",
dependencies: [
.byName(name: "Tauri")
],
path: "Sources")
]
)
@@ -1,480 +0,0 @@
import AVFoundation
import Tauri
private struct PlatformStartArgs: Decodable {
let sessionId: String
let microphone: Bool
let playback: Bool
let channel: Channel
}
private struct PlatformStopArgs: Decodable {
let sessionId: String
}
private enum PlatformStateKind: String, Encodable {
case idle
case active
}
private struct PlatformStateResponse: Encodable {
let sessionId: String?
let revision: UInt64
let state: PlatformStateKind
let microphone: Bool
let playback: Bool
}
private struct PlatformCapabilitiesResponse: Encodable {
let microphone: Bool
let backgroundAudio: Bool
}
private enum PlatformEventKind: String, Encodable {
case focus
case route
case interruption
case mediaServicesReset = "media_services_reset"
case failure
}
private enum PlatformFocus: String, Encodable {
case active
case lost
case regained
}
private enum PlatformInterruption: String, Encodable {
case began
case ended
}
private enum PlatformRoute: String, Encodable {
case speaker
case receiver
case bluetooth
case wired
case other
case none
}
private enum PlatformFailureCode: String, Encodable {
case busy
case permissionDenied = "permission_denied"
case audioSessionFailed = "audio_session_failed"
case stopFailed = "stop_failed"
}
private struct PlatformEvent: Encodable {
let sessionId: String
let revision: UInt64
let event: PlatformEventKind
let focus: PlatformFocus?
let route: PlatformRoute?
let interruption: PlatformInterruption?
let code: PlatformFailureCode?
}
final class CallLifecyclePlugin: Plugin {
private var platformSessionId: String?
private var platformEventChannel: Channel?
private var platformMicrophone = false
private var platformPlayback = false
private var platformRevision: UInt64 = 0
private var platformObservers: [NSObjectProtocol] = []
deinit {
removePlatformObservers()
if platformSessionId != nil {
try? AVAudioSession.sharedInstance().setActive(
false,
options: .notifyOthersOnDeactivation
)
}
}
@objc public func capabilities(_ invoke: Invoke) throws {
invoke.resolve(
PlatformCapabilitiesResponse(
microphone: true,
backgroundAudio: true
)
)
}
@objc public func start(_ invoke: Invoke) throws {
guard let args = try? invoke.parseArgs(PlatformStartArgs.self) else {
invoke.reject("Platform audio session start failed.", code: PlatformFailureCode.audioSessionFailed.rawValue)
return
}
Task { @MainActor [weak self] in
await self?.start(args, invoke: invoke)
}
}
@objc public func stop(_ invoke: Invoke) throws {
guard let args = try? invoke.parseArgs(PlatformStopArgs.self) else {
invoke.reject("Platform audio session stop failed.", code: PlatformFailureCode.stopFailed.rawValue)
return
}
Task { @MainActor [weak self] in
await self?.stop(args, invoke: invoke)
}
}
@objc public func getState(_ invoke: Invoke) throws {
Task { @MainActor [weak self] in
self?.resolvePlatformState(invoke)
}
}
@MainActor
private func start(_ args: PlatformStartArgs, invoke: Invoke) async {
if platformSessionId == args.sessionId {
invoke.resolve(platformState())
return
}
if platformSessionId != nil {
rejectPlatformStart(
sessionId: args.sessionId,
channel: args.channel,
code: .busy,
invoke: invoke
)
return
}
do {
if args.microphone {
try await requestPlatformMicrophonePermission()
}
try configurePlatformAudioSession(microphone: args.microphone, playback: args.playback)
} catch SetupError.denied {
rejectPlatformStart(
sessionId: args.sessionId,
channel: args.channel,
code: .permissionDenied,
invoke: invoke
)
return
} catch {
try? AVAudioSession.sharedInstance().setActive(
false,
options: .notifyOthersOnDeactivation
)
rejectPlatformStart(
sessionId: args.sessionId,
channel: args.channel,
code: .audioSessionFailed,
invoke: invoke
)
return
}
platformSessionId = args.sessionId
platformEventChannel = args.channel
platformMicrophone = args.microphone
platformPlayback = args.playback
platformRevision &+= 1
installPlatformObservers()
emitPlatformEvent(.focus, focus: .active)
invoke.resolve(platformState())
}
@MainActor
private func stop(_ args: PlatformStopArgs, invoke: Invoke) async {
guard platformSessionId == args.sessionId,
let activeSessionId = platformSessionId,
let activeChannel = platformEventChannel
else {
// A stale stop is intentionally a no-op. In particular, it cannot
// deactivate a newer session that reused this plugin instance.
invoke.resolve(platformState())
return
}
removePlatformObservers()
platformSessionId = nil
platformEventChannel = nil
platformMicrophone = false
platformPlayback = false
platformRevision &+= 1
do {
try AVAudioSession.sharedInstance().setActive(
false,
options: .notifyOthersOnDeactivation
)
invoke.resolve(platformState())
} catch {
sendPlatformEvent(
.failure,
sessionId: activeSessionId,
channel: activeChannel,
revision: platformRevision,
code: .stopFailed
)
invoke.reject("Platform audio session stop failed.", code: PlatformFailureCode.stopFailed.rawValue)
}
}
@MainActor
private func resolvePlatformState(_ invoke: Invoke) {
invoke.resolve(platformState())
}
@MainActor
private func requestPlatformMicrophonePermission() async throws {
let session = AVAudioSession.sharedInstance()
if session.recordPermission == .undetermined {
let granted = await withCheckedContinuation { continuation in
session.requestRecordPermission { granted in
continuation.resume(returning: granted)
}
}
guard granted else { throw SetupError.denied }
} else {
guard session.recordPermission == .granted else { throw SetupError.denied }
}
}
@MainActor
private func configurePlatformAudioSession(microphone: Bool, playback: Bool) throws {
let session = AVAudioSession.sharedInstance()
if microphone {
// Recording requires playAndRecord, which also covers playback.
try session.setCategory(
.playAndRecord,
mode: .voiceChat,
options: [.allowBluetooth, .allowBluetoothA2DP, .defaultToSpeaker]
)
} else if playback {
try session.setCategory(.playback)
} else {
try session.setCategory(.ambient)
}
try session.setActive(true)
}
@MainActor
private func installPlatformObservers() {
let center = NotificationCenter.default
let session = AVAudioSession.sharedInstance()
platformObservers = [
center.addObserver(
forName: AVAudioSession.interruptionNotification,
object: session,
queue: .main
) { [weak self] notification in
Task { @MainActor [weak self] in
self?.handlePlatformInterruption(notification)
}
},
center.addObserver(
forName: AVAudioSession.routeChangeNotification,
object: session,
queue: .main
) { [weak self] _ in
Task { @MainActor [weak self] in
self?.handlePlatformRouteChange()
}
},
center.addObserver(
forName: AVAudioSession.mediaServicesWereResetNotification,
object: session,
queue: .main
) { [weak self] _ in
Task { @MainActor [weak self] in
await self?.handlePlatformMediaServicesReset()
}
},
]
}
private func removePlatformObservers() {
let center = NotificationCenter.default
platformObservers.forEach { center.removeObserver($0) }
platformObservers.removeAll()
}
@MainActor
private func handlePlatformInterruption(_ notification: Notification) {
guard platformSessionId != nil else { return }
guard let value = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
let type = AVAudioSession.InterruptionType(rawValue: value)
else { return }
switch type {
case .began:
emitPlatformEvent(.focus, focus: .lost)
emitPlatformEvent(.interruption, interruption: .began)
case .ended:
let optionsValue = notification.userInfo?[AVAudioSessionInterruptionOptionKey] as? UInt ?? 0
let options = AVAudioSession.InterruptionOptions(rawValue: optionsValue)
if options.contains(.shouldResume) {
do {
try AVAudioSession.sharedInstance().setActive(true)
emitPlatformEvent(.interruption, interruption: .ended)
emitPlatformEvent(.focus, focus: .regained)
} catch {
failPlatformSession(.audioSessionFailed)
}
} else {
// No resume hint: keep the session inactive and report the bounded
// interruption/focus state so JS decides whether to restart.
emitPlatformEvent(.interruption, interruption: .ended)
emitPlatformEvent(.focus, focus: .lost)
}
@unknown default:
break
}
}
@MainActor
private func handlePlatformRouteChange() {
guard platformSessionId != nil else { return }
emitPlatformEvent(.route, route: currentPlatformRoute())
}
@MainActor
private func handlePlatformMediaServicesReset() async {
guard platformSessionId != nil else { return }
emitPlatformEvent(.mediaServicesReset)
do {
try configurePlatformAudioSession(
microphone: platformMicrophone,
playback: platformPlayback
)
} catch {
failPlatformSession(.audioSessionFailed)
}
}
@MainActor
private func failPlatformSession(_ code: PlatformFailureCode) {
guard let activeSessionId = platformSessionId,
let activeChannel = platformEventChannel
else { return }
platformRevision &+= 1
sendPlatformEvent(
.failure,
sessionId: activeSessionId,
channel: activeChannel,
revision: platformRevision,
code: code
)
removePlatformObservers()
platformSessionId = nil
platformEventChannel = nil
platformMicrophone = false
platformPlayback = false
try? AVAudioSession.sharedInstance().setActive(
false,
options: .notifyOthersOnDeactivation
)
}
@MainActor
private func rejectPlatformStart(
sessionId: String,
channel: Channel,
code: PlatformFailureCode,
invoke: Invoke
) {
platformRevision &+= 1
sendPlatformEvent(
.failure,
sessionId: sessionId,
channel: channel,
revision: platformRevision,
code: code
)
invoke.reject("Platform audio session start failed.", code: code.rawValue)
}
@MainActor
private func platformState() -> PlatformStateResponse {
PlatformStateResponse(
sessionId: platformSessionId,
revision: platformRevision,
state: platformSessionId == nil ? .idle : .active,
microphone: platformSessionId == nil ? false : platformMicrophone,
playback: platformSessionId == nil ? false : platformPlayback
)
}
@MainActor
private func emitPlatformEvent(
_ event: PlatformEventKind,
focus: PlatformFocus? = nil,
route: PlatformRoute? = nil,
interruption: PlatformInterruption? = nil
) {
guard let sessionId = platformSessionId,
let channel = platformEventChannel
else { return }
platformRevision &+= 1
sendPlatformEvent(
event,
sessionId: sessionId,
channel: channel,
revision: platformRevision,
focus: focus,
route: route,
interruption: interruption
)
}
private func sendPlatformEvent(
_ event: PlatformEventKind,
sessionId: String,
channel: Channel,
revision: UInt64,
focus: PlatformFocus? = nil,
route: PlatformRoute? = nil,
interruption: PlatformInterruption? = nil,
code: PlatformFailureCode? = nil
) {
try? channel.send(
PlatformEvent(
sessionId: sessionId,
revision: revision,
event: event,
focus: focus,
route: route,
interruption: interruption,
code: code
)
)
}
@MainActor
private func currentPlatformRoute() -> PlatformRoute {
guard let output = AVAudioSession.sharedInstance().currentRoute.outputs.first else {
return .none
}
switch output.portType {
case .builtInSpeaker:
return .speaker
case .builtInReceiver:
return .receiver
case .bluetoothA2DP, .bluetoothHFP, .bluetoothLE:
return .bluetooth
case .headphones, .headsetMic, .lineOut:
return .wired
default:
return .other
}
}
}
private enum SetupError: Error {
case denied
}
@_cdecl("init_plugin_call_lifecycle")
func initPlugin() -> Plugin {
return CallLifecyclePlugin()
}
@@ -1,30 +0,0 @@
{
"name": "tauri-plugin-call-lifecycle-api",
"version": "0.1.0",
"author": "Sable Contributors",
"description": "",
"type": "module",
"types": "./dist-js/index.d.ts",
"main": "./dist-js/index.cjs",
"module": "./dist-js/index.js",
"exports": {
"types": "./dist-js/index.d.ts",
"import": "./dist-js/index.js",
"require": "./dist-js/index.cjs"
},
"files": ["dist-js"],
"scripts": {
"build": "rollup -c",
"prepublishOnly": "pnpm build",
"pretest": "pnpm build"
},
"dependencies": {
"@tauri-apps/api": "^2.0.0"
},
"devDependencies": {
"@rollup/plugin-typescript": "^12.0.0",
"rollup": "^4.9.6",
"typescript": "^6.0.0",
"tslib": "^2.6.2"
}
}
@@ -1,13 +0,0 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-getPlatformCallCapabilities"
description = "Enables the getPlatformCallCapabilities command without any pre-configured scope."
commands.allow = ["getPlatformCallCapabilities"]
[[permission]]
identifier = "deny-getPlatformCallCapabilities"
description = "Denies the getPlatformCallCapabilities command without any pre-configured scope."
commands.deny = ["getPlatformCallCapabilities"]
@@ -1,13 +0,0 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-getPlatformCallState"
description = "Enables the getPlatformCallState command without any pre-configured scope."
commands.allow = ["getPlatformCallState"]
[[permission]]
identifier = "deny-getPlatformCallState"
description = "Denies the getPlatformCallState command without any pre-configured scope."
commands.deny = ["getPlatformCallState"]
@@ -1,13 +0,0 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-startPlatformCallLifecycle"
description = "Enables the startPlatformCallLifecycle command without any pre-configured scope."
commands.allow = ["startPlatformCallLifecycle"]
[[permission]]
identifier = "deny-startPlatformCallLifecycle"
description = "Denies the startPlatformCallLifecycle command without any pre-configured scope."
commands.deny = ["startPlatformCallLifecycle"]
@@ -1,13 +0,0 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-stopPlatformCallLifecycle"
description = "Enables the stopPlatformCallLifecycle command without any pre-configured scope."
commands.allow = ["stopPlatformCallLifecycle"]
[[permission]]
identifier = "deny-stopPlatformCallLifecycle"
description = "Denies the stopPlatformCallLifecycle command without any pre-configured scope."
commands.deny = ["stopPlatformCallLifecycle"]
@@ -1,124 +0,0 @@
## Default Permission
Default permissions for the plugin
#### This default permission set includes the following:
- `allow-getPlatformCallCapabilities`
- `allow-startPlatformCallLifecycle`
- `allow-stopPlatformCallLifecycle`
- `allow-getPlatformCallState`
## Permission Table
<table>
<tr>
<th>Identifier</th>
<th>Description</th>
</tr>
<tr>
<td>
`call-lifecycle:allow-getPlatformCallCapabilities`
</td>
<td>
Enables the getPlatformCallCapabilities command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`call-lifecycle:deny-getPlatformCallCapabilities`
</td>
<td>
Denies the getPlatformCallCapabilities command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`call-lifecycle:allow-getPlatformCallState`
</td>
<td>
Enables the getPlatformCallState command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`call-lifecycle:deny-getPlatformCallState`
</td>
<td>
Denies the getPlatformCallState command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`call-lifecycle:allow-startPlatformCallLifecycle`
</td>
<td>
Enables the startPlatformCallLifecycle command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`call-lifecycle:deny-startPlatformCallLifecycle`
</td>
<td>
Denies the startPlatformCallLifecycle command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`call-lifecycle:allow-stopPlatformCallLifecycle`
</td>
<td>
Enables the stopPlatformCallLifecycle command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`call-lifecycle:deny-stopPlatformCallLifecycle`
</td>
<td>
Denies the stopPlatformCallLifecycle command without any pre-configured scope.
</td>
</tr>
</table>
@@ -1,8 +0,0 @@
[default]
description = "Default permissions for the plugin"
permissions = [
"allow-getPlatformCallCapabilities",
"allow-startPlatformCallLifecycle",
"allow-stopPlatformCallLifecycle",
"allow-getPlatformCallState",
]
@@ -1,354 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "PermissionFile",
"description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",
"type": "object",
"properties": {
"default": {
"description": "The default permission set for the plugin",
"anyOf": [
{
"$ref": "#/definitions/DefaultPermission"
},
{
"type": "null"
}
]
},
"set": {
"description": "A list of permissions sets defined",
"type": "array",
"items": {
"$ref": "#/definitions/PermissionSet"
}
},
"permission": {
"description": "A list of inlined permissions",
"default": [],
"type": "array",
"items": {
"$ref": "#/definitions/Permission"
}
}
},
"definitions": {
"DefaultPermission": {
"description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",
"type": "object",
"required": [
"permissions"
],
"properties": {
"version": {
"description": "The version of the permission.",
"type": [
"integer",
"null"
],
"format": "uint64",
"minimum": 1.0
},
"description": {
"description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
"type": [
"string",
"null"
]
},
"permissions": {
"description": "All permissions this set contains.",
"type": "array",
"items": {
"type": "string"
}
}
}
},
"PermissionSet": {
"description": "A set of direct permissions grouped together under a new name.",
"type": "object",
"required": [
"description",
"identifier",
"permissions"
],
"properties": {
"identifier": {
"description": "A unique identifier for the permission.",
"type": "string"
},
"description": {
"description": "Human-readable description of what the permission does.",
"type": "string"
},
"permissions": {
"description": "All permissions this set contains.",
"type": "array",
"items": {
"$ref": "#/definitions/PermissionKind"
}
}
}
},
"Permission": {
"description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",
"type": "object",
"required": [
"identifier"
],
"properties": {
"version": {
"description": "The version of the permission.",
"type": [
"integer",
"null"
],
"format": "uint64",
"minimum": 1.0
},
"identifier": {
"description": "A unique identifier for the permission.",
"type": "string"
},
"description": {
"description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
"type": [
"string",
"null"
]
},
"commands": {
"description": "Allowed or denied commands when using this permission.",
"default": {
"allow": [],
"deny": []
},
"allOf": [
{
"$ref": "#/definitions/Commands"
}
]
},
"scope": {
"description": "Allowed or denied scoped when using this permission.",
"allOf": [
{
"$ref": "#/definitions/Scopes"
}
]
},
"platforms": {
"description": "Target platforms this permission applies. By default all platforms are affected by this permission.",
"type": [
"array",
"null"
],
"items": {
"$ref": "#/definitions/Target"
}
}
}
},
"Commands": {
"description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",
"type": "object",
"properties": {
"allow": {
"description": "Allowed command.",
"default": [],
"type": "array",
"items": {
"type": "string"
}
},
"deny": {
"description": "Denied command, which takes priority.",
"default": [],
"type": "array",
"items": {
"type": "string"
}
}
}
},
"Scopes": {
"description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",
"type": "object",
"properties": {
"allow": {
"description": "Data that defines what is allowed by the scope.",
"type": [
"array",
"null"
],
"items": {
"$ref": "#/definitions/Value"
}
},
"deny": {
"description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",
"type": [
"array",
"null"
],
"items": {
"$ref": "#/definitions/Value"
}
}
}
},
"Value": {
"description": "All supported ACL values.",
"anyOf": [
{
"description": "Represents a null JSON value.",
"type": "null"
},
{
"description": "Represents a [`bool`].",
"type": "boolean"
},
{
"description": "Represents a valid ACL [`Number`].",
"allOf": [
{
"$ref": "#/definitions/Number"
}
]
},
{
"description": "Represents a [`String`].",
"type": "string"
},
{
"description": "Represents a list of other [`Value`]s.",
"type": "array",
"items": {
"$ref": "#/definitions/Value"
}
},
{
"description": "Represents a map of [`String`] keys to [`Value`]s.",
"type": "object",
"additionalProperties": {
"$ref": "#/definitions/Value"
}
}
]
},
"Number": {
"description": "A valid ACL number.",
"anyOf": [
{
"description": "Represents an [`i64`].",
"type": "integer",
"format": "int64"
},
{
"description": "Represents a [`f64`].",
"type": "number",
"format": "double"
}
]
},
"Target": {
"description": "Platform target.",
"oneOf": [
{
"description": "MacOS.",
"type": "string",
"enum": [
"macOS"
]
},
{
"description": "Windows.",
"type": "string",
"enum": [
"windows"
]
},
{
"description": "Linux.",
"type": "string",
"enum": [
"linux"
]
},
{
"description": "Android.",
"type": "string",
"enum": [
"android"
]
},
{
"description": "iOS.",
"type": "string",
"enum": [
"iOS"
]
}
]
},
"PermissionKind": {
"type": "string",
"oneOf": [
{
"description": "Enables the getPlatformCallCapabilities command without any pre-configured scope.",
"type": "string",
"const": "allow-getPlatformCallCapabilities",
"markdownDescription": "Enables the getPlatformCallCapabilities command without any pre-configured scope."
},
{
"description": "Denies the getPlatformCallCapabilities command without any pre-configured scope.",
"type": "string",
"const": "deny-getPlatformCallCapabilities",
"markdownDescription": "Denies the getPlatformCallCapabilities command without any pre-configured scope."
},
{
"description": "Enables the getPlatformCallState command without any pre-configured scope.",
"type": "string",
"const": "allow-getPlatformCallState",
"markdownDescription": "Enables the getPlatformCallState command without any pre-configured scope."
},
{
"description": "Denies the getPlatformCallState command without any pre-configured scope.",
"type": "string",
"const": "deny-getPlatformCallState",
"markdownDescription": "Denies the getPlatformCallState command without any pre-configured scope."
},
{
"description": "Enables the startPlatformCallLifecycle command without any pre-configured scope.",
"type": "string",
"const": "allow-startPlatformCallLifecycle",
"markdownDescription": "Enables the startPlatformCallLifecycle command without any pre-configured scope."
},
{
"description": "Denies the startPlatformCallLifecycle command without any pre-configured scope.",
"type": "string",
"const": "deny-startPlatformCallLifecycle",
"markdownDescription": "Denies the startPlatformCallLifecycle command without any pre-configured scope."
},
{
"description": "Enables the stopPlatformCallLifecycle command without any pre-configured scope.",
"type": "string",
"const": "allow-stopPlatformCallLifecycle",
"markdownDescription": "Enables the stopPlatformCallLifecycle command without any pre-configured scope."
},
{
"description": "Denies the stopPlatformCallLifecycle command without any pre-configured scope.",
"type": "string",
"const": "deny-stopPlatformCallLifecycle",
"markdownDescription": "Denies the stopPlatformCallLifecycle command without any pre-configured scope."
},
{
"description": "Default permissions for the plugin\n#### This default permission set includes:\n\n- `allow-getPlatformCallCapabilities`\n- `allow-startPlatformCallLifecycle`\n- `allow-stopPlatformCallLifecycle`\n- `allow-getPlatformCallState`",
"type": "string",
"const": "default",
"markdownDescription": "Default permissions for the plugin\n#### This default permission set includes:\n\n- `allow-getPlatformCallCapabilities`\n- `allow-startPlatformCallLifecycle`\n- `allow-stopPlatformCallLifecycle`\n- `allow-getPlatformCallState`"
}
]
}
}
}
@@ -1,32 +0,0 @@
import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { cwd } from 'node:process'
import typescript from '@rollup/plugin-typescript'
const pkg = JSON.parse(readFileSync(join(cwd(), 'package.json'), 'utf8'))
export default {
input: 'guest-js/index.ts',
output: [
{
file: pkg.exports.import,
format: 'esm'
},
{
file: pkg.exports.require,
format: 'cjs'
}
],
plugins: [
typescript({
declaration: true,
declarationDir: dirname(pkg.exports.import),
rootDir: 'guest-js'
})
],
external: [
/^@tauri-apps\/api/,
...Object.keys(pkg.dependencies || {}),
...Object.keys(pkg.peerDependencies || {})
]
}
@@ -1,664 +0,0 @@
use std::marker::PhantomData;
use tauri::{async_runtime, AppHandle, Runtime};
use tokio::sync::{mpsc, oneshot};
#[cfg(mobile)]
use tauri::Emitter;
#[cfg(mobile)]
use crate::mobile::{
MobileBackend, NativePlatformCallEvent, NativeStartPlatformCallLifecycleRequest,
NativeStopPlatformCallLifecycleRequest,
};
use crate::error::{Error, Result};
#[cfg(mobile)]
use crate::models::{NativePlatformStartFields, PlatformCallEvent, PlatformCallEventKind};
use crate::models::{
PlatformCallCapabilities, PlatformCallState, PlatformCallStateKind,
StartPlatformCallLifecycleRequest, StopPlatformCallLifecycleRequest,
};
#[cfg(mobile)]
pub(crate) const PLATFORM_CALL_EVENT: &str = "plugin:call-lifecycle://platform-event";
pub(crate) enum Command {
GetPlatformCallCapabilities(oneshot::Sender<Result<PlatformCallCapabilities>>),
StartPlatformCallLifecycle(
StartPlatformCallLifecycleRequest,
oneshot::Sender<Result<PlatformCallState>>,
),
StopPlatformCallLifecycle(
StopPlatformCallLifecycleRequest,
oneshot::Sender<Result<PlatformCallState>>,
),
GetPlatformCallState(oneshot::Sender<Result<PlatformCallState>>),
}
#[cfg(mobile)]
enum InternalMessage {
PlatformCallEvent(NativePlatformCallEvent),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PlatformStartDecision {
Start,
Idempotent,
Busy,
Unsupported,
InvalidSession,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PlatformStopDecision {
Stop,
Idempotent,
Stale,
Unsupported,
InvalidSession,
}
#[derive(Debug, Clone)]
struct PlatformStateMachine {
revision: u64,
state: PlatformCallStateKind,
session_id: Option<String>,
microphone: bool,
playback: bool,
capabilities: PlatformCallCapabilities,
last_session_id: Option<String>,
}
impl Default for PlatformStateMachine {
fn default() -> Self {
Self {
revision: 0,
state: PlatformCallStateKind::Idle,
session_id: None,
microphone: false,
playback: false,
capabilities: PlatformCallCapabilities::current(),
last_session_id: None,
}
}
}
impl PlatformStateMachine {
fn snapshot(&self) -> PlatformCallState {
PlatformCallState {
revision: self.revision,
state: self.state,
session_id: self.session_id.clone(),
microphone: self.microphone,
playback: self.playback,
capabilities: self.capabilities,
}
}
fn start_decision(&self, request: &StartPlatformCallLifecycleRequest) -> PlatformStartDecision {
if !self.capabilities.supported {
return PlatformStartDecision::Unsupported;
}
if request.session_id.is_empty() {
return PlatformStartDecision::InvalidSession;
}
if (request.microphone && !self.capabilities.microphone)
|| (request.playback && !self.capabilities.playback)
{
return PlatformStartDecision::Unsupported;
}
match self.session_id.as_deref() {
None => PlatformStartDecision::Start,
Some(session_id)
if session_id == request.session_id
&& self.microphone == request.microphone
&& self.playback == request.playback =>
{
PlatformStartDecision::Idempotent
}
Some(_) => PlatformStartDecision::Busy,
}
}
fn stop_decision(&self, session_id: &str) -> PlatformStopDecision {
if !self.capabilities.supported {
return PlatformStopDecision::Unsupported;
}
if session_id.is_empty() {
return PlatformStopDecision::InvalidSession;
}
match self.session_id.as_deref() {
Some(current) if current == session_id => PlatformStopDecision::Stop,
Some(_) => PlatformStopDecision::Stale,
None if self.last_session_id.as_deref() == Some(session_id) => {
PlatformStopDecision::Idempotent
}
None => PlatformStopDecision::Stale,
}
}
fn activate(&mut self, request: &StartPlatformCallLifecycleRequest) {
self.revision += 1;
self.state = PlatformCallStateKind::Active;
self.session_id = Some(request.session_id.clone());
self.last_session_id = Some(request.session_id.clone());
self.microphone = request.microphone;
self.playback = request.playback;
}
fn stop(&mut self) {
self.revision += 1;
self.state = PlatformCallStateKind::Idle;
self.session_id = None;
self.microphone = false;
self.playback = false;
}
#[cfg(mobile)]
fn next_event_revision(&mut self) -> u64 {
self.revision += 1;
self.revision
}
#[cfg(mobile)]
fn fail(&mut self) {
self.state = PlatformCallStateKind::Idle;
self.session_id = None;
self.microphone = false;
self.playback = false;
}
}
struct Actor<R: Runtime> {
#[cfg(not(mobile))]
_runtime: PhantomData<fn() -> R>,
#[cfg(mobile)]
app: AppHandle<R>,
commands: mpsc::Receiver<Command>,
#[cfg(mobile)]
internal_tx: mpsc::UnboundedSender<InternalMessage>,
#[cfg(mobile)]
internal_rx: mpsc::UnboundedReceiver<InternalMessage>,
#[cfg(mobile)]
mobile: MobileBackend<R>,
platform: PlatformStateMachine,
#[cfg(mobile)]
platform_events_task: Option<async_runtime::JoinHandle<()>>,
}
pub struct CallLifecycle<R: Runtime> {
commands: mpsc::Sender<Command>,
_runtime: PhantomData<fn() -> R>,
}
impl<R: Runtime> CallLifecycle<R> {
#[cfg(not(mobile))]
pub(crate) fn new(_app: AppHandle<R>) -> Self {
let (commands, command_rx) = mpsc::channel(32);
async_runtime::spawn(run_actor::<R>(command_rx));
Self {
commands,
_runtime: PhantomData,
}
}
#[cfg(mobile)]
pub(crate) fn new(app: AppHandle<R>, mobile: MobileBackend<R>) -> Self {
let (commands, command_rx) = mpsc::channel(32);
let (internal_tx, internal_rx) = mpsc::unbounded_channel();
async_runtime::spawn(run_actor(app, command_rx, internal_tx, internal_rx, mobile));
Self {
commands,
_runtime: PhantomData,
}
}
pub async fn get_platform_call_capabilities(&self) -> Result<PlatformCallCapabilities> {
let (response, result) = oneshot::channel();
self.commands
.send(Command::GetPlatformCallCapabilities(response))
.await
.map_err(|_| Error::ActorUnavailable)?;
result.await.map_err(|_| Error::ActorUnavailable)?
}
pub async fn start_platform_call_lifecycle(
&self,
request: StartPlatformCallLifecycleRequest,
) -> Result<PlatformCallState> {
let (response, result) = oneshot::channel();
self.commands
.send(Command::StartPlatformCallLifecycle(request, response))
.await
.map_err(|_| Error::ActorUnavailable)?;
result.await.map_err(|_| Error::ActorUnavailable)?
}
pub async fn stop_platform_call_lifecycle(
&self,
request: StopPlatformCallLifecycleRequest,
) -> Result<PlatformCallState> {
let (response, result) = oneshot::channel();
self.commands
.send(Command::StopPlatformCallLifecycle(request, response))
.await
.map_err(|_| Error::ActorUnavailable)?;
result.await.map_err(|_| Error::ActorUnavailable)?
}
pub async fn get_platform_call_state(&self) -> Result<PlatformCallState> {
let (response, result) = oneshot::channel();
self.commands
.send(Command::GetPlatformCallState(response))
.await
.map_err(|_| Error::ActorUnavailable)?;
result.await.map_err(|_| Error::ActorUnavailable)?
}
}
#[cfg(not(mobile))]
async fn run_actor<R: Runtime>(commands: mpsc::Receiver<Command>) {
let mut actor: Actor<R> = Actor {
_runtime: PhantomData,
commands,
platform: PlatformStateMachine::default(),
};
loop {
let Some(command) = actor.commands.recv().await else {
break;
};
actor.handle_command(command).await;
}
actor.cleanup().await;
}
#[cfg(mobile)]
async fn run_actor<R: Runtime>(
app: AppHandle<R>,
commands: mpsc::Receiver<Command>,
internal_tx: mpsc::UnboundedSender<InternalMessage>,
internal_rx: mpsc::UnboundedReceiver<InternalMessage>,
mobile: MobileBackend<R>,
) {
let mut actor = Actor {
app,
commands,
internal_tx,
internal_rx,
mobile,
platform: PlatformStateMachine::default(),
platform_events_task: None,
};
loop {
tokio::select! {
command = actor.commands.recv() => {
let Some(command) = command else { break };
actor.handle_command(command).await;
}
internal = actor.internal_rx.recv() => {
let Some(internal) = internal else { break };
actor.handle_internal(internal).await;
}
}
}
actor.cleanup().await;
}
impl<R: Runtime> Actor<R> {
async fn handle_command(&mut self, command: Command) {
match command {
Command::GetPlatformCallCapabilities(response) => {
self.handle_get_platform_call_capabilities(response).await
}
Command::StartPlatformCallLifecycle(request, response) => {
self.handle_start_platform_call_lifecycle(request, response)
.await
}
Command::StopPlatformCallLifecycle(request, response) => {
self.handle_stop_platform_call_lifecycle(request, response)
.await
}
Command::GetPlatformCallState(response) => {
let _ = response.send(Ok(self.platform.snapshot()));
}
}
}
async fn handle_get_platform_call_capabilities(
&mut self,
response: oneshot::Sender<Result<PlatformCallCapabilities>>,
) {
#[cfg(mobile)]
let result = self.mobile.get_platform_call_capabilities().await;
#[cfg(not(mobile))]
let result = Ok(PlatformCallCapabilities::current());
match result {
Ok(capabilities) => {
self.platform.capabilities = capabilities;
let _ = response.send(Ok(capabilities));
}
Err(error) => {
let _ = response.send(Err(error));
}
}
}
async fn handle_start_platform_call_lifecycle(
&mut self,
request: StartPlatformCallLifecycleRequest,
response: oneshot::Sender<Result<PlatformCallState>>,
) {
match self.platform.start_decision(&request) {
PlatformStartDecision::Idempotent => {
let _ = response.send(Ok(self.platform.snapshot()));
}
PlatformStartDecision::Unsupported => {
let _ = response.send(Err(Error::PlatformCallUnsupported));
}
PlatformStartDecision::Busy => {
let _ = response.send(Err(Error::PlatformCallBusy));
}
PlatformStartDecision::InvalidSession => {
let _ = response.send(Err(Error::PlatformCallStaleSession));
}
PlatformStartDecision::Start => {
#[cfg(mobile)]
let result = {
let (events_sender, mut events) = mpsc::channel(32);
let channel = MobileBackend::platform_event_channel(events_sender);
let internal_tx = self.internal_tx.clone();
let forwarder = async_runtime::spawn(async move {
while let Some(event) = events.recv().await {
let _ = internal_tx.send(InternalMessage::PlatformCallEvent(event));
}
});
let result = self
.mobile
.start_platform_call_lifecycle(NativeStartPlatformCallLifecycleRequest {
fields: NativePlatformStartFields {
session_id: &request.session_id,
microphone: request.microphone,
playback: request.playback,
},
channel,
})
.await;
if result.is_err() {
forwarder.abort();
let _ = forwarder.await;
} else {
if let Some(stale) = self.platform_events_task.take() {
stale.abort();
}
self.platform_events_task = Some(forwarder);
}
result
};
#[cfg(not(mobile))]
let result: Result<()> = Err(Error::PlatformCallUnsupported);
match result {
Ok(()) => {
self.platform.activate(&request);
let _ = response.send(Ok(self.platform.snapshot()));
}
Err(error) => {
let _ = response.send(Err(error));
}
}
}
}
}
async fn handle_stop_platform_call_lifecycle(
&mut self,
request: StopPlatformCallLifecycleRequest,
response: oneshot::Sender<Result<PlatformCallState>>,
) {
match self.platform.stop_decision(&request.session_id) {
PlatformStopDecision::Idempotent => {
let _ = response.send(Ok(self.platform.snapshot()));
}
PlatformStopDecision::Unsupported => {
let _ = response.send(Err(Error::PlatformCallUnsupported));
}
PlatformStopDecision::Stale | PlatformStopDecision::InvalidSession => {
let _ = response.send(Err(Error::PlatformCallStaleSession));
}
PlatformStopDecision::Stop => {
#[cfg(mobile)]
let result = self
.mobile
.stop_platform_call_lifecycle(NativeStopPlatformCallLifecycleRequest {
session_id: &request.session_id,
})
.await;
#[cfg(not(mobile))]
let result: Result<()> = Err(Error::PlatformCallUnsupported);
match result {
Ok(()) => {
#[cfg(mobile)]
if let Some(task) = self.platform_events_task.take() {
task.abort();
let _ = task.await;
}
self.platform.stop();
let _ = response.send(Ok(self.platform.snapshot()));
}
Err(error) => {
let _ = response.send(Err(error));
}
}
}
}
}
#[cfg(mobile)]
async fn handle_internal(&mut self, message: InternalMessage) {
match message {
InternalMessage::PlatformCallEvent(event) => self.handle_platform_call_event(event),
}
}
#[cfg(mobile)]
fn handle_platform_call_event(&mut self, event: NativePlatformCallEvent) {
if self.platform.session_id.as_deref() != Some(event.session_id.as_str()) {
return;
}
let Some(kind) = event.to_kind() else {
return;
};
if matches!(kind, PlatformCallEventKind::Failed { .. }) {
self.platform.fail();
if let Some(task) = self.platform_events_task.take() {
task.abort();
}
}
let payload = PlatformCallEvent {
revision: self.platform.next_event_revision(),
session_id: event.session_id,
kind,
};
let _ = self.app.emit(PLATFORM_CALL_EVENT, payload);
}
async fn cleanup(&mut self) {
#[cfg(mobile)]
if let Some(task) = self.platform_events_task.take() {
task.abort();
let _ = task.await;
}
}
}
#[cfg(test)]
mod tests {
use super::{PlatformStartDecision, PlatformStateMachine, PlatformStopDecision};
use crate::models::{
PlatformCallCapabilities, PlatformCallStateKind, StartPlatformCallLifecycleRequest,
};
#[test]
fn platform_lifecycle_has_opaque_session_and_idempotent_stop_semantics() {
let mut machine = PlatformStateMachine::default();
assert_eq!(
machine.start_decision(&StartPlatformCallLifecycleRequest {
session_id: "session".into(),
microphone: true,
playback: true,
}),
PlatformStartDecision::Unsupported
);
machine.capabilities = PlatformCallCapabilities {
supported: true,
microphone: true,
playback: true,
};
let request = StartPlatformCallLifecycleRequest {
session_id: "opaque-session".into(),
microphone: true,
playback: true,
};
assert_eq!(
machine.start_decision(&request),
PlatformStartDecision::Start
);
machine.activate(&request);
assert_eq!(
machine.start_decision(&request),
PlatformStartDecision::Idempotent
);
assert_eq!(
machine.start_decision(&StartPlatformCallLifecycleRequest {
session_id: "another-session".into(),
microphone: true,
playback: true,
}),
PlatformStartDecision::Busy
);
assert_eq!(
machine.stop_decision("another-session"),
PlatformStopDecision::Stale
);
assert_eq!(
machine.stop_decision("opaque-session"),
PlatformStopDecision::Stop
);
machine.stop();
assert_eq!(
machine.stop_decision("opaque-session"),
PlatformStopDecision::Idempotent
);
assert_eq!(machine.snapshot().session_id, None);
}
#[test]
fn platform_stop_protects_against_replacement_session() {
let mut machine = PlatformStateMachine::default();
machine.capabilities = PlatformCallCapabilities {
supported: true,
microphone: true,
playback: true,
};
machine.activate(&StartPlatformCallLifecycleRequest {
session_id: "first".into(),
microphone: true,
playback: true,
});
machine.stop();
machine.activate(&StartPlatformCallLifecycleRequest {
session_id: "second".into(),
microphone: true,
playback: true,
});
// A stop targeted at the replaced session must not touch the active one.
assert_eq!(machine.stop_decision("first"), PlatformStopDecision::Stale);
assert_eq!(machine.stop_decision("second"), PlatformStopDecision::Stop);
machine.stop();
assert_eq!(
machine.stop_decision("never-seen"),
PlatformStopDecision::Stale
);
}
#[test]
fn empty_session_ids_are_rejected_before_any_transition() {
let mut machine = PlatformStateMachine::default();
machine.capabilities = PlatformCallCapabilities {
supported: true,
microphone: true,
playback: true,
};
assert_eq!(
machine.start_decision(&StartPlatformCallLifecycleRequest {
session_id: String::new(),
microphone: true,
playback: true,
}),
PlatformStartDecision::InvalidSession
);
assert_eq!(
machine.stop_decision(""),
PlatformStopDecision::InvalidSession
);
assert_eq!(machine.snapshot().revision, 0);
assert_eq!(machine.snapshot().state, PlatformCallStateKind::Idle);
}
#[test]
fn media_flags_must_be_supported_by_the_platform() {
let mut machine = PlatformStateMachine::default();
machine.capabilities = PlatformCallCapabilities {
supported: true,
microphone: true,
playback: false,
};
assert_eq!(
machine.start_decision(&StartPlatformCallLifecycleRequest {
session_id: "session".into(),
microphone: false,
playback: true,
}),
PlatformStartDecision::Unsupported
);
assert_eq!(
machine.start_decision(&StartPlatformCallLifecycleRequest {
session_id: "session".into(),
microphone: true,
playback: false,
}),
PlatformStartDecision::Start
);
}
#[test]
fn desktop_reports_truthful_unsupported_state() {
assert_eq!(
PlatformCallCapabilities::current().supported,
cfg!(any(target_os = "android", target_os = "ios"))
);
#[cfg(not(mobile))]
{
let machine = PlatformStateMachine::default();
assert_eq!(
machine.start_decision(&StartPlatformCallLifecycleRequest {
session_id: "session".into(),
microphone: true,
playback: true,
}),
PlatformStartDecision::Unsupported
);
assert_eq!(
machine.stop_decision("session"),
PlatformStopDecision::Unsupported
);
}
}
}
@@ -1,47 +0,0 @@
// The attribute is aliased to `tauri_command` on purpose: tauri-typegen scans
// every .rs file under `src-tauri/` and treats a bare `#[command]` attribute as
// a root command, which would emit unusable unprefixed root bindings for these
// namespaced plugin commands that the guest-js API already exposes.
use tauri::{command as tauri_command, AppHandle, Runtime};
use crate::models::*;
use crate::CallLifecycleExt;
use crate::Result;
#[allow(non_snake_case)]
#[tauri_command]
pub(crate) async fn getPlatformCallCapabilities<R: Runtime>(
app: AppHandle<R>,
) -> Result<PlatformCallCapabilities> {
app.call_lifecycle().get_platform_call_capabilities().await
}
#[allow(non_snake_case)]
#[tauri_command]
pub(crate) async fn startPlatformCallLifecycle<R: Runtime>(
app: AppHandle<R>,
payload: StartPlatformCallLifecycleRequest,
) -> Result<PlatformCallState> {
app.call_lifecycle()
.start_platform_call_lifecycle(payload)
.await
}
#[allow(non_snake_case)]
#[tauri_command]
pub(crate) async fn stopPlatformCallLifecycle<R: Runtime>(
app: AppHandle<R>,
payload: StopPlatformCallLifecycleRequest,
) -> Result<PlatformCallState> {
app.call_lifecycle()
.stop_platform_call_lifecycle(payload)
.await
}
#[allow(non_snake_case)]
#[tauri_command]
pub(crate) async fn getPlatformCallState<R: Runtime>(
app: AppHandle<R>,
) -> Result<PlatformCallState> {
app.call_lifecycle().get_platform_call_state().await
}
@@ -1,89 +0,0 @@
use serde::{ser::SerializeStruct, ser::Serializer, Serialize};
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("call lifecycle actor unavailable")]
ActorUnavailable,
#[error("platform call lifecycle is not supported on this platform")]
PlatformCallUnsupported,
#[error("platform call lifecycle is already active")]
PlatformCallBusy,
#[error("platform call session does not match the active session")]
PlatformCallStaleSession,
#[error("platform call lifecycle failed to start")]
PlatformCallStartFailed,
#[error("platform call lifecycle failed to stop")]
PlatformCallStopFailed,
}
impl Serialize for Error {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut error = serializer.serialize_struct("Error", 2)?;
error.serialize_field("code", self.code())?;
error.serialize_field("message", self.message())?;
error.end()
}
}
impl Error {
pub fn code(&self) -> &'static str {
match self {
Self::ActorUnavailable => "actor_unavailable",
Self::PlatformCallUnsupported => "platform_call_unsupported",
Self::PlatformCallBusy => "platform_call_busy",
Self::PlatformCallStaleSession => "platform_call_stale_session",
Self::PlatformCallStartFailed => "platform_call_start_failed",
Self::PlatformCallStopFailed => "platform_call_stop_failed",
}
}
pub fn message(&self) -> &'static str {
match self {
Self::ActorUnavailable => "call lifecycle unavailable",
Self::PlatformCallUnsupported => {
"platform call lifecycle is not supported on this platform"
}
Self::PlatformCallBusy => "platform call lifecycle is already active",
Self::PlatformCallStaleSession => {
"platform call session does not match the active session"
}
Self::PlatformCallStartFailed => "platform call lifecycle failed to start",
Self::PlatformCallStopFailed => "platform call lifecycle failed to stop",
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn platform_errors_have_stable_sanitized_shapes() {
let error = serde_json::to_value(Error::PlatformCallStaleSession).unwrap();
assert_eq!(
error,
serde_json::json!({
"code": "platform_call_stale_session",
"message": "platform call session does not match the active session"
})
);
assert_eq!(
Error::PlatformCallUnsupported.code(),
"platform_call_unsupported"
);
assert_eq!(Error::PlatformCallBusy.code(), "platform_call_busy");
assert_eq!(
Error::PlatformCallStartFailed.message(),
"platform call lifecycle failed to start"
);
assert_eq!(
Error::PlatformCallStopFailed.code(),
"platform_call_stop_failed"
);
}
}
@@ -1,53 +0,0 @@
use tauri::{
plugin::{Builder, TauriPlugin},
Manager, Runtime,
};
pub use models::*;
mod actor;
mod commands;
mod error;
#[cfg(mobile)]
mod mobile;
mod models;
pub use error::{Error, Result};
use actor::CallLifecycle;
/// Extensions to [`tauri::App`], [`tauri::AppHandle`] and [`tauri::Window`] to access the call-lifecycle APIs.
pub trait CallLifecycleExt<R: Runtime> {
fn call_lifecycle(&self) -> &CallLifecycle<R>;
}
impl<R: Runtime, T: Manager<R>> crate::CallLifecycleExt<R> for T {
fn call_lifecycle(&self) -> &CallLifecycle<R> {
self.state::<CallLifecycle<R>>().inner()
}
}
/// Initializes the plugin.
pub fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("call-lifecycle")
.invoke_handler(tauri::generate_handler![
commands::getPlatformCallCapabilities,
commands::startPlatformCallLifecycle,
commands::stopPlatformCallLifecycle,
commands::getPlatformCallState
])
.setup(|app, api| {
#[cfg(mobile)]
let mobile_backend = mobile::init(app, api)?;
#[cfg(not(mobile))]
let _ = api;
#[cfg(mobile)]
let call_lifecycle = CallLifecycle::new(app.clone(), mobile_backend);
#[cfg(not(mobile))]
let call_lifecycle = CallLifecycle::new(app.clone());
app.manage(call_lifecycle);
Ok(())
})
.build()
}
@@ -1,151 +0,0 @@
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use tauri::{
ipc::{Channel, InvokeResponseBody},
plugin::{PluginApi, PluginHandle},
AppHandle, Runtime,
};
use tokio::sync::mpsc;
use crate::{
error::Error,
models::{NativePlatformCallEvent, NativePlatformStartFields, PlatformCallCapabilities},
};
#[cfg(target_os = "android")]
const PLUGIN_IDENTIFIER: &str = "app.tauri.call_lifecycle";
#[cfg(target_os = "ios")]
tauri::ios_plugin_binding!(init_plugin_call_lifecycle);
#[cfg(target_os = "android")]
mod platform_commands {
pub(super) const CAPABILITIES: &str = "getPlatformLifecycleCapabilities";
pub(super) const START: &str = "startPlatformLifecycle";
pub(super) const STOP: &str = "stopPlatformLifecycle";
}
#[cfg(target_os = "ios")]
mod platform_commands {
pub(super) const CAPABILITIES: &str = "capabilities";
pub(super) const START: &str = "start";
pub(super) const STOP: &str = "stop";
}
/// Mirrors the Android `getPlatformLifecycleCapabilities` response.
#[cfg(target_os = "android")]
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct NativePlatformCapabilities {
#[serde(default)]
microphone: bool,
#[serde(default)]
audio_playback: bool,
}
/// Mirrors the iOS `capabilities` response.
#[cfg(target_os = "ios")]
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct NativePlatformCapabilities {
#[serde(default)]
microphone: bool,
#[serde(default)]
background_audio: bool,
}
impl From<NativePlatformCapabilities> for PlatformCallCapabilities {
fn from(native: NativePlatformCapabilities) -> Self {
// A native response is proof the platform lifecycle exists.
Self {
supported: true,
microphone: native.microphone,
#[cfg(target_os = "android")]
playback: native.audio_playback,
#[cfg(target_os = "ios")]
playback: native.background_audio,
}
}
}
#[derive(Clone)]
pub(crate) struct MobileBackend<R: Runtime> {
handle: PluginHandle<R>,
}
impl<R: Runtime> MobileBackend<R> {
pub(crate) fn new(handle: PluginHandle<R>) -> Self {
Self { handle }
}
pub(crate) fn platform_event_channel(
sender: mpsc::Sender<NativePlatformCallEvent>,
) -> Channel<NativePlatformCallEvent> {
Channel::new(move |body: InvokeResponseBody| {
if let Ok(event) = body.deserialize::<NativePlatformCallEvent>() {
let _ = sender.try_send(event);
}
Ok(())
})
}
pub(crate) async fn get_platform_call_capabilities(
&self,
) -> crate::Result<PlatformCallCapabilities> {
let native: NativePlatformCapabilities = self
.handle
.run_mobile_plugin_async(platform_commands::CAPABILITIES, ())
.await
.map_err(|_| Error::PlatformCallUnsupported)?;
Ok(native.into())
}
pub(crate) async fn start_platform_call_lifecycle(
&self,
request: NativeStartPlatformCallLifecycleRequest<'_>,
) -> crate::Result<()> {
self.handle
.run_mobile_plugin_async::<serde_json::Value>(platform_commands::START, request)
.await
.map(|_| ())
.map_err(|_| Error::PlatformCallStartFailed)
}
pub(crate) async fn stop_platform_call_lifecycle(
&self,
request: NativeStopPlatformCallLifecycleRequest<'_>,
) -> crate::Result<()> {
self.handle
.run_mobile_plugin_async::<serde_json::Value>(platform_commands::STOP, request)
.await
.map(|_| ())
.map_err(|_| Error::PlatformCallStopFailed)
}
}
/// Native start payload. The natives accept `{ sessionId, channel }` and
/// tolerate the extra `microphone`/`playback` flags, which the bridge forwards
/// so later stages do not need to re-extend the payload.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct NativeStartPlatformCallLifecycleRequest<'a> {
#[serde(flatten)]
pub fields: NativePlatformStartFields<'a>,
pub channel: Channel<NativePlatformCallEvent>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct NativeStopPlatformCallLifecycleRequest<'a> {
pub session_id: &'a str,
}
pub fn init<R: Runtime, C: DeserializeOwned>(
_app: &AppHandle<R>,
api: PluginApi<R, C>,
) -> crate::Result<MobileBackend<R>> {
#[cfg(target_os = "android")]
let handle = api.register_android_plugin(PLUGIN_IDENTIFIER, "CallLifecyclePlugin")?;
#[cfg(target_os = "ios")]
let handle = api.register_ios_plugin(init_plugin_call_lifecycle)?;
Ok(MobileBackend::new(handle))
}
@@ -1,385 +0,0 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformCallStateKind {
Idle,
Starting,
Active,
Stopping,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformCallRoute {
Earpiece,
Speaker,
Wired,
Bluetooth,
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformCallInterruption {
Began,
Ended,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformCallFailureCode {
Unsupported,
PermissionDenied,
AudioUnavailable,
StartFailed,
StopFailed,
StaleSession,
Busy,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum PlatformCallEventKind {
FocusChanged { focused: bool },
RouteChanged { route: PlatformCallRoute },
Interrupted { state: PlatformCallInterruption },
MediaReset,
Failed { code: PlatformCallFailureCode },
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlatformCallEvent {
pub revision: u64,
pub session_id: String,
#[serde(flatten)]
pub kind: PlatformCallEventKind,
}
/// Raw platform lifecycle event as emitted by the Android/iOS native plugins.
///
/// Native fields stay as strings at the boundary; the bridge maps them into the
/// bounded guest enums below, dropping unknown values instead of forwarding raw
/// native errors or device names.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NativePlatformCallEvent {
pub session_id: String,
#[serde(default)]
#[allow(dead_code)]
pub revision: Option<u64>,
pub event: String,
#[serde(default)]
pub focus: Option<String>,
#[serde(default)]
pub route: Option<String>,
#[serde(default)]
pub interruption: Option<String>,
#[serde(default)]
pub code: Option<String>,
}
impl NativePlatformCallEvent {
pub fn to_kind(&self) -> Option<PlatformCallEventKind> {
match self.event.as_str() {
// Android reports "gained"|"lost"|"ducked"; iOS reports "active"|"lost"|"regained".
"focus" => Some(PlatformCallEventKind::FocusChanged {
focused: matches!(
self.focus.as_deref(),
Some("gained" | "active" | "regained")
),
}),
// Union of Android (earpiece|speaker|wired|bluetooth|usb|unknown)
// and iOS (receiver|speaker|bluetooth|wired|other|none) routes.
"route" => Some(PlatformCallEventKind::RouteChanged {
route: match self.route.as_deref() {
Some("earpiece" | "receiver") => PlatformCallRoute::Earpiece,
Some("speaker") => PlatformCallRoute::Speaker,
Some("wired") => PlatformCallRoute::Wired,
Some("bluetooth") => PlatformCallRoute::Bluetooth,
_ => PlatformCallRoute::Unknown,
},
}),
"interruption" => Some(PlatformCallEventKind::Interrupted {
state: match self.interruption.as_deref() {
Some("began") => PlatformCallInterruption::Began,
_ => PlatformCallInterruption::Ended,
},
}),
"media_services_reset" => Some(PlatformCallEventKind::MediaReset),
// Android: invalid_request|busy|not_visible|permission_denied|
// audio_focus_failed|service_start_failed. iOS: busy|
// permission_denied|audio_session_failed|stop_failed.
"failure" => Some(PlatformCallEventKind::Failed {
code: match self.code.as_deref() {
Some("busy") => PlatformCallFailureCode::Busy,
Some("permission_denied") => PlatformCallFailureCode::PermissionDenied,
Some("audio_focus_failed" | "audio_session_failed") => {
PlatformCallFailureCode::AudioUnavailable
}
Some("stop_failed") => PlatformCallFailureCode::StopFailed,
_ => PlatformCallFailureCode::StartFailed,
},
}),
_ => None,
}
}
}
/// The media flags forwarded to the native platform-lifecycle plugins.
///
/// Kept in `models.rs` (not `mobile.rs`, which only compiles on mobile
/// targets) so the wire shape is regression-tested on the host.
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NativePlatformStartFields<'a> {
pub session_id: &'a str,
pub microphone: bool,
pub playback: bool,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StartPlatformCallLifecycleRequest {
pub session_id: String,
pub microphone: bool,
pub playback: bool,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StopPlatformCallLifecycleRequest {
pub session_id: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlatformCallCapabilities {
pub supported: bool,
pub microphone: bool,
pub playback: bool,
}
impl PlatformCallCapabilities {
pub fn current() -> Self {
let supported = cfg!(any(target_os = "android", target_os = "ios"));
Self {
supported,
microphone: supported,
playback: supported,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlatformCallState {
pub revision: u64,
pub state: PlatformCallStateKind,
pub session_id: Option<String>,
pub microphone: bool,
pub playback: bool,
pub capabilities: PlatformCallCapabilities,
}
#[cfg(test)]
mod tests {
use super::*;
fn native_event(event: &str) -> NativePlatformCallEvent {
NativePlatformCallEvent {
session_id: "session".into(),
revision: None,
event: event.into(),
focus: None,
route: None,
interruption: None,
code: None,
}
}
#[test]
fn native_focus_maps_to_bounded_focused_flag() {
for (raw, focused) in [
("gained", true),
("active", true),
("regained", true),
("lost", false),
("ducked", false),
] {
let mut event = native_event("focus");
event.focus = Some(raw.into());
assert_eq!(
event.to_kind(),
Some(PlatformCallEventKind::FocusChanged { focused }),
"focus {raw}"
);
}
assert_eq!(
native_event("focus").to_kind(),
Some(PlatformCallEventKind::FocusChanged { focused: false })
);
}
#[test]
fn native_route_maps_to_bounded_route_without_device_names() {
for (raw, route) in [
("earpiece", PlatformCallRoute::Earpiece),
("receiver", PlatformCallRoute::Earpiece),
("speaker", PlatformCallRoute::Speaker),
("wired", PlatformCallRoute::Wired),
("bluetooth", PlatformCallRoute::Bluetooth),
("usb", PlatformCallRoute::Unknown),
("other", PlatformCallRoute::Unknown),
("none", PlatformCallRoute::Unknown),
("bose-quietcomfort-35", PlatformCallRoute::Unknown),
] {
let mut event = native_event("route");
event.route = Some(raw.into());
assert_eq!(
event.to_kind(),
Some(PlatformCallEventKind::RouteChanged { route }),
"route {raw}"
);
}
}
#[test]
fn native_interruption_and_reset_map_to_bounded_variants() {
let mut began = native_event("interruption");
began.interruption = Some("began".into());
assert_eq!(
began.to_kind(),
Some(PlatformCallEventKind::Interrupted {
state: PlatformCallInterruption::Began
})
);
let mut ended = native_event("interruption");
ended.interruption = Some("ended".into());
assert_eq!(
ended.to_kind(),
Some(PlatformCallEventKind::Interrupted {
state: PlatformCallInterruption::Ended
})
);
assert_eq!(
native_event("media_services_reset").to_kind(),
Some(PlatformCallEventKind::MediaReset)
);
}
#[test]
fn native_failure_codes_map_to_safe_codes() {
for (raw, code) in [
("busy", PlatformCallFailureCode::Busy),
(
"permission_denied",
PlatformCallFailureCode::PermissionDenied,
),
(
"audio_focus_failed",
PlatformCallFailureCode::AudioUnavailable,
),
(
"audio_session_failed",
PlatformCallFailureCode::AudioUnavailable,
),
("stop_failed", PlatformCallFailureCode::StopFailed),
("invalid_request", PlatformCallFailureCode::StartFailed),
("not_visible", PlatformCallFailureCode::StartFailed),
("service_start_failed", PlatformCallFailureCode::StartFailed),
("Device is muted", PlatformCallFailureCode::StartFailed),
] {
let mut event = native_event("failure");
event.code = Some(raw.into());
assert_eq!(
event.to_kind(),
Some(PlatformCallEventKind::Failed { code }),
"code {raw}"
);
}
}
#[test]
fn unknown_native_event_is_dropped() {
assert_eq!(native_event("unknown_thing").to_kind(), None);
}
#[test]
fn native_start_fields_serialize_as_camel_case() {
let fields = NativePlatformStartFields {
session_id: "opaque-session",
microphone: true,
playback: false,
};
assert_eq!(
serde_json::to_value(fields).unwrap(),
serde_json::json!({
"sessionId": "opaque-session",
"microphone": true,
"playback": false
})
);
}
#[test]
fn native_event_deserializes_android_and_ios_payloads() {
let android: NativePlatformCallEvent = serde_json::from_value(serde_json::json!({
"sessionId": "s",
"revision": 3,
"event": "route",
"route": "usb"
}))
.unwrap();
assert_eq!(
android.to_kind(),
Some(PlatformCallEventKind::RouteChanged {
route: PlatformCallRoute::Unknown
})
);
let ios: NativePlatformCallEvent = serde_json::from_value(serde_json::json!({
"sessionId": "s",
"revision": 3,
"event": "interruption",
"interruption": "began"
}))
.unwrap();
assert_eq!(
ios.to_kind(),
Some(PlatformCallEventKind::Interrupted {
state: PlatformCallInterruption::Began
})
);
}
#[test]
fn platform_contract_serializes_only_bounded_wire_values() {
let event = serde_json::to_value(PlatformCallEvent {
revision: 4,
session_id: "opaque-session".into(),
kind: PlatformCallEventKind::RouteChanged {
route: PlatformCallRoute::Bluetooth,
},
})
.unwrap();
assert_eq!(
event,
serde_json::json!({
"revision": 4,
"sessionId": "opaque-session",
"type": "route_changed",
"route": "bluetooth"
})
);
assert!(serde_json::from_value::<PlatformCallEventKind>(
serde_json::json!({ "type": "failed", "code": "start_failed" })
)
.is_ok());
assert!(serde_json::from_value::<PlatformCallEventKind>(
serde_json::json!({ "type": "failed", "message": "raw native error" })
)
.is_err());
}
}
@@ -1,14 +0,0 @@
{
"compilerOptions": {
"target": "es2021",
"module": "esnext",
"moduleResolution": "bundler",
"skipLibCheck": true,
"strict": true,
"noUnusedLocals": true,
"noImplicitAny": true,
"noEmit": true
},
"include": ["guest-js/*.ts"],
"exclude": ["dist-js", "node_modules"]
}
-2
View File
@@ -347,8 +347,6 @@ pub fn run() {
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_dialog::init());
let builder = builder.plugin(tauri_plugin_call_lifecycle::init());
#[cfg(target_os = "ios")]
let builder = builder
.plugin(tauri_plugin_dialog::init())
-1
View File
@@ -20,7 +20,6 @@
"targets": "all",
"createUpdaterArtifacts": true,
"macOS": {
"minimumSystemVersion": "13.0",
"infoPlist": "Info.plist"
},
"iOS": {
-171
View File
@@ -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);
});
});
+2 -2
View File
@@ -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');
});
});
+4 -266
View File
@@ -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;
-8
View File
@@ -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);
});
}