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
feat(mobile): Return to the host app after keyboard Activate on iOS 26.4+ (#2365)
Chad Piha1f2be6d4a956
diff --git a/.github/workflows/mobile-ci.yml b/.github/workflows/mobile-ci.ymlindex 0b74c65d2..4336b65c0 100644--- a/.github/workflows/mobile-ci.yml+++ b/.github/workflows/mobile-ci.yml@@ -109,6 +109,8 @@ jobs:persist-credentials: false- name: Run native provider transport testsrun: python3 openwhispr-mobile/modules/background-uploader/tests/run-provider-transport-tests.py+ - name: Run keyboard return resolver tests+ run: bash openwhispr-mobile/modules/app-group-storage/tests/run-return-target-tests.sh- name: Run hotkey dictation logic testsrun: python3 openwhispr-mobile/plugins/hotkey-dictation/tests/run-hotkey-logic-tests.py- name: Run Live Activity resolver testsdiff --git a/openwhispr-mobile/app/(tabs)/_layout.tsx b/openwhispr-mobile/app/(tabs)/_layout.tsxindex 3d0e1a42a..43c47047e 100644--- a/openwhispr-mobile/app/(tabs)/_layout.tsx+++ b/openwhispr-mobile/app/(tabs)/_layout.tsx@@ -19,7 +19,8 @@ export default function TabsLayout() {const isNoteEditor =segments[1] === '(notes)' && segments[2] !== undefined && !NOTES_STATIC_ROUTES.has(segments[2]);// The keyboard-dictation handoff takes over the Record tab with a full-screen- // "Swipe back to your app" prompt — hide the tab bar so it reads as a takeover.+ // return screen ("Returning to your app…", "Back to <App>", or the swipe+ // instructions) — hide the tab bar so it reads as a takeover.const handoffActive = useHandoffStore((s) => s.isActive);return (diff --git a/openwhispr-mobile/modules/app-group-storage/README.md b/openwhispr-mobile/modules/app-group-storage/README.mdindex e8ca11049..ca6d9dc91 100644--- a/openwhispr-mobile/modules/app-group-storage/README.md+++ b/openwhispr-mobile/modules/app-group-storage/README.md@@ -17,7 +17,7 @@ import {- `setItem(key, value)`, `getItem(key)`, `removeItem(key)` — KV access on the shared suite- `startNativeRecording()`, `stopNativeRecording()`, `endProcessingTask()` — keyboard-extension recording lifecycle bridges- `convertRecordingToWav(fileUri)` — converts a keyboard recording to `16 kHz` mono WAV for provider-format fallback-- `returnToPreviousApp()` — return-to-host-app deep link after a keyboard handoff+- `returnToPreviousApp()`, `openHostApp()` — send the user back to the keyboard's host app after a handoff; resolve a `ReturnOutcome` (`opened` / `failed` / `no_target` / `skipped`). On iOS 26.4+ the host comes from `HostAppObserver` (the extension can no longer see it)- Three event subscriptions emitted by the iOS keyboard extension when a recording finishes, errors, or starts in the background## Keys it storesdiff --git a/openwhispr-mobile/modules/app-group-storage/expo-module.config.json b/openwhispr-mobile/modules/app-group-storage/expo-module.config.jsonindex 11608e922..09f8d8b9e 100644--- a/openwhispr-mobile/modules/app-group-storage/expo-module.config.json+++ b/openwhispr-mobile/modules/app-group-storage/expo-module.config.json@@ -1,6 +1,7 @@{"platforms": ["ios"],"ios": {- "modules": ["AppGroupStorageModule"]+ "modules": ["AppGroupStorageModule"],+ "appDelegateSubscribers": ["AppGroupStorageAppDelegate"]}}diff --git a/openwhispr-mobile/modules/app-group-storage/ios/AppGroupStorageAppDelegate.swift b/openwhispr-mobile/modules/app-group-storage/ios/AppGroupStorageAppDelegate.swiftnew file mode 100644index 000000000..dbcd1a5c3--- /dev/null+++ b/openwhispr-mobile/modules/app-group-storage/ios/AppGroupStorageAppDelegate.swift@@ -0,0 +1,16 @@+import ExpoModulesCore+import UIKit++/// Starts HostAppObserver before JS loads. On a cold launch from the keyboard+/// the host arrives about a second after launch and is gone once processed.+public class AppGroupStorageAppDelegate: ExpoAppDelegateSubscriber {+ public required init() {}++ public func application(+ _ application: UIApplication,+ didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil+ ) -> Bool {+ HostAppObserver.shared.start()+ return true+ }+}diff --git a/openwhispr-mobile/modules/app-group-storage/ios/AppGroupStorageModule.swift b/openwhispr-mobile/modules/app-group-storage/ios/AppGroupStorageModule.swiftindex 4ab414f24..fc145d933 100644--- a/openwhispr-mobile/modules/app-group-storage/ios/AppGroupStorageModule.swift+++ b/openwhispr-mobile/modules/app-group-storage/ios/AppGroupStorageModule.swift@@ -47,49 +47,6 @@ public class AppGroupStorageModule: Module {private static var darwinAgentActionNotificationName: String {"\(notificationPrefix).agentAction"}- private static let hostBundleFallbackUrls: [String: String] = [- "com.whatsapp.WhatsApp": "whatsapp://send",- "net.whatsapp.WhatsApp": "whatsapp://send",- "net.whatsapp.WhatsAppSMB": "whatsapp-business://",- "com.burbn.instagram": "instagram://",- "com.atebits.Tweetie2": "twitter://",- "com.facebook.Facebook": "fb://",- "com.facebook.Messenger": "fb-messenger://",- "com.tinyspeck.chatlyio": "slack://",- "com.skype.skype": "skype://",- "ph.telegra.Telegraph": "tg://",- "org.whispersystems.signal": "sgnl://",- "com.viber": "viber://",- "jp.naver.line": "line://",- "com.google.Gmail": "googlegmail://",- "com.google.Docs": "googledocs://",- "com.microsoft.Office.Outlook": "ms-outlook://",- "com.microsoft.skype.teams": "msteams://",- "com.apple.mobilemail": "message://",- "com.apple.MobileSMS": "sms://",- "com.apple.mobilenotes": "mobilenotes://",- "com.microsoft.teams": "msteams://",- "notion.id": "notion://",- "com.discord.Discord": "discord://",- "com.linkedin.LinkedIn": "linkedin://",- "com.reddit.Reddit": "reddit://",- "com.hammerandchisel.discord": "discord://",- "us.zoom.videomeetings": "zoomus://",- "com.openai.chat": "chatgpt://",- "com.google.chrome.ios": "googlechrome://",- "com.apple.mobilesafari": "x-web-search://",- "com.zhiliaoapp.musically": "snssdk1128://",- "com.snapchat.snapchat": "snapchat://",- "com.toyopagroup.picaboo": "snapchat://"- ]- private static let normalizedHostBundleFallbackUrls: [String: String] = {- var normalized: [String: String] = [:]- for (bundle, url) in hostBundleFallbackUrls {- normalized[bundle.lowercased()] = url- }- return normalized- }()-private let audioStateLock = NSLock()// Serializes session/engine lifecycle (start/stop/arm/release/rebuild).// startNativeRecording runs on the JS thread while the foreground re-arm and@@ -140,9 +97,10 @@ public class AppGroupStorageModule: Module {private var foregroundHeartbeatTimer: Timer?private let containingAppForegroundKey = "containing_app_foreground_at_ms"- private var returnNavigationInFlight: Bool = false- private var lastReturnAttemptUrl: String?- private var lastReturnAttemptAt: Date?+ private let returnAttemptGate = ReturnAttemptGate()+ // The host the last return resolved, kept for the "Back to <App>" button:+ // the extension keys are cleared on read and the observed host goes stale.+ private var lastReturnTarget: ReturnTarget?public func definition() -> ModuleDefinition {Name("AppGroupStorage")@@ -259,13 +217,21 @@ public class AppGroupStorageModule: Module {return modes.compactMap { $0.primaryLanguage }}- Function("returnToPreviousApp") { () -> Void in+ AsyncFunction("returnToPreviousApp") { (promise: Promise) inself.logMarker("returnToPreviousApp.invoked")+ let invokedAt = Date()DispatchQueue.main.async {- // On a cold launch UIApplication.open can fail while the app is still- // transitioning to active; a couple of short retries covers that- // window. Retrying a failed open is safe — nothing happened.- self.navigateBackToPreviousApp(maxRetries: 2)+ self.returnToHost(invokedAt: invokedAt) { outcome in+ promise.resolve(outcome.payload)+ }+ }+ }++ AsyncFunction("openHostApp") { (promise: Promise) in+ DispatchQueue.main.async {+ self.openLastHost { outcome in+ promise.resolve(outcome.payload)+ }}}@@ -2013,129 +1979,136 @@ public class AppGroupStorageModule: Module {// MARK: - Return to Previous App- private func navigateBackToPreviousApp(maxRetries: Int = 0, delay: TimeInterval = 0.2) {- guard let defaults = UserDefaults(suiteName: appGroupId) else {- #if DEBUG- NSLog("[AppGroupStorage] navigateBack: no app group defaults")- #endif- return+ private func returnToHost(invokedAt: Date, completion: @escaping (ReturnOutcome) -> Void) {+ guard let attempt = beginReturnAttempt(+ timeoutOutcome: {+ // Resolved but never heard back from `open`: offer the button for that host.+ guard let target = self.lastReturnTarget else {+ return ReturnOutcome(status: .noTarget, hostName: nil)+ }+ return ReturnOutcome(status: .failed, hostName: target.hostName)+ },+ completion: completion+ ) else { return }+ lastReturnTarget = nil++ let defaults = UserDefaults(suiteName: appGroupId)+ defaults?.synchronize()+ let extensionUrl = defaults?.string(forKey: "keyboard_return_url")+ let extensionBundle = defaults?.string(forKey: "keyboard_return_bundle")+ // One handoff, one read. A key left behind after a failed return would+ // send a later handoff (whose host the extension can't see) to this app.+ defaults?.removeObject(forKey: "keyboard_return_url")+ defaults?.removeObject(forKey: "keyboard_return_bundle")+ defaults?.synchronize()++ let openResolved: (ReturnTarget?) -> Void = { target in+ guard let target else {+ self.logMarker("navigateBack.missingUrl")+ attempt.finish(ReturnOutcome(status: .noTarget, hostName: nil))+ return+ }+ self.lastReturnTarget = target+ self.logMarker("navigateBack.resolved", extra: "source=\(target.source.rawValue)")+ self.open(target, retriesLeft: 2, delay: 0.2, attempt: attempt)+ }++ let observer = HostAppObserver.shared+ let since = invokedAt.addingTimeInterval(-ReturnTargetResolver.observerLookBack)+ if let target = ReturnTargetResolver.resolve(+ extensionUrl: extensionUrl,+ extensionBundle: extensionBundle,+ observedBundle: observer.latest(since: since)+ ) {+ openResolved(target)+ } else if ReturnTargetResolver.extensionSawHost(extensionBundle) {+ openResolved(nil)+ } else {+ // JS usually asks before the observer has seen the host. Wait for a new+ // observation: the observer also reports every other app that shows a+ // keyboard (Spotlight, say), and an unresolvable one inside the look-back+ // window would otherwise end the wait at once.+ observer.waitForHost(since: Date(), timeout: ReturnTargetResolver.observerWaitTimeout) { observed in+ openResolved(ReturnTargetResolver.resolve(+ extensionUrl: extensionUrl,+ extensionBundle: extensionBundle,+ observedBundle: observed+ ))+ }}- defaults.synchronize()+ }- guard let url = resolveReturnUrl(defaults: defaults) else {- #if DEBUG- NSLog("[AppGroupStorage] navigateBack: no return URL found in UserDefaults")- #endif- logMarker("navigateBack.missingUrl")+ private func openLastHost(completion: @escaping (ReturnOutcome) -> Void) {+ guard let target = lastReturnTarget else {+ completion(ReturnOutcome(status: .noTarget, hostName: nil))return}-- let urlString = url.absoluteString- if returnNavigationInFlight {- #if DEBUG- NSLog("[AppGroupStorage] navigateBack: open already in flight, skipping duplicate")- #endif- logMarker("navigateBack.skippedInFlight", extra: "url=\(urlString)")- return+ guard let attempt = beginReturnAttempt(+ timeoutOutcome: { ReturnOutcome(status: .failed, hostName: target.hostName) },+ completion: completion+ ) else { return }+ // A button tap is user-initiated and the app is active: one attempt, no retries.+ open(target, retriesLeft: 0, delay: 0, attempt: attempt)+ }++ /// Nil (after resolving `skipped`) while another return is in flight.+ private func beginReturnAttempt(+ timeoutOutcome: @escaping () -> ReturnOutcome,+ completion: @escaping (ReturnOutcome) -> Void+ ) -> ReturnAttempt? {+ let attempt = returnAttemptGate.begin(+ deadline: ReturnTargetResolver.returnDeadline,+ schedule: { delay, work in DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: work) },+ timeoutOutcome: {+ self.logMarker("navigateBack.deadline")+ return timeoutOutcome()+ },+ completion: completion+ )+ if attempt == nil {+ logMarker("navigateBack.skippedInFlight")+ completion(ReturnOutcome(status: .skipped, hostName: nil))}+ return attempt+ }- let now = Date()- if let lastUrl = lastReturnAttemptUrl,- let lastAttemptAt = lastReturnAttemptAt,- lastUrl == urlString,- now.timeIntervalSince(lastAttemptAt) < 1.2- {- #if DEBUG- NSLog("[AppGroupStorage] navigateBack: skipping rapid duplicate for %@", urlString)- #endif- logMarker("navigateBack.skippedRapidDuplicate", extra: "url=\(urlString)")+ private func open(+ _ target: ReturnTarget,+ retriesLeft: Int,+ delay: TimeInterval,+ attempt: ReturnAttempt+ ) {+ let urlString = target.url.absoluteString+ // The deadline already settled this return (JS may show the button or a+ // newer handoff may be under way), so a retry must not switch apps now.+ guard !attempt.isFinished else {+ logMarker("navigateBack.abandoned", extra: "url=\(urlString)")return}-- returnNavigationInFlight = true- lastReturnAttemptUrl = urlString- lastReturnAttemptAt = now-- #if DEBUG- NSLog("[AppGroupStorage] navigateBack: attempting open %@", urlString)- #endiflogMarker("navigateBack.attemptOpen", extra: "url=\(urlString)")- UIApplication.shared.open(url, options: [:]) { [weak self] success in- guard let self else { return }- self.returnNavigationInFlight = false- #if DEBUG- NSLog("[AppGroupStorage] navigateBack: open result=%@", success ? "success" : "failed")- #endif+ let appWasActive = UIApplication.shared.applicationState == .active+ UIApplication.shared.open(target.url, options: [:]) { success inself.logMarker(success ? "navigateBack.openSuccess" : "navigateBack.openFailed",extra: "url=\(urlString)")if success {- defaults.removeObject(forKey: "keyboard_return_url")- defaults.removeObject(forKey: "keyboard_return_bundle")- defaults.synchronize()- self.lastReturnAttemptUrl = nil- self.lastReturnAttemptAt = nil+ attempt.finish(ReturnOutcome(status: .opened, hostName: target.hostName))return}-- guard maxRetries > 0 else {- #if DEBUG- NSLog("[AppGroupStorage] navigateBack: exhausted retries for %@", urlString)- #endif- self.logMarker("navigateBack.retryExhausted", extra: "url=\(urlString)")+ guard ReturnTargetResolver.shouldRetry(+ openSucceeded: false, appWasActive: appWasActive, retriesLeft: retriesLeft+ ) else {+ self.logMarker("navigateBack.openFinalFailure", extra: "wasActive=\(appWasActive)")+ attempt.finish(ReturnOutcome(status: .failed, hostName: target.hostName))return}-DispatchQueue.main.asyncAfter(deadline: .now() + delay) {- self.navigateBackToPreviousApp(- maxRetries: maxRetries - 1,- delay: min(delay * 1.6, 1.0)- )+ self.open(target, retriesLeft: retriesLeft - 1, delay: min(delay * 1.6, 1.0), attempt: attempt)}}}- private func resolveReturnUrl(defaults: UserDefaults) -> URL? {- if let rawUrl = defaults.string(forKey: "keyboard_return_url"),- let normalizedUrl = normalizeReturnUrl(rawUrl) {- defaults.set(normalizedUrl.absoluteString, forKey: "keyboard_return_url")- defaults.synchronize()- return normalizedUrl- }-- guard let hostBundle = defaults.string(forKey: "keyboard_return_bundle") else {- return nil- }-- let trimmedBundle = hostBundle.trimmingCharacters(in: .whitespacesAndNewlines)- guard !trimmedBundle.isEmpty else {- return nil- }-- guard let fallbackUrlString =- Self.hostBundleFallbackUrls[trimmedBundle]- ?? Self.normalizedHostBundleFallbackUrls[trimmedBundle.lowercased()],- let fallbackUrl = URL(string: fallbackUrlString) else {- return nil- }-- defaults.set(fallbackUrlString, forKey: "keyboard_return_url")- defaults.synchronize()- return fallbackUrl- }-- private func normalizeReturnUrl(_ rawUrl: String) -> URL? {- let trimmed = rawUrl.trimmingCharacters(in: .whitespacesAndNewlines)- guard !trimmed.isEmpty else {- return nil- }-- let normalized =- trimmed.caseInsensitiveCompare("whatsapp://") == .orderedSame ? "whatsapp://send" : trimmed- return URL(string: normalized)- }-// MARK: - Background Taskprivate func endBackgroundTask() {diff --git a/openwhispr-mobile/modules/app-group-storage/ios/HostAppObserver.swift b/openwhispr-mobile/modules/app-group-storage/ios/HostAppObserver.swiftnew file mode 100644index 000000000..4729b2a4f--- /dev/null+++ b/openwhispr-mobile/modules/app-group-storage/ios/HostAppObserver.swift@@ -0,0 +1,105 @@+import UIKit++/// Learns which app opened a keyboard handoff.+///+/// iOS 26.4 stopped telling the keyboard extension its host (`_hostBundleID`+/// returns "<null>"). UIKit in the containing app still receives the remote+/// keyboard's source bundle in `_UIRemoteKeyboards.currentState`, about a second+/// after the keyboard opens the app. The value is transient (cleared once+/// processed), so it is observed from launch, never polled.+///+/// This is a UIKit implementation detail, not API. Every hop is checked; when+/// one is missing the observer stays inert and returns fall back to the swipe screen.+final class HostAppObserver: NSObject {+ static let shared = HostAppObserver()++ private(set) var isAvailable = false+ private var remoteKeyboards: NSObject?+ private var lastBundle: String?+ private var lastObservedAt: Date?+ private var waiters: [UUID: Waiter] = [:]++ private struct Waiter {+ let since: Date+ let completion: (String?) -> Void+ }++ func start() {+ dispatchPrecondition(condition: .onQueue(.main))+ guard remoteKeyboards == nil else { return }+ guard let remoteKeyboardsClass = NSClassFromString("_UIRemoteKeyboards") as? NSObject.Type else {+ log("unavailable: no _UIRemoteKeyboards")+ return+ }+ let sharedSelector = NSSelectorFromString("sharedRemoteKeyboards")+ guard remoteKeyboardsClass.responds(to: sharedSelector),+ let shared = remoteKeyboardsClass.perform(sharedSelector)?.takeUnretainedValue() as? NSObject,+ shared.responds(to: NSSelectorFromString("currentState"))+ else {+ log("unavailable: no sharedRemoteKeyboards.currentState")+ return+ }+ remoteKeyboards = shared+ shared.addObserver(self, forKeyPath: "currentState", options: [.new, .initial], context: nil)+ isAvailable = true+ log("installed")+ }++ func latest(since: Date) -> String? {+ guard let lastBundle, let lastObservedAt, lastObservedAt >= since else { return nil }+ return lastBundle+ }++ func waitForHost(since: Date, timeout: TimeInterval, completion: @escaping (String?) -> Void) {+ dispatchPrecondition(condition: .onQueue(.main))+ if let bundle = latest(since: since) {+ completion(bundle)+ return+ }+ guard isAvailable else {+ completion(nil)+ return+ }+ let id = UUID()+ waiters[id] = Waiter(since: since, completion: completion)+ DispatchQueue.main.asyncAfter(deadline: .now() + timeout) { [weak self] in+ guard let waiter = self?.waiters.removeValue(forKey: id) else { return }+ waiter.completion(nil)+ }+ }++ override func observeValue(+ forKeyPath keyPath: String?,+ of object: Any?,+ change: [NSKeyValueChangeKey: Any]?,+ context: UnsafeMutableRawPointer?+ ) {+ // NSNull (cleared state) is an NSObject that doesn't respond, so it reads as nil.+ let state = change?[.newKey] as? NSObject+ let sourceSelector = NSSelectorFromString("sourceBundleIdentifier")+ let bundle = state?.responds(to: sourceSelector) == true+ ? state?.perform(sourceSelector)?.takeUnretainedValue() as? String+ : nil+ DispatchQueue.main.async { self.record(bundle) }+ }++ private func record(_ rawBundle: String?) {+ guard let bundle = rawBundle?.trimmingCharacters(in: .whitespacesAndNewlines), !bundle.isEmpty,+ !ReturnTargetResolver.isContainingApp(bundle, appBundle: Bundle.main.bundleIdentifier ?? "")+ else { return }+ let observedAt = Date()+ lastBundle = bundle+ lastObservedAt = observedAt+ log("detected \(bundle)")+ for (id, waiter) in waiters where observedAt >= waiter.since {+ waiters.removeValue(forKey: id)+ waiter.completion(bundle)+ }+ }++ private func log(_ message: String) {+ #if DEBUG+ NSLog("[HostAppObserver] %@", message)+ #endif+ }+}diff --git a/openwhispr-mobile/modules/app-group-storage/ios/ReturnTargetResolver.swift b/openwhispr-mobile/modules/app-group-storage/ios/ReturnTargetResolver.swiftnew file mode 100644index 000000000..220c8cdb8--- /dev/null+++ b/openwhispr-mobile/modules/app-group-storage/ios/ReturnTargetResolver.swift@@ -0,0 +1,208 @@+import Foundation++/// An app the keyboard handoff can send the user back to: the URL that opens+/// it and the name the "Back to <App>" button shows.+struct HostApp: Equatable {+ let returnUrl: String+ let name: String+}++enum HostAppCatalog {+ static let entries: [String: HostApp] = [+ "com.whatsapp.WhatsApp": HostApp(returnUrl: "whatsapp://send", name: "WhatsApp"),+ "net.whatsapp.WhatsApp": HostApp(returnUrl: "whatsapp://send", name: "WhatsApp"),+ "net.whatsapp.WhatsAppSMB": HostApp(returnUrl: "whatsapp-business://", name: "WhatsApp Business"),+ "com.burbn.instagram": HostApp(returnUrl: "instagram://", name: "Instagram"),+ "com.atebits.Tweetie2": HostApp(returnUrl: "twitter://", name: "X"),+ "com.facebook.Facebook": HostApp(returnUrl: "fb://", name: "Facebook"),+ "com.facebook.Messenger": HostApp(returnUrl: "fb-messenger://", name: "Messenger"),+ "com.tinyspeck.chatlyio": HostApp(returnUrl: "slack://", name: "Slack"),+ "com.skype.skype": HostApp(returnUrl: "skype://", name: "Skype"),+ "ph.telegra.Telegraph": HostApp(returnUrl: "tg://", name: "Telegram"),+ "org.whispersystems.signal": HostApp(returnUrl: "sgnl://", name: "Signal"),+ "com.viber": HostApp(returnUrl: "viber://", name: "Viber"),+ "jp.naver.line": HostApp(returnUrl: "line://", name: "LINE"),+ "com.google.Gmail": HostApp(returnUrl: "googlegmail://", name: "Gmail"),+ "com.google.Docs": HostApp(returnUrl: "googledocs://", name: "Google Docs"),+ "com.microsoft.Office.Outlook": HostApp(returnUrl: "ms-outlook://", name: "Outlook"),+ "com.microsoft.skype.teams": HostApp(returnUrl: "msteams://", name: "Teams"),+ "com.apple.mobilemail": HostApp(returnUrl: "message://", name: "Mail"),+ "com.apple.MobileSMS": HostApp(returnUrl: "sms://", name: "Messages"),+ "com.apple.mobilenotes": HostApp(returnUrl: "mobilenotes://", name: "Notes"),+ "com.microsoft.teams": HostApp(returnUrl: "msteams://", name: "Teams"),+ "notion.id": HostApp(returnUrl: "notion://", name: "Notion"),+ "com.discord.Discord": HostApp(returnUrl: "discord://", name: "Discord"),+ "com.linkedin.LinkedIn": HostApp(returnUrl: "linkedin://", name: "LinkedIn"),+ "com.reddit.Reddit": HostApp(returnUrl: "reddit://", name: "Reddit"),+ "com.hammerandchisel.discord": HostApp(returnUrl: "discord://", name: "Discord"),+ "us.zoom.videomeetings": HostApp(returnUrl: "zoomus://", name: "Zoom"),+ "com.openai.chat": HostApp(returnUrl: "chatgpt://", name: "ChatGPT"),+ "com.google.chrome.ios": HostApp(returnUrl: "googlechrome://", name: "Chrome"),+ "com.apple.mobilesafari": HostApp(returnUrl: "x-web-search://", name: "Safari"),+ "com.zhiliaoapp.musically": HostApp(returnUrl: "snssdk1128://", name: "TikTok"),+ "com.snapchat.snapchat": HostApp(returnUrl: "snapchat://", name: "Snapchat"),+ "com.toyopagroup.picaboo": HostApp(returnUrl: "snapchat://", name: "Snapchat"),+ ]++ private static let normalizedEntries: [String: HostApp] = {+ var normalized: [String: HostApp] = [:]+ for (bundle, app) in entries {+ normalized[bundle.lowercased()] = app+ }+ return normalized+ }()++ static func lookup(_ bundle: String?) -> HostApp? {+ guard let trimmed = bundle?.trimmingCharacters(in: .whitespacesAndNewlines), !trimmed.isEmpty else {+ return nil+ }+ return entries[trimmed] ?? normalizedEntries[trimmed.lowercased()]+ }+}++enum ReturnTargetSource: String {+ case extensionUrl = "extension_url"+ case extensionBundle = "extension_bundle"+ case observer+}++struct ReturnTarget: Equatable {+ let url: URL+ let hostName: String?+ let source: ReturnTargetSource+}++enum ReturnOutcomeStatus: String {+ case opened+ case failed+ case noTarget = "no_target"+ case skipped+}++struct ReturnOutcome {+ let status: ReturnOutcomeStatus+ let hostName: String?++ var payload: [String: Any] {+ var result: [String: Any] = ["status": status.rawValue]+ if let hostName {+ result["hostName"] = hostName+ }+ return result+ }+}++enum ReturnTargetResolver {+ /// How long before a return request an observed host still belongs to this+ /// handoff. Keeps a warm launch from returning to an app the user left minutes ago.+ static let observerLookBack: TimeInterval = 5+ /// How long a return waits for the observer. On a cold launch the host arrives+ /// about a second after the keyboard opens the app, usually after JS asks to return.+ static let observerWaitTimeout: TimeInterval = 2+ /// Longest a return may stay in flight. Covers the observer wait plus the+ /// cold-launch retries, and ends well before JS's 6 s timeout (the main-queue+ /// hop can lag on a cold launch) so JS still gets the real outcome rather+ /// than its own fallback.+ static let returnDeadline: TimeInterval = 4.5++ /// The extension's own detection wins (it still works before iOS 26.4). The+ /// observer only stands in when the extension saw no host: a host it named+ /// but that isn't in the catalog is still that host, not the last one observed.+ static func resolve(extensionUrl: String?, extensionBundle: String?, observedBundle: String?) -> ReturnTarget? {+ let extensionHost = HostAppCatalog.lookup(extensionBundle)+ if let rawUrl = extensionUrl, let url = normalizeReturnUrl(rawUrl) {+ return ReturnTarget(url: url, hostName: extensionHost?.name, source: .extensionUrl)+ }+ if let host = extensionHost, let url = URL(string: host.returnUrl) {+ return ReturnTarget(url: url, hostName: host.name, source: .extensionBundle)+ }+ if !extensionSawHost(extensionBundle), let host = HostAppCatalog.lookup(observedBundle),+ let url = URL(string: host.returnUrl) {+ return ReturnTarget(url: url, hostName: host.name, source: .observer)+ }+ return nil+ }++ /// The extension names its host before iOS 26.4. When it did, waiting on the+ /// observer would only name the same host again.+ static func extensionSawHost(_ extensionBundle: String?) -> Bool {+ !(extensionBundle?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?? true)+ }++ static func normalizeReturnUrl(_ rawUrl: String) -> URL? {+ let trimmed = rawUrl.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !trimmed.isEmpty else {+ return nil+ }+ let normalized =+ trimmed.caseInsensitiveCompare("whatsapp://") == .orderedSame ? "whatsapp://send" : trimmed+ return URL(string: normalized)+ }++ static func isFresh(observedAt: Date, invokedAt: Date) -> Bool {+ observedAt >= invokedAt.addingTimeInterval(-observerLookBack)+ }++ /// The containing app and its extensions host the keyboard in place, so they+ /// are never a return target. Mirrors the keyboard's `isContainingAppBundle`.+ static func isContainingApp(_ bundle: String, appBundle: String) -> Bool {+ let host = bundle.lowercased()+ let app = appBundle.lowercased()+ guard !app.isEmpty else { return false }+ return host == app || host.hasPrefix(app + ".")+ }++ /// A cold launch can fail `open` while the app is still becoming active, and+ /// retrying is safe. An `open` made while the app was already active is final:+ /// iOS returns false when the user cancels its "wants to open" prompt, and a+ /// retry would show it again. The state is sampled before the call because the+ /// app is inactive while that prompt is up, so afterwards the two cases look alike.+ static func shouldRetry(openSucceeded: Bool, appWasActive: Bool, retriesLeft: Int) -> Bool {+ !openSucceeded && !appWasActive && retriesLeft > 0+ }+}++/// One return in flight at a time, finished exactly once, and never longer than+/// its deadline: a hung `open` completion must not leave every later handoff+/// refused as `skipped` (and stuck on "Returning…").+final class ReturnAttemptGate {+ private var current: ReturnAttempt?++ var isInFlight: Bool { current.map { !$0.isFinished } ?? false }++ /// Starts an attempt, or returns nil while another is in flight. `schedule`+ /// runs the deadline (the main queue in the app).+ func begin(+ deadline: TimeInterval,+ schedule: (TimeInterval, @escaping () -> Void) -> Void,+ timeoutOutcome: @escaping () -> ReturnOutcome,+ completion: @escaping (ReturnOutcome) -> Void+ ) -> ReturnAttempt? {+ guard !isInFlight else { return nil }+ let attempt = ReturnAttempt(completion: completion)+ current = attempt+ schedule(deadline) {+ guard !attempt.isFinished else { return }+ attempt.finish(timeoutOutcome())+ }+ return attempt+ }+}++/// A single return's outcome, reported once. Work still queued for it (an+/// observer wait, an `open` retry) checks `isFinished` and stops once the+/// deadline has settled it, so it can't switch apps under a UI that moved on.+final class ReturnAttempt {+ private(set) var isFinished = false+ private let completion: (ReturnOutcome) -> Void++ init(completion: @escaping (ReturnOutcome) -> Void) {+ self.completion = completion+ }++ func finish(_ outcome: ReturnOutcome) {+ guard !isFinished else { return }+ isFinished = true+ completion(outcome)+ }+}diff --git a/openwhispr-mobile/modules/app-group-storage/src/__tests__/returnOutcome.test.ts b/openwhispr-mobile/modules/app-group-storage/src/__tests__/returnOutcome.test.tsnew file mode 100644index 000000000..aaca04037--- /dev/null+++ b/openwhispr-mobile/modules/app-group-storage/src/__tests__/returnOutcome.test.ts@@ -0,0 +1,35 @@+import { parseReturnOutcome } from '../returnOutcome';++describe('parseReturnOutcome', () => {+ it('keeps the host name for opened and failed', () => {+ expect(parseReturnOutcome({ status: 'opened', hostName: 'Slack' })).toEqual({+ status: 'opened',+ hostName: 'Slack',+ });+ expect(parseReturnOutcome({ status: 'failed', hostName: ' Messages ' })).toEqual({+ status: 'failed',+ hostName: 'Messages',+ });+ });++ it('treats a missing or blank host name as unknown', () => {+ expect(parseReturnOutcome({ status: 'failed' })).toEqual({ status: 'failed', hostName: null });+ expect(parseReturnOutcome({ status: 'opened', hostName: ' ' })).toEqual({+ status: 'opened',+ hostName: null,+ });+ });++ it('passes skipped and no_target through', () => {+ expect(parseReturnOutcome({ status: 'skipped' })).toEqual({ status: 'skipped' });+ expect(parseReturnOutcome({ status: 'no_target' })).toEqual({ status: 'no_target' });+ });++ // An unreadable result must fall back to the swipe screen, never to "Returning…".+ it.each([undefined, null, 'opened', 42, {}, { status: 'weird' }])(+ 'maps %p to no_target',+ (raw) => {+ expect(parseReturnOutcome(raw)).toEqual({ status: 'no_target' });+ },+ );+});diff --git a/openwhispr-mobile/modules/app-group-storage/src/index.ts b/openwhispr-mobile/modules/app-group-storage/src/index.tsindex 6383639c7..697076546 100644--- a/openwhispr-mobile/modules/app-group-storage/src/index.ts+++ b/openwhispr-mobile/modules/app-group-storage/src/index.ts@@ -1,5 +1,8 @@import { EventEmitter, requireNativeModule } from 'expo';import { Platform } from 'react-native';+import { NO_RETURN_TARGET, parseReturnOutcome, type ReturnOutcome } from './returnOutcome';++export { NO_RETURN_TARGET, parseReturnOutcome, type ReturnOutcome } from './returnOutcome';type EventSubscription = {remove(): void;@@ -14,7 +17,8 @@ interface AppGroupStorageModule {analyzeSpeechActivity(fileUri: string): Promise<SpeechActivityAnalysis>;convertRecordingToWav(fileUri: string): Promise<RecordingConversionResult>;getActiveInputModes(): string[];- returnToPreviousApp(): void;+ returnToPreviousApp(): Promise<unknown>;+ openHostApp(): Promise<unknown>;startNativeRecording(): boolean;stopNativeRecording(): void;endProcessingTask(): void;@@ -140,9 +144,24 @@ export const AppGroupStorage = {}},- returnToPreviousApp(): void {- if (!NativeModule) return;- NativeModule.returnToPreviousApp();+ /** Sends the user back to the keyboard's host app. Resolves `no_target` whenever it can't. */+ async returnToPreviousApp(): Promise<ReturnOutcome> {+ if (!NativeModule) return NO_RETURN_TARGET;+ try {+ return parseReturnOutcome(await NativeModule.returnToPreviousApp());+ } catch {+ return NO_RETURN_TARGET;+ }+ },++ /** "Back to <App>" button: reopens the host resolved by the last return. */+ async openHostApp(): Promise<ReturnOutcome> {+ if (!NativeModule) return NO_RETURN_TARGET;+ try {+ return parseReturnOutcome(await NativeModule.openHostApp());+ } catch {+ return NO_RETURN_TARGET;+ }},startNativeRecording(): boolean {diff --git a/openwhispr-mobile/modules/app-group-storage/src/returnOutcome.ts b/openwhispr-mobile/modules/app-group-storage/src/returnOutcome.tsnew file mode 100644index 000000000..4bf58c1ea--- /dev/null+++ b/openwhispr-mobile/modules/app-group-storage/src/returnOutcome.ts@@ -0,0 +1,23 @@+/** What happened when OpenWhispr tried to send the user back to the keyboard's host app. */+export type ReturnOutcome =+ | { status: 'opened'; hostName: string | null }+ | { status: 'failed'; hostName: string | null }+ | { status: 'no_target' }+ | { status: 'skipped' };++export const NO_RETURN_TARGET: ReturnOutcome = { status: 'no_target' };++export function parseReturnOutcome(raw: unknown): ReturnOutcome {+ if (!raw || typeof raw !== 'object') return NO_RETURN_TARGET;+ const { status, hostName } = raw as { status?: unknown; hostName?: unknown };+ const name = typeof hostName === 'string' && hostName.trim() ? hostName.trim() : null;+ switch (status) {+ case 'opened':+ case 'failed':+ return { status, hostName: name };+ case 'skipped':+ return { status: 'skipped' };+ default:+ return NO_RETURN_TARGET;+ }+}diff --git a/openwhispr-mobile/modules/app-group-storage/tests/ReturnTargetResolverTests.swift b/openwhispr-mobile/modules/app-group-storage/tests/ReturnTargetResolverTests.swiftnew file mode 100644index 000000000..24bb602e1--- /dev/null+++ b/openwhispr-mobile/modules/app-group-storage/tests/ReturnTargetResolverTests.swift@@ -0,0 +1,171 @@+import Foundation++@main+struct ReturnTargetResolverTests {+ static func main() {+ extensionUrlWinsAndKeepsTheBundleName()+ bareWhatsAppUrlIsNormalized()+ blankExtensionUrlFallsThroughToExtensionBundle()+ extensionBundleLookupIgnoresCaseAndWhitespace()+ observerIsUsedWhenTheExtensionKnowsNothing()+ extensionHostOutsideTheCatalogIgnoresTheObserver()+ unknownObservedBundleResolvesNothing()+ nothingKnownResolvesNothing()+ staleObservationIsIgnored()+ containingAppAndItsExtensionsAreNeverTheHost()+ shouldRetryOnlyWhileLaunching()+ outcomePayloadOmitsMissingHostName()+ everyCatalogEntryOpens()+ gateAllowsOneAttemptAtATime()+ gateDeadlineEndsAHungAttempt()+ lateFinishFromAnOldAttemptLeavesTheNewOneInFlight()+ print("ReturnTargetResolverTests: all passed")+ }++ static func extensionUrlWinsAndKeepsTheBundleName() {+ let target = ReturnTargetResolver.resolve(+ extensionUrl: "slack://", extensionBundle: "com.tinyspeck.chatlyio", observedBundle: "com.apple.MobileSMS")+ precondition(target?.url.absoluteString == "slack://", "extension URL must win")+ precondition(target?.hostName == "Slack", "name comes from the extension bundle")+ precondition(target?.source == .extensionUrl, "source is the extension URL")+ }++ static func bareWhatsAppUrlIsNormalized() {+ let target = ReturnTargetResolver.resolve(+ extensionUrl: " WhatsApp:// ", extensionBundle: nil, observedBundle: nil)+ precondition(target?.url.absoluteString == "whatsapp://send", "bare whatsapp:// opens the send screen")+ }++ static func blankExtensionUrlFallsThroughToExtensionBundle() {+ let target = ReturnTargetResolver.resolve(+ extensionUrl: " ", extensionBundle: "com.apple.MobileSMS", observedBundle: nil)+ precondition(target?.url.absoluteString == "sms://", "blank URL falls through to the bundle")+ precondition(target?.source == .extensionBundle, "source is the extension bundle")+ precondition(target?.hostName == "Messages", "Messages name")+ }++ static func extensionBundleLookupIgnoresCaseAndWhitespace() {+ precondition(HostAppCatalog.lookup(" COM.TINYSPECK.CHATLYIO\n")?.name == "Slack", "case/whitespace-insensitive")+ precondition(HostAppCatalog.lookup(nil) == nil, "nil bundle")+ precondition(HostAppCatalog.lookup("") == nil, "empty bundle")+ }++ static func observerIsUsedWhenTheExtensionKnowsNothing() {+ let target = ReturnTargetResolver.resolve(+ extensionUrl: nil, extensionBundle: nil, observedBundle: "com.tinyspeck.chatlyio")+ precondition(target?.url.absoluteString == "slack://", "observer bundle resolves")+ precondition(target?.source == .observer, "source is the observer")+ precondition(target?.hostName == "Slack", "observer host name")+ }++ static func extensionHostOutsideTheCatalogIgnoresTheObserver() {+ precondition(+ ReturnTargetResolver.resolve(+ extensionUrl: nil, extensionBundle: "com.example.unknown", observedBundle: "com.tinyspeck.chatlyio") == nil,+ "the extension's own host wins even when it can't be opened")+ precondition(ReturnTargetResolver.extensionSawHost(" com.example.unknown "), "a named host")+ precondition(!ReturnTargetResolver.extensionSawHost(" "), "a blank host")+ precondition(!ReturnTargetResolver.extensionSawHost(nil), "no host")+ }++ static func unknownObservedBundleResolvesNothing() {+ precondition(+ ReturnTargetResolver.resolve(extensionUrl: nil, extensionBundle: nil, observedBundle: "com.example.unknown") == nil,+ "a host outside the catalog has no return URL")+ }++ static func nothingKnownResolvesNothing() {+ precondition(+ ReturnTargetResolver.resolve(extensionUrl: nil, extensionBundle: nil, observedBundle: nil) == nil,+ "no inputs, no target")+ }++ static func staleObservationIsIgnored() {+ let invokedAt = Date(timeIntervalSince1970: 1_000)+ precondition(ReturnTargetResolver.isFresh(observedAt: invokedAt.addingTimeInterval(-4.9), invokedAt: invokedAt), "4.9 s before is fresh")+ precondition(!ReturnTargetResolver.isFresh(observedAt: invokedAt.addingTimeInterval(-5.1), invokedAt: invokedAt), "5.1 s before is stale")+ precondition(ReturnTargetResolver.isFresh(observedAt: invokedAt.addingTimeInterval(1.0), invokedAt: invokedAt), "after the request is fresh")+ }++ static func containingAppAndItsExtensionsAreNeverTheHost() {+ let app = "com.chadpiha.openwhispr"+ precondition(ReturnTargetResolver.isContainingApp("com.chadpiha.openwhispr", appBundle: app), "own app")+ precondition(ReturnTargetResolver.isContainingApp("COM.CHADPIHA.OPENWHISPR.keyboard", appBundle: app), "own extension")+ precondition(!ReturnTargetResolver.isContainingApp("com.chadpiha.openwhisprx", appBundle: app), "prefix without dot is another app")+ precondition(!ReturnTargetResolver.isContainingApp("com.tinyspeck.chatlyio", appBundle: app), "Slack")+ precondition(!ReturnTargetResolver.isContainingApp("com.tinyspeck.chatlyio", appBundle: ""), "unknown own bundle")+ }++ static func shouldRetryOnlyWhileLaunching() {+ precondition(ReturnTargetResolver.shouldRetry(openSucceeded: false, appWasActive: false, retriesLeft: 2), "an open made while still launching retries")+ precondition(!ReturnTargetResolver.shouldRetry(openSucceeded: false, appWasActive: true, retriesLeft: 2), "an open made while active is final (prompt cancelled)")+ precondition(!ReturnTargetResolver.shouldRetry(openSucceeded: false, appWasActive: false, retriesLeft: 0), "no retries left")+ precondition(!ReturnTargetResolver.shouldRetry(openSucceeded: true, appWasActive: false, retriesLeft: 2), "success never retries")+ }++ static func outcomePayloadOmitsMissingHostName() {+ let opened = ReturnOutcome(status: .opened, hostName: "Slack").payload+ precondition(opened["status"] as? String == "opened" && opened["hostName"] as? String == "Slack", "opened payload")+ let none = ReturnOutcome(status: .noTarget, hostName: nil).payload+ precondition(none["status"] as? String == "no_target" && none["hostName"] == nil, "no_target payload")+ }++ static func everyCatalogEntryOpens() {+ for (bundle, app) in HostAppCatalog.entries {+ precondition(URL(string: app.returnUrl) != nil, "\(bundle) has an unparseable URL")+ precondition(!app.name.isEmpty, "\(bundle) has no name")+ }+ }++ static func startGate(+ _ gate: ReturnAttemptGate,+ scheduled: @escaping (TimeInterval, @escaping () -> Void) -> Void,+ timeout: ReturnOutcome,+ completion: @escaping (ReturnOutcome) -> Void+ ) -> ReturnAttempt? {+ gate.begin(deadline: ReturnTargetResolver.returnDeadline, schedule: scheduled, timeoutOutcome: { timeout }, completion: completion)+ }++ static func gateAllowsOneAttemptAtATime() {+ let gate = ReturnAttemptGate()+ var outcomes: [ReturnOutcomeStatus] = []+ let attempt = startGate(gate, scheduled: { _, _ in }, timeout: ReturnOutcome(status: .noTarget, hostName: nil)) {+ outcomes.append($0.status)+ }+ precondition(attempt != nil, "the first attempt starts")+ let second = startGate(gate, scheduled: { _, _ in }, timeout: ReturnOutcome(status: .noTarget, hostName: nil)) { _ in }+ precondition(second == nil, "a second attempt is refused while one is in flight")+ attempt?.finish(ReturnOutcome(status: .opened, hostName: "Slack"))+ attempt?.finish(ReturnOutcome(status: .failed, hostName: "Slack"))+ precondition(outcomes == [.opened], "an attempt finishes exactly once")+ precondition(!gate.isInFlight, "finishing frees the gate")+ }++ static func gateDeadlineEndsAHungAttempt() {+ let gate = ReturnAttemptGate()+ var deadlines: [(TimeInterval, () -> Void)] = []+ var outcomes: [ReturnOutcome] = []+ let attempt = startGate(gate, scheduled: { deadlines.append(($0, $1)) }, timeout: ReturnOutcome(status: .failed, hostName: "Slack")) {+ outcomes.append($0)+ }+ precondition(deadlines.count == 1 && deadlines[0].0 == ReturnTargetResolver.returnDeadline, "the deadline is scheduled")+ precondition(ReturnTargetResolver.returnDeadline <= 4.5, "native gives up well before JS's 6 s timeout so JS sees the real outcome")+ deadlines[0].1()+ precondition(outcomes.map(\.status) == [.failed] && outcomes.first?.hostName == "Slack", "the deadline resolves failed with the host")+ precondition(!gate.isInFlight, "the deadline frees the gate for the next handoff")+ precondition(attempt?.isFinished == true, "queued retries see the attempt is over")+ attempt?.finish(ReturnOutcome(status: .opened, hostName: "Slack"))+ precondition(outcomes.count == 1, "a late real outcome is ignored")+ }++ static func lateFinishFromAnOldAttemptLeavesTheNewOneInFlight() {+ let gate = ReturnAttemptGate()+ var deadlines: [() -> Void] = []+ let first = startGate(gate, scheduled: { deadlines.append($1) }, timeout: ReturnOutcome(status: .noTarget, hostName: nil)) { _ in }+ deadlines[0]()+ let second = startGate(gate, scheduled: { _, _ in }, timeout: ReturnOutcome(status: .noTarget, hostName: nil)) { _ in }+ precondition(second != nil, "a new attempt starts after the old one timed out")+ first?.finish(ReturnOutcome(status: .opened, hostName: "Slack"))+ precondition(gate.isInFlight, "the old attempt's late completion must not free the new one")+ }+}diff --git a/openwhispr-mobile/modules/app-group-storage/tests/run-return-target-tests.sh b/openwhispr-mobile/modules/app-group-storage/tests/run-return-target-tests.shnew file mode 100755index 000000000..244d7cba7--- /dev/null+++ b/openwhispr-mobile/modules/app-group-storage/tests/run-return-target-tests.sh@@ -0,0 +1,10 @@+#!/usr/bin/env bash+# Compiles the Foundation-only return resolver with its tests and runs them.+set -euo pipefail+here="$(cd "$(dirname "$0")" && pwd)"+build_dir="$(mktemp -d)"+trap 'rm -rf "$build_dir"' EXIT+swiftc -swift-version 5 -o "$build_dir/return-target-tests" \+ "$here/../ios/ReturnTargetResolver.swift" \+ "$here/ReturnTargetResolverTests.swift"+"$build_dir/return-target-tests"diff --git a/openwhispr-mobile/plugins/keyboard-extension/README.md b/openwhispr-mobile/plugins/keyboard-extension/README.mdindex ad1aeec5a..5b4b043ec 100644--- a/openwhispr-mobile/plugins/keyboard-extension/README.md+++ b/openwhispr-mobile/plugins/keyboard-extension/README.md@@ -15,8 +15,8 @@ A custom iOS keyboard extension that lets the user dictate from any text field s1. User installs the keyboard from iOS Settings → General → Keyboard → Keyboards → Add New.2. User opens any app, switches to the OpenWhispr keyboard, taps the mic.-3. Extension writes a flag to the App Group, then opens the configured app scheme at `/keyboard-dictation` (handled by [src/screens/HomeScreen.tsx](../../src/screens/HomeScreen.tsx)).-4. The main app starts a native recording, then calls `AppGroupStorage.returnToPreviousApp()` to swap back to the host.+3. Extension writes a flag to the App Group, then opens the configured app scheme at `/keyboard-dictation` (handled by [src/hooks/useKeyboardHandoff.ts](../../src/hooks/useKeyboardHandoff.ts)).+4. The main app starts a native recording, then sends the user back to the host app (`returnToHost` in [src/lib/handoffReturn.ts](../../src/lib/handoffReturn.ts)). iOS 26.4+ hides the host from the extension, so the containing app learns it from UIKit ([`HostAppObserver.swift`](../../modules/app-group-storage/ios/HostAppObserver.swift)). When no host is found, the app shows the "Swipe back to your app" screen instead.5. Recording continues in the background. When stopped, the main app writes the transcript to `keyboard_pending_transcript` and the extension pastes it on next focus.## Apple capabilities requireddiff --git a/openwhispr-mobile/plugins/speaker-diarization/withSpeakerDiarization.js b/openwhispr-mobile/plugins/speaker-diarization/withSpeakerDiarization.jsindex aded6e3c4..a47a333d6 100644--- a/openwhispr-mobile/plugins/speaker-diarization/withSpeakerDiarization.js+++ b/openwhispr-mobile/plugins/speaker-diarization/withSpeakerDiarization.js@@ -39,17 +39,16 @@ const MARKER = 'spm_pkg "FluidAudio"';// one generation pass. That breaks here: @generated_uuids is empty at injection time,// so the counter restarts at 0 and re-emits <prefix>00000000 — the PBXProject's own// UUID — overwriting the PBXProject block and leaving a project with no root object.-// Restore the collision check that stock Xcodeproj already performs.+// Fall back to stock Xcodeproj, which draws random UUIDs and drops any already in+// use. Adding that check to CocoaPods' counter instead hangs `pod install`: the+// counter only advances by the UUIDs it keeps, so a batch that collides entirely+// is regenerated forever.// See https://github.com/maplibre/maplibre-react-native/issues/1499.const UUID_FIX_BLOCK ="require 'cocoapods'\n" +'Pod::Project.class_eval do\n' +' def generate_available_uuid_list(count = 100)\n' +- ' start = @generated_uuids.size\n' +- " uniques = Array.new(count) { |i| format('%.6s%07X0', @uuid_prefix, start + i) }\n" +- ' uniques -= (@generated_uuids + uuids)\n' +- ' @generated_uuids += uniques\n' +- ' @available_uuids += uniques\n' ++ ' super\n' +' end\n' +'end\n';diff --git a/openwhispr-mobile/src/components/features/KeyboardHandoffReturnView.tsx b/openwhispr-mobile/src/components/features/KeyboardHandoffReturnView.tsxnew file mode 100644index 000000000..49c162462--- /dev/null+++ b/openwhispr-mobile/src/components/features/KeyboardHandoffReturnView.tsx@@ -0,0 +1,73 @@+import React from 'react';+import { Pressable, View } from 'react-native';+import { useSafeAreaInsets } from 'react-native-safe-area-context';+import { Button } from '@/components/ui/Button';+import { Text } from '@/components/ui/Text';+import { SystemIcon } from '@/components/ui/SystemIcon';++type KeyboardHandoffReturnViewProps = {+ mode: 'returning' | 'back_to_host';+ hostName: string | null;+ onCancel: () => void;+ onBackToHost: () => void;+};++/**+ * The keyboard handoff screen while OpenWhispr sends the user back to the app+ * they were typing in. Deliberately near-empty: it is on screen for about a+ * second, and sits behind the iOS "wants to open" prompt when iOS shows one.+ * No cancel while returning: the return can't be called off, so cancelling+ * would flash Home and then switch apps anyway.+ */+export function KeyboardHandoffReturnView({+ mode,+ hostName,+ onCancel,+ onBackToHost,+}: KeyboardHandoffReturnViewProps): React.JSX.Element {+ const insets = useSafeAreaInsets();+ const showBackToHost = mode === 'back_to_host' && hostName;++ return (+ <View className="flex-1 bg-systemBackground" style={{ paddingTop: insets.top + 8 }}>+ <View className="h-9 flex-row justify-end px-5">+ {showBackToHost ? (+ <Pressable+ onPress={onCancel}+ hitSlop={8}+ className="w-9 h-9 rounded-full items-center justify-center bg-secondarySystemBackground active:opacity-70"+ accessibilityRole="button"+ accessibilityLabel="Cancel and discard"+ >+ <SystemIcon name="xmark" mdName="X" size={13} color="secondaryLabel" />+ </Pressable>+ ) : null}+ </View>++ <View className="flex-1 items-center justify-center px-8">+ {showBackToHost ? (+ <>+ <Text+ accessibilityRole="header"+ className="text-2xl font-semibold text-label text-center"+ >+ You're recording+ </Text>+ <Button+ onPress={onBackToHost}+ accessibilityRole="button"+ accessibilityLabel={`Back to ${hostName}`}+ className="mt-6 min-w-[200px]"+ >+ {`Back to ${hostName}`}+ </Button>+ </>+ ) : (+ <Text className="text-[15px] text-secondaryLabel text-center">+ Returning to your app…+ </Text>+ )}+ </View>+ </View>+ );+}diff --git a/openwhispr-mobile/src/components/features/__tests__/KeyboardHandoffReturnView.test.tsx b/openwhispr-mobile/src/components/features/__tests__/KeyboardHandoffReturnView.test.tsxnew file mode 100644index 000000000..4676340e0--- /dev/null+++ b/openwhispr-mobile/src/components/features/__tests__/KeyboardHandoffReturnView.test.tsx@@ -0,0 +1,64 @@+import React from 'react';+import { fireEvent, render, screen } from '@testing-library/react-native';++jest.mock('react-native-safe-area-context', () => ({+ useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }),+}));+jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));+jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));++import { KeyboardHandoffReturnView } from '../KeyboardHandoffReturnView';++describe('KeyboardHandoffReturnView', () => {+ it('stays quiet while returning: no button, no instructions', () => {+ render(+ <KeyboardHandoffReturnView+ mode="returning"+ hostName={null}+ onCancel={jest.fn()}+ onBackToHost={jest.fn()}+ />,+ );+ expect(screen.getByText('Returning to your app…')).toBeOnTheScreen();+ expect(screen.queryByRole('button', { name: /^Back to/ })).not.toBeOnTheScreen();+ expect(screen.queryByText(/Swipe/)).not.toBeOnTheScreen();+ });++ it('offers one button back to the named host', () => {+ const onBackToHost = jest.fn();+ render(+ <KeyboardHandoffReturnView+ mode="back_to_host"+ hostName="Slack"+ onCancel={jest.fn()}+ onBackToHost={onBackToHost}+ />,+ );+ fireEvent.press(screen.getByRole('button', { name: 'Back to Slack' }));+ expect(onBackToHost).toHaveBeenCalledTimes(1);+ });++ it('offers cancel only once the return has settled', () => {+ const onCancel = jest.fn();+ const { rerender } = render(+ <KeyboardHandoffReturnView+ mode="returning"+ hostName={null}+ onCancel={onCancel}+ onBackToHost={jest.fn()}+ />,+ );+ expect(screen.queryByLabelText('Cancel and discard')).not.toBeOnTheScreen();++ rerender(+ <KeyboardHandoffReturnView+ mode="back_to_host"+ hostName="Slack"+ onCancel={onCancel}+ onBackToHost={jest.fn()}+ />,+ );+ fireEvent.press(screen.getByRole('button', { name: 'Cancel and discard' }));+ expect(onCancel).toHaveBeenCalledTimes(1);+ });+});diff --git a/openwhispr-mobile/src/hooks/__tests__/useKeyboardHandoff.fullAccessRoute.test.ts b/openwhispr-mobile/src/hooks/__tests__/useKeyboardHandoff.fullAccessRoute.test.tsindex 4ccbd6419..ed65d502b 100644--- a/openwhispr-mobile/src/hooks/__tests__/useKeyboardHandoff.fullAccessRoute.test.ts+++ b/openwhispr-mobile/src/hooks/__tests__/useKeyboardHandoff.fullAccessRoute.test.ts@@ -26,6 +26,7 @@ const mockHandoffStoreState = {setCheckingInitialUrl: jest.fn(),setNoSpeechDetected: jest.fn(),setTranscribing: jest.fn(),+ setReturnState: jest.fn(),reset: jest.fn(),};const mockSubscription = { remove: jest.fn() };@@ -208,6 +209,7 @@ beforeEach(() => {storage.getItem.mockReturnValue(null);storage.setItem.mockReset().mockReturnValue(true);storage.startNativeRecording.mockReturnValue(true);+ storage.returnToPreviousApp.mockResolvedValue({ status: 'opened', hostName: 'Slack' });mockCleanupTranscript.mockResolvedValue('clean transcript');mockTranscribeAndCleanup.mockResolvedValue({text: 'clean transcript',@@ -774,6 +776,38 @@ describe('provider job lifecycle', () => {});});+describe('useKeyboardHandoff — return to the host app', () => {+ it('returns to the host after starting a recording and records the outcome', async () => {+ storage.returnToPreviousApp.mockResolvedValue({ status: 'failed', hostName: 'Slack' });+ mountWithInitialUrl('openwhispr://keyboard-dictation?source=keyboard');++ await waitFor(() =>+ expect(mockHandoffStoreState.setReturnState).toHaveBeenCalledWith('manual', 'Slack'),+ );+ expect(storage.startNativeRecording).toHaveBeenCalled();+ expect(storage.returnToPreviousApp).toHaveBeenCalledTimes(1);+ });++ it('shows the swipe screen when there is no host to return to', async () => {+ storage.returnToPreviousApp.mockResolvedValue({ status: 'no_target' });+ mountWithInitialUrl('openwhispr://keyboard-dictation?source=keyboard');++ await waitFor(() =>+ expect(mockHandoffStoreState.setReturnState).toHaveBeenCalledWith('manual', null),+ );+ });++ // The keyboard inside OpenWhispr records in place; there is nowhere to return to.+ it('never returns when the keyboard is hosted by OpenWhispr itself', async () => {+ mountWithInitialUrl(+ 'openwhispr://keyboard-dictation?source=keyboard&hostBundle=com.gizmolabs.openwhispr',+ );++ await waitFor(() => expect(storage.startNativeRecording).toHaveBeenCalled());+ expect(storage.returnToPreviousApp).not.toHaveBeenCalled();+ });+});+describe('useKeyboardHandoff — hotkey readiness', () => {// The hotkey's cold start waits for this key before it records, so it must// only appear once both recording listeners exist.diff --git a/openwhispr-mobile/src/hooks/useKeyboardHandoff.ts b/openwhispr-mobile/src/hooks/useKeyboardHandoff.tsindex 11422f73e..78d06b49a 100644--- a/openwhispr-mobile/src/hooks/useKeyboardHandoff.ts+++ b/openwhispr-mobile/src/hooks/useKeyboardHandoff.ts@@ -46,6 +46,7 @@ import {} from '../../modules/app-group-storage/src';import { LiveActivity } from '../../modules/live-activity/src';import { isNoSpeechError } from '@/lib/permissions';+import { returnToHost } from '@/lib/handoffReturn';const NO_SPEECH_DISPLAY_MS = 2200;@@ -573,7 +574,7 @@ export function useKeyboardHandoff() {if (intent === 'agent-action') {runAgentAction(`url:${intent}`);if (!selfHosted) {- AppGroupStorage.returnToPreviousApp();+ void returnToHost();}return;}@@ -585,7 +586,7 @@ export function useKeyboardHandoff() {// in OpenWhispr either. Bounce back so the keyboard shows the live// recording/transcribing state instead of a dead tap.if (!selfHosted) {- AppGroupStorage.returnToPreviousApp();+ void returnToHost();}return;}@@ -608,7 +609,7 @@ export function useKeyboardHandoff() {setKeyboardStatus('setup_required', 'Complete provider setup in AI Models.');cleanup({ resetStatus: false });if (!selfHosted) {- AppGroupStorage.returnToPreviousApp();+ void returnToHost();}return;}@@ -642,7 +643,7 @@ export function useKeyboardHandoff() {// surfaces the error state there. Leaving them in OpenWhispr with no// visible failure is the worst outcome.if (!selfHosted) {- AppGroupStorage.returnToPreviousApp();+ void returnToHost();}return;}@@ -650,7 +651,7 @@ export function useKeyboardHandoff() {LiveActivity.startSession();if (!selfHosted) {- AppGroupStorage.returnToPreviousApp();+ void returnToHost();}};diff --git a/openwhispr-mobile/src/lib/__tests__/handoffReturn.test.ts b/openwhispr-mobile/src/lib/__tests__/handoffReturn.test.tsnew file mode 100644index 000000000..9bac1be4f--- /dev/null+++ b/openwhispr-mobile/src/lib/__tests__/handoffReturn.test.ts@@ -0,0 +1,111 @@+const mockReturnToPreviousApp = jest.fn();+jest.mock('../../../modules/app-group-storage/src', () => ({+ AppGroupStorage: { returnToPreviousApp: () => mockReturnToPreviousApp() },+ NO_RETURN_TARGET: { status: 'no_target' },+}));++import { useHandoffStore } from '@/store/useHandoffStore';+import {+ applyReturnOutcome,+ returnToHost,+ RETURN_OUTCOME_TIMEOUT_MS,+ selectHandoffView,+} from '../handoffReturn';++function returnSnapshot(): { returnState: string; returnHostName: string | null } {+ const { returnState, returnHostName } = useHandoffStore.getState();+ return { returnState, returnHostName };+}++beforeEach(() => {+ jest.useRealTimers();+ mockReturnToPreviousApp.mockReset();+ useHandoffStore.getState().setActive(true);+});++describe('useHandoffStore return state', () => {+ it('starts every handoff in the returning state', () => {+ useHandoffStore.getState().setReturnState('manual', 'Slack');+ useHandoffStore.getState().setActive(true);+ expect(returnSnapshot()).toEqual({ returnState: 'returning', returnHostName: null });+ });+});++describe('applyReturnOutcome', () => {+ // The app is backgrounded after a successful open; if the user comes back+ // mid-recording, "Returning…" would be a lie. Offer the button instead.+ it('offers the button after a successful return', () => {+ applyReturnOutcome({ status: 'opened', hostName: 'Slack' });+ expect(returnSnapshot()).toEqual({ returnState: 'manual', returnHostName: 'Slack' });+ });++ it('offers the button when the return failed (prompt cancelled)', () => {+ applyReturnOutcome({ status: 'failed', hostName: 'Slack' });+ expect(returnSnapshot()).toEqual({ returnState: 'manual', returnHostName: 'Slack' });+ });++ it('falls back to the swipe screen when there is no target', () => {+ applyReturnOutcome({ status: 'no_target' });+ expect(returnSnapshot()).toEqual({ returnState: 'manual', returnHostName: null });+ });++ it('ignores a skipped duplicate and an absent outcome', () => {+ applyReturnOutcome({ status: 'skipped' });+ applyReturnOutcome(undefined);+ expect(returnSnapshot()).toEqual({ returnState: 'returning', returnHostName: null });+ });+});++describe('returnToHost', () => {+ it('uses the native return by default and applies its outcome', async () => {+ mockReturnToPreviousApp.mockResolvedValue({ status: 'failed', hostName: 'Messages' });+ await returnToHost();+ expect(mockReturnToPreviousApp).toHaveBeenCalledTimes(1);+ expect(returnSnapshot()).toEqual({ returnState: 'manual', returnHostName: 'Messages' });+ });++ it('uses the opener it is given', async () => {+ const openHost = jest.fn().mockResolvedValue({ status: 'opened', hostName: 'Slack' });+ await returnToHost(openHost);+ expect(openHost).toHaveBeenCalledTimes(1);+ expect(mockReturnToPreviousApp).not.toHaveBeenCalled();+ });++ it('gives up on a return that never resolves', async () => {+ jest.useFakeTimers();+ const pending = returnToHost(() => new Promise(() => {}));+ jest.advanceTimersByTime(RETURN_OUTCOME_TIMEOUT_MS);+ await pending;+ expect(returnSnapshot()).toEqual({ returnState: 'manual', returnHostName: null });+ });+});++describe('selectHandoffView', () => {+ const base = {+ noSpeech: false,+ transcribing: false,+ returnState: 'returning' as const,+ returnHostName: null,+ };++ it('shows the quiet returning screen until the return reports back', () => {+ expect(selectHandoffView(base)).toBe('returning');+ });++ it('offers the button when the host is known', () => {+ expect(selectHandoffView({ ...base, returnState: 'manual', returnHostName: 'Slack' })).toBe(+ 'back_to_host',+ );+ });++ it('falls back to the swipe screen when the host is unknown', () => {+ expect(selectHandoffView({ ...base, returnState: 'manual' })).toBe('swipe');+ });++ it('lets no-speech and transcribing win over the return state', () => {+ expect(selectHandoffView({ ...base, noSpeech: true, transcribing: true })).toBe('no_speech');+ expect(selectHandoffView({ ...base, transcribing: true, returnState: 'manual' })).toBe(+ 'transcribing',+ );+ });+});diff --git a/openwhispr-mobile/src/lib/handoffReturn.ts b/openwhispr-mobile/src/lib/handoffReturn.tsnew file mode 100644index 000000000..5a420e2a3--- /dev/null+++ b/openwhispr-mobile/src/lib/handoffReturn.ts@@ -0,0 +1,48 @@+import {+ AppGroupStorage,+ NO_RETURN_TARGET,+ type ReturnOutcome,+} from '../../modules/app-group-storage/src';+import { useHandoffStore, type HandoffReturnState } from '@/store/useHandoffStore';++/**+ * Upper bound on a return, in case native never resolves. Native settles every+ * return within its own 4.5 s deadline (`ReturnTargetResolver.returnDeadline`),+ * and this has to outlast it with room for a busy main thread on a cold launch,+ * or the user gets the swipe screen instead of native's real outcome.+ */+export const RETURN_OUTCOME_TIMEOUT_MS = 6_000;++export function applyReturnOutcome(outcome: ReturnOutcome | undefined): void {+ if (!outcome || outcome.status === 'skipped') return;+ const hostName = outcome.status === 'no_target' ? null : outcome.hostName;+ useHandoffStore.getState().setReturnState('manual', hostName);+}++export async function returnToHost(+ openHost: () => Promise<ReturnOutcome> = () => AppGroupStorage.returnToPreviousApp(),+): Promise<void> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const timedOut = new Promise<ReturnOutcome>((resolve) => {+ timer = setTimeout(() => resolve(NO_RETURN_TARGET), RETURN_OUTCOME_TIMEOUT_MS);+ });+ try {+ applyReturnOutcome(await Promise.race([openHost(), timedOut]));+ } finally {+ clearTimeout(timer);+ }+}++export type HandoffView = 'no_speech' | 'transcribing' | 'returning' | 'back_to_host' | 'swipe';++export function selectHandoffView(input: {+ noSpeech: boolean;+ transcribing: boolean;+ returnState: HandoffReturnState;+ returnHostName: string | null;+}): HandoffView {+ if (input.noSpeech) return 'no_speech';+ if (input.transcribing) return 'transcribing';+ if (input.returnState === 'returning') return 'returning';+ return input.returnHostName ? 'back_to_host' : 'swipe';+}diff --git a/openwhispr-mobile/src/screens/HomeScreen.tsx b/openwhispr-mobile/src/screens/HomeScreen.tsxindex 31ae01edc..adad94e0d 100644--- a/openwhispr-mobile/src/screens/HomeScreen.tsx+++ b/openwhispr-mobile/src/screens/HomeScreen.tsx@@ -46,6 +46,8 @@ import { TranscriptModal } from '@/components/features/TranscriptModal';import { RecordingOverlay } from '@/components/features/RecordingOverlay';import { ParakeetNudgeBanner } from '@/components/features/ParakeetNudgeBanner';import { KeyboardFullAccessBanner } from '@/components/features/KeyboardFullAccessBanner';+import { KeyboardHandoffReturnView } from '@/components/features/KeyboardHandoffReturnView';+import { returnToHost, selectHandoffView } from '@/lib/handoffReturn';import { HardwareKeyboardNudgeBanner } from '@/components/features/HardwareKeyboardNudgeBanner';import { SwipeableCard } from '@/components/ui/SwipeableCard';import { Glass } from '@/components/ui/Glass';@@ -126,6 +128,8 @@ export default function HomeScreen() {const isCheckingInitialUrl = useHandoffStore((s) => s.isCheckingInitialUrl);const handoffNoSpeech = useHandoffStore((s) => s.noSpeechDetected);const handoffTranscribing = useHandoffStore((s) => s.isTranscribing);+ const handoffReturnState = useHandoffStore((s) => s.returnState);+ const handoffReturnHostName = useHandoffStore((s) => s.returnHostName);const [showNoSpeechToast, setShowNoSpeechToast] = useState(false);const { register: registerSuperwallGate } = useSuperwallGate();const transcripts = useTranscriptStore((state) => state.transcripts);@@ -270,6 +274,11 @@ export default function HomeScreen() {AppGroupStorage.stopNativeRecording();};+ const handleBackToHost = () => {+ safeHaptics('light');+ void returnToHost(() => AppGroupStorage.openHostApp());+ };+const handleRecordPress = async () => {const recordingProvider = getTranscriptionProvider('dictation');if (!isRecording && recordingProvider === 'cloud' && accountRequiredForCloud(user)) {@@ -471,7 +480,25 @@ export default function HomeScreen() {}if (isKeyboardHandoffSession) {- if (handoffNoSpeech) {+ const handoffView = selectHandoffView({+ noSpeech: handoffNoSpeech,+ transcribing: handoffTranscribing,+ returnState: handoffReturnState,+ returnHostName: handoffReturnHostName,+ });++ if (handoffView === 'returning' || handoffView === 'back_to_host') {+ return (+ <KeyboardHandoffReturnView+ mode={handoffView}+ hostName={handoffReturnHostName}+ onCancel={handleCancelHandoffRecording}+ onBackToHost={handleBackToHost}+ />+ );+ }++ if (handoffView === 'no_speech') {return (<View className="flex-1 bg-systemBackground items-center justify-center px-10"><SystemIcon name="mic.slash.fill" mdName="MicOff" size={48} color="tertiaryLabel" />diff --git a/openwhispr-mobile/src/store/useHandoffStore.ts b/openwhispr-mobile/src/store/useHandoffStore.tsindex da1ad5ad8..34f804fd0 100644--- a/openwhispr-mobile/src/store/useHandoffStore.ts+++ b/openwhispr-mobile/src/store/useHandoffStore.ts@@ -1,14 +1,20 @@import { create } from 'zustand';+/** `returning` until the native return reports back; `manual` once the user may need to act. */+export type HandoffReturnState = 'returning' | 'manual';+interface HandoffState {isActive: boolean;isCheckingInitialUrl: boolean;noSpeechDetected: boolean;isTranscribing: boolean;+ returnState: HandoffReturnState;+ returnHostName: string | null;setActive: (v: boolean) => void;setCheckingInitialUrl: (v: boolean) => void;setNoSpeechDetected: (v: boolean) => void;setTranscribing: (v: boolean) => void;+ setReturnState: (state: HandoffReturnState, hostName: string | null) => void;}export const useHandoffStore = create<HandoffState>((set) => ({@@ -16,8 +22,14 @@ export const useHandoffStore = create<HandoffState>((set) => ({isCheckingInitialUrl: true,noSpeechDetected: false,isTranscribing: false,- setActive: (v) => set({ isActive: v }),+ returnState: 'returning',+ returnHostName: null,+ setActive: (v) =>+ set(+ v ? { isActive: true, returnState: 'returning', returnHostName: null } : { isActive: false },+ ),setCheckingInitialUrl: (v) => set({ isCheckingInitialUrl: v }),setNoSpeechDetected: (v) => set({ noSpeechDetected: v }),setTranscribing: (v) => set({ isTranscribing: v }),+ setReturnState: (returnState, returnHostName) => set({ returnState, returnHostName }),}));