From 12e24a3c0ed428f0e6eda268317753c497766705 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Wed, 29 Jul 2026 20:16:31 +0200 Subject: [PATCH] refactor(call): remove native lifecycle integration --- .cargo/config.toml | 2 - .gitignore | 3 - mise.toml | 2 +- package.json | 3 +- pnpm-lock.yaml | 10 - rust-toolchain.toml | 2 +- scripts/macos-bin/xcode-select | 10 - scripts/tauri.js | 129 +--- src-tauri/Cargo.lock | 48 +- src-tauri/Cargo.toml | 2 - src-tauri/capabilities/desktop.json | 3 +- src-tauri/capabilities/mobile.json | 3 +- .../tauri-plugin-call-lifecycle/.gitignore | 20 - .../tauri-plugin-call-lifecycle/Cargo.toml | 22 - .../android/build.gradle.kts | 33 - .../android/settings.gradle | 30 - .../android/src/main/AndroidManifest.xml | 17 - .../CallLifecycleForegroundService.kt | 103 --- .../call_lifecycle/CallLifecyclePlugin.kt | 469 ------------- .../tauri-plugin-call-lifecycle/build.rs | 13 - .../dist-js/index.cjs | 32 - .../dist-js/index.d.ts | 51 -- .../dist-js/index.js | 25 - .../guest-js/index.ts | 85 --- .../ios/Package.swift | 28 - .../ios/Sources/CallLifecyclePlugin.swift | 480 ------------- .../tauri-plugin-call-lifecycle/package.json | 30 - .../commands/getPlatformCallCapabilities.toml | 13 - .../commands/getPlatformCallState.toml | 13 - .../commands/startPlatformCallLifecycle.toml | 13 - .../commands/stopPlatformCallLifecycle.toml | 13 - .../permissions/autogenerated/reference.md | 124 ---- .../permissions/default.toml | 8 - .../permissions/schemas/schema.json | 354 ---------- .../rollup.config.js | 32 - .../tauri-plugin-call-lifecycle/src/actor.rs | 664 ------------------ .../src/commands.rs | 47 -- .../tauri-plugin-call-lifecycle/src/error.rs | 89 --- .../tauri-plugin-call-lifecycle/src/lib.rs | 53 -- .../tauri-plugin-call-lifecycle/src/mobile.rs | 151 ---- .../tauri-plugin-call-lifecycle/src/models.rs | 385 ---------- .../tauri-plugin-call-lifecycle/tsconfig.json | 14 - src-tauri/src/lib.rs | 2 - src-tauri/tauri.conf.json | 1 - src/app/components/SecretStorage.test.tsx | 171 ----- src/app/components/SecretStorage.tsx | 4 +- .../features/call/LivekitJsMediaTest.test.tsx | 17 - src/app/features/call/LivekitJsMediaTest.tsx | 1 - .../features/call/livekitJsController.test.ts | 492 +------------ src/app/features/call/livekitJsController.ts | 270 +------ src/app/generated/tauri/commands.ts | 8 - .../call/platformCallLifecycle.test.ts | 99 --- src/app/plugins/call/platformCallLifecycle.ts | 81 --- 53 files changed, 37 insertions(+), 4737 deletions(-) delete mode 100644 .cargo/config.toml delete mode 100755 scripts/macos-bin/xcode-select delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/.gitignore delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/Cargo.toml delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/android/build.gradle.kts delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/android/settings.gradle delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/android/src/main/AndroidManifest.xml delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/android/src/main/java/app/tauri/call_lifecycle/CallLifecycleForegroundService.kt delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/android/src/main/java/app/tauri/call_lifecycle/CallLifecyclePlugin.kt delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/build.rs delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/dist-js/index.cjs delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/dist-js/index.d.ts delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/dist-js/index.js delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/guest-js/index.ts delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/ios/Package.swift delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/ios/Sources/CallLifecyclePlugin.swift delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/package.json delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/getPlatformCallCapabilities.toml delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/getPlatformCallState.toml delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/startPlatformCallLifecycle.toml delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/stopPlatformCallLifecycle.toml delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/reference.md delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/default.toml delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/schemas/schema.json delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/rollup.config.js delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/src/actor.rs delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/src/commands.rs delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/src/error.rs delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/src/lib.rs delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/src/mobile.rs delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/src/models.rs delete mode 100644 src-tauri/plugins/tauri-plugin-call-lifecycle/tsconfig.json delete mode 100644 src/app/components/SecretStorage.test.tsx delete mode 100644 src/app/plugins/call/platformCallLifecycle.test.ts delete mode 100644 src/app/plugins/call/platformCallLifecycle.ts diff --git a/.cargo/config.toml b/.cargo/config.toml deleted file mode 100644 index 89cecbf33..000000000 --- a/.cargo/config.toml +++ /dev/null @@ -1,2 +0,0 @@ -[env] -MACOSX_DEPLOYMENT_TARGET = { value = "13.0", force = true } diff --git a/.gitignore b/.gitignore index 73e50380a..96e0abe44 100644 --- a/.gitignore +++ b/.gitignore @@ -69,6 +69,3 @@ result .direnv ## auto-generated pre-commit config .pre-commit-config.yaml - -# Local deepwork state -.slim/deepwork/ diff --git a/mise.toml b/mise.toml index a00ce0205..503fe0818 100644 --- a/mise.toml +++ b/mise.toml @@ -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" diff --git a/package.json b/package.json index e0b429072..1b298d9d6 100644 --- a/package.json +++ b/package.json @@ -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" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 199eb7f6f..3deb3da51 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -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: tauri-plugin-android-fs-api@28.4.0: 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} - teex@1.0.1: 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 - teex@1.0.1: dependencies: streamx: 2.28.0 diff --git a/rust-toolchain.toml b/rust-toolchain.toml index bea1926b8..59277fee7 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,3 +1,3 @@ [toolchain] -channel = "1.97" +channel = "1.97.1" components = ["clippy", "rustfmt"] diff --git a/scripts/macos-bin/xcode-select b/scripts/macos-bin/xcode-select deleted file mode 100755 index 3b33f9bb5..000000000 --- a/scripts/macos-bin/xcode-select +++ /dev/null @@ -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 "$@" diff --git a/scripts/tauri.js b/scripts/tauri.js index 91c6a31bc..52f340daa 100755 --- a/scripts/tauri.js +++ b/scripts/tauri.js @@ -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(); diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 9bff789ff..92cfcbb15 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -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]] diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 9b9cae991..d7985edf6 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -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 diff --git a/src-tauri/capabilities/desktop.json b/src-tauri/capabilities/desktop.json index f1f0662a5..f42f6888e 100644 --- a/src-tauri/capabilities/desktop.json +++ b/src-tauri/capabilities/desktop.json @@ -9,7 +9,6 @@ "store:default", "notifications:default", "process:default", - "dialog:default", - "call-lifecycle:default" + "dialog:default" ] } diff --git a/src-tauri/capabilities/mobile.json b/src-tauri/capabilities/mobile.json index 2413b617a..e5500a57d 100644 --- a/src-tauri/capabilities/mobile.json +++ b/src-tauri/capabilities/mobile.json @@ -8,7 +8,6 @@ "deep-link:default", "edge-to-edge:default", "notifications:default", - "sharekit:default", - "call-lifecycle:default" + "sharekit:default" ] } diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/.gitignore b/src-tauri/plugins/tauri-plugin-call-lifecycle/.gitignore deleted file mode 100644 index f23de25d2..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/.gitignore +++ /dev/null @@ -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/** diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/Cargo.toml b/src-tauri/plugins/tauri-plugin-call-lifecycle/Cargo.toml deleted file mode 100644 index c866a522e..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/Cargo.toml +++ /dev/null @@ -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"] } diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/android/build.gradle.kts b/src-tauri/plugins/tauri-plugin-call-lifecycle/android/build.gradle.kts deleted file mode 100644 index e30aabb33..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/android/build.gradle.kts +++ /dev/null @@ -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") -} diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/android/settings.gradle b/src-tauri/plugins/tauri-plugin-call-lifecycle/android/settings.gradle deleted file mode 100644 index 305f6f120..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/android/settings.gradle +++ /dev/null @@ -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') diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/android/src/main/AndroidManifest.xml b/src-tauri/plugins/tauri-plugin-call-lifecycle/android/src/main/AndroidManifest.xml deleted file mode 100644 index 4705edf1c..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/android/src/main/AndroidManifest.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/android/src/main/java/app/tauri/call_lifecycle/CallLifecycleForegroundService.kt b/src-tauri/plugins/tauri-plugin-call-lifecycle/android/src/main/java/app/tauri/call_lifecycle/CallLifecycleForegroundService.kt deleted file mode 100644 index 6fcee8c6b..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/android/src/main/java/app/tauri/call_lifecycle/CallLifecycleForegroundService.kt +++ /dev/null @@ -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 - } -} diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/android/src/main/java/app/tauri/call_lifecycle/CallLifecyclePlugin.kt b/src-tauri/plugins/tauri-plugin-call-lifecycle/android/src/main/java/app/tauri/call_lifecycle/CallLifecyclePlugin.kt deleted file mode 100644 index ebc426bd3..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/android/src/main/java/app/tauri/call_lifecycle/CallLifecyclePlugin.kt +++ /dev/null @@ -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() - 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) { - handlePlatformRouteChanged() - } - - override fun onAudioDevicesRemoved(removedDevices: Array) { - 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", - ) - } -} diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/build.rs b/src-tauri/plugins/tauri-plugin-call-lifecycle/build.rs deleted file mode 100644 index d3efaec2f..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/build.rs +++ /dev/null @@ -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(); -} diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/dist-js/index.cjs b/src-tauri/plugins/tauri-plugin-call-lifecycle/dist-js/index.cjs deleted file mode 100644 index 26ad43908..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/dist-js/index.cjs +++ /dev/null @@ -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; diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/dist-js/index.d.ts b/src-tauri/plugins/tauri-plugin-call-lifecycle/dist-js/index.d.ts deleted file mode 100644 index a796759aa..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/dist-js/index.d.ts +++ /dev/null @@ -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; -export declare function startPlatformCallLifecycle(request: StartPlatformCallLifecycleRequest): Promise; -export declare function stopPlatformCallLifecycle(request: StopPlatformCallLifecycleRequest): Promise; -export declare function getPlatformCallState(): Promise; -export declare function listenPlatformCallEvent(handler: (event: PlatformCallEvent) => void): Promise; diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/dist-js/index.js b/src-tauri/plugins/tauri-plugin-call-lifecycle/dist-js/index.js deleted file mode 100644 index 30cbe87f8..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/dist-js/index.js +++ /dev/null @@ -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 }; diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-call-lifecycle/guest-js/index.ts deleted file mode 100644 index 603079e29..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/guest-js/index.ts +++ /dev/null @@ -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 { - return await invoke( - 'plugin:call-lifecycle|getPlatformCallCapabilities' - ); -} - -export async function startPlatformCallLifecycle( - request: StartPlatformCallLifecycleRequest -): Promise { - return await invoke('plugin:call-lifecycle|startPlatformCallLifecycle', { - payload: request, - }); -} - -export async function stopPlatformCallLifecycle( - request: StopPlatformCallLifecycleRequest -): Promise { - return await invoke('plugin:call-lifecycle|stopPlatformCallLifecycle', { - payload: request, - }); -} - -export async function getPlatformCallState(): Promise { - return await invoke('plugin:call-lifecycle|getPlatformCallState'); -} - -export async function listenPlatformCallEvent( - handler: (event: PlatformCallEvent) => void -): Promise { - return await listen(PLATFORM_CALL_EVENT, ({ payload }) => handler(payload)); -} diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/ios/Package.swift b/src-tauri/plugins/tauri-plugin-call-lifecycle/ios/Package.swift deleted file mode 100644 index ac722f9e2..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/ios/Package.swift +++ /dev/null @@ -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") - ] -) diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/ios/Sources/CallLifecyclePlugin.swift b/src-tauri/plugins/tauri-plugin-call-lifecycle/ios/Sources/CallLifecyclePlugin.swift deleted file mode 100644 index aa5bdb418..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/ios/Sources/CallLifecyclePlugin.swift +++ /dev/null @@ -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() -} diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/package.json b/src-tauri/plugins/tauri-plugin-call-lifecycle/package.json deleted file mode 100644 index 050b253de..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/package.json +++ /dev/null @@ -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" - } -} diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/getPlatformCallCapabilities.toml b/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/getPlatformCallCapabilities.toml deleted file mode 100644 index 46d1aca39..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/getPlatformCallCapabilities.toml +++ /dev/null @@ -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"] diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/getPlatformCallState.toml b/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/getPlatformCallState.toml deleted file mode 100644 index 93cd8437a..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/getPlatformCallState.toml +++ /dev/null @@ -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"] diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/startPlatformCallLifecycle.toml b/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/startPlatformCallLifecycle.toml deleted file mode 100644 index 042ed7ab8..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/startPlatformCallLifecycle.toml +++ /dev/null @@ -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"] diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/stopPlatformCallLifecycle.toml b/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/stopPlatformCallLifecycle.toml deleted file mode 100644 index 4e8b712d7..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/stopPlatformCallLifecycle.toml +++ /dev/null @@ -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"] diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/reference.md b/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/reference.md deleted file mode 100644 index 7434973ca..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/reference.md +++ /dev/null @@ -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 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IdentifierDescription
- -`call-lifecycle:allow-getPlatformCallCapabilities` - - - -Enables the getPlatformCallCapabilities command without any pre-configured scope. - -
- -`call-lifecycle:deny-getPlatformCallCapabilities` - - - -Denies the getPlatformCallCapabilities command without any pre-configured scope. - -
- -`call-lifecycle:allow-getPlatformCallState` - - - -Enables the getPlatformCallState command without any pre-configured scope. - -
- -`call-lifecycle:deny-getPlatformCallState` - - - -Denies the getPlatformCallState command without any pre-configured scope. - -
- -`call-lifecycle:allow-startPlatformCallLifecycle` - - - -Enables the startPlatformCallLifecycle command without any pre-configured scope. - -
- -`call-lifecycle:deny-startPlatformCallLifecycle` - - - -Denies the startPlatformCallLifecycle command without any pre-configured scope. - -
- -`call-lifecycle:allow-stopPlatformCallLifecycle` - - - -Enables the stopPlatformCallLifecycle command without any pre-configured scope. - -
- -`call-lifecycle:deny-stopPlatformCallLifecycle` - - - -Denies the stopPlatformCallLifecycle command without any pre-configured scope. - -
diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/default.toml b/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/default.toml deleted file mode 100644 index d098ab4a8..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/default.toml +++ /dev/null @@ -1,8 +0,0 @@ -[default] -description = "Default permissions for the plugin" -permissions = [ - "allow-getPlatformCallCapabilities", - "allow-startPlatformCallLifecycle", - "allow-stopPlatformCallLifecycle", - "allow-getPlatformCallState", -] diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/schemas/schema.json deleted file mode 100644 index 1ffdb31df..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/schemas/schema.json +++ /dev/null @@ -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 `

` 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 `

` 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`" - } - ] - } - } -} \ No newline at end of file diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/rollup.config.js b/src-tauri/plugins/tauri-plugin-call-lifecycle/rollup.config.js deleted file mode 100644 index 118be066c..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/rollup.config.js +++ /dev/null @@ -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 || {}) - ] -} diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/actor.rs b/src-tauri/plugins/tauri-plugin-call-lifecycle/src/actor.rs deleted file mode 100644 index 165415f69..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/actor.rs +++ /dev/null @@ -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>), - StartPlatformCallLifecycle( - StartPlatformCallLifecycleRequest, - oneshot::Sender>, - ), - StopPlatformCallLifecycle( - StopPlatformCallLifecycleRequest, - oneshot::Sender>, - ), - GetPlatformCallState(oneshot::Sender>), -} - -#[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, - microphone: bool, - playback: bool, - capabilities: PlatformCallCapabilities, - last_session_id: Option, -} - -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 { - #[cfg(not(mobile))] - _runtime: PhantomData R>, - #[cfg(mobile)] - app: AppHandle, - commands: mpsc::Receiver, - #[cfg(mobile)] - internal_tx: mpsc::UnboundedSender, - #[cfg(mobile)] - internal_rx: mpsc::UnboundedReceiver, - #[cfg(mobile)] - mobile: MobileBackend, - platform: PlatformStateMachine, - #[cfg(mobile)] - platform_events_task: Option>, -} - -pub struct CallLifecycle { - commands: mpsc::Sender, - _runtime: PhantomData R>, -} - -impl CallLifecycle { - #[cfg(not(mobile))] - pub(crate) fn new(_app: AppHandle) -> Self { - let (commands, command_rx) = mpsc::channel(32); - async_runtime::spawn(run_actor::(command_rx)); - Self { - commands, - _runtime: PhantomData, - } - } - - #[cfg(mobile)] - pub(crate) fn new(app: AppHandle, mobile: MobileBackend) -> 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 { - 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 { - 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 { - 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 { - 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(commands: mpsc::Receiver) { - let mut actor: Actor = 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( - app: AppHandle, - commands: mpsc::Receiver, - internal_tx: mpsc::UnboundedSender, - internal_rx: mpsc::UnboundedReceiver, - mobile: MobileBackend, -) { - 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 Actor { - 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>, - ) { - #[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>, - ) { - 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>, - ) { - 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 - ); - } - } -} diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/commands.rs b/src-tauri/plugins/tauri-plugin-call-lifecycle/src/commands.rs deleted file mode 100644 index 334efd9fc..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/commands.rs +++ /dev/null @@ -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( - app: AppHandle, -) -> Result { - app.call_lifecycle().get_platform_call_capabilities().await -} - -#[allow(non_snake_case)] -#[tauri_command] -pub(crate) async fn startPlatformCallLifecycle( - app: AppHandle, - payload: StartPlatformCallLifecycleRequest, -) -> Result { - app.call_lifecycle() - .start_platform_call_lifecycle(payload) - .await -} - -#[allow(non_snake_case)] -#[tauri_command] -pub(crate) async fn stopPlatformCallLifecycle( - app: AppHandle, - payload: StopPlatformCallLifecycleRequest, -) -> Result { - app.call_lifecycle() - .stop_platform_call_lifecycle(payload) - .await -} - -#[allow(non_snake_case)] -#[tauri_command] -pub(crate) async fn getPlatformCallState( - app: AppHandle, -) -> Result { - app.call_lifecycle().get_platform_call_state().await -} diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/error.rs b/src-tauri/plugins/tauri-plugin-call-lifecycle/src/error.rs deleted file mode 100644 index a55c15ec3..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/error.rs +++ /dev/null @@ -1,89 +0,0 @@ -use serde::{ser::SerializeStruct, ser::Serializer, Serialize}; - -pub type Result = std::result::Result; - -#[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(&self, serializer: S) -> std::result::Result - 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" - ); - } -} diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/lib.rs b/src-tauri/plugins/tauri-plugin-call-lifecycle/src/lib.rs deleted file mode 100644 index 9c6e44938..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/lib.rs +++ /dev/null @@ -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 { - fn call_lifecycle(&self) -> &CallLifecycle; -} - -impl> crate::CallLifecycleExt for T { - fn call_lifecycle(&self) -> &CallLifecycle { - self.state::>().inner() - } -} - -/// Initializes the plugin. -pub fn init() -> TauriPlugin { - 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() -} diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/mobile.rs b/src-tauri/plugins/tauri-plugin-call-lifecycle/src/mobile.rs deleted file mode 100644 index de6e5f701..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/mobile.rs +++ /dev/null @@ -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 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 { - handle: PluginHandle, -} - -impl MobileBackend { - pub(crate) fn new(handle: PluginHandle) -> Self { - Self { handle } - } - - pub(crate) fn platform_event_channel( - sender: mpsc::Sender, - ) -> Channel { - Channel::new(move |body: InvokeResponseBody| { - if let Ok(event) = body.deserialize::() { - let _ = sender.try_send(event); - } - Ok(()) - }) - } - - pub(crate) async fn get_platform_call_capabilities( - &self, - ) -> crate::Result { - 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::(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::(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, -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct NativeStopPlatformCallLifecycleRequest<'a> { - pub session_id: &'a str, -} - -pub fn init( - _app: &AppHandle, - api: PluginApi, -) -> crate::Result> { - #[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)) -} diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/models.rs b/src-tauri/plugins/tauri-plugin-call-lifecycle/src/models.rs deleted file mode 100644 index cd80a144a..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/models.rs +++ /dev/null @@ -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, - pub event: String, - #[serde(default)] - pub focus: Option, - #[serde(default)] - pub route: Option, - #[serde(default)] - pub interruption: Option, - #[serde(default)] - pub code: Option, -} - -impl NativePlatformCallEvent { - pub fn to_kind(&self) -> Option { - 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, - 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::( - serde_json::json!({ "type": "failed", "code": "start_failed" }) - ) - .is_ok()); - assert!(serde_json::from_value::( - serde_json::json!({ "type": "failed", "message": "raw native error" }) - ) - .is_err()); - } -} diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/tsconfig.json b/src-tauri/plugins/tauri-plugin-call-lifecycle/tsconfig.json deleted file mode 100644 index 059112270..000000000 --- a/src-tauri/plugins/tauri-plugin-call-lifecycle/tsconfig.json +++ /dev/null @@ -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"] -} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 6b70a0d73..20fa2fb6e 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -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()) diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 0901c0a5f..7fb809737 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -20,7 +20,6 @@ "targets": "all", "createUpdaterArtifacts": true, "macOS": { - "minimumSystemVersion": "13.0", "infoPlist": "Info.plist" }, "iOS": { diff --git a/src/app/components/SecretStorage.test.tsx b/src/app/components/SecretStorage.test.tsx deleted file mode 100644 index aca70f2aa..000000000 --- a/src/app/components/SecretStorage.test.tsx +++ /dev/null @@ -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>(async () => new Uint8Array([4, 5, 6])) -); -const checkKey = vi.hoisted(() => vi.fn<() => Promise>()); - -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( - - ); - - 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( - - ); - - 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( - - ); - - 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( - - ); - - 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( - - ); - - 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( - - ); - - 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( - - ); - - submitRecoveryKey('correct passphrase'); - - await waitFor(() => expect(onDecodedRecoveryKey).toHaveBeenCalledTimes(1)); - expect(onDecodedRecoveryKey).toHaveBeenCalledWith(validKey); - }); -}); diff --git a/src/app/components/SecretStorage.tsx b/src/app/components/SecretStorage.tsx index 6bfc66681..1b63d1087 100644 --- a/src/app/components/SecretStorage.tsx +++ b/src/app/components/SecretStorage.tsx @@ -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); } diff --git a/src/app/features/call/LivekitJsMediaTest.test.tsx b/src/app/features/call/LivekitJsMediaTest.test.tsx index 764f58cfe..84e6d249b 100644 --- a/src/app/features/call/LivekitJsMediaTest.test.tsx +++ b/src/app/features/call/LivekitJsMediaTest.test.tsx @@ -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>() - .mockRejectedValue({ code: 'platform-lifecycle-failed', message: 'raw native detail' }); - render( - {}} /> - ); - - 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(); diff --git a/src/app/features/call/LivekitJsMediaTest.tsx b/src/app/features/call/LivekitJsMediaTest.tsx index 15dc44028..1ea9325a9 100644 --- a/src/app/features/call/LivekitJsMediaTest.tsx +++ b/src/app/features/call/LivekitJsMediaTest.tsx @@ -47,7 +47,6 @@ const mediaFailureMessages: Record = { '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.', }; diff --git a/src/app/features/call/livekitJsController.test.ts b/src/app/features/call/livekitJsController.test.ts index a48698acf..d048e5090 100644 --- a/src/app/features/call/livekitJsController.test.ts +++ b/src/app/features/call/livekitJsController.test.ts @@ -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>(), - getPlatformState: vi.fn<() => Promise>(), - onPlatformCallEvent: vi.fn<() => Promise>(), - startPlatformLifecycle: vi.fn<() => Promise>(), - stopPlatformLifecycle: vi.fn<() => Promise>(), -})); - -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>; - start: Mock<(request: LivekitJsPlatformStartRequest) => Promise>; - stop: Mock<(request: { sessionId: string }) => Promise>; - emit: (event: PlatformCallEvent) => void; -}; - -const makePlatform = (supported: boolean, order: string[]): FakePlatform => { - let handler: ((event: PlatformCallEvent) => void) | undefined; - const getCapabilities = vi.fn<() => Promise>().mockImplementation(async () => { - order.push('platform-caps'); - return { supported, microphone: supported, playback: supported }; - }); - const start = vi - .fn<(request: LivekitJsPlatformStartRequest) => Promise>() - .mockImplementation(async (request) => { - order.push(`platform-start:${request.microphone}:${request.playback}`); - return { sessionId: request.sessionId }; - }); - const stop = vi - .fn<(request: { sessionId: string }) => Promise>() - .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'); - }); }); diff --git a/src/app/features/call/livekitJsController.ts b/src/app/features/call/livekitJsController.ts index da7d99e3d..276295019 100644 --- a/src/app/features/call/livekitJsController.ts +++ b/src/app/features/call/livekitJsController.ts @@ -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; }; -export type LivekitJsPlatformStartRequest = { - sessionId: string; - microphone: boolean; - playback: boolean; -}; - -export type LivekitJsPlatformBridge = { - getCapabilities: () => Promise; - start: (request: LivekitJsPlatformStartRequest) => Promise; - stop: (request: { sessionId: string }) => Promise; - 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; }; @@ -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; - platformActive: boolean; - platformFlags: { microphone: boolean; playback: boolean }; - platformDesired: { microphone: boolean; playback: boolean }; - platformRevision: number; - platformUnlisten?: () => void; - platformEventOp?: Promise; mediaPublished: boolean; cleanupPromise?: Promise; resourcesReady: Promise; @@ -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 => { - 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) => { - 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 => { - if (!current.platformCaps) { - current.platformCaps = platformBridge.getCapabilities(); - } - return current.platformCaps; - }; - - const applyPlatformEvent = async ( - current: ControllerRecord, - event: PlatformCallEvent - ): Promise => { - 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 => { - 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 => { - 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, - platformOrder: 'platform-first' | 'platform-after' = 'platform-first' + action: (participant: LivekitLocalParticipantLike) => Promise ): Promise => { - 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 => { - 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 => + 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 => 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; diff --git a/src/app/generated/tauri/commands.ts b/src/app/generated/tauri/commands.ts index f402febf8..1c22a5f8b 100644 --- a/src/app/generated/tauri/commands.ts +++ b/src/app/generated/tauri/commands.ts @@ -106,18 +106,10 @@ export async function showSnapOverlay(): Promise { return invoke('show_snap_overlay'); } -export async function startCallForegroundService(): Promise { - return invoke('start_call_foreground_service'); -} - export async function startWindowTrackingWithTarget(params: types.StartWindowTrackingWithTargetParams): Promise { return invoke('start_window_tracking_with_target', params); } -export async function stopCallForegroundService(): Promise { - return invoke('stop_call_foreground_service'); -} - export async function stopWindowTracking(): Promise { return invoke('stop_window_tracking'); } diff --git a/src/app/plugins/call/platformCallLifecycle.test.ts b/src/app/plugins/call/platformCallLifecycle.test.ts deleted file mode 100644 index b4c743f03..000000000 --- a/src/app/plugins/call/platformCallLifecycle.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest'; - -const pluginGetCapabilities = vi.hoisted(() => vi.fn<() => Promise>()); -const pluginGetState = vi.hoisted(() => vi.fn<() => Promise>()); -const pluginListenEvent = vi.hoisted(() => - vi.fn<(handler: (event: unknown) => void) => Promise>() -); -const pluginStart = vi.hoisted(() => vi.fn<(request: unknown) => Promise>()); -const pluginStop = vi.hoisted(() => vi.fn<(request: unknown) => Promise>()); - -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); - }); -}); diff --git a/src/app/plugins/call/platformCallLifecycle.ts b/src/app/plugins/call/platformCallLifecycle.ts deleted file mode 100644 index 3b73c3bab..000000000 --- a/src/app/plugins/call/platformCallLifecycle.ts +++ /dev/null @@ -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(['earpiece', 'speaker', 'wired', 'bluetooth', 'unknown']); - -const FAILURE_CODES = new Set([ - '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; - 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 { - return pluginListenEvent((payload) => { - if (isBoundedEvent(payload)) handler(payload); - }); -}