()
+ 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 connect(_ invoke: Invoke) throws {
let args = try invoke.parseArgs(ConnectArgs.self)
@@ -86,6 +197,48 @@ final class CallLifecyclePlugin: Plugin, RoomDelegate {
}
}
+ @objc public func setMediaEnabled(_ invoke: Invoke) throws {
+ let args = try invoke.parseArgs(SetMediaEnabledArgs.self)
+ Task { @MainActor [weak self] in
+ await self?.setMediaEnabled(args, invoke: invoke)
+ }
+ }
+
+ @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 connect(_ args: ConnectArgs, invoke: Invoke) async {
generation &+= 1
@@ -175,6 +328,112 @@ final class CallLifecyclePlugin: Plugin, RoomDelegate {
invoke.resolve(ConnectResponse(operationId: args.operationId, connectionId: args.connectionId))
}
+ @MainActor
+ private func start(_ args: PlatformStartArgs, invoke: Invoke) async {
+ if room != nil {
+ rejectPlatformStart(
+ sessionId: args.sessionId,
+ channel: args.channel,
+ code: .busy,
+ invoke: invoke
+ )
+ return
+ }
+
+ 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 disconnect(_ args: DisconnectArgs, invoke: Invoke) async {
guard let activeRoom = room,
@@ -205,6 +464,48 @@ final class CallLifecyclePlugin: Plugin, RoomDelegate {
invoke.resolve(ConnectResponse(operationId: args.operationId, connectionId: args.connectionId))
}
+ @MainActor
+ private func setMediaEnabled(_ args: SetMediaEnabledArgs, invoke: Invoke) async {
+ let code = args.kind.failureCode
+ guard let activeRoom = room,
+ operationId == args.operationId,
+ connectionId == args.connectionId
+ else {
+ invoke.reject("Native call media toggle failed.", code: code.rawValue)
+ return
+ }
+
+ // ReplayKit broadcast support is not implemented; screen share is
+ // explicitly unsupported on iOS.
+ guard args.kind != .screenShare else {
+ invoke.reject("Screen share is not supported on iOS.", code: code.rawValue)
+ return
+ }
+
+ do {
+ switch args.kind {
+ case .microphone:
+ if args.enabled {
+ try await requestMicrophoneAndConfigureAudio()
+ }
+ try await activeRoom.localParticipant.setMicrophone(enabled: args.enabled)
+ case .camera:
+ if args.enabled {
+ guard await requestCameraPermission() else { throw SetupError.denied }
+ }
+ try await activeRoom.localParticipant.setCamera(enabled: args.enabled)
+ case .screenShare:
+ throw SetupError.denied
+ }
+ } catch {
+ invoke.reject("Native call media toggle failed.", code: code.rawValue)
+ return
+ }
+
+ invoke.resolve(
+ ConnectResponse(operationId: args.operationId, connectionId: args.connectionId))
+ }
+
@MainActor
private func fail(
_ failure: SetupFailure,
@@ -263,6 +564,251 @@ final class CallLifecyclePlugin: Plugin, RoomDelegate {
try session.setActive(true)
}
+ @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 }
+ let value = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
+ let type = value.flatMap(AVAudioSession.InterruptionType.init(rawValue:))
+ 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
+ }
+ }
+
@MainActor
private func requestCameraPermission() async -> Bool {
switch AVCaptureDevice.authorizationStatus(for: .video) {
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
new file mode 100644
index 000000000..46d1aca39
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/getPlatformCallCapabilities.toml
@@ -0,0 +1,13 @@
+# 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
new file mode 100644
index 000000000..93cd8437a
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/getPlatformCallState.toml
@@ -0,0 +1,13 @@
+# 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/set_media_enabled.toml b/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/set_media_enabled.toml
new file mode 100644
index 000000000..98d0d76a6
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/set_media_enabled.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-set-media-enabled"
+description = "Enables the set_media_enabled command without any pre-configured scope."
+commands.allow = ["set_media_enabled"]
+
+[[permission]]
+identifier = "deny-set-media-enabled"
+description = "Denies the set_media_enabled command without any pre-configured scope."
+commands.deny = ["set_media_enabled"]
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
new file mode 100644
index 000000000..042ed7ab8
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/startPlatformCallLifecycle.toml
@@ -0,0 +1,13 @@
+# 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
new file mode 100644
index 000000000..4e8b712d7
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/commands/stopPlatformCallLifecycle.toml
@@ -0,0 +1,13 @@
+# 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
index 1ea007202..718d1c16d 100644
--- a/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/reference.md
+++ b/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/autogenerated/reference.md
@@ -6,7 +6,12 @@ Default permissions for the plugin
- `allow-connect`
- `allow-disconnect`
+- `allow-set-media-enabled`
- `allow-get-state`
+- `allow-getPlatformCallCapabilities`
+- `allow-startPlatformCallLifecycle`
+- `allow-stopPlatformCallLifecycle`
+- `allow-getPlatformCallState`
## Permission Table
@@ -72,6 +77,58 @@ Denies the disconnect command without any pre-configured scope.
|
+`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-get-state`
|
@@ -92,6 +149,84 @@ Enables the get_state command without any pre-configured scope.
Denies the get_state command without any pre-configured scope.
+
+
+
+
+|
+
+`call-lifecycle:allow-set-media-enabled`
+
+ |
+
+
+Enables the set_media_enabled command without any pre-configured scope.
+
+ |
+
+
+
+|
+
+`call-lifecycle:deny-set-media-enabled`
+
+ |
+
+
+Denies the set_media_enabled 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
index ada76b365..5d9ad298f 100644
--- a/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/default.toml
+++ b/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/default.toml
@@ -1,3 +1,12 @@
[default]
description = "Default permissions for the plugin"
-permissions = ["allow-connect", "allow-disconnect", "allow-get-state"]
+permissions = [
+ "allow-connect",
+ "allow-disconnect",
+ "allow-set-media-enabled",
+ "allow-get-state",
+ "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
index 3561320b3..27dcd64df 100644
--- a/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/schemas/schema.json
+++ b/src-tauri/plugins/tauri-plugin-call-lifecycle/permissions/schemas/schema.json
@@ -318,6 +318,30 @@
"const": "deny-disconnect",
"markdownDescription": "Denies the disconnect command without any pre-configured scope."
},
+ {
+ "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 get_state command without any pre-configured scope.",
"type": "string",
@@ -331,10 +355,46 @@
"markdownDescription": "Denies the get_state command without any pre-configured scope."
},
{
- "description": "Default permissions for the plugin\n#### This default permission set includes:\n\n- `allow-connect`\n- `allow-disconnect`\n- `allow-get-state`",
+ "description": "Enables the set_media_enabled command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-set-media-enabled",
+ "markdownDescription": "Enables the set_media_enabled command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the set_media_enabled command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-set-media-enabled",
+ "markdownDescription": "Denies the set_media_enabled 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-connect`\n- `allow-disconnect`\n- `allow-set-media-enabled`\n- `allow-get-state`\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-connect`\n- `allow-disconnect`\n- `allow-get-state`"
+ "markdownDescription": "Default permissions for the plugin\n#### This default permission set includes:\n\n- `allow-connect`\n- `allow-disconnect`\n- `allow-set-media-enabled`\n- `allow-get-state`\n- `allow-getPlatformCallCapabilities`\n- `allow-startPlatformCallLifecycle`\n- `allow-stopPlatformCallLifecycle`\n- `allow-getPlatformCallState`"
}
]
}
diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/actor.rs b/src-tauri/plugins/tauri-plugin-call-lifecycle/src/actor.rs
index 3136c5eab..2ceb9407c 100644
--- a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/actor.rs
+++ b/src-tauri/plugins/tauri-plugin-call-lifecycle/src/actor.rs
@@ -10,6 +10,7 @@ use tokio::sync::{mpsc, oneshot};
#[cfg(mobile)]
use crate::mobile::{
MobileBackend, NativeConnectRequest, NativeControlEvent, NativeControlEventKind,
+ NativeStartPlatformCallLifecycleRequest, NativeStopPlatformCallLifecycleRequest,
};
#[cfg(test)]
@@ -21,6 +22,13 @@ use std::sync::{
use crate::error::{Error, Result};
use crate::models::{
CallLifecycleError, CallState, ConnectRequest, ConnectionState, DisconnectRequest,
+ MediaCapabilities, MediaKind, MediaState, PlatformCallCapabilities, PlatformCallState,
+ PlatformCallStateKind, SetMediaEnabledRequest, StartPlatformCallLifecycleRequest,
+ StopPlatformCallLifecycleRequest,
+};
+#[cfg(mobile)]
+use crate::models::{
+ NativePlatformCallEvent, NativePlatformStartFields, PlatformCallEvent, PlatformCallEventKind,
};
#[cfg(target_os = "linux")]
@@ -66,6 +74,8 @@ enum ScreenShareFailureEvent {
pub(crate) const STATE_EVENT: &str = "plugin:call-lifecycle://state";
pub(crate) const ERROR_EVENT: &str = "plugin:call-lifecycle://error";
+#[cfg(mobile)]
+pub(crate) const PLATFORM_CALL_EVENT: &str = "plugin:call-lifecycle://platform-event";
#[cfg(not(any(target_os = "android", target_os = "ios")))]
type RoomEvents = mpsc::UnboundedReceiver;
@@ -117,7 +127,18 @@ impl OwnedRoom {
pub(crate) enum Command {
Connect(ConnectRequest, oneshot::Sender>),
Disconnect(DisconnectRequest, oneshot::Sender>),
+ SetMediaEnabled(SetMediaEnabledRequest, oneshot::Sender>),
GetState(oneshot::Sender),
+ GetPlatformCallCapabilities(oneshot::Sender>),
+ StartPlatformCallLifecycle(
+ StartPlatformCallLifecycleRequest,
+ oneshot::Sender>,
+ ),
+ StopPlatformCallLifecycle(
+ StopPlatformCallLifecycleRequest,
+ oneshot::Sender>,
+ ),
+ GetPlatformCallState(oneshot::Sender>),
}
enum InternalMessage {
@@ -126,6 +147,8 @@ enum InternalMessage {
operation_id: String,
room: Option,
},
+ #[cfg(mobile)]
+ PlatformCallEvent(NativePlatformCallEvent),
}
struct PendingConnection {
@@ -210,6 +233,15 @@ impl CallLifecycle {
result.await.map_err(|_| Error::ActorUnavailable)?
}
+ pub async fn set_media_enabled(&self, request: SetMediaEnabledRequest) -> Result {
+ let (response, result) = oneshot::channel();
+ self.commands
+ .send(Command::SetMediaEnabled(request, response))
+ .await
+ .map_err(|_| Error::ActorUnavailable)?;
+ result.await.map_err(|_| Error::ActorUnavailable)?
+ }
+
pub async fn get_state(&self) -> Result {
let (response, result) = oneshot::channel();
self.commands
@@ -218,6 +250,48 @@ impl CallLifecycle {
.map_err(|_| Error::ActorUnavailable)?;
result.await.map_err(|_| Error::ActorUnavailable)
}
+
+ 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)?
+ }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -245,11 +319,20 @@ fn event_matches_generation(
active_operation_id == event_operation_id && active_connection_id == event_connection_id
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum MediaToggleDecision {
+ Apply,
+ Idempotent,
+ Stale,
+ Unsupported,
+}
+
#[derive(Debug, Clone)]
struct StateMachine {
state: ConnectionState,
revision: u64,
connection_id: Option,
+ media: MediaState,
}
impl Default for StateMachine {
@@ -258,6 +341,7 @@ impl Default for StateMachine {
state: ConnectionState::Idle,
revision: 0,
connection_id: None,
+ media: MediaState::default(),
}
}
}
@@ -268,6 +352,8 @@ impl StateMachine {
revision: self.revision,
state: self.state,
connection_id: self.connection_id.clone(),
+ media: self.media,
+ capabilities: MediaCapabilities::current(),
}
}
@@ -300,6 +386,165 @@ impl StateMachine {
self.revision += 1;
self.state = state;
self.connection_id = connection_id;
+ if !matches!(
+ state,
+ ConnectionState::Connected | ConnectionState::Reconnecting
+ ) {
+ self.media = MediaState::default();
+ }
+ }
+
+ fn confirm_media(&mut self, kind: MediaKind, enabled: bool) {
+ self.revision += 1;
+ self.media.set(kind, enabled);
+ }
+
+ fn media_decision(&self, request: &SetMediaEnabledRequest) -> MediaToggleDecision {
+ if self.connection_id.as_deref() != Some(request.connection_id.as_str()) {
+ return MediaToggleDecision::Stale;
+ }
+ if !matches!(
+ self.state,
+ ConnectionState::Connected | ConnectionState::Reconnecting
+ ) {
+ return MediaToggleDecision::Stale;
+ }
+ if !MediaCapabilities::current().supports(request.kind) {
+ return MediaToggleDecision::Unsupported;
+ }
+ if self.media.enabled(request.kind) == request.enabled {
+ return MediaToggleDecision::Idempotent;
+ }
+ MediaToggleDecision::Apply
+ }
+}
+
+#[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;
}
}
@@ -319,6 +564,9 @@ struct Actor {
audio_failure: Option>,
camera_failure: Option>,
screen_share_failure: Option>,
+ platform: PlatformStateMachine,
+ #[cfg(mobile)]
+ platform_events_task: Option>,
}
async fn run_actor(
@@ -341,6 +589,9 @@ async fn run_actor(
audio_failure: None,
camera_failure: None,
screen_share_failure: None,
+ platform: PlatformStateMachine::default(),
+ #[cfg(mobile)]
+ platform_events_task: None,
};
actor.emit_state();
@@ -491,9 +742,26 @@ impl Actor {
Command::Disconnect(request, response) => {
self.handle_disconnect(request, response).await
}
+ Command::SetMediaEnabled(request, response) => {
+ self.handle_set_media_enabled(request, response).await
+ }
Command::GetState(response) => {
let _ = response.send(self.machine.snapshot());
}
+ 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()));
+ }
}
}
@@ -502,6 +770,14 @@ impl Actor {
request: ConnectRequest,
response: oneshot::Sender>,
) {
+ // Mutual exclusion with the platform lifecycle: a native room cannot
+ // start while a platform call session owns the audio session.
+ if self.platform.session_id.is_some() {
+ let error = Error::Busy;
+ self.emit_error(&error, Some(request.connection_id));
+ let _ = response.send(Err(error));
+ return;
+ }
match self.machine.connect_decision(&request.connection_id) {
ConnectDecision::Same => {
let _ = response.send(Ok(self.machine.snapshot()));
@@ -649,8 +925,211 @@ impl Actor {
}
}
+ async fn handle_set_media_enabled(
+ &mut self,
+ request: SetMediaEnabledRequest,
+ response: oneshot::Sender>,
+ ) {
+ match self.machine.media_decision(&request) {
+ MediaToggleDecision::Idempotent => {
+ let _ = response.send(Ok(self.machine.snapshot()));
+ }
+ MediaToggleDecision::Stale => {
+ let error = Error::StaleConnection;
+ self.emit_error(&error, Some(request.connection_id));
+ let _ = response.send(Err(error));
+ }
+ MediaToggleDecision::Unsupported => {
+ let error = Error::MediaUnsupported;
+ self.emit_error(&error, Some(request.connection_id));
+ let _ = response.send(Err(error));
+ }
+ MediaToggleDecision::Apply => self.apply_media_toggle(request, response).await,
+ }
+ }
+
+ async fn apply_media_toggle(
+ &mut self,
+ request: SetMediaEnabledRequest,
+ response: oneshot::Sender>,
+ ) {
+ let connection_id = request.connection_id.clone();
+ let Some(active) = self.active.as_mut() else {
+ let error = Error::StaleConnection;
+ self.emit_error(&error, Some(connection_id));
+ let _ = response.send(Err(error));
+ return;
+ };
+ let enabled = request.enabled;
+ let outcome = match request.kind {
+ MediaKind::Microphone => {
+ toggle_microphone(active, &mut self.audio_failure, enabled).await
+ }
+ MediaKind::Camera => toggle_camera(active, &mut self.camera_failure, enabled).await,
+ MediaKind::ScreenShare => {
+ toggle_screen_share(active, &mut self.screen_share_failure, enabled, &self.app)
+ .await
+ }
+ };
+ match outcome {
+ Ok(()) => {
+ self.machine.confirm_media(request.kind, request.enabled);
+ self.emit_state();
+ let _ = response.send(Ok(self.machine.snapshot()));
+ }
+ Err(error) => {
+ self.emit_error(&error, Some(connection_id));
+ let _ = response.send(Err(error));
+ }
+ }
+ }
+
+ 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 => {
+ // The native-room mode and the platform lifecycle are mutually
+ // exclusive: both platforms own a single audio session.
+ if self.pending.is_some() || self.active.is_some() {
+ let error = Error::PlatformCallBusy;
+ self.emit_error(&error, None);
+ let _ = response.send(Err(error));
+ return;
+ }
+
+ #[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));
+ }
+ }
+ }
+ }
+ }
+
async fn handle_internal(&mut self, message: InternalMessage) {
match message {
+ #[cfg(mobile)]
+ InternalMessage::PlatformCallEvent(event) => {
+ self.handle_platform_call_event(event);
+ }
InternalMessage::ConnectFinished {
connection_id,
operation_id,
@@ -787,6 +1266,18 @@ impl Actor {
self.screen_share_failure = screen_share_failure;
}
+ #[allow(unused_mut)]
+ let mut media = MediaState::default();
+ #[cfg(target_os = "linux")]
+ {
+ media.microphone = audio.is_some();
+ }
+ #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
+ {
+ media.camera = camera.is_some();
+ media.screen_share = screen_share.is_some();
+ }
+
self.active = Some(ActiveConnection {
connection_id: connection_id.clone(),
operation_id,
@@ -804,12 +1295,36 @@ impl Actor {
#[cfg(test)]
screen_share_shutdown_marker: None,
});
+ // Media is only confirmed once the sessions above have started.
+ self.machine.media = media;
self.transition(ConnectionState::Connected, Some(connection_id));
let _ = pending.response.send(Ok(self.machine.snapshot()));
}
}
}
+ #[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 handle_audio_failure(&mut self) {
#[cfg(not(target_os = "linux"))]
{
@@ -980,6 +1495,11 @@ impl Actor {
}
async fn cleanup(&mut self) {
+ #[cfg(mobile)]
+ if let Some(task) = self.platform_events_task.take() {
+ task.abort();
+ let _ = task.await;
+ }
if let Some(pending) = self.pending.take() {
pending.task.abort();
let _ = pending.task.await;
@@ -995,6 +1515,176 @@ impl Actor {
}
}
+#[cfg(target_os = "linux")]
+async fn toggle_microphone(
+ active: &mut ActiveConnection,
+ audio_failure: &mut Option>,
+ enabled: bool,
+) -> Result<()> {
+ if enabled {
+ let result = match &active.room {
+ OwnedRoom::LiveKit(room) => AudioSession::start(room).await,
+ #[cfg(test)]
+ OwnedRoom::Fake(_) => Err("audio requires a live room".to_owned()),
+ #[cfg(test)]
+ OwnedRoom::FakeOrdered(_) => Err("audio requires a live room".to_owned()),
+ };
+ match result {
+ Ok((audio, failure_rx)) => {
+ active.audio = Some(audio);
+ *audio_failure = Some(failure_rx);
+ Ok(())
+ }
+ Err(_) => Err(Error::AudioFailed),
+ }
+ } else {
+ audio_failure.take();
+ if let Some(mut audio) = active.audio.take() {
+ audio.shutdown().await;
+ }
+ Ok(())
+ }
+}
+
+#[cfg(all(
+ not(target_os = "linux"),
+ not(any(target_os = "android", target_os = "ios"))
+))]
+async fn toggle_microphone(
+ active: &mut ActiveConnection,
+ _audio_failure: &mut Option>,
+ enabled: bool,
+) -> Result<()> {
+ let _ = (active, enabled);
+ Err(Error::MediaUnsupported)
+}
+
+#[cfg(mobile)]
+async fn toggle_microphone(
+ active: &mut ActiveConnection,
+ _audio_failure: &mut Option>,
+ enabled: bool,
+) -> Result<()> {
+ active
+ .room
+ .set_media_enabled(
+ &active.operation_id,
+ &active.connection_id,
+ MediaKind::Microphone,
+ enabled,
+ )
+ .await
+}
+
+#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
+async fn toggle_camera(
+ active: &mut ActiveConnection,
+ camera_failure: &mut Option>,
+ enabled: bool,
+) -> Result<()> {
+ if enabled {
+ let result = match &active.room {
+ OwnedRoom::LiveKit(room) => CameraSession::start(room).await,
+ #[cfg(test)]
+ OwnedRoom::Fake(_) => Err("camera requires a live room".to_owned()),
+ #[cfg(test)]
+ OwnedRoom::FakeOrdered(_) => Err("camera requires a live room".to_owned()),
+ };
+ match result {
+ Ok((camera, failure_rx)) => {
+ active.camera = Some(camera);
+ *camera_failure = Some(failure_rx);
+ Ok(())
+ }
+ Err(_) => Err(Error::CameraFailed),
+ }
+ } else {
+ camera_failure.take();
+ if let Some(mut camera) = active.camera.take() {
+ camera.shutdown().await;
+ }
+ Ok(())
+ }
+}
+
+#[cfg(mobile)]
+async fn toggle_camera(
+ active: &mut ActiveConnection,
+ _camera_failure: &mut Option>,
+ enabled: bool,
+) -> Result<()> {
+ active
+ .room
+ .set_media_enabled(
+ &active.operation_id,
+ &active.connection_id,
+ MediaKind::Camera,
+ enabled,
+ )
+ .await
+}
+
+#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
+async fn toggle_screen_share(
+ active: &mut ActiveConnection,
+ screen_share_failure: &mut Option>,
+ enabled: bool,
+ app: &AppHandle,
+) -> Result<()> {
+ if enabled {
+ let result = match &active.room {
+ OwnedRoom::LiveKit(room) => {
+ #[cfg(target_os = "windows")]
+ {
+ ScreenShareSession::start(app, room).await
+ }
+ #[cfg(not(target_os = "windows"))]
+ {
+ let _ = app;
+ ScreenShareSession::start(room).await
+ }
+ }
+ #[cfg(test)]
+ OwnedRoom::Fake(_) => Err("screen share requires a live room".to_owned()),
+ #[cfg(test)]
+ OwnedRoom::FakeOrdered(_) => Err("screen share requires a live room".to_owned()),
+ };
+ match result {
+ Ok((screen_share, failure_rx)) => {
+ active.screen_share = Some(screen_share);
+ *screen_share_failure = Some(failure_rx);
+ Ok(())
+ }
+ Err(_) => Err(Error::ScreenShareFailed),
+ }
+ } else {
+ let _ = app;
+ screen_share_failure.take();
+ if let Some(mut screen_share) = active.screen_share.take() {
+ screen_share.shutdown().await;
+ }
+ Ok(())
+ }
+}
+
+#[cfg(mobile)]
+async fn toggle_screen_share(
+ active: &mut ActiveConnection,
+ _screen_share_failure: &mut Option>,
+ enabled: bool,
+ _app: &AppHandle,
+) -> Result<()> {
+ active
+ .room
+ .set_media_enabled(
+ &active.operation_id,
+ &active.connection_id,
+ MediaKind::ScreenShare,
+ enabled,
+ )
+ .await
+}
+
#[cfg(not(any(target_os = "android", target_os = "ios")))]
async fn close_active_connection(active: Option) -> std::result::Result<(), ()> {
if let Some(active) = active {
@@ -1060,14 +1750,22 @@ async fn close_queued_rooms(internal_rx: &mut mpsc::UnboundedReceiver SetMediaEnabledRequest {
+ SetMediaEnabledRequest {
+ connection_id: connection_id.into(),
+ kind,
+ enabled,
+ }
+ }
+
+ #[cfg(target_os = "linux")]
+ fn actor_with_camera(
+ app: tauri::AppHandle,
+ camera: Option,
+ media: MediaState,
+ ) -> super::Actor {
+ let (_commands_tx, commands) = tokio::sync::mpsc::channel(1);
+ let (internal_tx, internal_rx) = tokio::sync::mpsc::unbounded_channel();
+ let (_events_tx, events) = tokio::sync::mpsc::unbounded_channel();
+
+ super::Actor {
+ app,
+ commands,
+ internal_tx,
+ internal_rx,
+ machine: super::StateMachine {
+ state: ConnectionState::Connected,
+ revision: 1,
+ connection_id: Some("one".into()),
+ media,
+ },
+ pending: None,
+ active: Some(super::ActiveConnection {
+ connection_id: "one".into(),
+ operation_id: "one:1".into(),
+ room: super::OwnedRoom::Fake(Arc::new(AtomicUsize::new(0))),
+ events,
+ audio: None,
+ camera,
+ screen_share: None,
+ screen_share_shutdown_marker: None,
+ }),
+ audio_failure: None,
+ camera_failure: None,
+ screen_share_failure: None,
+ platform: super::PlatformStateMachine::default(),
+ #[cfg(mobile)]
+ platform_events_task: None,
+ }
+ }
+
+ #[cfg(target_os = "linux")]
+ #[tokio::test]
+ async fn failed_media_start_preserves_confirmed_state_without_emitting_state() {
+ let app = tauri::test::mock_app();
+ let state_events = Arc::new(AtomicUsize::new(0));
+ let listener_events = state_events.clone();
+ let _listener = app.listen(super::STATE_EVENT, move |_| {
+ listener_events.fetch_add(1, Ordering::SeqCst);
+ });
+ let mut actor = actor_with_camera(app.handle().clone(), None, MediaState::default());
+ let before = actor.machine.snapshot();
+ let (response, result) = tokio::sync::oneshot::channel();
+
+ actor
+ .handle_set_media_enabled(media_request("one", MediaKind::Camera, true), response)
+ .await;
+
+ assert!(matches!(result.await, Ok(Err(Error::CameraFailed))));
+ assert_eq!(actor.machine.snapshot(), before);
+ assert_eq!(state_events.load(Ordering::SeqCst), 0);
+ }
+
+ #[cfg(target_os = "linux")]
+ #[tokio::test]
+ async fn successful_media_stop_emits_confirmed_snapshot_once() {
+ let app = tauri::test::mock_app();
+ let state_events = Arc::new(Mutex::new(Vec::::new()));
+ let listener_events = state_events.clone();
+ let _listener = app.listen(super::STATE_EVENT, move |event| {
+ listener_events
+ .lock()
+ .unwrap()
+ .push(serde_json::from_str(event.payload()).unwrap());
+ });
+ let mut actor = actor_with_camera(
+ app.handle().clone(),
+ Some(crate::camera::CameraSession::without_devices(None)),
+ MediaState {
+ camera: true,
+ ..Default::default()
+ },
+ );
+ let (response, result) = tokio::sync::oneshot::channel();
+
+ actor
+ .handle_set_media_enabled(media_request("one", MediaKind::Camera, false), response)
+ .await;
+
+ let state = result.await.unwrap().unwrap();
+ assert_eq!(state.revision, 2);
+ assert!(!state.media.camera);
+ assert_eq!(actor.machine.snapshot(), state);
+ assert_eq!(
+ &*state_events.lock().unwrap(),
+ &[serde_json::to_value(state).unwrap()]
+ );
+ }
+
+ #[test]
+ fn media_toggle_is_stale_when_idle_in_progress_or_for_another_connection() {
+ let mut machine = StateMachine::default();
+ assert_eq!(
+ machine.media_decision(&media_request("one", MediaKind::Camera, true)),
+ MediaToggleDecision::Stale
+ );
+ machine.transition(ConnectionState::Connecting, Some("one".into()));
+ assert_eq!(
+ machine.media_decision(&media_request("one", MediaKind::Camera, true)),
+ MediaToggleDecision::Stale
+ );
+ machine.transition(ConnectionState::Connected, Some("one".into()));
+ assert_eq!(
+ machine.media_decision(&media_request("two", MediaKind::Camera, true)),
+ MediaToggleDecision::Stale
+ );
+ assert!(machine.snapshot().connection_id.is_some());
+ }
+
+ #[test]
+ fn media_toggle_respects_truthful_capabilities() {
+ let mut machine = StateMachine::default();
+ machine.transition(ConnectionState::Connected, Some("one".into()));
+ let capabilities = MediaCapabilities::current();
+ let kinds = [
+ (MediaKind::Microphone, capabilities.microphone),
+ (MediaKind::Camera, capabilities.camera),
+ (MediaKind::ScreenShare, capabilities.screen_share),
+ ];
+ for (kind, supported) in kinds {
+ let expected = if supported {
+ MediaToggleDecision::Apply
+ } else {
+ MediaToggleDecision::Unsupported
+ };
+ assert_eq!(
+ machine.media_decision(&media_request("one", kind, true)),
+ expected,
+ "unexpected decision for {kind:?}"
+ );
+ }
+ #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
+ {
+ assert!(capabilities.camera);
+ assert!(capabilities.screen_share);
+ }
+ assert_eq!(capabilities.microphone, cfg!(target_os = "linux"));
+ }
+
+ #[test]
+ fn media_toggle_is_idempotent_without_a_revision_bump() {
+ let mut machine = StateMachine::default();
+ machine.transition(ConnectionState::Connected, Some("one".into()));
+ machine.confirm_media(MediaKind::Camera, true);
+ let revision = machine.snapshot().revision;
+ assert_eq!(
+ machine.media_decision(&media_request("one", MediaKind::Camera, true)),
+ MediaToggleDecision::Idempotent
+ );
+ assert_eq!(machine.snapshot().revision, revision);
+ assert_eq!(
+ machine.media_decision(&media_request("one", MediaKind::Camera, false)),
+ MediaToggleDecision::Apply
+ );
+ assert_eq!(machine.snapshot().revision, revision);
+ }
+
+ #[test]
+ fn confirmed_media_bumps_revision_and_resets_outside_connected_states() {
+ let mut machine = StateMachine::default();
+ machine.transition(ConnectionState::Connecting, Some("one".into()));
+ assert_eq!(machine.snapshot().media, Default::default());
+
+ machine.transition(ConnectionState::Connected, Some("one".into()));
+ machine.confirm_media(MediaKind::ScreenShare, true);
+ let snapshot = machine.snapshot();
+ assert!(snapshot.media.screen_share);
+ assert_eq!(snapshot.revision, 3);
+
+ machine.transition(ConnectionState::Reconnecting, Some("one".into()));
+ assert!(machine.snapshot().media.screen_share);
+
+ machine.transition(ConnectionState::Disconnecting, Some("one".into()));
+ assert_eq!(machine.snapshot().media, Default::default());
+ machine.transition(ConnectionState::Idle, None);
+ let snapshot = machine.snapshot();
+ assert_eq!(snapshot.media, Default::default());
+ assert!(snapshot.connection_id.is_none());
+ }
+
+ #[test]
+ fn media_toggle_reconnecting_keeps_confirmed_state_and_stays_togglable() {
+ let mut machine = StateMachine::default();
+ machine.transition(ConnectionState::Connected, Some("one".into()));
+ machine.confirm_media(MediaKind::Camera, true);
+ machine.transition(ConnectionState::Reconnecting, Some("one".into()));
+ assert!(machine.snapshot().media.camera);
+ if MediaCapabilities::current().camera {
+ assert_eq!(
+ machine.media_decision(&media_request("one", MediaKind::Camera, false)),
+ MediaToggleDecision::Apply
+ );
+ }
+ }
+
+ #[test]
+ fn set_media_enabled_request_and_call_state_have_stable_wire_shapes() {
+ let request: SetMediaEnabledRequest = serde_json::from_value(serde_json::json!({
+ "connectionId": "one",
+ "kind": "screen_share",
+ "enabled": true
+ }))
+ .unwrap();
+ assert_eq!(request.kind, MediaKind::ScreenShare);
+ assert!(request.enabled);
+
+ let state = serde_json::to_value(StateMachine::default().snapshot()).unwrap();
+ assert_eq!(
+ state["media"],
+ serde_json::json!({
+ "microphone": false,
+ "camera": false,
+ "screenShare": false
+ })
+ );
+ assert!(state["capabilities"].is_object());
+
+ let error = serde_json::to_value(Error::MediaUnsupported).unwrap();
+ assert_eq!(
+ error,
+ serde_json::json!({
+ "code": "media_unsupported",
+ "message": "media kind is not supported on this platform"
+ })
+ );
+ }
+
+ #[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);
+ }
+
+ #[cfg(target_os = "linux")]
+ #[tokio::test]
+ async fn platform_start_is_busy_while_native_room_is_active() {
+ let app = tauri::test::mock_app();
+ let mut actor = actor_with_camera(app.handle().clone(), None, MediaState::default());
+ actor.platform.capabilities = PlatformCallCapabilities {
+ supported: true,
+ microphone: true,
+ playback: true,
+ };
+ let revision_before = actor.platform.snapshot().revision;
+ let (response, result) = tokio::sync::oneshot::channel();
+
+ actor
+ .handle_start_platform_call_lifecycle(
+ StartPlatformCallLifecycleRequest {
+ session_id: "session".into(),
+ microphone: true,
+ playback: true,
+ },
+ response,
+ )
+ .await;
+
+ assert!(matches!(result.await, Ok(Err(Error::PlatformCallBusy))));
+ assert_eq!(actor.platform.snapshot().revision, revision_before);
+ assert_eq!(
+ actor.platform.snapshot().state,
+ super::PlatformCallStateKind::Idle
+ );
+ }
+
+ #[cfg(target_os = "linux")]
+ #[tokio::test]
+ async fn connect_is_busy_while_platform_call_session_is_active() {
+ let app = tauri::test::mock_app();
+ let mut actor = actor_with_camera(app.handle().clone(), None, MediaState::default());
+ // No active native room: clear it so only the platform session remains.
+ let connection = actor.active.take();
+ let _ = super::close_active_connection(connection).await;
+ actor.transition(ConnectionState::Idle, None);
+ actor.platform.activate(&StartPlatformCallLifecycleRequest {
+ session_id: "session".into(),
+ microphone: true,
+ playback: true,
+ });
+ let (response, result) = tokio::sync::oneshot::channel();
+
+ actor
+ .handle_connect(
+ ConnectRequest {
+ connection_id: "one".into(),
+ server_url: "wss://livekit.example".into(),
+ participant_token: SecretString::from("secret-jwt"),
+ audio: false,
+ video: false,
+ screen_share: false,
+ },
+ response,
+ )
+ .await;
+
+ assert!(matches!(result.await, Ok(Err(Error::Busy))));
+ assert_eq!(actor.machine.snapshot().state, ConnectionState::Idle);
+ assert_eq!(
+ actor.platform.snapshot().session_id.as_deref(),
+ Some("session")
+ );
+ }
+
+ #[test]
+ fn platform_stop_protects_against_replacement_session() {
+ let mut machine = PlatformStateMachine::default();
+ machine.capabilities = PlatformCallCapabilities {
+ supported: true,
+ microphone: true,
+ playback: true,
+ };
+ let first = StartPlatformCallLifecycleRequest {
+ session_id: "first".into(),
+ microphone: true,
+ playback: true,
+ };
+ machine.activate(&first);
+ 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 platform_contract_serializes_only_bounded_wire_values() {
+ let event = serde_json::to_value(crate::models::PlatformCallEvent {
+ revision: 4,
+ session_id: "opaque-session".into(),
+ kind: crate::models::PlatformCallEventKind::RouteChanged {
+ route: crate::models::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/src/commands.rs b/src-tauri/plugins/tauri-plugin-call-lifecycle/src/commands.rs
index 64aed22ae..ade2d9cb7 100644
--- a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-call-lifecycle/src/commands.rs
@@ -20,7 +20,53 @@ pub(crate) async fn disconnect(
app.call_lifecycle().disconnect(payload).await
}
+#[command]
+pub(crate) async fn set_media_enabled(
+ app: AppHandle,
+ payload: SetMediaEnabledRequest,
+) -> Result {
+ app.call_lifecycle().set_media_enabled(payload).await
+}
+
#[command]
pub(crate) async fn get_state(app: AppHandle) -> Result {
app.call_lifecycle().get_state().await
}
+
+#[allow(non_snake_case)]
+#[command]
+pub(crate) async fn getPlatformCallCapabilities(
+ app: AppHandle,
+) -> Result {
+ app.call_lifecycle().get_platform_call_capabilities().await
+}
+
+#[allow(non_snake_case)]
+#[command]
+pub(crate) async fn startPlatformCallLifecycle(
+ app: AppHandle,
+ payload: StartPlatformCallLifecycleRequest,
+) -> Result {
+ app.call_lifecycle()
+ .start_platform_call_lifecycle(payload)
+ .await
+}
+
+#[allow(non_snake_case)]
+#[command]
+pub(crate) async fn stopPlatformCallLifecycle(
+ app: AppHandle,
+ payload: StopPlatformCallLifecycleRequest,
+) -> Result {
+ app.call_lifecycle()
+ .stop_platform_call_lifecycle(payload)
+ .await
+}
+
+#[allow(non_snake_case)]
+#[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
index c27415936..d99cf363e 100644
--- a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/error.rs
+++ b/src-tauri/plugins/tauri-plugin-call-lifecycle/src/error.rs
@@ -22,6 +22,18 @@ pub enum Error {
CameraFailed,
#[error("native screen share failed")]
ScreenShareFailed,
+ #[error("media kind is not supported on this platform")]
+ MediaUnsupported,
+ #[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 {
@@ -48,6 +60,12 @@ impl Error {
Self::VideoFailed => "video_failed",
Self::CameraFailed => "camera_failed",
Self::ScreenShareFailed => "screen_share_failed",
+ Self::MediaUnsupported => "media_unsupported",
+ 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",
}
}
@@ -62,6 +80,16 @@ impl Error {
Self::VideoFailed => "native video failed",
Self::CameraFailed => "native camera failed",
Self::ScreenShareFailed => "native screen share failed",
+ Self::MediaUnsupported => "media kind is not supported on this platform",
+ 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",
}
}
}
diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/lib.rs b/src-tauri/plugins/tauri-plugin-call-lifecycle/src/lib.rs
index f2325f348..c0a71f160 100644
--- a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/lib.rs
+++ b/src-tauri/plugins/tauri-plugin-call-lifecycle/src/lib.rs
@@ -47,7 +47,12 @@ pub fn init() -> TauriPlugin {
.invoke_handler(tauri::generate_handler![
commands::connect,
commands::disconnect,
- commands::get_state
+ commands::set_media_enabled,
+ commands::get_state,
+ commands::getPlatformCallCapabilities,
+ commands::startPlatformCallLifecycle,
+ commands::stopPlatformCallLifecycle,
+ commands::getPlatformCallState
])
.setup(|app, api| {
#[cfg(mobile)]
diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/mobile.rs b/src-tauri/plugins/tauri-plugin-call-lifecycle/src/mobile.rs
index b0e49d209..a6eec96af 100644
--- a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/mobile.rs
+++ b/src-tauri/plugins/tauri-plugin-call-lifecycle/src/mobile.rs
@@ -6,7 +6,13 @@ use tauri::{
};
use tokio::sync::mpsc;
-use crate::{error::Error, models::DisconnectRequest};
+use crate::{
+ error::Error,
+ models::{
+ DisconnectRequest, MediaKind, NativePlatformCallEvent, NativePlatformStartFields,
+ PlatformCallCapabilities,
+ },
+};
#[cfg(target_os = "android")]
const PLUGIN_IDENTIFIER: &str = "app.tauri.call_lifecycle";
@@ -53,6 +59,56 @@ pub(crate) struct NativeControlEvent {
pub kind: NativeControlEventKind,
}
+#[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(Debug, Clone, Deserialize)]
#[serde(tag = "event", rename_all = "snake_case")]
pub(crate) enum NativeControlEventKind {
@@ -103,6 +159,17 @@ impl MobileBackend {
})
}
+ 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 connect(
&self,
request: NativeConnectRequest<'_>,
@@ -128,6 +195,63 @@ impl MobileBackend {
.map(|_| ())
.map_err(|_| Error::CloseFailed)
}
+
+ pub(crate) async fn set_media_enabled(
+ &self,
+ operation_id: &str,
+ connection_id: &str,
+ kind: MediaKind,
+ enabled: bool,
+ ) -> crate::Result<()> {
+ let payload = NativeSetMediaEnabledRequest {
+ operation_id,
+ connection_id,
+ kind,
+ enabled,
+ };
+ self.handle
+ .run_mobile_plugin_async::("setMediaEnabled", payload)
+ .await
+ .map(|_| ())
+ .map_err(|_| match kind {
+ MediaKind::Microphone => Error::AudioFailed,
+ MediaKind::Camera => Error::CameraFailed,
+ MediaKind::ScreenShare => Error::ScreenShareFailed,
+ })
+ }
+
+ 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)
+ }
}
#[derive(Debug, Serialize)]
@@ -137,6 +261,32 @@ struct NativeDisconnectRequest<'a> {
connection_id: &'a str,
}
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct NativeSetMediaEnabledRequest<'a> {
+ operation_id: &'a str,
+ connection_id: &'a str,
+ kind: MediaKind,
+ enabled: bool,
+}
+
+/// 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,
diff --git a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/models.rs b/src-tauri/plugins/tauri-plugin-call-lifecycle/src/models.rs
index 0527d2cae..c823540ec 100644
--- a/src-tauri/plugins/tauri-plugin-call-lifecycle/src/models.rs
+++ b/src-tauri/plugins/tauri-plugin-call-lifecycle/src/models.rs
@@ -21,6 +21,438 @@ pub struct DisconnectRequest {
pub connection_id: String,
}
+#[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,
+ }
+ }
+}
+
+#[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
+ })
+ );
+ }
+}
+
+/// 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,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum MediaKind {
+ Microphone,
+ Camera,
+ ScreenShare,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SetMediaEnabledRequest {
+ pub connection_id: String,
+ pub kind: MediaKind,
+ pub enabled: bool,
+}
+
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MediaState {
+ pub microphone: bool,
+ pub camera: bool,
+ pub screen_share: bool,
+}
+
+impl MediaState {
+ pub fn enabled(&self, kind: MediaKind) -> bool {
+ match kind {
+ MediaKind::Microphone => self.microphone,
+ MediaKind::Camera => self.camera,
+ MediaKind::ScreenShare => self.screen_share,
+ }
+ }
+
+ pub fn set(&mut self, kind: MediaKind, enabled: bool) {
+ match kind {
+ MediaKind::Microphone => self.microphone = enabled,
+ MediaKind::Camera => self.camera = enabled,
+ MediaKind::ScreenShare => self.screen_share = enabled,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MediaCapabilities {
+ pub microphone: bool,
+ pub camera: bool,
+ pub screen_share: bool,
+}
+
+impl MediaCapabilities {
+ pub fn current() -> Self {
+ let desktop = cfg!(any(
+ target_os = "linux",
+ target_os = "macos",
+ target_os = "windows"
+ ));
+ Self {
+ microphone: cfg!(any(
+ target_os = "linux",
+ target_os = "android",
+ target_os = "ios"
+ )),
+ camera: desktop || cfg!(any(target_os = "android", target_os = "ios")),
+ screen_share: desktop || cfg!(target_os = "android"),
+ }
+ }
+
+ pub fn supports(&self, kind: MediaKind) -> bool {
+ match kind {
+ MediaKind::Microphone => self.microphone,
+ MediaKind::Camera => self.camera,
+ MediaKind::ScreenShare => self.screen_share,
+ }
+ }
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ConnectionState {
@@ -37,6 +469,8 @@ pub struct CallState {
pub revision: u64,
pub state: ConnectionState,
pub connection_id: Option,
+ pub media: MediaState,
+ pub capabilities: MediaCapabilities,
}
#[derive(Debug, Clone, Serialize)]
diff --git a/src/app/features/call/CallView.test.tsx b/src/app/features/call/CallView.test.tsx
new file mode 100644
index 000000000..7d55d11eb
--- /dev/null
+++ b/src/app/features/call/CallView.test.tsx
@@ -0,0 +1,388 @@
+import { act, render, renderHook, screen } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { NativeCallSession } from '$state/nativeCall';
+import { getDebugLogger, type LogEntry } from '$utils/debugLogger';
+import type * as Platform from '$utils/platform';
+import { NATIVE_CALL_PROBE_STORAGE_KEY } from './nativeCallProbe';
+import {
+ getNativeCallDiagnostics,
+ serializeNativeCallDiagnostics,
+ useNativeCallDiagnostics,
+ useNativeCallProbeSession,
+ NativeMediaControls,
+ LivekitJsCallProbe,
+} from './CallView';
+
+const setMediaEnabled = vi.hoisted(() => vi.fn<(...args: unknown[]) => Promise>());
+
+vi.mock('$plugins/call/callLifecycle', () => ({
+ getState: vi.fn<() => Promise>(),
+ onState: vi.fn<(handler: unknown) => Promise>(),
+ setMediaEnabled,
+}));
+
+const desktopTauri = vi.hoisted(() => vi.fn<() => boolean>());
+const mobileTauri = vi.hoisted(() => vi.fn<() => boolean>());
+
+vi.mock('$utils/platform', async (importOriginal) => ({
+ ...(await importOriginal()),
+ isDesktopTauri: desktopTauri,
+ isMobileTauri: mobileTauri,
+}));
+
+const makeSession = (): NativeCallSession => ({
+ roomId: '!room:example.org',
+ connectionId: 'connection-id',
+ lifecycle: 'connected',
+ hangup: vi.fn<() => Promise>().mockResolvedValue(),
+});
+
+const mediaSnapshot = {
+ connectionId: 'connection-id',
+ media: { microphone: true, camera: false, screenShare: false },
+ capabilities: { microphone: true, camera: true, screenShare: false },
+};
+
+describe('native media controls', () => {
+ beforeEach(() => {
+ setMediaEnabled.mockReset();
+ setMediaEnabled.mockResolvedValue({});
+ });
+
+ it('shows only advertised controls and reflects confirmed state', () => {
+ render();
+
+ expect(screen.getByRole('button', { name: 'Turn off microphone' })).toBeEnabled();
+ expect(screen.getByRole('button', { name: 'Start camera' })).toBeEnabled();
+ expect(screen.queryByRole('button', { name: 'Start screen sharing' })).not.toBeInTheDocument();
+ });
+
+ it('sends the requested media kind and state, then blocks duplicate requests', async () => {
+ let resolveRequest!: (value: unknown) => void;
+ setMediaEnabled.mockReturnValue(
+ new Promise((resolve) => {
+ resolveRequest = resolve;
+ })
+ );
+ render();
+
+ const camera = screen.getByRole('button', { name: 'Start camera' });
+ await act(async () => camera.click());
+ expect(setMediaEnabled).toHaveBeenCalledWith({
+ connectionId: 'connection-id',
+ kind: 'camera',
+ enabled: true,
+ });
+ expect(camera).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Turn off microphone' })).toBeDisabled();
+
+ await act(async () => resolveRequest({}));
+ });
+
+ it('shows a recoverable error when the native command fails', async () => {
+ setMediaEnabled.mockRejectedValueOnce(new Error('native failure'));
+ render();
+
+ const camera = screen.getByRole('button', { name: 'Start camera' });
+ await act(async () => camera.click());
+
+ expect(screen.getByText('Couldn’t change camera.')).toBeInTheDocument();
+ expect(camera).toBeEnabled();
+ expect(screen.getByRole('button', { name: 'Turn off microphone' })).toBeEnabled();
+ });
+
+ it('shows the safe failure code and records a sanitized diagnostic on rejection', async () => {
+ const debugLogger = getDebugLogger();
+ debugLogger.clear();
+ debugLogger.setEnabled(true);
+ setMediaEnabled.mockRejectedValueOnce({
+ code: 'camera_failed',
+ message: 'native camera failed',
+ });
+ render();
+
+ const camera = screen.getByRole('button', { name: 'Start camera' });
+ await act(async () => camera.click());
+
+ expect(screen.getByText('Couldn’t change camera (camera_failed).')).toBeInTheDocument();
+ expect(camera).toBeEnabled();
+ expect(getNativeCallDiagnostics(debugLogger.getLogs())).toContainEqual({
+ stage: 'media control',
+ code: 'camera_failed',
+ errorName: 'UnknownError',
+ errorMessage: 'native camera failed',
+ });
+ });
+
+ it('supports media_unsupported and never logs raw invoke details', async () => {
+ const debugLogger = getDebugLogger();
+ debugLogger.clear();
+ debugLogger.setEnabled(true);
+ setMediaEnabled.mockRejectedValueOnce({
+ code: 'media_unsupported',
+ message: 'media kind is not supported on this platform',
+ });
+ const { rerender } = render(
+
+ );
+
+ await act(async () => screen.getByRole('button', { name: 'Start camera' }).click());
+ expect(screen.getByText('Couldn’t change camera (media_unsupported).')).toBeInTheDocument();
+
+ setMediaEnabled.mockRejectedValueOnce({
+ code: 'https://evil.example/token?access_token=code-secret',
+ message: 'invoke failed at https://evil.example/track?token=message-secret',
+ });
+ rerender();
+ await act(async () => screen.getByRole('button', { name: 'Start camera' }).click());
+
+ expect(screen.getByText('Couldn’t change camera.')).toBeInTheDocument();
+ const payload = serializeNativeCallDiagnostics(getNativeCallDiagnostics(debugLogger.getLogs()));
+ expect(payload).not.toContain('evil.example');
+ expect(payload).not.toContain('secret');
+ });
+});
+
+describe('LiveKit JS connection probe', () => {
+ it('renders connection and E2EE readiness without media controls', () => {
+ render(
+ {}} />
+ );
+
+ expect(screen.getByText('LiveKit JS connection probe')).toBeInTheDocument();
+ expect(screen.getByText('Connection: Connected')).toBeInTheDocument();
+ expect(screen.getByText('E2EE readiness:')).toHaveTextContent('Ready');
+ expect(
+ screen.getByText('Connection-only experiment · media is not published')
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', { name: /microphone|camera|screen/i })
+ ).not.toBeInTheDocument();
+ });
+
+ it('uses safe status and setup failure text', () => {
+ render(
+ {}}
+ />
+ );
+
+ expect(screen.getByText('Connection: Connection failed')).toBeInTheDocument();
+ expect(screen.getByText('E2EE readiness:')).toHaveTextContent('Unavailable');
+ expect(screen.getByText('LiveKit JS connection setup failed.')).toBeInTheDocument();
+ expect(screen.queryByText(/token|url|secret|error:/i)).not.toBeInTheDocument();
+ });
+
+ it('shows unavailable E2EE status and calls hangup from End', () => {
+ const onHangup = vi.fn<() => void>();
+ render(
+
+ );
+
+ expect(screen.getByText('E2EE readiness:')).toHaveTextContent('Unavailable on this device');
+ screen.getByRole('button', { name: 'End' }).click();
+ expect(onHangup).toHaveBeenCalledOnce();
+ });
+});
+
+describe('native call probe session gate', () => {
+ beforeEach(() => {
+ desktopTauri.mockReturnValue(true);
+ mobileTauri.mockReturnValue(false);
+ localStorage.clear();
+ vi.stubEnv('VITE_ENABLE_NATIVE_CALL_PROBE', 'false');
+ });
+
+ it('hangs up a native session once when native calls are disabled', () => {
+ const session = makeSession();
+ const { rerender } = renderHook(
+ ({ nativeCallsEnabled }) => useNativeCallProbeSession(session, nativeCallsEnabled),
+ { initialProps: { nativeCallsEnabled: false } }
+ );
+
+ expect(session.hangup).toHaveBeenCalledTimes(1);
+
+ rerender({ nativeCallsEnabled: false });
+ expect(session.hangup).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the native session when a developer override enables the probe', () => {
+ localStorage.setItem(NATIVE_CALL_PROBE_STORAGE_KEY, '1');
+ const session = makeSession();
+
+ renderHook(() => useNativeCallProbeSession(session, false));
+
+ expect(session.hangup).not.toHaveBeenCalled();
+ });
+});
+
+describe('native call diagnostics', () => {
+ const debugLogger = getDebugLogger();
+
+ beforeEach(() => {
+ debugLogger.clear();
+ debugLogger.setEnabled(true);
+ });
+
+ it('filters controller call logs and keeps only sanitized diagnostic fields', () => {
+ const logs = [
+ {
+ timestamp: 1,
+ level: 'error',
+ category: 'call',
+ namespace: 'nativeCallController',
+ message: 'Native call setup failed',
+ data: {
+ stage: 'connecting',
+ errorName: 'Error',
+ errorMessage: 'redacted',
+ cause: { errorName: 'UnknownError', errorMessage: 'redacted', token: 'secret' },
+ roomId: '!secret:example.org',
+ },
+ },
+ {
+ timestamp: 2,
+ level: 'error',
+ category: 'call',
+ namespace: 'nativeCallController',
+ message: 'Native call setup failed',
+ data: { stage: 'authorizing', errorName: 'Error', errorMessage: 'redacted' },
+ },
+ {
+ timestamp: 3,
+ level: 'error',
+ category: 'network',
+ namespace: 'nativeCallController',
+ message: 'Ignored',
+ data: { stage: 'ignored' },
+ },
+ ] satisfies LogEntry[];
+
+ expect(getNativeCallDiagnostics(logs)).toEqual([
+ { stage: 'authorizing', errorName: 'Error', errorMessage: 'redacted' },
+ {
+ stage: 'connecting',
+ errorName: 'Error',
+ errorMessage: 'redacted',
+ cause: { errorName: 'UnknownError', errorMessage: 'redacted' },
+ },
+ ]);
+ });
+
+ it('updates when a matching logger entry arrives', () => {
+ const { result } = renderHook(() => useNativeCallDiagnostics());
+
+ act(() => {
+ debugLogger.log('error', 'call', 'nativeCallController', 'Native call setup failed', {
+ stage: 'authorizing',
+ errorName: 'Error',
+ errorMessage: 'redacted',
+ });
+ });
+
+ expect(result.current).toEqual([
+ { stage: 'authorizing', errorName: 'Error', errorMessage: 'redacted' },
+ ]);
+ });
+
+ it('copies only the safe diagnostic payload', () => {
+ const diagnostics = getNativeCallDiagnostics([
+ {
+ timestamp: 1,
+ level: 'error',
+ category: 'call',
+ namespace: 'nativeCallController',
+ message: 'Native call setup failed',
+ data: {
+ code: 'connect_failed',
+ stage: 'joining the call',
+ errorName: 'Error',
+ errorMessage: 'redacted',
+ roomId: '!secret:example.org',
+ token: 'secret-token',
+ },
+ },
+ ] satisfies LogEntry[]);
+
+ const payload = serializeNativeCallDiagnostics(diagnostics);
+
+ expect(JSON.parse(payload)).toEqual([
+ {
+ code: 'connect_failed',
+ stage: 'joining the call',
+ errorName: 'Error',
+ errorMessage: 'redacted',
+ },
+ ]);
+ expect(payload).not.toContain('secret');
+ });
+
+ it('redacts unallowlisted diagnostic values in fields and nested causes', () => {
+ const diagnostics = getNativeCallDiagnostics([
+ {
+ timestamp: 1,
+ level: 'error',
+ category: 'call',
+ namespace: 'nativeCallController',
+ message: 'Native call setup failed',
+ data: {
+ stage: 'https://evil.example/token?access_token=stage-secret',
+ errorName: 'RawNativeException',
+ errorMessage: 'https://evil.example/token?access_token=message-secret',
+ cause: {
+ errorName: 'RawCauseException token-secret',
+ errorMessage: 'raw cause exception https://evil.example/cause-secret',
+ },
+ },
+ },
+ ] satisfies LogEntry[]);
+ const payload = serializeNativeCallDiagnostics(diagnostics);
+
+ expect(diagnostics).toEqual([
+ {
+ stage: 'redacted',
+ errorName: 'redacted',
+ errorMessage: 'redacted',
+ cause: { errorName: 'redacted', errorMessage: 'redacted' },
+ },
+ ]);
+ expect(payload).not.toContain('evil.example');
+ expect(payload).not.toContain('secret');
+ expect(payload).not.toContain('RawNativeException');
+ expect(payload).not.toContain('RawCauseException');
+ });
+
+ it('redacts an unallowlisted lifecycle code in UI-derived diagnostics and copy payload', () => {
+ const diagnostics = getNativeCallDiagnostics([
+ {
+ timestamp: 1,
+ level: 'error',
+ category: 'call',
+ namespace: 'nativeCallController',
+ message: 'Native call connection failed',
+ data: {
+ code: 'https://evil.example/token?access_token=code-secret',
+ stage: 'connecting',
+ errorName: 'Error',
+ errorMessage: 'redacted',
+ },
+ },
+ ] satisfies LogEntry[]);
+ const payload = serializeNativeCallDiagnostics(diagnostics);
+
+ expect(diagnostics).toEqual([
+ {
+ code: 'redacted',
+ stage: 'connecting',
+ errorName: 'Error',
+ errorMessage: 'redacted',
+ },
+ ]);
+ expect(payload).not.toContain('evil.example');
+ expect(payload).not.toContain('code-secret');
+ });
+});
diff --git a/src/app/features/call/CallView.tsx b/src/app/features/call/CallView.tsx
index 434948bcf..5427a77e3 100644
--- a/src/app/features/call/CallView.tsx
+++ b/src/app/features/call/CallView.tsx
@@ -1,5 +1,18 @@
import { useCallback, useEffect, useRef, useState, type RefObject } from 'react';
-import { Badge, Box, Button, color, Header, Scroll, Text, toRem } from 'folds';
+import {
+ Badge,
+ Box,
+ Button,
+ color,
+ Header,
+ IconButton,
+ Scroll,
+ Spinner,
+ Text,
+ toRem,
+ Tooltip,
+ TooltipProvider,
+} from 'folds';
import { useAtomValue } from 'jotai';
import { ContainerColor } from '$styles/ContainerColor.css';
import { useRoom } from '$hooks/useRoom';
@@ -13,7 +26,259 @@ import { CallMemberRenderer } from './CallMemberCard';
import { PrescreenControls } from './PrescreenControls';
import { callEmbedAtom, callEmbedStartErrorAtom } from '$state/callEmbed';
import { canJoinCall } from './callStartCapabilities';
+import type { NativeCallSession } from '$state/nativeCall';
import { nativeCallAtom } from '$state/nativeCall';
+import type { LivekitJsCallSession } from '$state/livekitJsCall';
+import { livekitJsCallAtom } from '$state/livekitJsCall';
+import { isNativeCallProbeEnabled } from './nativeCallProbe';
+import { settingsAtom } from '$state/settings';
+import { useSetting } from '$state/hooks/settings';
+import { createDebugLogger, getDebugLogger, type LogEntry } from '$utils/debugLogger';
+import { copyToClipboard } from '$utils/dom';
+import {
+ Microphone,
+ MicrophoneSlash,
+ ScreenShare,
+ VideoCamera,
+ VideoCameraSlash,
+ sizedIcon,
+} from '$components/icons/phosphor';
+import { getState, onState, setMediaEnabled, type MediaKind } from '$plugins/call/callLifecycle';
+import { canRenderLivekitJsMediaTest, LivekitJsMediaTestSurface } from './LivekitJsMediaTest';
+
+type NativeMediaSnapshot = {
+ connectionId: string;
+ media: {
+ microphone: boolean;
+ camera: boolean;
+ screenShare: boolean;
+ };
+ capabilities: {
+ microphone: boolean;
+ camera: boolean;
+ screenShare: boolean;
+ };
+};
+
+type NativeMediaKind = MediaKind;
+
+const nativeMediaDebug = createDebugLogger('nativeCallController');
+
+const allowlistedErrorField = (
+ error: unknown,
+ property: 'code' | 'name' | 'message',
+ allowlist: Set
+): string | undefined => {
+ const value = isRecord(error) ? error[property] : undefined;
+ return typeof value === 'string' && allowlist.has(value) ? value : undefined;
+};
+
+// Records a bounded, allowlisted diagnostic for a failed media toggle and
+// returns the safe failure code (if known). Raw invoke messages, URLs, and
+// tokens are never logged.
+const logMediaControlFailure = (error: unknown): string | undefined => {
+ const code = allowlistedErrorField(error, 'code', nativeCallCodes);
+ nativeMediaDebug.error('call', 'Native media control failed', {
+ stage: 'media control',
+ code: code ?? 'unknown',
+ errorName: allowlistedErrorField(error, 'name', nativeCallErrorNames) ?? 'UnknownError',
+ errorMessage: allowlistedErrorField(error, 'message', nativeCallErrorMessages) ?? 'redacted',
+ });
+ return code === 'unknown' ? undefined : code;
+};
+
+const toNativeMediaSnapshot = (state: unknown): NativeMediaSnapshot | undefined => {
+ if (!isRecord(state) || !isRecord(state.media) || !isRecord(state.capabilities)) return undefined;
+ if (typeof state.connectionId !== 'string') return undefined;
+
+ const media = state.media;
+ const capabilities = state.capabilities;
+ if (
+ typeof media.microphone !== 'boolean' ||
+ typeof media.camera !== 'boolean' ||
+ typeof media.screenShare !== 'boolean' ||
+ typeof capabilities.microphone !== 'boolean' ||
+ typeof capabilities.camera !== 'boolean' ||
+ typeof capabilities.screenShare !== 'boolean'
+ ) {
+ return undefined;
+ }
+
+ return {
+ connectionId: state.connectionId,
+ media: {
+ microphone: media.microphone,
+ camera: media.camera,
+ screenShare: media.screenShare,
+ },
+ capabilities: {
+ microphone: capabilities.microphone,
+ camera: capabilities.camera,
+ screenShare: capabilities.screenShare,
+ },
+ };
+};
+
+export function NativeMediaControls({
+ connectionId,
+ snapshot,
+}: {
+ connectionId: string;
+ snapshot: NativeMediaSnapshot | undefined;
+}) {
+ const [pending, setPending] = useState();
+ const [error, setError] = useState();
+
+ const toggle = useCallback(
+ async (kind: NativeMediaKind, enabled: boolean) => {
+ if (pending || !snapshot) return;
+ setPending(kind);
+ setError(undefined);
+ try {
+ await setMediaEnabled({
+ connectionId,
+ kind,
+ enabled,
+ });
+ } catch (toggleError) {
+ const code = logMediaControlFailure(toggleError);
+ setError(
+ `Couldn’t change ${kind === 'screen_share' ? 'screen sharing' : kind}${
+ code ? ` (${code})` : ''
+ }.`
+ );
+ } finally {
+ setPending(undefined);
+ }
+ },
+ [connectionId, pending, snapshot]
+ );
+
+ if (!snapshot) return null;
+
+ const controls: Array<{
+ kind: NativeMediaKind;
+ enabled: boolean;
+ supported: boolean;
+ label: string;
+ icon: typeof Microphone;
+ }> = [
+ {
+ kind: 'microphone',
+ enabled: snapshot.media.microphone,
+ supported: snapshot.capabilities.microphone,
+ label: snapshot.media.microphone ? 'Turn off microphone' : 'Turn on microphone',
+ icon: snapshot.media.microphone ? Microphone : MicrophoneSlash,
+ },
+ {
+ kind: 'camera',
+ enabled: snapshot.media.camera,
+ supported: snapshot.capabilities.camera,
+ label: snapshot.media.camera ? 'Stop camera' : 'Start camera',
+ icon: snapshot.media.camera ? VideoCamera : VideoCameraSlash,
+ },
+ {
+ kind: 'screen_share',
+ enabled: snapshot.media.screenShare,
+ supported: snapshot.capabilities.screenShare,
+ label: snapshot.media.screenShare ? 'Stop screen sharing' : 'Start screen sharing',
+ icon: ScreenShare,
+ },
+ ];
+
+ return (
+
+
+ {controls.map(({ kind, enabled, supported, label, icon }) => {
+ if (!supported) return null;
+ const busy = pending === kind;
+ return (
+
+ {label}
+
+ }
+ >
+ {(anchorRef) => (
+ void toggle(kind, !enabled)}
+ >
+ {busy ? (
+
+ ) : (
+ sizedIcon(icon, '100', {
+ filled: kind === 'microphone' ? !enabled : enabled,
+ })
+ )}
+
+ )}
+
+ );
+ })}
+
+ {error && (
+
+ {error}
+
+ )}
+
+ );
+}
+
+function useNativeMediaSnapshot(
+ connectionId: string,
+ active: boolean
+): NativeMediaSnapshot | undefined {
+ const [snapshot, setSnapshot] = useState();
+
+ useEffect(() => {
+ if (!active) {
+ setSnapshot(undefined);
+ return undefined;
+ }
+ let current = true;
+ void (async () => {
+ try {
+ const next = toNativeMediaSnapshot(await getState());
+ if (current && next?.connectionId === connectionId) setSnapshot(next);
+ } catch {
+ // The probe can still receive a state event if the initial read fails.
+ }
+ })();
+ const unlisten = onState((state) => {
+ const next = toNativeMediaSnapshot(state);
+ if (next?.connectionId === connectionId) setSnapshot(next);
+ });
+ return () => {
+ current = false;
+ void (async () => {
+ (await unlisten)();
+ })();
+ };
+ }, [active, connectionId]);
+
+ return snapshot;
+}
function LivekitServerMissingMessage() {
return (
@@ -83,24 +348,58 @@ function WidgetPreparationErrorMessage({ message }: { message: string }) {
function NativeCallProbe({
lifecycle,
+ connectionId,
error,
onHangup,
}: {
lifecycle: string;
+ connectionId: string;
error?: string;
onHangup: () => void;
}) {
+ const diagnostics = useNativeCallDiagnostics();
+ const mediaSnapshot = useNativeMediaSnapshot(connectionId, lifecycle !== 'error');
+
return (
Native call: {lifecycle}
- Media is not implemented.
+ Experimental native call
+
{error && (
{error}
)}
+
+ Native diagnostics
+
+ {diagnostics.length > 0 ? (
+ diagnostics.map((diagnostic) => (
+
+ {diagnostic.code && `${diagnostic.code} · `}
+ {diagnostic.stage} · {diagnostic.errorName}: {diagnostic.errorMessage}
+ {diagnostic.cause &&
+ ` (cause: ${diagnostic.cause.errorName}: ${diagnostic.cause.errorMessage})`}
+
+ ))
+ ) : (
+ No native call diagnostics yet.
+ )}
+
+
+