Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(mobile): Show the keyboard setup tutorial over Settings again (#2412)

Chad Piha7a6907969e56
diff --git a/openwhispr-mobile/modules/pip-tutorial/ios/PipTutorialModule.swift b/openwhispr-mobile/modules/pip-tutorial/ios/PipTutorialModule.swift
index 21f91c217..3fd79ea5c 100644
--- a/openwhispr-mobile/modules/pip-tutorial/ios/PipTutorialModule.swift
+++ b/openwhispr-mobile/modules/pip-tutorial/ios/PipTutorialModule.swift
@@ -6,6 +6,19 @@ import os.log
private let log = Logger(subsystem: "com.gizmolabs.openwhispr", category: "PipTutorial")
+// Outcomes `start` resolves with. Anything but `started` means no overlay is showing;
+// JS reports the unexpected ones so a silent failure shows up in Sentry.
+private enum StartOutcome {
+ static let started = "started"
+ static let unsupported = "unsupported"
+ static let videoMissing = "video_missing"
+ static let noRootView = "no_root_view"
+ static let controllerFailed = "controller_failed"
+ static let timeout = "timeout"
+ static let stopped = "stopped"
+ static func failed(_ error: Error) -> String { "failed:\(error.localizedDescription)" }
+}
+
public class PipTutorialModule: Module {
private var player: AVPlayer?
private var playerLayer: AVPlayerLayer?
@@ -15,6 +28,9 @@ public class PipTutorialModule: Module {
private var statusObserver: NSKeyValueObservation?
private var startPromise: Promise?
private var startTimeoutWorkItem: DispatchWorkItem?
+ // True only while the session is the one this module configured, so teardown
+ // never deactivates a session the dictation mic owns.
+ private var ownsAudioSession = false
public func definition() -> ModuleDefinition {
Name("PipTutorial")
@@ -41,38 +57,31 @@ public class PipTutorialModule: Module {
guard AVPictureInPictureController.isPictureInPictureSupported() else {
log.error("PiP not supported on this device")
- promise.resolve(false)
+ promise.resolve(StartOutcome.unsupported)
return
}
guard let url = Bundle.main.url(forResource: videoName, withExtension: "mp4") else {
log.error("Video not found in bundle: \(videoName).mp4")
- promise.resolve(false)
+ promise.resolve(StartOutcome.videoMissing)
return
}
log.info("Video URL: \(url.absoluteString, privacy: .public)")
DispatchQueue.main.async { [weak self] in
guard let self = self else {
- promise.resolve(false)
+ promise.resolve(StartOutcome.stopped)
return
}
- self.resolveStart(false)
self.teardownOnMain()
guard let rootView = Self.activeRootView() else {
log.error("No root view found; cannot attach player layer")
- promise.resolve(false)
+ promise.resolve(StartOutcome.noRootView)
return
}
- do {
- try AVAudioSession.sharedInstance().setCategory(
- .playback, mode: .moviePlayback, options: [.mixWithOthers])
- try AVAudioSession.sharedInstance().setActive(true, options: [])
- } catch {
- log.error("AVAudioSession setup failed: \(error.localizedDescription)")
- }
+ self.prepareAudioSession()
let player = AVPlayer(url: url)
player.isMuted = true
@@ -84,17 +93,21 @@ public class PipTutorialModule: Module {
guard let self = self else { return }
if self.pipController?.isPictureInPictureActive == true {
log.info("PiP start callback timed out after activation; keeping session alive")
- self.resolveStart(true)
+ self.resolveStart(StartOutcome.started)
return
}
- log.error("Timed out waiting for PiP to start")
- self.teardownOnMain()
+ let possible = self.pipController?.isPictureInPicturePossible == true
+ log.error("Timed out waiting for PiP to start (possible=\(possible, privacy: .public))")
+ self.teardownOnMain(outcome: "\(StartOutcome.timeout):possible=\(possible)")
}
self.startTimeoutWorkItem = timeoutWorkItem
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: timeoutWorkItem)
+ // PiP stays impossible for a layer outside the visible window, so keep it on
+ // screen at a single point in the top-left corner, which the display's rounded
+ // corner hides.
let layer = AVPlayerLayer(player: player)
- layer.frame = CGRect(x: -1000, y: -1000, width: 200, height: 100)
+ layer.frame = CGRect(x: 0, y: 0, width: 1, height: 1)
layer.videoGravity = .resizeAspectFill
rootView.layer.addSublayer(layer)
self.playerLayer = layer
@@ -102,7 +115,7 @@ public class PipTutorialModule: Module {
guard let pipController = AVPictureInPictureController(playerLayer: layer) else {
log.error("Failed to create AVPictureInPictureController")
- self.teardownOnMain()
+ self.teardownOnMain(outcome: StartOutcome.controllerFailed)
return
}
if #available(iOS 14.2, *) {
@@ -110,10 +123,10 @@ public class PipTutorialModule: Module {
}
let delegate = PipDelegate(
onDidStart: { [weak self] in
- self?.resolveStart(true)
+ self?.resolveStart(StartOutcome.started)
},
- onFailedToStart: { [weak self] in
- self?.resolveStart(false)
+ onFailedToStart: { [weak self] error in
+ self?.resolveStart(StartOutcome.failed(error))
}
)
pipController.delegate = delegate
@@ -150,12 +163,41 @@ public class PipTutorialModule: Module {
}
}
- private func resolveStart(_ success: Bool) {
+ // The dictation mic keeps a `.playAndRecord` session running while it's warm, and a
+ // recording holds `.record`. Switching either to `.playback` would cut the mic's input,
+ // and `.playAndRecord` already allows PiP, so only configure a session nobody has set up
+ // (or one an earlier tutorial left as `.playback`).
+ private func prepareAudioSession() {
+ let session = AVAudioSession.sharedInstance()
+ let category = session.category
+ guard category == .ambient || category == .soloAmbient || category == .playback else {
+ log.info("Leaving audio session as \(category.rawValue, privacy: .public)")
+ return
+ }
+ do {
+ try session.setCategory(.playback, mode: .moviePlayback, options: [.mixWithOthers])
+ try session.setActive(true, options: [])
+ ownsAudioSession = true
+ } catch {
+ log.error("AVAudioSession setup failed: \(error.localizedDescription)")
+ }
+ }
+
+ private func releaseAudioSession() {
+ guard ownsAudioSession else { return }
+ ownsAudioSession = false
+ let session = AVAudioSession.sharedInstance()
+ // The dictation mic may have taken the session over since the tutorial started.
+ guard session.category == .playback else { return }
+ try? session.setActive(false, options: [.notifyOthersOnDeactivation])
+ }
+
+ private func resolveStart(_ outcome: String) {
startTimeoutWorkItem?.cancel()
startTimeoutWorkItem = nil
guard let promise = startPromise else { return }
startPromise = nil
- promise.resolve(success)
+ promise.resolve(outcome)
}
private func teardown() {
@@ -165,8 +207,8 @@ public class PipTutorialModule: Module {
}
}
- private func teardownOnMain() {
- resolveStart(false)
+ private func teardownOnMain(outcome: String = StartOutcome.stopped) {
+ resolveStart(outcome)
statusObserver?.invalidate()
statusObserver = nil
if let observer = loopObserver {
@@ -180,8 +222,7 @@ public class PipTutorialModule: Module {
playerLayer = nil
pipController = nil
delegateRetainer = nil
- try? AVAudioSession.sharedInstance().setActive(
- false, options: [.notifyOthersOnDeactivation])
+ releaseAudioSession()
}
private static func activeRootView() -> UIView? {
@@ -200,9 +241,9 @@ public class PipTutorialModule: Module {
private final class PipDelegate: NSObject, AVPictureInPictureControllerDelegate {
private let onDidStart: () -> Void
- private let onFailedToStart: () -> Void
+ private let onFailedToStart: (Error) -> Void
- init(onDidStart: @escaping () -> Void, onFailedToStart: @escaping () -> Void) {
+ init(onDidStart: @escaping () -> Void, onFailedToStart: @escaping (Error) -> Void) {
self.onDidStart = onDidStart
self.onFailedToStart = onFailedToStart
}
@@ -219,7 +260,7 @@ private final class PipDelegate: NSObject, AVPictureInPictureControllerDelegate
failedToStartPictureInPictureWithError error: Error
) {
log.error("PiP failed to start: \(error.localizedDescription)")
- onFailedToStart()
+ onFailedToStart(error)
}
func pictureInPictureControllerWillStopPictureInPicture(_ controller: AVPictureInPictureController) {
log.info("PiP will stop")
diff --git a/openwhispr-mobile/modules/pip-tutorial/ios/Resources/README.md b/openwhispr-mobile/modules/pip-tutorial/ios/Resources/README.md
index b587606f5..e5f6f266f 100644
--- a/openwhispr-mobile/modules/pip-tutorial/ios/Resources/README.md
+++ b/openwhispr-mobile/modules/pip-tutorial/ios/Resources/README.md
@@ -55,4 +55,4 @@ Save the resulting `keyboard-install.mp4` into this folder, then `npx expo prebu
## Behavior when missing
-If a video file is absent, `PipTutorial.start(name)` returns `false`. Callers fall back to the existing static `InstructionOverlay` (the in-app dark card on `KeyboardSetupStep`). No build break, no runtime error.
+If a video file is absent, `PipTutorial.start(name)` resolves `video_missing`, which `startKeyboardPipTutorial` reports to Sentry. Callers fall back to the existing static `InstructionOverlay` (the in-app dark card on `KeyboardIntroStep`). No build break, no runtime error.
diff --git a/openwhispr-mobile/modules/pip-tutorial/src/index.ts b/openwhispr-mobile/modules/pip-tutorial/src/index.ts
index 83f301a9e..c2e10ece6 100644
--- a/openwhispr-mobile/modules/pip-tutorial/src/index.ts
+++ b/openwhispr-mobile/modules/pip-tutorial/src/index.ts
@@ -3,10 +3,29 @@ import { Platform } from 'react-native';
interface PipTutorialNativeModule {
isAvailable(): boolean;
- start(videoName: string): Promise<boolean>;
+ // Builds before start reported an outcome resolve a boolean, and an OTA update can run this JS
+ // on one of them.
+ start(videoName: string): Promise<PipStartOutcome | boolean>;
stop(): Promise<void>;
}
+/**
+ * `started`, or why the overlay isn't showing. `stopped`: a later start or a stop replaced it.
+ * `unavailable`: the iOS module isn't linked. `failed`: an older native build gave no reason.
+ */
+export type PipStartOutcome =
+ | 'started'
+ | 'unsupported'
+ | 'video_missing'
+ | 'no_root_view'
+ | 'controller_failed'
+ | 'stopped'
+ | 'unavailable'
+ | 'error'
+ | 'failed'
+ | `timeout:possible=${boolean}`
+ | `failed:${string}`;
+
let NativeModule: PipTutorialNativeModule | null = null;
if (Platform.OS === 'ios') {
try {
@@ -42,16 +61,17 @@ export const PipTutorial = {
* The video must be bundled in modules/pip-tutorial/ios/Resources/ as
* `<videoName>.mp4` so it ends up in the main app bundle at runtime.
*
- * Returns `true` if PiP was successfully prepared, `false` if the device
- * doesn't support PiP or the named video isn't bundled. Caller should fall
- * back to a static overlay when this returns false.
+ * Resolves `started` once the overlay is showing, otherwise the reason it
+ * isn't (see `PipStartOutcome`). Never rejects.
*/
- async start(videoName: string): Promise<boolean> {
- if (!NativeModule) return false;
+ async start(videoName: string): Promise<PipStartOutcome> {
+ if (!NativeModule) return 'unavailable';
try {
- return await NativeModule.start(videoName);
+ const outcome = await NativeModule.start(videoName);
+ if (typeof outcome === 'string') return outcome;
+ return outcome ? 'started' : 'failed';
} catch {
- return false;
+ return 'error';
}
},
diff --git a/openwhispr-mobile/src/lib/__tests__/keyboardPipTutorial.test.ts b/openwhispr-mobile/src/lib/__tests__/keyboardPipTutorial.test.ts
new file mode 100644
index 000000000..613ff8fe1
--- /dev/null
+++ b/openwhispr-mobile/src/lib/__tests__/keyboardPipTutorial.test.ts
@@ -0,0 +1,71 @@
+const mockPipStart = jest.fn<Promise<string>, [string]>();
+const mockCaptureMessage = jest.fn();
+
+jest.mock('../../../modules/pip-tutorial/src', () => ({
+ PipTutorial: {
+ start: (video: string) => mockPipStart(video),
+ stop: () => Promise.resolve(),
+ },
+}));
+jest.mock('@/lib/sentry', () => ({
+ Sentry: { captureMessage: (...args: unknown[]) => mockCaptureMessage(...args) },
+}));
+
+import { startKeyboardPipTutorial } from '../keyboardPipTutorial';
+
+beforeEach(() => {
+ mockPipStart.mockReset();
+ mockCaptureMessage.mockReset();
+});
+
+afterEach(() => {
+ jest.useRealTimers();
+});
+
+describe('startKeyboardPipTutorial', () => {
+ it('reports nothing when the overlay starts', async () => {
+ mockPipStart.mockResolvedValue('started');
+
+ await expect(startKeyboardPipTutorial()).resolves.toBe(true);
+
+ expect(mockPipStart).toHaveBeenCalledWith('keyboard-install');
+ expect(mockCaptureMessage).not.toHaveBeenCalled();
+ });
+
+ it('reports why the overlay did not start', async () => {
+ mockPipStart.mockResolvedValue('timeout:possible=false');
+
+ await expect(startKeyboardPipTutorial()).resolves.toBe(false);
+
+ expect(mockCaptureMessage).toHaveBeenCalledWith('Keyboard PiP tutorial did not start', {
+ level: 'warning',
+ tags: { pipOutcome: 'timeout' },
+ extra: { outcome: 'timeout:possible=false' },
+ });
+ });
+
+ it.each(['stopped', 'unsupported'])(
+ 'does not report the expected outcome %s',
+ async (outcome) => {
+ mockPipStart.mockResolvedValue(outcome);
+
+ await expect(startKeyboardPipTutorial()).resolves.toBe(false);
+
+ expect(mockCaptureMessage).not.toHaveBeenCalled();
+ },
+ );
+
+ it('reports a native start that never settles', async () => {
+ jest.useFakeTimers();
+ mockPipStart.mockReturnValue(new Promise<string>(() => undefined));
+
+ const started = startKeyboardPipTutorial();
+ await jest.advanceTimersByTimeAsync(2500);
+
+ await expect(started).resolves.toBe(false);
+ expect(mockCaptureMessage).toHaveBeenCalledWith(
+ 'Keyboard PiP tutorial did not start',
+ expect.objectContaining({ tags: { pipOutcome: 'js_timeout' } }),
+ );
+ });
+});
diff --git a/openwhispr-mobile/src/lib/__tests__/pipTutorialModule.test.ts b/openwhispr-mobile/src/lib/__tests__/pipTutorialModule.test.ts
new file mode 100644
index 000000000..dae610fb8
--- /dev/null
+++ b/openwhispr-mobile/src/lib/__tests__/pipTutorialModule.test.ts
@@ -0,0 +1,44 @@
+import { Platform } from 'react-native';
+
+const mockNativeStart = jest.fn<Promise<string | boolean>, [string]>();
+
+jest.mock('expo', () => ({
+ requireNativeModule: () => ({
+ isAvailable: () => true,
+ start: (video: string) => mockNativeStart(video),
+ stop: () => Promise.resolve(),
+ }),
+}));
+
+// The module resolves its native half on import, and only on iOS.
+Platform.OS = 'ios';
+const { PipTutorial } =
+ require('../../../modules/pip-tutorial/src') as typeof import('../../../modules/pip-tutorial/src');
+
+beforeEach(() => {
+ mockNativeStart.mockReset();
+});
+
+describe('PipTutorial.start', () => {
+ it('passes the native outcome through', async () => {
+ mockNativeStart.mockResolvedValue('timeout:possible=false');
+
+ await expect(PipTutorial.start('keyboard-install')).resolves.toBe('timeout:possible=false');
+ });
+
+ // An OTA update can run this JS on a build whose native start still resolves a boolean.
+ it.each([
+ [true, 'started'],
+ [false, 'failed'],
+ ])('maps an older build’s %s to %s', async (legacy, outcome) => {
+ mockNativeStart.mockResolvedValue(legacy);
+
+ await expect(PipTutorial.start('keyboard-install')).resolves.toBe(outcome);
+ });
+
+ it('reports a native call that throws', async () => {
+ mockNativeStart.mockRejectedValue(new Error('boom'));
+
+ await expect(PipTutorial.start('keyboard-install')).resolves.toBe('error');
+ });
+});
diff --git a/openwhispr-mobile/src/lib/keyboardPipTutorial.ts b/openwhispr-mobile/src/lib/keyboardPipTutorial.ts
index 257c711cd..d321e298b 100644
--- a/openwhispr-mobile/src/lib/keyboardPipTutorial.ts
+++ b/openwhispr-mobile/src/lib/keyboardPipTutorial.ts
@@ -1,4 +1,5 @@
-import { PipTutorial } from '../../modules/pip-tutorial/src';
+import { PipTutorial, type PipStartOutcome } from '../../modules/pip-tutorial/src';
+import { Sentry } from '@/lib/sentry';
// The bundled clip that walks through Settings ▸ Keyboards. Both the onboarding
// install step and the Full Access recovery screen play it, because both send the
@@ -10,16 +11,34 @@ const KEYBOARD_INSTALL_VIDEO = 'keyboard-install';
// a stalled start block the thing the user actually asked for.
const START_TIMEOUT_MS = 2500;
+type PipFailure = Exclude<PipStartOutcome, 'started'> | 'js_timeout';
+
+// A newer start or a stop replaced this one, or the device has no PiP: nothing went wrong.
+const EXPECTED_OUTCOMES: ReadonlySet<PipFailure> = new Set(['stopped', 'unsupported']);
+
+// The user heads into Settings either way, so a failed start is invisible to them; report it.
+function reportFailedStart(outcome: PipFailure): void {
+ if (EXPECTED_OUTCOMES.has(outcome)) return;
+ Sentry.captureMessage('Keyboard PiP tutorial did not start', {
+ level: 'warning',
+ tags: { pipOutcome: outcome.split(':')[0] },
+ extra: { outcome },
+ });
+}
+
/** Resolves false (never rejects) when PiP is unsupported, unbundled, or slow. */
export async function startKeyboardPipTutorial(): Promise<boolean> {
let timeoutHandle: ReturnType<typeof setTimeout> | null = null;
try {
- return await Promise.race([
+ const outcome = await Promise.race([
PipTutorial.start(KEYBOARD_INSTALL_VIDEO),
- new Promise<boolean>((resolve) => {
- timeoutHandle = setTimeout(() => resolve(false), START_TIMEOUT_MS);
+ new Promise<'js_timeout'>((resolve) => {
+ timeoutHandle = setTimeout(() => resolve('js_timeout'), START_TIMEOUT_MS);
}),
]);
+ if (outcome === 'started') return true;
+ reportFailedStart(outcome);
+ return false;
} finally {
if (timeoutHandle) clearTimeout(timeoutHandle);
}
diff --git a/openwhispr-mobile/src/screens/__tests__/KeyboardFullAccessScreen.test.tsx b/openwhispr-mobile/src/screens/__tests__/KeyboardFullAccessScreen.test.tsx
index fe1e02e39..a6486abca 100644
--- a/openwhispr-mobile/src/screens/__tests__/KeyboardFullAccessScreen.test.tsx
+++ b/openwhispr-mobile/src/screens/__tests__/KeyboardFullAccessScreen.test.tsx
@@ -5,7 +5,7 @@ import { act, fireEvent, render, screen } from '@testing-library/react-native';
const mockRouterBack = jest.fn();
const mockRouterReplace = jest.fn();
const mockCanGoBack = jest.fn(() => true);
-const mockPipStart = jest.fn((_video: string) => Promise.resolve(true));
+const mockPipStart = jest.fn((_video: string) => Promise.resolve('started'));
const mockPipStop = jest.fn(() => Promise.resolve(true));
const mockGetItem = jest.fn<string | null, [string]>(() => null);
@@ -153,9 +153,9 @@ describe('KeyboardFullAccessScreen', () => {
// A double-tap on the CTA must not queue a second Settings launch behind the
// first — the in-flight ref is the only thing preventing that.
it('does not launch Settings twice while a launch is in flight', async () => {
- let releasePip: (value: boolean) => void = () => {};
+ let releasePip: (value: string) => void = () => {};
mockPipStart.mockReturnValueOnce(
- new Promise<boolean>((resolve) => {
+ new Promise<string>((resolve) => {
releasePip = resolve;
}),
);
@@ -169,7 +169,7 @@ describe('KeyboardFullAccessScreen', () => {
expect(mockPipStart).toHaveBeenCalledTimes(1);
await act(async () => {
- releasePip(true);
+ releasePip('started');
});
expect(openSettingsSpy).toHaveBeenCalledTimes(1);
});