Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(mobile): end the Live Activity when the app closes or can suspend (#2776)
Chad Piha86083babb684
diff --git a/openwhispr-mobile/modules/app-group-storage/ios/AppGroupStorageModule.swift b/openwhispr-mobile/modules/app-group-storage/ios/AppGroupStorageModule.swiftindex fc145d933..098150258 100644--- a/openwhispr-mobile/modules/app-group-storage/ios/AppGroupStorageModule.swift+++ b/openwhispr-mobile/modules/app-group-storage/ios/AppGroupStorageModule.swift@@ -92,6 +92,7 @@ public class AppGroupStorageModule: Module {private var backgroundObserverToken: NSObjectProtocol?private var audioInterruptionObserverToken: NSObjectProtocol?private var mediaServicesResetObserverToken: NSObjectProtocol?+ private var engineConfigurationObserverToken: NSObjectProtocol?// Refreshed while OpenWhispr is foreground so the keyboard can tell it is// hosted by our own app (record in place) rather than another app (hand off).private var foregroundHeartbeatTimer: Timer?@@ -1163,6 +1164,10 @@ public class AppGroupStorageModule: Module {} catch {logMarker("audioEngine.deactivateSessionFailed", extra: "reason=\(reason) error=\(error.localizedDescription)")}+ // A backgrounded app can suspend now, so LiveActivityController drops the idle+ // session card before iOS can kill the app without warning.+ NotificationCenter.default.post(+ name: Notification.Name("\(Self.notificationPrefix).warmMicReleased"), object: nil)logMarker("audioEngine.stopped", extra: "reason=\(reason)")}@@ -1706,6 +1711,13 @@ public class AppGroupStorageModule: Module {) { [weak self] _ inself?.handleMediaServicesReset()}+ engineConfigurationObserverToken = center.addObserver(+ forName: .AVAudioEngineConfigurationChange,+ object: nil,+ queue: .main+ ) { [weak self] notification in+ self?.handleAudioEngineConfigurationChange(notification)+ }logMarker("audioSessionObservers.added")}@@ -1719,6 +1731,10 @@ public class AppGroupStorageModule: Module {center.removeObserver(token)mediaServicesResetObserverToken = nil}+ if let token = engineConfigurationObserverToken {+ center.removeObserver(token)+ engineConfigurationObserverToken = nil+ }}private func handleAudioSessionInterruption(_ notification: Notification) {@@ -1782,6 +1798,26 @@ public class AppGroupStorageModule: Module {armWarmMic(reason: "mediaServicesReset")}+ /// The engine stops itself when the input format changes (a Bluetooth headset+ /// connecting, another audio client changing the category), with no other signal.+ /// Left alone, the shared flags would keep claiming a warm mic: the keyboard skips+ /// Activate, and a backgrounded app keeps its Live Activity until it suspends and+ /// dies. Rebuild on the current session, or release so the flags tell the truth.+ private func handleAudioEngineConfigurationChange(_ notification: Notification) {+ audioPipelineLock.lock()+ defer { audioPipelineLock.unlock() }+ guard let engine = notification.object as? AVAudioEngine, engine === audioEngine else { return }+ audioStateLock.lock()+ let recording = isClipRecording+ audioStateLock.unlock()+ logMarker("audioEngine.configurationChange", extra: "recording=\(recording)")+ // stopRecording reads the dead engine and clears the warm flag itself.+ guard !recording else { return }+ if !ensureAudioEngineRunning(reason: "configurationChange") {+ releaseWarmMic(reason: "configurationChange")+ }+ }+private func handleAppDidBecomeActive() {startForegroundHeartbeat()guard isDictationModeEnabled() else { return }diff --git a/openwhispr-mobile/modules/live-activity/ios/LiveActivityController.swift b/openwhispr-mobile/modules/live-activity/ios/LiveActivityController.swiftindex fd402fb78..6a831e20a 100644--- a/openwhispr-mobile/modules/live-activity/ios/LiveActivityController.swift+++ b/openwhispr-mobile/modules/live-activity/ios/LiveActivityController.swift@@ -24,9 +24,13 @@ final class LiveActivityController {private var statusNotificationName: String { "\(bundleId).keyboardStatusChanged" }private var dictationModeNotificationName: String { "\(bundleId).dictationModeChanged" }private var endMeetingNotificationName: String { "\(bundleId).endMeetingRequested" }+ /// In-process, posted by AppGroupStorageModule when it stops the warm mic.+ private var warmMicReleasedNotificationName: String { "\(bundleId).warmMicReleased" }private var sharedDefaults: UserDefaults? { UserDefaults(suiteName: "group.\(bundleId)") }private var isObserving = falseprivate var foregroundObserverToken: NSObjectProtocol?+ private var terminateObserverToken: NSObjectProtocol?+ private var backgroundObserverTokens: [NSObjectProtocol] = []/// Non-nil while MeetingRecordScreen has a meeting recording or processing.private var meeting: MeetingSnapshot?@@ -66,6 +70,11 @@ final class LiveActivityController {sharedDefaults?.string(forKey: "keyboard_recording_active") == "1"}+ // The warm mic's audio session is what keeps a backgrounded app running.+ private func isWarmMicHeld() -> Bool {+ sharedDefaults?.string(forKey: "background_session_warm_mic") == "1"+ }+// MARK: - Observationfunc startObserving() {@@ -89,7 +98,28 @@ final class LiveActivityController {// The controller is a process-lifetime singleton, like the Darwin boxes.self.reconcile(requestOnly: true)}- self.log.info("Observing keyboard, dictation-mode, and end-meeting notifications")+ // ActivityKit keeps a card up for hours after its process dies, so a swiped-away+ // app would leave the pill claiming a session (or meeting) that no longer exists.+ self.terminateObserverToken = NotificationCenter.default.addObserver(+ forName: UIApplication.willTerminateNotification,+ object: nil,+ queue: .main+ ) { _ in+ self.endAllBeforeTermination()+ }+ // Once the app can suspend, the idle session card has to go: a suspended app+ // is killed without willTerminate. Covers backgrounding without a warm mic+ // and the warm mic's release (idle timeout, interruption) in the background.+ // Request-only, so a card that stays keeps its timer.+ self.backgroundObserverTokens = [+ UIApplication.didEnterBackgroundNotification,+ Notification.Name(self.warmMicReleasedNotificationName),+ ].map { name in+ NotificationCenter.default.addObserver(forName: name, object: nil, queue: .main) { _ in+ self.reconcileBeforeSuspension()+ }+ }+ self.log.info("Observing keyboard, dictation-mode, end-meeting, and app lifecycle notifications")}}@@ -212,6 +242,20 @@ final class LiveActivityController {backgroundTask = .invalid}+ /// The app can suspend as soon as the notification handler returns, before the+ /// queued end lands, so a short background task holds it until the reconcile is done.+ private func reconcileBeforeSuspension() {+ var task = UIBackgroundTaskIdentifier.invalid+ let finish = {+ guard task != .invalid else { return }+ UIApplication.shared.endBackgroundTask(task)+ task = .invalid+ }+ task = UIApplication.shared.beginBackgroundTask(+ withName: "OpenWhisprLiveActivitySuspend", expirationHandler: finish)+ reconcile(requestOnly: true, completion: finish)+ }+// MARK: - Resolve + applyprivate func onMain(_ work: @escaping () -> Void) {@@ -276,6 +320,7 @@ final class LiveActivityController {meeting: meeting,keyboardRecording: isRecordingActive(),dictationMode: isDictationModeEnabled(),+ appAwake: UIApplication.shared.applicationState != .background || isWarmMicHeld(),now: now)else {await endAllActivities()@@ -326,6 +371,29 @@ final class LiveActivityController {}}#endif++ /// The process exits as soon as willTerminate returns, so the end must land before+ /// this does. It bypasses the op queue: that runs on the main actor, which the wait+ /// below blocks. iOS only sends willTerminate to a running app (the warm mic or a+ /// meeting kept it awake); a suspended app is killed without it.+ private func endAllBeforeTermination() {+ #if canImport(ActivityKit)+ if #available(iOS 16.2, *) {+ let done = DispatchSemaphore(value: 0)+ // High priority: the blocked main thread can't donate its priority through a semaphore.+ Task.detached(priority: .high) {+ for activity in Activity<RecordingActivityAttributes>.activities {+ await activity.end(nil, dismissalPolicy: .immediate)+ }+ done.signal()+ }+ // willTerminate gets about 5 seconds before iOS kills the process.+ if done.wait(timeout: .now() + 2) == .timedOut {+ log.error("Timed out ending Live Activities before termination")+ }+ }+ #endif+ }}/// Carries a Darwin observer's handler through the C callback's context pointer.diff --git a/openwhispr-mobile/modules/live-activity/ios/LiveActivityResolver.swift b/openwhispr-mobile/modules/live-activity/ios/LiveActivityResolver.swiftindex 5e0a17473..0accfd3ef 100644--- a/openwhispr-mobile/modules/live-activity/ios/LiveActivityResolver.swift+++ b/openwhispr-mobile/modules/live-activity/ios/LiveActivityResolver.swift@@ -22,10 +22,14 @@ public struct MeetingSnapshot: Equatable {/// keyboard/dictation-mode events can never overwrite or end it mid-meeting; when the/// meeting clears, the activity falls back to the dictation session (or ends).public enum LiveActivityResolver {+ /// `appAwake`: the app is foreground, or the warm mic keeps it running in the+ /// background. Otherwise it is about to suspend, and iOS can kill a suspended app+ /// without a willTerminate, so an idle session card would outlive it.public static func resolve(meeting: MeetingSnapshot?,keyboardRecording: Bool,dictationMode: Bool,+ appAwake: Bool,now: Date) -> RecordingActivityContentState? {if let meeting {@@ -42,7 +46,7 @@ public enum LiveActivityResolver {if keyboardRecording {return RecordingActivityContentState(phase: .recording, startedAt: now)}- if dictationMode {+ if dictationMode && appAwake {return RecordingActivityContentState(phase: .idle, startedAt: now)}return nildiff --git a/openwhispr-mobile/modules/live-activity/tests/LiveActivityResolverTests.swift b/openwhispr-mobile/modules/live-activity/tests/LiveActivityResolverTests.swiftindex d70a4e728..6cf0e175e 100644--- a/openwhispr-mobile/modules/live-activity/tests/LiveActivityResolverTests.swift+++ b/openwhispr-mobile/modules/live-activity/tests/LiveActivityResolverTests.swift@@ -21,36 +21,53 @@ struct LiveActivityResolverTests {// A meeting wins over every keyboard/dictation combination.for keyboard in [false, true] {for dictation in [false, true] {- check(- LiveActivityResolver.resolve(- meeting: recording, keyboardRecording: keyboard, dictationMode: dictation, now: now)- == RecordingActivityContentState(- mode: .meeting, phase: .recording, startedAt: start, title: "Weekly sync"),- "recording meeting wins (keyboard=\(keyboard), dictation=\(dictation))")- check(- LiveActivityResolver.resolve(- meeting: processing, keyboardRecording: keyboard, dictationMode: dictation, now: now)- == RecordingActivityContentState(- mode: .meeting, phase: .processing, startedAt: start, recordedSeconds: 2530),- "processing meeting wins (keyboard=\(keyboard), dictation=\(dictation))")+ for awake in [false, true] {+ let flags = "keyboard=\(keyboard), dictation=\(dictation), awake=\(awake)"+ check(+ LiveActivityResolver.resolve(+ meeting: recording, keyboardRecording: keyboard, dictationMode: dictation,+ appAwake: awake, now: now)+ == RecordingActivityContentState(+ mode: .meeting, phase: .recording, startedAt: start, title: "Weekly sync"),+ "recording meeting wins (\(flags))")+ check(+ LiveActivityResolver.resolve(+ meeting: processing, keyboardRecording: keyboard, dictationMode: dictation,+ appAwake: awake, now: now)+ == RecordingActivityContentState(+ mode: .meeting, phase: .processing, startedAt: start, recordedSeconds: 2530),+ "processing meeting wins (\(flags))")+ }}}// Without a meeting: keyboard recording > dictation idle > nothing.let keyboardOnly = RecordingActivityContentState(phase: .recording, startedAt: now)check(- LiveActivityResolver.resolve(meeting: nil, keyboardRecording: true, dictationMode: false, now: now)+ LiveActivityResolver.resolve(meeting: nil, keyboardRecording: true, dictationMode: false, appAwake: true, now: now)== keyboardOnly, "keyboard recording without dictation mode")check(- LiveActivityResolver.resolve(meeting: nil, keyboardRecording: true, dictationMode: true, now: now)+ LiveActivityResolver.resolve(meeting: nil, keyboardRecording: true, dictationMode: true, appAwake: true, now: now)== keyboardOnly, "keyboard recording with dictation mode")check(- LiveActivityResolver.resolve(meeting: nil, keyboardRecording: false, dictationMode: true, now: now)+ LiveActivityResolver.resolve(meeting: nil, keyboardRecording: false, dictationMode: true, appAwake: true, now: now)== RecordingActivityContentState(phase: .idle, startedAt: now), "dictation idle")check(- LiveActivityResolver.resolve(meeting: nil, keyboardRecording: false, dictationMode: false, now: now)+ LiveActivityResolver.resolve(meeting: nil, keyboardRecording: false, dictationMode: false, appAwake: true, now: now)== nil, "nothing to show ends the activity")+ // Backgrounded without the warm mic, the app is about to suspend, and iOS can kill+ // a suspended app without warning: the idle card must not outlive it.+ check(+ LiveActivityResolver.resolve(meeting: nil, keyboardRecording: false, dictationMode: true, appAwake: false, now: now)+ == nil, "dictation idle ends once the app can suspend")+ check(+ LiveActivityResolver.resolve(meeting: nil, keyboardRecording: true, dictationMode: true, appAwake: false, now: now)+ == keyboardOnly, "a keyboard recording keeps its card while backgrounded")+ check(+ LiveActivityResolver.resolve(meeting: nil, keyboardRecording: false, dictationMode: false, appAwake: false, now: now)+ == nil, "nothing to show while backgrounded ends the activity")+// Stale dates.let meetingState = RecordingActivityContentState(mode: .meeting, phase: .recording, startedAt: start)