Skip to content

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

feat(mobile): Add tone preview and live voice assistant to onboarding (#2329)

Chad Pihac69831912c9f
diff --git a/openwhispr-mobile/app/(account)/_layout.tsx b/openwhispr-mobile/app/(account)/_layout.tsx
index 2c0baf389..e98c46e44 100644
--- a/openwhispr-mobile/app/(account)/_layout.tsx
+++ b/openwhispr-mobile/app/(account)/_layout.tsx
@@ -44,7 +44,7 @@ export default function AccountLayout() {
<Stack.Screen name="ai-models" options={{ title: 'AI Models', headerLargeTitle: false }} />
<Stack.Screen
name="dictation-agent"
- options={{ title: 'Dictation Agent', headerLargeTitle: false }}
+ options={{ title: 'Voice Assistant', headerLargeTitle: false }}
/>
<Stack.Screen
name="keyboard-tone"
diff --git a/openwhispr-mobile/plugins/keyboard-extension/ios/KeyboardViewController.swift b/openwhispr-mobile/plugins/keyboard-extension/ios/KeyboardViewController.swift
index d2b97287a..5b755b8ad 100644
--- a/openwhispr-mobile/plugins/keyboard-extension/ios/KeyboardViewController.swift
+++ b/openwhispr-mobile/plugins/keyboard-extension/ios/KeyboardViewController.swift
@@ -1659,7 +1659,7 @@ final class KeyboardViewController: UIInputViewController, UIGestureRecognizerDe
UIImage.SymbolConfiguration(pointSize: 15, weight: .semibold),
forImageIn: .normal
)
- agentButton.accessibilityLabel = "Ask the dictation agent"
+ agentButton.accessibilityLabel = "Ask the voice assistant"
let agentPress = UILongPressGestureRecognizer(
target: self,
action: #selector(handleAgentButtonPress(_:))
diff --git a/openwhispr-mobile/src/components/onboarding/OnboardingShell.tsx b/openwhispr-mobile/src/components/onboarding/OnboardingShell.tsx
index fedc86f09..eabc78f00 100644
--- a/openwhispr-mobile/src/components/onboarding/OnboardingShell.tsx
+++ b/openwhispr-mobile/src/components/onboarding/OnboardingShell.tsx
@@ -1,12 +1,17 @@
-import { type ReactElement, type ReactNode } from 'react';
-import { Pressable, View } from 'react-native';
+import { useRef, useState, type ReactElement, type ReactNode } from 'react';
+import { ActivityIndicator, Pressable, View } from 'react-native';
import { Text } from '@/components/ui/Text';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Button } from '@/components/ui/Button';
+import { SystemIcon } from '@/components/ui/SystemIcon';
+import { describeOnboardingError } from '@/lib/onboardingErrors';
interface OnboardingShellProps {
progress?: { current: number; total: number };
- onSkip?: () => void;
+ onSkip?: () => void | Promise<unknown>;
+ onBack?: () => void | Promise<unknown>;
+ /** Shows a question-mark button in the top-right for steps a user can get stuck on. */
+ onHelp?: () => void;
/** Label for the top-right dismiss affordance. Onboarding steps skip ahead;
* standalone screens that reuse this shell close instead. */
skipLabel?: string;
@@ -19,16 +24,20 @@ interface OnboardingShellProps {
ctaLabel: string;
ctaDisabled?: boolean;
ctaLoading?: boolean;
- onCta: () => void;
+ onCta: () => void | Promise<unknown>;
secondaryCtaLabel?: string;
- onSecondaryCta?: () => void;
+ onSecondaryCta?: () => void | Promise<unknown>;
secondaryCtaVariant?: 'link' | 'card';
children?: ReactNode;
}
+type OnboardingAction = 'primary' | 'secondary' | 'back' | 'skip';
+
export function OnboardingShell({
progress,
onSkip,
+ onBack,
+ onHelp,
skipLabel = 'Skip',
title,
titleAccent,
@@ -43,64 +52,156 @@ export function OnboardingShell({
secondaryCtaVariant = 'link',
children,
}: OnboardingShellProps): ReactElement {
+ const inFlight = useRef(false);
+ const failedAction = useRef<OnboardingAction | null>(null);
+ const [busyAction, setBusyAction] = useState<OnboardingAction | null>(null);
+ const busy = busyAction !== null;
+ const [error, setError] = useState<string | null>(null);
+ const run = async (actionName: OnboardingAction): Promise<void> => {
+ if (inFlight.current) return;
+ const action = { primary: onCta, secondary: onSecondaryCta, back: onBack, skip: onSkip }[
+ actionName
+ ];
+ if (!action) return;
+ inFlight.current = true;
+ setBusyAction(actionName);
+ setError(null);
+ try {
+ await action();
+ } catch (cause) {
+ failedAction.current = actionName;
+ setError(describeOnboardingError(cause, 'Could not save your progress. Try again.'));
+ } finally {
+ inFlight.current = false;
+ setBusyAction(null);
+ }
+ };
return (
<SafeAreaView className="flex-1 bg-systemBackground" edges={['top', 'bottom']}>
- <View className="flex-row items-center justify-between px-6 pt-2">
- <View className="flex-1 pr-4">
- {progress ? (
- <Text className="text-[13px] font-medium text-secondaryLabel">
- Step {progress.current} of {progress.total}
- </Text>
+ <View className="flex-1">
+ <View className="flex-row items-center justify-between px-6 pt-2">
+ {onBack ? (
+ <Pressable
+ onPress={() => run('back')}
+ disabled={busy}
+ hitSlop={12}
+ accessibilityRole="button"
+ accessibilityLabel="Back"
+ className="mr-4 py-2"
+ >
+ <SystemIcon
+ name="chevron.left"
+ mdName="ChevronLeft"
+ size={20}
+ color="secondaryLabel"
+ />
+ </Pressable>
) : null}
- </View>
- {onSkip ? (
- <Pressable onPress={onSkip} hitSlop={12} accessibilityRole="button">
- <Text className="text-[15px] font-medium text-secondaryLabel">{skipLabel}</Text>
- </Pressable>
- ) : null}
- </View>
-
- <View className="flex-1 px-6 pt-8">
- {titleNode ?? (
- <Text
- accessibilityRole="header"
- className="text-[30px] font-medium leading-[36px] text-label"
- >
- {renderTitle(title, titleAccent)}
- </Text>
- )}
- {subtitle ? (
- <Text className="mt-2 text-[16px] leading-[21px] text-secondaryLabel">{subtitle}</Text>
- ) : null}
-
- <View className="mt-6 flex-1">{children}</View>
- </View>
-
- <View className="px-6 pb-4">
- <Button onPress={onCta} disabled={ctaDisabled} loading={ctaLoading} size="lg">
- {ctaLabel}
- </Button>
- {secondaryCtaLabel && onSecondaryCta ? (
- secondaryCtaVariant === 'card' ? (
+ <View className="flex-1 pr-4">
+ {progress ? (
+ <Text className="text-[13px] font-medium text-secondaryLabel">
+ Step {progress.current} of {progress.total}
+ </Text>
+ ) : null}
+ </View>
+ {onHelp ? (
<Pressable
- onPress={onSecondaryCta}
+ onPress={onHelp}
+ hitSlop={12}
accessibilityRole="button"
- className="mt-3 items-center justify-center rounded-full border border-separator bg-secondarySystemGroupedBackground py-4 active:opacity-80"
+ accessibilityLabel="Help"
+ className={onSkip ? 'mr-4' : undefined}
>
- <Text className="text-[16px] font-semibold text-label">{secondaryCtaLabel}</Text>
+ <SystemIcon
+ name="questionmark.circle"
+ mdName="CircleHelp"
+ size={22}
+ color="secondaryLabel"
+ />
</Pressable>
- ) : (
+ ) : null}
+ {onSkip ? (
<Pressable
- onPress={onSecondaryCta}
- className="mt-3 items-center justify-center py-2"
+ onPress={() => run('skip')}
+ disabled={busy}
+ hitSlop={12}
accessibilityRole="button"
>
- <Text className="text-[15px] font-medium text-secondaryLabel">
- {secondaryCtaLabel}
- </Text>
+ <Text className="text-[15px] font-medium text-secondaryLabel">{skipLabel}</Text>
</Pressable>
- )
- ) : null}
+ ) : null}
+ </View>
+
+ <View className="flex-1 px-6 pt-8">
+ {titleNode ?? (
+ <Text
+ accessibilityRole="header"
+ className="text-[30px] font-medium leading-[36px] text-label"
+ >
+ {renderTitle(title, titleAccent)}
+ </Text>
+ )}
+ {subtitle ? (
+ <Text className="mt-2 text-[16px] leading-[21px] text-secondaryLabel">{subtitle}</Text>
+ ) : null}
+
+ <View className="mt-6 flex-1">{children}</View>
+ </View>
+
+ <View className="px-6 pb-4">
+ {error ? (
+ <View className="mb-3 flex-row items-center gap-3">
+ <Text accessibilityRole="alert" className="flex-1 text-[14px] text-systemRed">
+ {error}
+ </Text>
+ <Pressable
+ accessibilityRole="button"
+ disabled={busy || (failedAction.current === 'primary' && ctaDisabled)}
+ hitSlop={12}
+ onPress={() => {
+ if (failedAction.current) run(failedAction.current);
+ }}
+ >
+ <Text className="text-[15px] font-medium text-primary">Retry</Text>
+ </Pressable>
+ </View>
+ ) : null}
+ <Button
+ onPress={() => run('primary')}
+ disabled={ctaDisabled || busy}
+ loading={ctaLoading || busyAction === 'primary'}
+ size="lg"
+ >
+ {ctaLabel}
+ </Button>
+ {secondaryCtaLabel && onSecondaryCta ? (
+ secondaryCtaVariant === 'card' ? (
+ <Pressable
+ onPress={() => run('secondary')}
+ disabled={busy}
+ accessibilityRole="button"
+ accessibilityState={{ busy: busyAction === 'secondary', disabled: busy }}
+ className="mt-3 flex-row items-center justify-center gap-2 rounded-full border border-separator bg-secondarySystemGroupedBackground py-4 active:opacity-80"
+ >
+ {busyAction === 'secondary' ? <ActivityIndicator size="small" /> : null}
+ <Text className="text-[16px] font-semibold text-label">{secondaryCtaLabel}</Text>
+ </Pressable>
+ ) : (
+ <Pressable
+ onPress={() => run('secondary')}
+ disabled={busy}
+ className="mt-3 flex-row items-center justify-center gap-2 py-2"
+ accessibilityRole="button"
+ accessibilityState={{ busy: busyAction === 'secondary', disabled: busy }}
+ >
+ {busyAction === 'secondary' ? <ActivityIndicator size="small" /> : null}
+ <Text className="text-[15px] font-medium text-secondaryLabel">
+ {secondaryCtaLabel}
+ </Text>
+ </Pressable>
+ )
+ ) : null}
+ </View>
</View>
</SafeAreaView>
);
diff --git a/openwhispr-mobile/src/components/onboarding/__tests__/OnboardingShell.test.tsx b/openwhispr-mobile/src/components/onboarding/__tests__/OnboardingShell.test.tsx
new file mode 100644
index 000000000..86b9a07df
--- /dev/null
+++ b/openwhispr-mobile/src/components/onboarding/__tests__/OnboardingShell.test.tsx
@@ -0,0 +1,136 @@
+import type React from 'react';
+import { act, fireEvent, render, screen } from '@testing-library/react-native';
+import { Sentry } from '@/lib/sentry';
+import { OnboardingError } from '@/lib/onboardingErrors';
+import { OnboardingShell } from '../OnboardingShell';
+
+jest.mock('react-native-safe-area-context', () => ({ SafeAreaView: require('react-native').View }));
+jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
+jest.mock('@/lib/sentry', () => ({ Sentry: { captureException: jest.fn() } }));
+jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
+jest.mock('@/components/ui/Button', () => {
+ const { Pressable, Text } = require('react-native');
+ return {
+ Button: ({
+ children,
+ onPress,
+ disabled,
+ loading,
+ }: {
+ children: React.ReactNode;
+ onPress: () => void;
+ disabled?: boolean;
+ loading?: boolean;
+ }) => (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityState={{ busy: Boolean(loading), disabled: Boolean(disabled || loading) }}
+ onPress={onPress}
+ disabled={disabled || loading}
+ >
+ <Text>{children}</Text>
+ </Pressable>
+ ),
+ };
+});
+
+beforeEach(() => jest.clearAllMocks());
+
+// Tapping "Use Local" used to spin the "Use Cloud" button, which read as Cloud being chosen.
+it.each(['card', 'link'] as const)('marks only the pressed %s control as busy', async (variant) => {
+ let release!: () => void;
+ render(
+ <OnboardingShell
+ title="How should we transcribe?"
+ ctaLabel="Use Cloud"
+ onCta={jest.fn()}
+ secondaryCtaLabel="Use Local"
+ secondaryCtaVariant={variant}
+ onSecondaryCta={() => new Promise<void>((resolve) => (release = resolve))}
+ />,
+ );
+
+ fireEvent.press(screen.getByText('Use Local'));
+
+ expect(screen.getByRole('button', { name: 'Use Local' })).toBeBusy();
+ expect(screen.getByRole('button', { name: 'Use Cloud' })).not.toBeBusy();
+ expect(screen.getByRole('button', { name: 'Use Cloud' })).toBeDisabled();
+ await act(async () => release());
+});
+
+it('reports an unexpected failure and shows the fallback instead of its text', async () => {
+ const error = new Error("Calling the 'setValueWithKeyAsync' function has failed");
+ render(<OnboardingShell title="Tone" ctaLabel="Continue" onCta={() => Promise.reject(error)} />);
+
+ fireEvent.press(screen.getByText('Continue'));
+
+ expect(await screen.findByText('Could not save your progress. Try again.')).toBeTruthy();
+ expect(screen.queryByText(/setValueWithKeyAsync/)).toBeNull();
+ expect(Sentry.captureException).toHaveBeenCalledWith(error);
+});
+
+it('shows a failure written for the user as is', async () => {
+ const message = 'Cloud needs a connection to set up. Try again or use Local for now.';
+ render(
+ <OnboardingShell
+ title="Mode"
+ ctaLabel="Use Cloud"
+ onCta={() => Promise.reject(new OnboardingError(message))}
+ />,
+ );
+
+ fireEvent.press(screen.getByText('Use Cloud'));
+
+ expect(await screen.findByText(message)).toBeTruthy();
+ expect(Sentry.captureException).not.toHaveBeenCalled();
+});
+
+it('retries the action that failed, not the primary one', async () => {
+ const onCta = jest.fn();
+ const onSecondaryCta = jest
+ .fn()
+ .mockRejectedValueOnce(new Error('Keychain unavailable'))
+ .mockResolvedValueOnce(undefined);
+ render(
+ <OnboardingShell
+ title="Mode"
+ ctaLabel="Use Cloud"
+ onCta={onCta}
+ secondaryCtaLabel="Use Local"
+ onSecondaryCta={onSecondaryCta}
+ />,
+ );
+
+ fireEvent.press(screen.getByText('Use Local'));
+ fireEvent.press(await screen.findByText('Retry'));
+
+ await act(async () => undefined);
+ expect(onSecondaryCta).toHaveBeenCalledTimes(2);
+ expect(onCta).not.toHaveBeenCalled();
+});
+
+it('shows Back as an arrow that screen readers still call Back', async () => {
+ const onBack = jest.fn();
+ render(<OnboardingShell title="Tone" ctaLabel="Continue" onCta={jest.fn()} onBack={onBack} />);
+
+ expect(screen.queryByText('Back')).toBeNull();
+ fireEvent.press(screen.getByRole('button', { name: 'Back' }));
+
+ await act(async () => undefined);
+ expect(onBack).toHaveBeenCalledTimes(1);
+});
+
+it('offers a help button only on steps that provide help', () => {
+ const onHelp = jest.fn();
+ const { rerender } = render(
+ <OnboardingShell title="Switch" ctaLabel="I switched" onCta={jest.fn()} />,
+ );
+ expect(screen.queryByRole('button', { name: 'Help' })).toBeNull();
+
+ rerender(
+ <OnboardingShell title="Switch" ctaLabel="I switched" onCta={jest.fn()} onHelp={onHelp} />,
+ );
+ fireEvent.press(screen.getByRole('button', { name: 'Help' }));
+
+ expect(onHelp).toHaveBeenCalledTimes(1);
+});
diff --git a/openwhispr-mobile/src/components/superwall/SuperwallGateProvider.tsx b/openwhispr-mobile/src/components/superwall/SuperwallGateProvider.tsx
index 55231150f..7e9555158 100644
--- a/openwhispr-mobile/src/components/superwall/SuperwallGateProvider.tsx
+++ b/openwhispr-mobile/src/components/superwall/SuperwallGateProvider.tsx
@@ -1,8 +1,8 @@
-import React, { useCallback, useMemo, useRef } from 'react';
+import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Alert } from 'react-native';
import { router } from 'expo-router';
import { usePlacement, useSuperwall } from 'expo-superwall';
-import type { PaywallResult, PaywallSkippedReason } from 'expo-superwall';
+import type { PaywallResult, PaywallSkippedReason, PaywallState } from 'expo-superwall';
import { SuperwallGateContext } from '@/hooks/useSuperwallGate';
import type {
RegisterSuperwallGateOptions,
@@ -36,9 +36,60 @@ type PendingGate = {
purchaseCompletionReported: boolean;
terminalEventProcessed: boolean;
closed: boolean;
+ cancelled?: boolean;
+ removeAbortListener?: () => void;
resolve: (granted: boolean) => void;
};
+type PlacementCallbacks = NonNullable<Parameters<typeof usePlacement>[0]>;
+type NativeRegister = ReturnType<typeof usePlacement>['registerPlacement'];
+type OnboardingOffer = {
+ id: number;
+ gate: PendingGate;
+ start: (register: NativeRegister) => void;
+};
+
+function OnboardingOfferHandler({
+ offer,
+ callbacks,
+ dismiss,
+ retire,
+}: {
+ offer: OnboardingOffer;
+ callbacks: PlacementCallbacks;
+ dismiss: () => void;
+ retire: (gate: PendingGate) => void;
+}): null {
+ const startedRef = useRef(false);
+ const { gate } = offer;
+ // Each offer gets its own SDK handler identity, including after an explicit
+ // onboarding reset. Keep cancelled listeners until native sends a terminal event.
+ const { registerPlacement } = usePlacement({
+ onPresent(info) {
+ if (gate.cancelled) dismiss();
+ else if (!gate.closed) callbacks.onPresent?.(info);
+ },
+ onDismiss(info, result) {
+ if (!gate.closed) callbacks.onDismiss?.(info, result);
+ retire(gate);
+ },
+ onSkip(reason) {
+ if (!gate.closed) callbacks.onSkip?.(reason);
+ retire(gate);
+ },
+ onError(error) {
+ if (!gate.closed) callbacks.onError?.(error);
+ retire(gate);
+ },
+ });
+ useEffect(() => {
+ if (startedRef.current) return;
+ startedRef.current = true;
+ if (!gate.cancelled) offer.start(registerPlacement);
+ }, [gate, offer, registerPlacement]);
+ return null;
+}
+
// Dev-only visibility into gate decisions: Sentry breadcrumbs are invisible
// without a DSN, and skips are deliberately silent in the UI.
function debugLog(message: string, data?: Record<string, unknown>): void {
@@ -102,6 +153,7 @@ function completeGate(
if (granted && reportNoPurchaseAccess) reportAccessGrantedWithoutPurchase(gate);
if (gate.closed) return;
gate.closed = true;
+ gate.removeAbortListener?.();
gate.resolve(granted);
if (runFeature && !gate.featureRan) {
gate.featureRan = true;
@@ -273,14 +325,21 @@ export function DisabledSuperwallGateProvider({ children }: Props) {
export function EnabledSuperwallGateProvider({ children }: Props) {
const user = useAuthStore((state) => state.user);
- const { isConfigured, configurationError } = useSuperwall((state) => ({
+ const { isConfigured, configurationError, dismiss } = useSuperwall((state) => ({
isConfigured: state.isConfigured,
configurationError: state.configurationError,
+ dismiss: state.dismiss,
}));
const activePlacementRef = useRef<SuperwallPlacement | null>(null);
const pendingGateRef = useRef<PendingGate | null>(null);
const presentationGatesRef = useRef<PendingGate[]>([]);
+ const nextOfferId = useRef(0);
+ const [onboardingOffers, setOnboardingOffers] = useState<OnboardingOffer[]>([]);
+ const [onboardingState, setOnboardingState] = useState<PaywallState>({ status: 'idle' });
+ const retireOffer = useCallback((gate: PendingGate): void => {
+ setOnboardingOffers((offers) => offers.filter((offer) => offer.gate !== gate));
+ }, []);
const routeToAuth = useRouteToAuth(activePlacementRef);
const finishActiveGate = useCallback(
@@ -309,9 +368,12 @@ export function EnabledSuperwallGateProvider({ children }: Props) {
[],
);
- const { registerPlacement, state } = usePlacement({
+ const placementCallbacks: PlacementCallbacks = {
onPresent(paywallInfo) {
const gate = pendingGateRef.current;
+ if (gate?.placement === SUPERWALL_PLACEMENTS.onboardingPaywall) {
+ setOnboardingState({ status: 'presented', paywallInfo });
+ }
if (gate && !presentationGatesRef.current.includes(gate)) {
presentationGatesRef.current.push(gate);
}
@@ -438,7 +500,21 @@ export function EnabledSuperwallGateProvider({ children }: Props) {
);
if (gate?.transactional && !billingFallback) showBillingUnavailable();
},
- });
+ };
+
+ const dismissCancelledOffer = useCallback((): void => {
+ dismiss().catch((error: unknown) => {
+ Sentry.captureException(error, {
+ tags: { feature: 'superwall', operation: 'dismiss-cancelled-onboarding' },
+ });
+ });
+ }, [dismiss]);
+
+ const { registerPlacement, state: billingState } = usePlacement(placementCallbacks);
+ const state =
+ activePlacementRef.current === SUPERWALL_PLACEMENTS.onboardingPaywall
+ ? onboardingState
+ : billingState;
const register = useCallback(
async ({
@@ -447,8 +523,11 @@ export function EnabledSuperwallGateProvider({ children }: Props) {
feature,
onAccessGrantedWithoutPurchase,
onPurchaseComplete,
+ signal,
requiresAccount = isTransactionalSuperwallPlacement(placement),
}: RegisterSuperwallGateOptions): Promise<boolean> => {
+ const isOnboarding = placement === SUPERWALL_PLACEMENTS.onboardingPaywall;
+ if (isOnboarding && signal?.aborted) return false;
debugLog('register', {
placement,
requiresAccount,
@@ -551,13 +630,35 @@ export function EnabledSuperwallGateProvider({ children }: Props) {
};
pendingGateRef.current = gate;
+ if (isOnboarding && signal) {
+ const cancel = (): void => {
+ gate.cancelled = true;
+ const wasPresented = presentationGatesRef.current.includes(gate);
+ presentationGatesRef.current = presentationGatesRef.current.filter(
+ (item) => item !== gate,
+ );
+ if (pendingGateRef.current === gate) {
+ pendingGateRef.current = null;
+ activePlacementRef.current = null;
+ }
+ completeGate(gate, false, false, false);
+ if (wasPresented) dismissCancelledOffer();
+ };
+ signal.addEventListener('abort', cancel);
+ gate.removeAbortListener = () => signal.removeEventListener('abort', cancel);
+ }
+
const finishGate = (
granted: boolean,
runFeature: boolean,
reportNoPurchaseAccess: boolean,
) => {
if (gate.terminalEventProcessed) return;
+ // Only an aborted onboarding offer drops a late completion. A skipped billing placement
+ // still reports access so its caller can open billing management.
+ if (gate.cancelled) return;
const isPresented = presentationGatesRef.current.includes(gate);
+ if (isOnboarding && isPresented) return;
completeGate(gate, granted, runFeature, reportNoPurchaseAccess && !isPresented);
if (isPresented) return;
if (pendingGateRef.current === gate) pendingGateRef.current = null;
@@ -565,47 +666,85 @@ export function EnabledSuperwallGateProvider({ children }: Props) {
};
debugLog('registering placement with Superwall', { placement, params });
- registerPlacement({
- placement,
- params,
- feature: () => {
- if (gate.closed) return;
- debugLog('feature gate granted', { placement });
- Sentry.addBreadcrumb({
- category: 'superwall',
- message: 'feature gate granted',
- level: 'info',
- data: { placement },
- });
- finishGate(true, true, true);
- },
- })
- .then(() => {
- debugLog('registerPlacement resolved (access granted)', { placement });
- finishGate(true, true, true);
+ const start = (present: NativeRegister): void => {
+ present({
+ placement,
+ params,
+ feature: () => {
+ if (gate.closed) return;
+ debugLog('feature gate granted', { placement });
+ Sentry.addBreadcrumb({
+ category: 'superwall',
+ message: 'feature gate granted',
+ level: 'info',
+ data: { placement },
+ });
+ finishGate(true, true, true);
+ if (isOnboarding && !presentationGatesRef.current.includes(gate) && !gate.cancelled)
+ retireOffer(gate);
+ },
})
- .catch((error) => {
- debugLog('registerPlacement REJECTED', { placement, error: String(error) });
- if (gate.closed) return;
- Sentry.captureException(error, {
- tags: { feature: 'superwall', operation: 'register-placement' },
- extra: { placement, isConfigured },
+ .then(() => {
+ debugLog('registerPlacement resolved (access granted)', { placement });
+ finishGate(true, true, true);
+ })
+ .catch((error) => {
+ debugLog('registerPlacement REJECTED', { placement, error: String(error) });
+ if (gate.closed) return;
+ Sentry.captureException(error, {
+ tags: { feature: 'superwall', operation: 'register-placement' },
+ extra: { placement, isConfigured },
+ });
+ const billingFallback = canOpenExistingBilling(placement);
+ const failOpen = !gate.transactional;
+ const finish =
+ isOnboarding && presentationGatesRef.current.includes(gate)
+ ? finishPresentationGate
+ : finishGate;
+ finish(
+ failOpen || billingFallback,
+ failOpen || billingFallback,
+ failOpen || billingFallback,
+ );
+ if (gate.transactional && !billingFallback) showBillingUnavailable();
+ if (isOnboarding) retireOffer(gate);
});
- const billingFallback = canOpenExistingBilling(placement);
- const failOpen = !gate.transactional;
- finishGate(
- failOpen || billingFallback,
- failOpen || billingFallback,
- failOpen || billingFallback,
- );
- if (gate.transactional && !billingFallback) showBillingUnavailable();
- });
+ };
+ if (isOnboarding) {
+ setOnboardingState({ status: 'idle' });
+ const offer = { id: nextOfferId.current++, gate, start };
+ setOnboardingOffers((offers) => [...offers, offer]);
+ } else {
+ start(registerPlacement);
+ }
});
},
- [configurationError, isConfigured, registerPlacement, routeToAuth, user],
+ [
+ configurationError,
+ isConfigured,
+ registerPlacement,
+ dismissCancelledOffer,
+ finishPresentationGate,
+ retireOffer,
+ routeToAuth,
+ user,
+ ],
);
const value = useMemo(() => ({ register, state, isConfigured }), [isConfigured, register, state]);
- return <SuperwallGateContext.Provider value={value}>{children}</SuperwallGateContext.Provider>;
+ return (
+ <SuperwallGateContext.Provider value={value}>
+ {children}
+ {onboardingOffers.map((offer) => (
+ <OnboardingOfferHandler
+ key={offer.id}
+ offer={offer}
+ callbacks={placementCallbacks}
+ dismiss={dismissCancelledOffer}
+ retire={retireOffer}
+ />
+ ))}
+ </SuperwallGateContext.Provider>
+ );
}
diff --git a/openwhispr-mobile/src/components/superwall/__tests__/SuperwallGateProvider.test.tsx b/openwhispr-mobile/src/components/superwall/__tests__/SuperwallGateProvider.test.tsx
index e153421aa..c24d6d4a6 100644
--- a/openwhispr-mobile/src/components/superwall/__tests__/SuperwallGateProvider.test.tsx
+++ b/openwhispr-mobile/src/components/superwall/__tests__/SuperwallGateProvider.test.tsx
@@ -33,6 +33,7 @@ const mockRegisterPlacement = jest.fn(
const mockReconcileStoreBilling = jest.fn();
const mockLogPaywallViewed = jest.fn();
const mockLogSubscription = jest.fn();
+const mockDismiss = jest.fn(async () => undefined);
jest.mock('expo-router', () => ({
router: { push: jest.fn(), replace: jest.fn() },
@@ -45,10 +46,16 @@ jest.mock(
selector({
isConfigured: mockIsConfigured,
configurationError: mockConfigurationError,
+ dismiss: mockDismiss,
}),
usePlacement: (callbacks: Record<string, (...args: any[]) => void>) => {
- mockPlacementCallbacks = callbacks;
- return { registerPlacement: mockRegisterPlacement, state: { status: 'idle' } };
+ return {
+ registerPlacement: (options: { feature?: () => void }) => {
+ mockPlacementCallbacks = callbacks;
+ return mockRegisterPlacement(options);
+ },
+ state: { status: 'idle' },
+ };
},
}),
{ virtual: true },
@@ -117,12 +124,14 @@ function GateConsumer({
onAccessGrantedWithoutPurchase,
onPurchaseComplete,
label = 'register',
+ signal,
}: {
placement: SuperwallPlacement;
feature?: () => void;
onAccessGrantedWithoutPurchase?: () => void;
onPurchaseComplete?: (completion: SuperwallPurchaseCompletion) => void;
label?: string;
+ signal?: AbortSignal;
}): React.JSX.Element {
const { register } = useSuperwallGate();
const [result, setResult] = useState('pending');
@@ -136,6 +145,7 @@ function GateConsumer({
feature,
onAccessGrantedWithoutPurchase,
onPurchaseComplete,
+ signal,
};
register(options).then((granted) => setResult(String(granted)));
}}
@@ -191,6 +201,87 @@ describe('SuperwallGateProvider', () => {
});
});
+ it('retires an aborted onboarding offer and dismisses late presentation without affecting later billing', async () => {
+ mockShouldPresent = false;
+ const controller = new AbortController();
+ const screen = render(
+ <EnabledSuperwallGateProvider>
+ <GateConsumer
+ placement={SUPERWALL_PLACEMENTS.onboardingPaywall}
+ signal={controller.signal}
+ label="onboard"
+ />
+ <GateConsumer placement={SUPERWALL_PLACEMENTS.accountBillingOpen} label="billing" />
+ </EnabledSuperwallGateProvider>,
+ );
+ fireEvent.press(screen.getByText('onboard'));
+ const cancelledCallbacks = mockPlacementCallbacks;
+ await act(async () => controller.abort());
+ mockShouldPresent = true;
+ fireEvent.press(screen.getByText('billing'));
+ expect(mockRegisterPlacement).toHaveBeenCalledTimes(2);
+ const billingCallbacks = mockPlacementCallbacks;
+ await act(async () => {
+ cancelledCallbacks.onPresent({ identifier: 'old-offer', name: 'Offer' });
+ cancelledCallbacks.onDismiss({}, { type: 'declined' });
+ });
+ expect(mockDismiss).toHaveBeenCalledTimes(1);
+ expect(screen.getAllByTestId('result')[1].props.children).toBe('pending');
+ await act(async () => billingCallbacks.onDismiss({}, { type: 'declined' }));
+ expect(screen.getAllByTestId('result')[1].props.children).toBe('false');
+ });
+
+ it('drops a late completion from an aborted onboarding offer', async () => {
+ mockShouldPresent = false;
+ const controller = new AbortController();
+ const onAccessGrantedWithoutPurchase = jest.fn();
+ const screen = render(
+ <EnabledSuperwallGateProvider>
+ <GateConsumer
+ placement={SUPERWALL_PLACEMENTS.onboardingPaywall}
+ signal={controller.signal}
+ onAccessGrantedWithoutPurchase={onAccessGrantedWithoutPurchase}
+ />
+ </EnabledSuperwallGateProvider>,
+ );
+ fireEvent.press(screen.getByText('register'));
+ const completeAbortedPlacement = mockResolveNativePlacement;
+ await act(async () => controller.abort());
+ await act(async () => completeAbortedPlacement?.());
+
+ expect(onAccessGrantedWithoutPurchase).not.toHaveBeenCalled();
+ });
+
+ it('allows a fresh onboarding run after cancellation while ignoring events from the old offer', async () => {
+ mockShouldPresent = false;
+ const firstRun = new AbortController();
+ const secondRun = new AbortController();
+ const screen = render(
+ <EnabledSuperwallGateProvider>
+ <GateConsumer
+ placement={SUPERWALL_PLACEMENTS.onboardingPaywall}
+ signal={firstRun.signal}
+ label="first run"
+ />
+ <GateConsumer
+ placement={SUPERWALL_PLACEMENTS.onboardingPaywall}
+ signal={secondRun.signal}
+ label="second run"
+ />
+ </EnabledSuperwallGateProvider>,
+ );
+ fireEvent.press(screen.getByText('first run'));
+ const oldCallbacks = mockPlacementCallbacks;
+ await act(async () => firstRun.abort());
+ fireEvent.press(screen.getByText('second run'));
+ expect(mockRegisterPlacement).toHaveBeenCalledTimes(2);
+ const currentCallbacks = mockPlacementCallbacks;
+ await act(async () => oldCallbacks.onSkip({ type: 'PlacementNotFound' }));
+ expect(screen.getAllByTestId('result')[1].props.children).toBe('pending');
+ await act(async () => currentCallbacks.onSkip({ type: 'PlacementNotFound' }));
+ expect(screen.getAllByTestId('result')[1].props.children).toBe('true');
+ });
+
it('logs a paywall view only when Superwall presents one', () => {
const screen = render(
<EnabledSuperwallGateProvider>
@@ -769,6 +860,28 @@ describe('SuperwallGateProvider', () => {
expect(secondOnPurchaseComplete).toHaveBeenCalledTimes(1);
});
+ // The native SDK still completes the placement after a PlacementNotFound skip. Only an aborted
+ // onboarding offer may drop that late grant: the Billing row relies on it to open management.
+ it('still reports access without purchase when the placement completes after a skip', async () => {
+ const onAccessGrantedWithoutPurchase = jest.fn();
+ const screen = render(
+ <EnabledSuperwallGateProvider>
+ <GateConsumer
+ placement={SUPERWALL_PLACEMENTS.accountBillingOpen}
+ onAccessGrantedWithoutPurchase={onAccessGrantedWithoutPurchase}
+ />
+ </EnabledSuperwallGateProvider>,
+ );
+
+ mockShouldPresent = false;
+ fireEvent.press(screen.getByText('register'));
+ act(() => mockPlacementCallbacks.onSkip?.({ type: 'PlacementNotFound' }));
+ await waitFor(() => expect(screen.getByTestId('result').props.children).toBe('false'));
+ await act(async () => mockResolveNativePlacement?.());
+
+ expect(onAccessGrantedWithoutPurchase).toHaveBeenCalledTimes(1);
+ });
+
it('fails open after a pre-presentation error and allows a later registration', async () => {
const feature = jest.fn();
const firstOnPurchaseComplete = jest.fn();
diff --git a/openwhispr-mobile/src/components/ui/FormSheet.tsx b/openwhispr-mobile/src/components/ui/FormSheet.tsx
index bf0bca40c..749a24fa2 100644
--- a/openwhispr-mobile/src/components/ui/FormSheet.tsx
+++ b/openwhispr-mobile/src/components/ui/FormSheet.tsx
@@ -1,19 +1,14 @@
-import { type ReactNode, useEffect } from 'react';
-import { Dimensions, Modal, Pressable, ScrollView, View, type ViewStyle } from 'react-native';
-import { Gesture, GestureDetector, GestureHandlerRootView } from 'react-native-gesture-handler';
-import Animated, {
- runOnJS,
- useAnimatedStyle,
- useSharedValue,
- withSpring,
- withTiming,
-} from 'react-native-reanimated';
+import { type ReactNode } from 'react';
+import { Modal, Pressable, ScrollView, View, type ViewStyle } from 'react-native';
+import { GestureDetector, GestureHandlerRootView } from 'react-native-gesture-handler';
+import Animated from 'react-native-reanimated';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Text } from '@/components/ui/Text';
import { GlassIconButton } from '@/components/ui/GlassIconButton';
import { GradientGlassSurface } from '@/components/ui/GradientGlassSurface';
import { SystemIcon } from '@/components/ui/SystemIcon';
import { useKeyboardHeight } from '@/hooks/useKeyboardHeight';
+import { useSheetDragToDismiss } from '@/hooks/useSheetDragToDismiss';
const SHEET_RADIUS = 28;
// Gap below the safe-area inset, leaving a sliver of the dimmed screen above the
@@ -21,10 +16,6 @@ const SHEET_RADIUS = 28;
const SHEET_TOP_PEEK = 8;
// Breathing room between the primary button and the keyboard's top edge.
const BUTTON_KEYBOARD_GAP = 10;
-// Drag distance / fling velocity past which a downward pull dismisses the sheet.
-const DISMISS_DISTANCE = 110;
-const DISMISS_VELOCITY = 800;
-const SCREEN_HEIGHT = Dimensions.get('window').height;
const SUBMIT_SHADOW: ViewStyle = {
shadowColor: '#2457D6',
@@ -68,30 +59,7 @@ export function FormSheet({
}: FormSheetProps) {
const insets = useSafeAreaInsets();
const keyboardHeight = useKeyboardHeight(visible);
- const translateY = useSharedValue(0);
-
- useEffect(() => {
- if (visible) translateY.value = 0;
- }, [visible, translateY]);
-
- const dragGesture = Gesture.Pan()
- .activeOffsetY(10)
- .onUpdate((event) => {
- translateY.value = Math.max(0, event.translationY);
- })
- .onEnd((event) => {
- if (event.translationY > DISMISS_DISTANCE || event.velocityY > DISMISS_VELOCITY) {
- translateY.value = withTiming(SCREEN_HEIGHT, { duration: 200 }, () => {
- runOnJS(onClose)();
- });
- } else {
- translateY.value = withSpring(0, { damping: 20, stiffness: 220 });
- }
- });
-
- const sheetStyle = useAnimatedStyle(() => ({
- transform: [{ translateY: translateY.value }],
- }));
+ const { dragGesture, sheetStyle } = useSheetDragToDismiss(visible, onClose);
const bottomPad =
keyboardHeight > 0 ? keyboardHeight + BUTTON_KEYBOARD_GAP : Math.max(insets.bottom, 16);
diff --git a/openwhispr-mobile/src/hooks/__tests__/useSheetDragToDismiss.test.ts b/openwhispr-mobile/src/hooks/__tests__/useSheetDragToDismiss.test.ts
new file mode 100644
index 000000000..a8efbffad
--- /dev/null
+++ b/openwhispr-mobile/src/hooks/__tests__/useSheetDragToDismiss.test.ts
@@ -0,0 +1,13 @@
+import { shouldDismissSheetDrag } from '../useSheetDragToDismiss';
+
+jest.mock('react-native-reanimated', () => ({}));
+jest.mock('react-native-gesture-handler', () => ({}));
+
+it.each([
+ ['a short pull', 60, 200, false],
+ ['a pull past the distance', 140, 100, true],
+ ['a quick fling', 40, 1200, true],
+ ['an upward drag', -200, -1500, false],
+])('treats %s as dismiss=%s', (_label, translationY, velocityY, expected) => {
+ expect(shouldDismissSheetDrag(translationY, velocityY)).toBe(expected);
+});
diff --git a/openwhispr-mobile/src/hooks/useOnboardingPracticeMode.ts b/openwhispr-mobile/src/hooks/useOnboardingPracticeMode.ts
new file mode 100644
index 000000000..c4ec828b6
--- /dev/null
+++ b/openwhispr-mobile/src/hooks/useOnboardingPracticeMode.ts
@@ -0,0 +1,27 @@
+import { useEffect } from 'react';
+import { useConfigStore } from '@/store/useConfigStore';
+import { useOnboardingStore } from '@/store/useOnboardingStore';
+import { useProcessingModeStore } from '@/store/useProcessingModeStore';
+
+/**
+ * Lets an onboarding practice step run on Cloud before the user has chosen a mode. Reports whether
+ * Local is in effect instead, in which case the step shows an example rather than a live try.
+ */
+export function useOnboardingPracticeMode(): { localSelected: boolean } {
+ const selectedMode = useOnboardingStore((state) => state.selectedMode);
+ // Replaying onboarding starts with no choice made, but a saved Local default still stands.
+ const savedMode = useConfigStore((state) => state.config?.defaultMode);
+ const localSelected = (selectedMode ?? savedMode) === 'private';
+
+ useEffect(() => {
+ // Practice may use Cloud before the choice, but must never override a Local choice.
+ if (selectedMode !== null || localSelected) return;
+ const previous = useProcessingModeStore.getState();
+ previous.setActiveMode('cloud', true);
+ return () => {
+ useProcessingModeStore.getState().setActiveMode(previous.activeMode, previous.isUserOverride);
+ };
+ }, [selectedMode, localSelected]);
+
+ return { localSelected };
+}
diff --git a/openwhispr-mobile/src/hooks/useOnboardingStep.ts b/openwhispr-mobile/src/hooks/useOnboardingStep.ts
new file mode 100644
index 000000000..879bc5e33
--- /dev/null
+++ b/openwhispr-mobile/src/hooks/useOnboardingStep.ts
@@ -0,0 +1,20 @@
+import { useCallback } from 'react';
+import {
+ getStepProgress,
+ useOnboardingStore,
+ type OnboardingStepId,
+} from '@/store/useOnboardingStore';
+
+export function useOnboardingStep(step: OnboardingStepId): {
+ goNext: () => Promise<void>;
+ goBack: () => Promise<void>;
+ progress: ReturnType<typeof getStepProgress>;
+} {
+ const next = useOnboardingStore((state) => state.goNext);
+ const back = useOnboardingStore((state) => state.goBack);
+ return {
+ goNext: useCallback(() => next(step), [next, step]),
+ goBack: useCallback(() => back(step), [back, step]),
+ progress: getStepProgress(step),
+ };
+}
diff --git a/openwhispr-mobile/src/hooks/useSheetDragToDismiss.ts b/openwhispr-mobile/src/hooks/useSheetDragToDismiss.ts
new file mode 100644
index 000000000..41f6323b7
--- /dev/null
+++ b/openwhispr-mobile/src/hooks/useSheetDragToDismiss.ts
@@ -0,0 +1,60 @@
+import { useEffect } from 'react';
+import { Dimensions } from 'react-native';
+import { Gesture } from 'react-native-gesture-handler';
+import {
+ runOnJS,
+ useAnimatedStyle,
+ useSharedValue,
+ withSpring,
+ withTiming,
+} from 'react-native-reanimated';
+
+// Drag distance / fling velocity past which a downward pull dismisses the sheet.
+const DISMISS_DISTANCE = 110;
+const DISMISS_VELOCITY = 800;
+const SCREEN_HEIGHT = Dimensions.get('window').height;
+
+export function shouldDismissSheetDrag(translationY: number, velocityY: number): boolean {
+ 'worklet';
+ return translationY > DISMISS_DISTANCE || velocityY > DISMISS_VELOCITY;
+}
+
+/**
+ * Pull-down-to-dismiss for a bottom sheet: attach `dragGesture` to the draggable area with a
+ * GestureDetector and `sheetStyle` to the sheet. A short pull springs back; a long pull or a fling
+ * slides the sheet away and then calls `onClose`.
+ */
+export function useSheetDragToDismiss(
+ visible: boolean,
+ onClose: () => void,
+): {
+ dragGesture: ReturnType<typeof Gesture.Pan>;
+ sheetStyle: ReturnType<typeof useAnimatedStyle>;
+} {
+ const translateY = useSharedValue(0);
+
+ useEffect(() => {
+ if (visible) translateY.value = 0;
+ }, [visible, translateY]);
+
+ const dragGesture = Gesture.Pan()
+ .activeOffsetY(10)
+ .onUpdate((event) => {
+ translateY.value = Math.max(0, event.translationY);
+ })
+ .onEnd((event) => {
+ if (shouldDismissSheetDrag(event.translationY, event.velocityY)) {
+ translateY.value = withTiming(SCREEN_HEIGHT, { duration: 200 }, () => {
+ runOnJS(onClose)();
+ });
+ } else {
+ translateY.value = withSpring(0, { damping: 20, stiffness: 220 });
+ }
+ });
+
+ const sheetStyle = useAnimatedStyle(() => ({
+ transform: [{ translateY: translateY.value }],
+ }));
+
+ return { dragGesture, sheetStyle };
+}
diff --git a/openwhispr-mobile/src/hooks/useSuperwallGate.ts b/openwhispr-mobile/src/hooks/useSuperwallGate.ts
index e4007d7f2..1e36661fa 100644
--- a/openwhispr-mobile/src/hooks/useSuperwallGate.ts
+++ b/openwhispr-mobile/src/hooks/useSuperwallGate.ts
@@ -15,6 +15,8 @@ export type RegisterSuperwallGateOptions = {
onAccessGrantedWithoutPurchase?: () => void;
onPurchaseComplete?: (completion: SuperwallPurchaseCompletion) => void;
requiresAccount?: boolean;
+ /** Cancels the optional onboarding offer when its screen is left. */
+ signal?: AbortSignal;
};
type SuperwallGateContextValue = {
diff --git a/openwhispr-mobile/src/lib/__tests__/onboardingErrors.test.ts b/openwhispr-mobile/src/lib/__tests__/onboardingErrors.test.ts
new file mode 100644
index 000000000..9d9f8f420
--- /dev/null
+++ b/openwhispr-mobile/src/lib/__tests__/onboardingErrors.test.ts
@@ -0,0 +1,24 @@
+import { Sentry } from '@/lib/sentry';
+import { OnboardingError, describeOnboardingError } from '../onboardingErrors';
+
+jest.mock('@/lib/sentry', () => ({ Sentry: { captureException: jest.fn() } }));
+
+beforeEach(() => jest.clearAllMocks());
+
+it('shows messages written for users without reporting them', () => {
+ const message = describeOnboardingError(
+ new OnboardingError('Cloud needs an account.'),
+ 'Could not save progress.',
+ );
+ expect(message).toBe('Cloud needs an account.');
+ expect(Sentry.captureException).not.toHaveBeenCalled();
+});
+
+// Native failures read like "Calling the 'setValueWithKeyAsync' function has failed → OSStatus".
+it('reports unexpected failures and shows the fallback instead of their text', () => {
+ const error = new Error("Calling the 'setValueWithKeyAsync' function has failed");
+ expect(describeOnboardingError(error, 'Could not save progress.')).toBe(
+ 'Could not save progress.',
+ );
+ expect(Sentry.captureException).toHaveBeenCalledWith(error);
+});
diff --git a/openwhispr-mobile/src/lib/__tests__/onboardingMode.test.ts b/openwhispr-mobile/src/lib/__tests__/onboardingMode.test.ts
new file mode 100644
index 000000000..1084fe586
--- /dev/null
+++ b/openwhispr-mobile/src/lib/__tests__/onboardingMode.test.ts
@@ -0,0 +1,108 @@
+import { chooseOnboardingMode } from '../onboardingMode';
+import { OnboardingError } from '../onboardingErrors';
+
+jest.mock('@/lib/sentry', () => ({ Sentry: { captureException: jest.fn() } }));
+const mockUpdateConfig = jest.fn();
+const mockChooseMode = jest.fn();
+const mockEnsureSession = jest.fn();
+const mockResetMode = jest.fn();
+let mockError: string | null = null;
+let mockUser: { id: string; isAnonymous: boolean } | null = null;
+let mockGuest = false;
+let mockCurrentStep = 'privacy-mode';
+jest.mock('@/store/useConfigStore', () => ({
+ useConfigStore: {
+ getState: () => ({
+ config: { defaultMode: 'private' },
+ updateConfig: mockUpdateConfig,
+ error: mockError,
+ }),
+ },
+}));
+jest.mock('@/store/useProcessingModeStore', () => ({
+ useProcessingModeStore: { getState: () => ({ resetToDefault: mockResetMode }) },
+}));
+jest.mock('@/store/useOnboardingStore', () => ({
+ useOnboardingStore: {
+ getState: () => ({ currentStep: mockCurrentStep, chooseMode: mockChooseMode }),
+ },
+}));
+jest.mock('@/store/useAuthStore', () => ({
+ useAuthStore: {
+ getState: () => ({
+ user: mockUser,
+ isGuest: mockGuest,
+ ensureAnonymousSession: mockEnsureSession,
+ }),
+ },
+}));
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockError = null;
+ mockUser = null;
+ mockGuest = false;
+ mockCurrentStep = 'privacy-mode';
+ mockUpdateConfig.mockResolvedValue(undefined);
+ mockChooseMode.mockResolvedValue(undefined);
+ mockEnsureSession.mockResolvedValue(undefined);
+});
+it('retries anonymous authentication before allowing Cloud', async () => {
+ mockEnsureSession.mockImplementationOnce(async () => {
+ mockUser = { id: 'anon', isAnonymous: true };
+ });
+ await chooseOnboardingMode('cloud', 'privacy-mode');
+ expect(mockChooseMode).toHaveBeenCalledWith('cloud', 'privacy-mode');
+ expect(mockUpdateConfig).toHaveBeenCalledWith({ defaultMode: 'cloud' });
+});
+it('rejects Cloud without a session from download fallbacks too', async () => {
+ mockCurrentStep = 'private-download';
+ const attempt = chooseOnboardingMode('cloud', 'private-download');
+ await expect(attempt).rejects.toThrow('connection');
+ await expect(attempt).rejects.toBeInstanceOf(OnboardingError);
+ expect(mockUpdateConfig).not.toHaveBeenCalled();
+ expect(mockChooseMode).not.toHaveBeenCalled();
+});
+it('does not advance or change the active mode after a failed save', async () => {
+ mockUpdateConfig.mockImplementationOnce(async () => {
+ mockError = 'Cannot save';
+ });
+ await expect(chooseOnboardingMode('private', 'privacy-mode')).rejects.toThrow('Cannot save');
+ expect(mockChooseMode).not.toHaveBeenCalled();
+ expect(mockResetMode).not.toHaveBeenCalled();
+});
+it('does not change the mode for a stale screen callback', async () => {
+ mockCurrentStep = 'language';
+ await chooseOnboardingMode('private', 'privacy-mode');
+ expect(mockUpdateConfig).not.toHaveBeenCalled();
+});
+
+it('restores Local if a Cloud choice saves configuration but fails to save onboarding progress', async () => {
+ mockUser = { id: 'anon', isAnonymous: true };
+ mockCurrentStep = 'private-download';
+ mockChooseMode.mockRejectedValueOnce(new Error('Keychain unavailable'));
+ await expect(chooseOnboardingMode('cloud', 'private-download')).rejects.toThrow(
+ 'Keychain unavailable',
+ );
+ expect(mockUpdateConfig).toHaveBeenLastCalledWith({ defaultMode: 'private' });
+ expect(mockResetMode).toHaveBeenLastCalledWith('private');
+});
+
+it('refuses Cloud for a guest at the mode choice with a message meant for them', async () => {
+ mockGuest = true;
+ await expect(chooseOnboardingMode('cloud', 'privacy-mode')).rejects.toBeInstanceOf(
+ OnboardingError,
+ );
+ expect(mockUpdateConfig).not.toHaveBeenCalled();
+});
+
+// Guests can't open a session during setup. Refusing Cloud here too would leave a guest whose
+// download failed with no way to finish, so the choice is saved for after sign-in, as before.
+it('lets a guest leave a stuck download for Cloud', async () => {
+ mockGuest = true;
+ mockCurrentStep = 'private-download';
+ await chooseOnboardingMode('cloud', 'private-download');
+ expect(mockEnsureSession).not.toHaveBeenCalled();
+ expect(mockUpdateConfig).toHaveBeenCalledWith({ defaultMode: 'cloud' });
+ expect(mockChooseMode).toHaveBeenCalledWith('cloud', 'private-download');
+});
diff --git a/openwhispr-mobile/src/lib/__tests__/transcribeAndCleanup.tone.test.ts b/openwhispr-mobile/src/lib/__tests__/transcribeAndCleanup.tone.test.ts
index bd28478ec..209b297f2 100644
--- a/openwhispr-mobile/src/lib/__tests__/transcribeAndCleanup.tone.test.ts
+++ b/openwhispr-mobile/src/lib/__tests__/transcribeAndCleanup.tone.test.ts
@@ -31,8 +31,9 @@ jest.mock('@/store/useConfigStore', () => ({
// store (for final-text expansion) and dictationHints imports both stores. Mock
// them so importing the unit under test doesn't pull in the native expo-sqlite db.
// Empty entries → expansion is a no-op, keeping these tests focused on tone.
+let mockUser = { id: 'u', isAnonymous: false };
jest.mock('@/store/useAuthStore', () => ({
- useAuthStore: { getState: () => ({ user: { id: 'u', isAnonymous: false } }) },
+ useAuthStore: { getState: () => ({ user: mockUser }) },
}));
jest.mock('@/store/useSnippetsStore', () => ({
@@ -64,6 +65,7 @@ const mockCleanup = cleanupTranscript as jest.Mock;
beforeEach(() => {
jest.clearAllMocks();
+ mockUser = { id: 'u', isAnonymous: false };
mockTranscribe.mockResolvedValue({ text: 'hello world', provider: 'cloud', duration: 1 });
});
@@ -85,6 +87,30 @@ describe('transcribeAndCleanup tone', () => {
expect(result.text).toBe('cleaned:hello world');
});
+ // /api/reason refuses anonymous sessions, so forcing the serial path would drop cleanup
+ // entirely. The fused pass still cleans; the tone waits for a real account.
+ it('keeps fused cleanup for an anonymous session with a non-default tone', async () => {
+ mockUser = { id: 'anon', isAnonymous: true };
+ mockFused.mockResolvedValue({
+ text: 'Hello world.',
+ originalText: 'hello world',
+ provider: 'cloud',
+ duration: 1,
+ cleanupApplied: true,
+ fusedCleanup: true,
+ });
+
+ const result = await transcribeAndCleanup({
+ audioUri: 'file://a.wav',
+ provider: 'cloud',
+ requestContext: 'keyboard',
+ keyboardTone: 'formal',
+ });
+
+ expect(mockFused).toHaveBeenCalled();
+ expect(result.text).toBe('Hello world.');
+ });
+
it('does not pass tone for the default keyboard tone and may use fused', async () => {
mockFused.mockResolvedValue({
text: 'hi',
diff --git a/openwhispr-mobile/src/lib/onboardingErrors.ts b/openwhispr-mobile/src/lib/onboardingErrors.ts
new file mode 100644
index 000000000..7fcbd771d
--- /dev/null
+++ b/openwhispr-mobile/src/lib/onboardingErrors.ts
@@ -0,0 +1,12 @@
+import { Sentry } from '@/lib/sentry';
+
+/** A failure whose message is written for the user, such as Cloud needing an account. */
+export class OnboardingError extends Error {}
+
+// Anything else is a native or storage failure whose message would read as noise on screen,
+// so the user gets the step's fallback and the error goes to Sentry.
+export function describeOnboardingError(cause: unknown, fallback: string): string {
+ if (cause instanceof OnboardingError) return cause.message;
+ Sentry.captureException(cause);
+ return fallback;
+}
diff --git a/openwhispr-mobile/src/lib/onboardingMode.ts b/openwhispr-mobile/src/lib/onboardingMode.ts
new file mode 100644
index 000000000..a4623d4bc
--- /dev/null
+++ b/openwhispr-mobile/src/lib/onboardingMode.ts
@@ -0,0 +1,48 @@
+import { useAuthStore } from '@/store/useAuthStore';
+import { useConfigStore } from '@/store/useConfigStore';
+import { useOnboardingStore } from '@/store/useOnboardingStore';
+import { useProcessingModeStore } from '@/store/useProcessingModeStore';
+import type { ProcessingMode, UserConfig } from '@/types';
+import { OnboardingError } from './onboardingErrors';
+
+// updateConfig reports persistence errors in its store instead of rejecting.
+// Onboarding must not advance until the user's preference is actually saved.
+export async function saveOnboardingConfig(updates: Partial<UserConfig>): Promise<void> {
+ await useConfigStore.getState().updateConfig(updates);
+ const error = useConfigStore.getState().error;
+ if (error) throw new Error(error);
+}
+
+export async function chooseOnboardingMode(
+ mode: ProcessingMode,
+ from: 'privacy-mode' | 'private-download',
+): Promise<void> {
+ if (useOnboardingStore.getState().currentStep !== from) return;
+ const auth = useAuthStore.getState();
+ // Guests can't open a session during setup. On the download step Cloud is their only way past a
+ // download that can't finish, so it's saved for after sign-in instead of refused.
+ if (mode === 'cloud' && !auth.user && !(auth.isGuest && from === 'private-download')) {
+ if (auth.isGuest)
+ throw new OnboardingError(
+ 'Cloud needs an account. Use Local for now, or sign in after setup.',
+ );
+ await auth.ensureAnonymousSession();
+ if (!useAuthStore.getState().user) {
+ throw new OnboardingError(
+ 'Cloud needs a connection to set up. Try again or use Local for now.',
+ );
+ }
+ }
+ if (useOnboardingStore.getState().currentStep !== from) return;
+ const previousMode = useConfigStore.getState().config?.defaultMode ?? 'cloud';
+ await saveOnboardingConfig({ defaultMode: mode });
+ useProcessingModeStore.getState().resetToDefault(mode);
+ try {
+ await useOnboardingStore.getState().chooseMode(mode, from);
+ } catch (error) {
+ // Keep the active engine consistent with the screen when progress cannot be saved.
+ useProcessingModeStore.getState().resetToDefault(previousMode);
+ await saveOnboardingConfig({ defaultMode: previousMode });
+ throw error;
+ }
+}
diff --git a/openwhispr-mobile/src/lib/transcribeAndCleanup.ts b/openwhispr-mobile/src/lib/transcribeAndCleanup.ts
index 97f3428fc..b5fa871fb 100644
--- a/openwhispr-mobile/src/lib/transcribeAndCleanup.ts
+++ b/openwhispr-mobile/src/lib/transcribeAndCleanup.ts
@@ -3,10 +3,12 @@ import {
isLocalModelMissingError,
} from '@/services/transcription/TranscriptionService';
import { ReasoningService } from '@/services/reasoning/ReasoningService';
+import { useAuthStore } from '@/store/useAuthStore';
import { useConfigStore } from '@/store/useConfigStore';
import { getActiveCustomCleanupPrompt } from '@/store/useCustomPromptsStore';
import { useProcessingModeStore } from '@/store/useProcessingModeStore';
import { useSnippetsStore } from '@/store/useSnippetsStore';
+import { requiresRealAccount } from './accountAccess';
import { cleanupTranscript, AGENT_ACTION_TIMEOUT_MS } from './cleanupTranscript';
import {
getDictationAgentName,
@@ -112,11 +114,13 @@ async function shouldAttemptFusedCloudCleanup(request: TranscriptionRequest): Pr
return false;
}
// A non-default keyboard tone must use the serial path: tone is injected via
- // /api/reason, which only the serial cleanup pass calls.
+ // /api/reason, which only the serial cleanup pass calls. That endpoint refuses
+ // anonymous sessions, so they keep the fused cleanup and go without the tone.
if (
request.requestContext === 'keyboard' &&
request.keyboardTone &&
- request.keyboardTone !== 'default'
+ request.keyboardTone !== 'default' &&
+ !requiresRealAccount(useAuthStore.getState().user)
) {
return false;
}
diff --git a/openwhispr-mobile/src/screens/DictationAgentScreen.tsx b/openwhispr-mobile/src/screens/DictationAgentScreen.tsx
index bbe4d066a..e5f5ba7e6 100644
--- a/openwhispr-mobile/src/screens/DictationAgentScreen.tsx
+++ b/openwhispr-mobile/src/screens/DictationAgentScreen.tsx
@@ -44,8 +44,9 @@ export function DictationAgentScreen(): React.JSX.Element {
<SettingsScreen keyboardShouldPersistTaps="handled">
<View className="mx-4 mb-2 px-4">
<Text className="text-[13px] text-secondaryLabel">
- When you say your agent name while dictating, OpenWhispr rewrites what you said into
- polished, ready-to-use text instead of inserting it word for word. Requires Cloud mode.
+ When you say your assistant’s name while dictating, OpenWhispr rewrites what you said
+ into polished, ready-to-use text instead of inserting it word for word. Requires Cloud
+ mode.
</Text>
</View>
@@ -56,7 +57,7 @@ export function DictationAgentScreen(): React.JSX.Element {
style={{ borderCurve: 'continuous' }}
>
<Text className="text-[13px] text-secondaryLabel">
- Dictation Agent requires Cloud mode. Your settings are saved and will apply once
+ Voice Assistant requires Cloud mode. Your settings are saved and will apply once
Cloud mode is active.
</Text>
</View>
@@ -68,8 +69,8 @@ export function DictationAgentScreen(): React.JSX.Element {
iconStyle="line"
icon="person.wave.2"
mdIcon="UserRoundCog"
- title="Enable Dictation Agent"
- description="Say your agent name while dictating to have OpenWhispr rewrite what you said."
+ title="Enable Voice Assistant"
+ description="Say your assistant’s name while dictating to have OpenWhispr rewrite what you said."
rightElement={
<SettingsSwitch
value={enabled}
@@ -81,7 +82,7 @@ export function DictationAgentScreen(): React.JSX.Element {
/>
</SettingsSection>
- <SettingsSection title="Agent Name">
+ <SettingsSection title="Assistant Name">
<View className="px-4 py-3">
<TextInput
value={nameValue}
@@ -101,8 +102,8 @@ export function DictationAgentScreen(): React.JSX.Element {
</SettingsSection>
<View className="mx-4 -mt-5 mb-7 px-4">
<Text className="text-[13px] text-secondaryLabel">
- Say this name anywhere while dictating to trigger the agent. The name is automatically
- added to your transcription hints so the speech model recognises it.
+ Say this name anywhere while dictating to trigger the voice assistant. The name is
+ automatically added to your transcription hints so the speech model recognises it.
</Text>
</View>
@@ -112,7 +113,7 @@ export function DictationAgentScreen(): React.JSX.Element {
icon="text.cursor"
mdIcon="TextCursor"
title="Share Cursor Context"
- description="Selected text is always sent when you use the agent. When on, the surrounding text near your cursor is also sent. Off by default."
+ description="Selected text is always sent when you use the voice assistant. When on, the surrounding text near your cursor is also sent. Off by default."
rightElement={
<SettingsSwitch
value={shareContext}
diff --git a/openwhispr-mobile/src/screens/PreferencesScreen.tsx b/openwhispr-mobile/src/screens/PreferencesScreen.tsx
index 549bb72a9..93ecc6bfe 100644
--- a/openwhispr-mobile/src/screens/PreferencesScreen.tsx
+++ b/openwhispr-mobile/src/screens/PreferencesScreen.tsx
@@ -76,8 +76,8 @@ export default function PreferencesScreen() {
iconStyle="line"
icon="person.wave.2"
mdIcon="UserRoundCog"
- title="Dictation Agent"
- description="Trigger AI actions by saying your agent name"
+ title="Voice Assistant"
+ description="Trigger AI actions by saying your assistant’s name"
subtitle={agentName}
onPress={() => router.push('/(account)/dictation-agent')}
/>
diff --git a/openwhispr-mobile/src/screens/PrivacyDataScreen.tsx b/openwhispr-mobile/src/screens/PrivacyDataScreen.tsx
index 58fc77112..fc509299b 100644
--- a/openwhispr-mobile/src/screens/PrivacyDataScreen.tsx
+++ b/openwhispr-mobile/src/screens/PrivacyDataScreen.tsx
@@ -130,8 +130,8 @@ export default function PrivacyDataScreen() {
iconStyle="line"
icon="text.cursor"
mdIcon="TextCursor"
- title="Dictation Agent Context"
- description="Selected text is always sent to the cloud service when you use the Dictation Agent. If Share Cursor Context is on, the surrounding text near your cursor is also sent. This setting is off by default and can be changed in Dictation Agent settings."
+ title="Voice Assistant Context"
+ description="Selected text is always sent to the cloud service when you use the Voice Assistant. If Share Cursor Context is on, the surrounding text near your cursor is also sent. This setting is off by default and can be changed in Voice Assistant settings."
showChevron={false}
/>
<SettingsRow
diff --git a/openwhispr-mobile/src/screens/__tests__/voiceAssistantNaming.test.tsx b/openwhispr-mobile/src/screens/__tests__/voiceAssistantNaming.test.tsx
new file mode 100644
index 000000000..179aef63a
--- /dev/null
+++ b/openwhispr-mobile/src/screens/__tests__/voiceAssistantNaming.test.tsx
@@ -0,0 +1,71 @@
+import React from 'react';
+import { render, screen } from '@testing-library/react-native';
+
+jest.mock('expo-router', () => ({ router: { push: jest.fn() } }));
+jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
+jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
+jest.mock('@/store/useConfigStore', () => ({
+ useConfigStore: (selector: (state: unknown) => unknown) =>
+ selector({ config: null, updateConfig: jest.fn() }),
+}));
+jest.mock('@/hooks/useConfigToggle', () => ({ useConfigToggle: () => jest.fn() }));
+jest.mock('../../../modules/live-activity/src', () => ({
+ LiveActivity: { isDictationModeEnabled: () => false, setDictationMode: jest.fn() },
+}));
+// Private mode, so the "needs Cloud" notice renders too.
+jest.mock('@/store/useProcessingModeStore', () => ({
+ useProcessingModeStore: (selector: (state: unknown) => unknown) =>
+ selector({ activeMode: 'private' }),
+}));
+jest.mock('@/store/useAuthStore', () => ({
+ useAuthStore: (selector: (state: unknown) => unknown) =>
+ selector({ user: { id: 'user', isAnonymous: false }, isGuest: false }),
+}));
+jest.mock('@/sync/useSyncStore', () => ({
+ useSyncStore: () => ({
+ status: 'idle',
+ lastSyncAt: null,
+ subscriptionRequired: false,
+ policyBlocked: false,
+ }),
+}));
+jest.mock('@/sync/syncEngine', () => ({ requestSync: jest.fn() }));
+jest.mock('@/store/useUsageStore', () => ({
+ useUsageStore: (selector: (state: unknown) => unknown) =>
+ selector({ usage: null, load: jest.fn(async () => undefined) }),
+}));
+jest.mock('@/store/useNotesStore', () => ({
+ useNotesStore: (selector: (state: unknown) => unknown) =>
+ selector({
+ voiceProfiles: [],
+ loadVoiceProfiles: jest.fn(async () => undefined),
+ deleteAllVoiceProfiles: jest.fn(async () => undefined),
+ }),
+}));
+jest.mock('@/lib/alerts', () => ({ confirmDestructive: jest.fn() }));
+
+import { DictationAgentScreen } from '../DictationAgentScreen';
+import PreferencesScreen from '../PreferencesScreen';
+import PrivacyDataScreen from '../PrivacyDataScreen';
+
+// The feature is the voice assistant everywhere users meet it, matching onboarding and desktop.
+it('lists the voice assistant in Preferences', () => {
+ render(<PreferencesScreen />);
+ expect(screen.getByText('Voice Assistant')).toBeTruthy();
+ expect(screen.getByText('Trigger AI actions by saying your assistant’s name')).toBeTruthy();
+ expect(screen.queryByText(/agent/i)).toBeNull();
+});
+
+it('names the voice assistant throughout its settings screen', () => {
+ render(<DictationAgentScreen />);
+ expect(screen.getByText('Enable Voice Assistant')).toBeTruthy();
+ expect(screen.getByText('Assistant Name')).toBeTruthy();
+ expect(screen.getByText(/Voice Assistant requires Cloud mode/)).toBeTruthy();
+ expect(screen.queryByText(/agent/i)).toBeNull();
+});
+
+it('names the voice assistant in Privacy & Data', () => {
+ render(<PrivacyDataScreen />);
+ expect(screen.getByText('Voice Assistant Context')).toBeTruthy();
+ expect(screen.queryByText(/Dictation Agent/)).toBeNull();
+});
diff --git a/openwhispr-mobile/src/screens/onboarding/OnboardingFlow.tsx b/openwhispr-mobile/src/screens/onboarding/OnboardingFlow.tsx
index e85a3dc95..6bffe19eb 100644
--- a/openwhispr-mobile/src/screens/onboarding/OnboardingFlow.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/OnboardingFlow.tsx
@@ -1,6 +1,8 @@
import { useEffect, type ComponentType, type ReactElement } from 'react';
import { View } from 'react-native';
import { useOnboardingStore, type OnboardingStepId } from '@/store/useOnboardingStore';
+import { VoiceAgentStep } from './steps/VoiceAgentStep';
+import { ToneStep } from './steps/ToneStep';
import { GetStartedStep } from './steps/GetStartedStep';
import { SecurityFirstStep } from './steps/SecurityFirstStep';
import { WelcomeStep } from './steps/WelcomeStep';
@@ -27,6 +29,8 @@ const STEP_COMPONENTS: Record<OnboardingStepId, ComponentType> = {
'keyboard-switch': KeyboardSwitchStep,
microphone: MicrophoneStep,
'dictation-email': DictationEmailStep,
+ 'voice-agent': VoiceAgentStep,
+ tone: ToneStep,
'privacy-mode': PrivacyModeStep,
'private-download': PrivateDownloadStep,
language: LanguageStep,
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/CreateAccountStep.tsx b/openwhispr-mobile/src/screens/onboarding/steps/CreateAccountStep.tsx
index f2a8d16ed..204c16423 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/CreateAccountStep.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/CreateAccountStep.tsx
@@ -1,28 +1,34 @@
-import { useCallback, useEffect, useRef, type ReactElement } from 'react';
+import { useOnboardingStep } from '@/hooks/useOnboardingStep';
+import { useCallback, useEffect, useRef, useState, type ReactElement } from 'react';
+import { View } from 'react-native';
import AuthScreen from '@/screens/AuthScreen';
-import { Sentry } from '@/lib/sentry';
+import { OnboardingShell } from '@/components/onboarding/OnboardingShell';
+import { describeOnboardingError } from '@/lib/onboardingErrors';
import { useAuthStore } from '@/store/useAuthStore';
-import { useOnboardingStore } from '@/store/useOnboardingStore';
// Account creation runs on an anonymous session, so "signed in" here has to
// mean a *real* account — otherwise the step would end the moment it mounted.
export function CreateAccountStep(): ReactElement {
- const goNext = useOnboardingStore((s) => s.goNext);
+ const { goNext } = useOnboardingStep('create-account');
const user = useAuthStore((s) => s.user);
const isGuest = useAuthStore((s) => s.isGuest);
const hasContinuedRef = useRef(false);
+ const [advanceError, setAdvanceError] = useState<string | null>(null);
// The auth change that ends this step can re-render before the next step
// mounts, so goNext() would otherwise fire more than once.
- const continueOnce = useCallback(() => {
+ // A retry keeps its error screen up until it succeeds, which unmounts this step.
+ const continueOnce = useCallback(async (): Promise<void> => {
if (hasContinuedRef.current) return;
hasContinuedRef.current = true;
- goNext().catch((error: unknown) => {
- // A failed keychain write must not latch this shut: the user would sit
- // on a sign-in screen with no way forward. Report it and allow a retry.
+ try {
+ await goNext();
+ } catch (error) {
+ // A failed keychain write must not latch this shut. The sign-in that ended
+ // the step won't happen again, so the user needs a retry of their own.
hasContinuedRef.current = false;
- Sentry.captureException(error);
- });
+ setAdvanceError(describeOnboardingError(error, 'Could not save your progress. Try again.'));
+ }
}, [goNext]);
useEffect(() => {
@@ -30,6 +36,19 @@ export function CreateAccountStep(): ReactElement {
if ((user && !user.isAnonymous) || isGuest) continueOnce();
}, [continueOnce, isGuest, user]);
+ if (advanceError) {
+ return (
+ <OnboardingShell
+ title="Almost there"
+ subtitle={advanceError}
+ ctaLabel="Retry"
+ onCta={continueOnce}
+ >
+ <View className="flex-1" />
+ </OnboardingShell>
+ );
+ }
+
// The override exists to keep an anonymous session alive across the skip.
// With no session there is nothing to keep, and advancing would only
// re-render the same sign-in screen underneath; AuthScreen's default guest
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/DictationEmailStep.tsx b/openwhispr-mobile/src/screens/onboarding/steps/DictationEmailStep.tsx
index 8ccb85411..bc9689705 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/DictationEmailStep.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/DictationEmailStep.tsx
@@ -1,9 +1,9 @@
-import { useEffect, useRef, useState } from 'react';
+import { useCallback, useEffect, useRef, useState, type ReactElement } from 'react';
import {
Image,
Keyboard,
PlatformColor,
- Pressable,
+ ScrollView,
StyleSheet,
TextInput,
View,
@@ -12,47 +12,95 @@ import {
import { Text } from '@/components/ui/Text';
import { OnboardingShell } from '@/components/onboarding/OnboardingShell';
import { SpaceGrotesk } from '@/lib/fonts';
-import { getStepProgress, useOnboardingStore } from '@/store/useOnboardingStore';
+import { OnboardingError } from '@/lib/onboardingErrors';
+import { useOnboardingPracticeMode } from '@/hooks/useOnboardingPracticeMode';
+import { useOnboardingStep } from '@/hooks/useOnboardingStep';
+import { useAuthStore } from '@/store/useAuthStore';
import { useHandoffStore } from '@/store/useHandoffStore';
+import { addKeyboardStatusChangedListener } from '../../../../modules/app-group-storage/src';
-const STEP_ID = 'dictation-email';
-
-const SAMPLE_EMAIL = `Hey Tim, excited to chat. Are you free next Friday at 3pm… actually, 4pm? Thanks, Chad`;
+const SAMPLE_EMAIL =
+ 'Hey Tim, excited to chat. Are you free next Friday at 3pm… actually, 4pm? Thanks, Chad';
const GMAIL_ICON = require('../../../../assets/onboarding/app-icons/gmail.png');
const MAIL_ICON = require('../../../../assets/onboarding/app-icons/mail.png');
const OUTLOOK_ICON = require('../../../../assets/onboarding/app-icons/outlook.png');
-export function DictationEmailStep() {
- const goNext = useOnboardingStore((s) => s.goNext);
+export function DictationEmailStep(): ReactElement {
+ const { goNext, progress } = useOnboardingStep('dictation-email');
+ const { localSelected } = useOnboardingPracticeMode();
+ const user = useAuthStore((state) => state.user);
+ const ensureSession = useAuthStore((state) => state.ensureAnonymousSession);
+ const isTranscribing = useHandoffStore((state) => state.isTranscribing);
+ const input = useRef<TextInput>(null);
+ const dismissOnInsert = useRef(false);
const [value, setValue] = useState('');
-
- // Auto-hide the keyboard the moment a dictation finishes — scoped to this step
- // only, so the transcribed email and the Continue button are immediately visible.
- // Everywhere else the keyboard stays up for continuous dictation. Dictation into
- // this in-app field is "self-hosted", so useHandoffStore.isActive never flips;
- // isTranscribing is the flag that toggles true→false as the transcript lands.
- const isTranscribing = useHandoffStore((s) => s.isTranscribing);
- const wasTranscribing = useRef(false);
+ const [status, setStatus] = useState('idle');
+ const [error, setError] = useState<string | null>(null);
+ const liveAvailable = !localSelected && !!user;
+ const busy =
+ status === 'recording' || status === 'transcribing' || status === 'cleaning' || isTranscribing;
useEffect(() => {
- if (wasTranscribing.current && !isTranscribing) {
- Keyboard.dismiss();
- }
- wasTranscribing.current = isTranscribing;
- }, [isTranscribing]);
+ const subscription = addKeyboardStatusChangedListener((event) => {
+ if (!event.status) return;
+ setStatus(event.status);
+ if (event.status === 'ready') dismissOnInsert.current = true;
+ if (
+ event.status === 'error' ||
+ event.status === 'no_speech' ||
+ event.status === 'setup_required'
+ ) {
+ setError(
+ event.status === 'no_speech'
+ ? 'No speech detected. Try again.'
+ : event.error || 'Dictation could not finish. Try again.',
+ );
+ Keyboard.dismiss();
+ } else if (event.status === 'recording') {
+ // The keyboard settles back to idle after a failure, so only a new attempt clears it.
+ setError(null);
+ }
+ });
+ return () => subscription?.remove();
+ }, []);
+
+ const retry = useCallback(async (): Promise<void> => {
+ await ensureSession();
+ if (!useAuthStore.getState().user)
+ throw new OnboardingError('Still no connection. Check it and try again, or skip for now.');
+ setError(null);
+ setStatus('idle');
+ setValue('');
+ input.current?.focus();
+ }, [ensureSession]);
+
+ const note = localSelected
+ ? 'Practice uses Cloud. Skip it to keep Local.'
+ : !user
+ ? 'Cloud practice needs a connection. Try again or skip for now.'
+ : status === 'recording'
+ ? 'Listening…'
+ : busy
+ ? 'Transcribing…'
+ : value.trim()
+ ? 'Your email is ready'
+ : 'Tap the field, then the keyboard mic. Practice uses Cloud.';
return (
<OnboardingShell
- progress={getStepProgress(STEP_ID)}
- onSkip={goNext}
+ progress={progress}
+ onSkip={busy ? undefined : goNext}
title="Try dictating an email"
titleAccent="email"
subtitle="Don't type — just talk naturally. OpenWhispr formats it for you."
ctaLabel="Continue"
+ ctaDisabled={busy}
onCta={goNext}
+ secondaryCtaLabel={!localSelected && (error || !user) ? 'Retry' : undefined}
+ onSecondaryCta={retry}
>
- <Pressable className="flex-1" onPress={Keyboard.dismiss}>
+ <ScrollView keyboardShouldPersistTaps="handled" showsVerticalScrollIndicator={false}>
{/* Compose-style card — a light email hint (To / Subject), not a real client */}
<View className="overflow-hidden rounded-2xl border border-separator bg-secondarySystemGroupedBackground">
<View className="flex-row items-center gap-3 border-b border-separator px-4 py-3">
@@ -73,20 +121,39 @@ export function DictationEmailStep() {
Read this aloud
</Text>
<TextInput
+ ref={input}
+ accessibilityLabel="Your dictated email"
value={value}
- onChangeText={setValue}
+ onChangeText={(text) => {
+ setValue(text);
+ // Native readiness precedes the keyboard consuming its pending transcript, and the
+ // status stays ready afterwards, so dismiss once per dictation, not on every edit.
+ if (dismissOnInsert.current && text.trim()) {
+ dismissOnInsert.current = false;
+ Keyboard.dismiss();
+ }
+ }}
+ editable={liveAvailable}
+ autoFocus={liveAvailable}
multiline
placeholder={SAMPLE_EMAIL}
placeholderTextColor="#9CA3AF"
style={styles.emailInput}
textAlignVertical="top"
autoCorrect={false}
- autoFocus
scrollEnabled
/>
</View>
</View>
+ <Text
+ accessibilityRole={error ? 'alert' : undefined}
+ accessibilityLiveRegion="polite"
+ className={`mt-3 text-[13px] ${error ? 'text-systemRed' : 'text-secondaryLabel'}`}
+ >
+ {error ?? note}
+ </Text>
+
{/* Reassurance — works anywhere */}
<View className="mt-4 flex-row items-center justify-center">
<AppIcon source={GMAIL_ICON} size={18} />
@@ -94,7 +161,7 @@ export function DictationEmailStep() {
<AppIcon source={OUTLOOK_ICON} size={27} overlap />
<Text className="ml-2.5 text-[12px] text-tertiaryLabel">works in any email app</Text>
</View>
- </Pressable>
+ </ScrollView>
</OnboardingShell>
);
}
@@ -107,7 +174,7 @@ function AppIcon({
source: ImageSourcePropType;
overlap?: boolean;
size?: number;
-}) {
+}): ReactElement {
return (
<View
className={`h-7 w-7 items-center justify-center overflow-hidden rounded-full border-2 border-systemBackground bg-white ${
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/GetStartedStep.tsx b/openwhispr-mobile/src/screens/onboarding/steps/GetStartedStep.tsx
index 5e0d7844f..409de0e3a 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/GetStartedStep.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/GetStartedStep.tsx
@@ -1,15 +1,25 @@
+import { useOnboardingStep } from '@/hooks/useOnboardingStep';
+import { useState } from 'react';
import { View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Button } from '@/components/ui/Button';
import { Text } from '@/components/ui/Text';
import { OpenWhisprMark } from '@/components/ui/OpenWhisprMark';
import { BRAND_GRADIENT } from '@/config/colors';
-import { useOnboardingStore } from '@/store/useOnboardingStore';
+import { describeOnboardingError } from '@/lib/onboardingErrors';
const DEEP_BLUE = BRAND_GRADIENT[2];
export function GetStartedStep() {
- const goNext = useOnboardingStore((s) => s.goNext);
+ const { goNext } = useOnboardingStep('get-started');
+ const [error, setError] = useState<string | null>(null);
+
+ const start = (): void => {
+ setError(null);
+ goNext().catch((cause: unknown) =>
+ setError(describeOnboardingError(cause, 'Could not save your progress. Try again.')),
+ );
+ };
return (
<SafeAreaView className="flex-1 bg-systemBackground" edges={['top', 'bottom']}>
@@ -22,7 +32,12 @@ export function GetStartedStep() {
</View>
<View className="px-6 pb-4">
- <Button onPress={goNext} size="lg">
+ {error ? (
+ <Text accessibilityRole="alert" className="mb-3 text-center text-[14px] text-systemRed">
+ {error}
+ </Text>
+ ) : null}
+ <Button onPress={start} size="lg">
Get Started
</Button>
</View>
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/GraduationStep.tsx b/openwhispr-mobile/src/screens/onboarding/steps/GraduationStep.tsx
index 623c6a369..e4dfe07b2 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/GraduationStep.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/GraduationStep.tsx
@@ -1,9 +1,18 @@
-import { useCallback, useEffect, useState } from 'react';
-import { Image, Linking, Platform, Pressable, View, type ImageSourcePropType } from 'react-native';
+import { useCallback, useEffect, useRef, useState } from 'react';
+import {
+ Image,
+ Linking,
+ Platform,
+ Pressable,
+ ScrollView,
+ View,
+ type ImageSourcePropType,
+} from 'react-native';
import { Text } from '@/components/ui/Text';
import { OnboardingShell } from '@/components/onboarding/OnboardingShell';
import { SystemIcon, type LucideIconName } from '@/components/ui/SystemIcon';
import { useOnboardingStore } from '@/store/useOnboardingStore';
+import { describeOnboardingError } from '@/lib/onboardingErrors';
interface AppTarget {
key: string;
@@ -132,7 +141,10 @@ const TARGETS: AppTarget[] = [
];
export function GraduationStep() {
- const goNext = useOnboardingStore((s) => s.goNext);
+ const finish = useOnboardingStore((s) => s.finish);
+ const completing = useRef(false);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
const [installedKeys, setInstalledKeys] = useState<Set<string>>(() => {
return new Set(TARGETS.filter((t) => t.alwaysAvailable).map((t) => t.key));
});
@@ -176,13 +188,24 @@ export function GraduationStep() {
const visibleTargets = TARGETS.filter((t) => installedKeys.has(t.key));
- // Launching an external app deliberately does NOT advance. The next step
- // presents a paywall from an effect, and iOS cannot present from a
- // backgrounded app — it would fail open and skip the paywall entirely. The
- // user comes back to this screen and continues from the CTA.
- const handleTarget = useCallback((target: AppTarget) => {
- Linking.openURL(target.url).catch(() => {});
- }, []);
+ const complete = useCallback(
+ async (url?: string): Promise<void> => {
+ if (completing.current) return;
+ completing.current = true;
+ setBusy(true);
+ setError(null);
+ try {
+ await finish();
+ if (url) await Linking.openURL(url);
+ } catch (cause) {
+ setError(describeOnboardingError(cause, 'Could not finish setup. Try again.'));
+ } finally {
+ completing.current = false;
+ setBusy(false);
+ }
+ },
+ [finish],
+ );
return (
<OnboardingShell
@@ -190,21 +213,48 @@ export function GraduationStep() {
titleAccent="speaking"
subtitle="Try OpenWhispr anywhere — tap and hold the globe key in any app to switch keyboards."
ctaLabel="Start using OpenWhispr"
- onCta={goNext}
+ onCta={() => complete()}
+ ctaLoading={busy}
>
- <View className="flex-1 flex-row flex-wrap gap-3 pt-2">
+ {error ? (
+ <Text accessibilityRole="alert" className="mb-3 text-systemRed">
+ {error}
+ </Text>
+ ) : null}
+ <ScrollView
+ contentContainerStyle={{
+ flexDirection: 'row',
+ flexWrap: 'wrap',
+ gap: 12,
+ paddingBottom: 16,
+ }}
+ >
{visibleTargets.map((target) => (
- <TargetCard key={target.key} target={target} onPress={() => handleTarget(target)} />
+ <TargetCard
+ key={target.key}
+ target={target}
+ disabled={busy}
+ onPress={() => void complete(target.url)}
+ />
))}
- </View>
+ </ScrollView>
</OnboardingShell>
);
}
-function TargetCard({ target, onPress }: { target: AppTarget; onPress: () => void }) {
+function TargetCard({
+ target,
+ onPress,
+ disabled,
+}: {
+ target: AppTarget;
+ onPress: () => void;
+ disabled: boolean;
+}) {
return (
<Pressable
onPress={onPress}
+ disabled={disabled}
accessibilityRole="button"
accessibilityLabel={target.title}
className="w-[48%] items-center rounded-xl border border-separator bg-secondarySystemGroupedBackground py-4 active:opacity-90"
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/KeyboardIntroStep.tsx b/openwhispr-mobile/src/screens/onboarding/steps/KeyboardIntroStep.tsx
index c49951b06..4b4d4f4f0 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/KeyboardIntroStep.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/KeyboardIntroStep.tsx
@@ -1,14 +1,14 @@
+import { useOnboardingStep } from '@/hooks/useOnboardingStep';
import { useCallback, useEffect, useRef, useState } from 'react';
-import { AppState, Linking, type AppStateStatus, View } from 'react-native';
+import { Alert, AppState, Linking, type AppStateStatus, View } from 'react-native';
import { OnboardingShell } from '@/components/onboarding/OnboardingShell';
import { AnimatedKeyboardPreview } from '@/components/onboarding/AnimatedKeyboardPreview';
import { FullAccessReasons } from '@/components/onboarding/FullAccessReasons';
import { InstructionOverlay } from '@/components/onboarding/InstructionOverlay';
-import { getStepProgress, useOnboardingStore } from '@/store/useOnboardingStore';
+import { useOnboardingStore } from '@/store/useOnboardingStore';
import { isKeyboardInstalled } from '@/lib/keyboardInstallation';
import { startKeyboardPipTutorial, stopKeyboardPipTutorial } from '@/lib/keyboardPipTutorial';
-
-const STEP_ID = 'keyboard-intro';
+import { describeOnboardingError } from '@/lib/onboardingErrors';
const STEPS = [
'Tap Keyboards',
@@ -19,7 +19,7 @@ const STEPS = [
];
export function KeyboardIntroStep() {
- const goNext = useOnboardingStore((s) => s.goNext);
+ const { goNext, progress } = useOnboardingStep('keyboard-intro');
const setKeyboardInstalled = useOnboardingStore((s) => s.setKeyboardInstalled);
const [openedSettings, setOpenedSettings] = useState(false);
const [hasReturned, setHasReturned] = useState(false);
@@ -27,11 +27,26 @@ export function KeyboardIntroStep() {
const leftAppRef = useRef(false);
const settingsLaunchInFlightRef = useRef(false);
const skipCheckRef = useRef(false);
+ const advancingRef = useRef(false);
const stopPipTutorial = useCallback(() => {
stopKeyboardPipTutorial();
}, []);
+ const advance = useCallback(async (): Promise<void> => {
+ if (advancingRef.current) return;
+ advancingRef.current = true;
+ try {
+ stopPipTutorial();
+ await setKeyboardInstalled(true);
+ await goNext();
+ } catch (error) {
+ advancingRef.current = false;
+ setHasReturned(true);
+ Alert.alert('Could not continue', describeOnboardingError(error, 'Try again.'));
+ }
+ }, [goNext, setKeyboardInstalled, stopPipTutorial]);
+
// Mirror MicrophoneStep's auto-skip pattern: if the OpenWhispr keyboard is
// already enabled in iOS, advance immediately without showing this screen.
useEffect(() => {
@@ -39,9 +54,9 @@ export function KeyboardIntroStep() {
skipCheckRef.current = true;
if (isKeyboardInstalled()) {
stopPipTutorial();
- setKeyboardInstalled(true).then(() => goNext());
+ void advance();
}
- }, [goNext, setKeyboardInstalled, stopPipTutorial]);
+ }, [advance, stopPipTutorial]);
useEffect(() => {
let pollHandle: ReturnType<typeof setInterval> | null = null;
@@ -70,17 +85,17 @@ export function KeyboardIntroStep() {
if (isKeyboardInstalled()) {
stopPolling();
stopPipTutorial();
- setKeyboardInstalled(true).then(() => goNext());
- return;
+ void advance();
+ return true;
}
attempts += 1;
if (attempts >= maxAttempts) {
stopPolling();
setHasReturned(true);
}
+ return false;
};
- tryDetect();
- if (!pollHandle) {
+ if (!tryDetect()) {
pollHandle = setInterval(tryDetect, 200);
}
}
@@ -90,7 +105,7 @@ export function KeyboardIntroStep() {
stopPolling();
stopPipTutorial();
};
- }, [goNext, setKeyboardInstalled, stopPipTutorial]);
+ }, [advance, stopPipTutorial]);
const openSettings = useCallback(async () => {
if (settingsLaunchInFlightRef.current) return;
@@ -108,15 +123,9 @@ export function KeyboardIntroStep() {
}
}, []);
- const handleConfirm = useCallback(async () => {
- stopPipTutorial();
- await setKeyboardInstalled(true);
- await goNext();
- }, [setKeyboardInstalled, goNext, stopPipTutorial]);
-
return (
<OnboardingShell
- progress={getStepProgress(STEP_ID)}
+ progress={progress}
title={hasReturned ? 'Did you enable the keyboard?' : 'Use OpenWhispr in any app.'}
titleAccent={hasReturned ? 'enable' : 'any app'}
subtitle={
@@ -127,9 +136,9 @@ export function KeyboardIntroStep() {
ctaLabel={hasReturned ? 'Try again' : 'Open Settings'}
ctaDisabled={settingsLaunchPending}
ctaLoading={settingsLaunchPending}
- onCta={hasReturned ? openSettings : openSettings}
+ onCta={openSettings}
secondaryCtaLabel={hasReturned ? "I've enabled it" : undefined}
- onSecondaryCta={hasReturned ? handleConfirm : undefined}
+ onSecondaryCta={hasReturned ? advance : undefined}
>
<View className="flex-1 justify-center gap-4">
{openedSettings ? (
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/KeyboardSwitchHelpSheet.tsx b/openwhispr-mobile/src/screens/onboarding/steps/KeyboardSwitchHelpSheet.tsx
new file mode 100644
index 000000000..aa79d0bd5
--- /dev/null
+++ b/openwhispr-mobile/src/screens/onboarding/steps/KeyboardSwitchHelpSheet.tsx
@@ -0,0 +1,85 @@
+import type { ReactElement } from 'react';
+import { Linking, Modal, Pressable, View } from 'react-native';
+import { GestureDetector, GestureHandlerRootView } from 'react-native-gesture-handler';
+import Animated from 'react-native-reanimated';
+import { Text } from '@/components/ui/Text';
+import { Button } from '@/components/ui/Button';
+import { useSheetDragToDismiss } from '@/hooks/useSheetDragToDismiss';
+
+interface Props {
+ visible: boolean;
+ onClose: () => void;
+ /** Fires once the sheet has fully gone, the first moment iOS will accept a focus request again. */
+ onDismissed: () => void;
+}
+
+const FIXES: { problem: string; fix: string }[] = [
+ {
+ problem: 'Not in the list?',
+ fix: 'Turn on OpenWhispr in Settings → Keyboards, then come back.',
+ },
+ {
+ problem: 'Can’t find the globe?',
+ fix: 'It’s below the letters, bottom left. If you see 😀 instead, press and hold that.',
+ },
+ {
+ problem: 'Switched but nothing happened?',
+ fix: 'Turn on Allow Full Access in Settings → Keyboards.',
+ },
+];
+
+// The keyboard covers the switch step's own button, so this sheet is where someone stuck on the
+// step finds the fixes. It deliberately offers no way past the step: the app can't be used
+// without the keyboard, and it is much harder to debug once onboarding is over.
+export function KeyboardSwitchHelpSheet({ visible, onClose, onDismissed }: Props): ReactElement {
+ const { dragGesture, sheetStyle } = useSheetDragToDismiss(visible, onClose);
+ return (
+ <Modal
+ visible={visible}
+ transparent
+ animationType="slide"
+ onRequestClose={onClose}
+ onDismiss={onDismissed}
+ >
+ <GestureHandlerRootView className="flex-1">
+ <Pressable
+ accessibilityLabel="Dismiss"
+ onPress={onClose}
+ className="absolute inset-0 bg-black/40"
+ />
+ <GestureDetector gesture={dragGesture}>
+ <Animated.View
+ style={sheetStyle}
+ className="absolute bottom-0 left-0 right-0 rounded-t-3xl bg-systemBackground px-6 pb-8 pt-3"
+ >
+ <View className="mb-4 h-1 w-9 self-center rounded-full bg-separator" />
+ <Text accessibilityRole="header" className="text-[22px] font-bold text-label">
+ Can’t switch to OpenWhispr?
+ </Text>
+
+ <View className="mt-4 gap-3">
+ {FIXES.map(({ problem, fix }) => (
+ <Text key={problem} className="text-[15px] leading-[21px] text-secondaryLabel">
+ <Text className="font-semibold text-label">{problem}</Text> {fix}
+ </Text>
+ ))}
+ </View>
+
+ <View className="mt-6">
+ <Button onPress={() => Linking.openSettings()} size="lg">
+ Open Settings
+ </Button>
+ <Pressable
+ onPress={onClose}
+ className="mt-3 items-center py-2"
+ accessibilityRole="button"
+ >
+ <Text className="text-[15px] font-medium text-secondaryLabel">Close</Text>
+ </Pressable>
+ </View>
+ </Animated.View>
+ </GestureDetector>
+ </GestureHandlerRootView>
+ </Modal>
+ );
+}
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/KeyboardSwitchStep.tsx b/openwhispr-mobile/src/screens/onboarding/steps/KeyboardSwitchStep.tsx
index c802108f0..a26ee38dc 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/KeyboardSwitchStep.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/KeyboardSwitchStep.tsx
@@ -1,5 +1,6 @@
-import { useCallback, useEffect, useRef } from 'react';
-import { StyleSheet, TextInput, View } from 'react-native';
+import { useOnboardingStep } from '@/hooks/useOnboardingStep';
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { Keyboard, StyleSheet, TextInput, View } from 'react-native';
import { Text } from '@/components/ui/Text';
import Animated, {
Easing,
@@ -17,9 +18,8 @@ import { KeyboardDetectedToast } from '@/components/onboarding/KeyboardDetectedT
import { SystemIcon } from '@/components/ui/SystemIcon';
import { SpaceGrotesk } from '@/lib/fonts';
import { useKeyboardHeartbeat } from '@/hooks/useKeyboardHeartbeat';
-import { getStepProgress, useOnboardingStore } from '@/store/useOnboardingStore';
-
-const STEP_ID = 'keyboard-switch';
+import { describeOnboardingError } from '@/lib/onboardingErrors';
+import { KeyboardSwitchHelpSheet } from './KeyboardSwitchHelpSheet';
// Worklet-safe color literals — `interpolateColor` runs on the UI thread, so
// PlatformColor / iosColor() can't be used here. These match `systemBlue` and
@@ -34,9 +34,16 @@ const TRANSPARENT = 'rgba(0,0,0,0)';
const ROW_HEIGHT = 48;
export function KeyboardSwitchStep() {
- const goNext = useOnboardingStore((s) => s.goNext);
+ const { goNext, progress } = useOnboardingStep('keyboard-switch');
const inputRef = useRef<TextInput>(null);
- const detected = useKeyboardHeartbeat(goNext);
+ const [advanceError, setAdvanceError] = useState<string | null>(null);
+ const [helpVisible, setHelpVisible] = useState(false);
+ const advanceOnDetection = useCallback((): void => {
+ goNext().catch((error: unknown) => {
+ setAdvanceError(describeOnboardingError(error, 'Could not save progress.'));
+ });
+ }, [goNext]);
+ const detected = useKeyboardHeartbeat(advanceOnDetection);
useEffect(() => {
// Bring up the system keyboard so the user can reach the globe key.
@@ -46,21 +53,31 @@ export function KeyboardSwitchStep() {
return () => clearTimeout(focusTimer);
}, []);
- const handleManualAdvance = useCallback(() => {
- goNext();
- }, [goNext]);
-
const titleNode = <KeyboardSwitchTitle />;
+ // The keyboard covers this step's button and iOS keeps it above a modal, so help puts it away
+ // while open and brings it back for another try once the sheet has gone.
+ const openHelp = (): void => {
+ Keyboard.dismiss();
+ setHelpVisible(true);
+ };
+ const closeHelp = (): void => setHelpVisible(false);
+
return (
<>
<OnboardingShell
- progress={getStepProgress(STEP_ID)}
- title="Almost done. Press and hold the globe icon in the bottom-left corner of your keyboard, then select OpenWhispr."
+ progress={progress}
+ onHelp={openHelp}
+ title="Press and hold the globe icon in the bottom-left corner of your keyboard, then select OpenWhispr."
titleNode={titleNode}
- ctaLabel="I switched"
- onCta={handleManualAdvance}
+ ctaLabel={advanceError ? 'Retry' : 'I switched'}
+ onCta={goNext}
>
+ {advanceError ? (
+ <Text accessibilityRole="alert" className="text-systemRed">
+ {advanceError}
+ </Text>
+ ) : null}
<View className="flex-1 items-center justify-start pt-6">
<AnimatedKeyboardSwitchPreview />
</View>
@@ -79,6 +96,11 @@ export function KeyboardSwitchStep() {
/>
</OnboardingShell>
+ <KeyboardSwitchHelpSheet
+ visible={helpVisible}
+ onClose={closeHelp}
+ onDismissed={() => inputRef.current?.focus()}
+ />
{detected ? <KeyboardDetectedToast message="OpenWhispr keyboard is active" /> : null}
</>
);
@@ -87,7 +109,9 @@ export function KeyboardSwitchStep() {
function KeyboardSwitchTitle() {
return (
<View>
- <Text className="text-[28px] font-medium leading-[34px] text-label">Almost done.</Text>
+ <Text className="text-[28px] font-medium leading-[34px] text-label">
+ Switch to OpenWhispr.
+ </Text>
<View className="flex-row flex-wrap items-center">
<Text className="text-[28px] font-medium leading-[34px] text-label">
Press and hold the{' '}
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/LanguageStep.tsx b/openwhispr-mobile/src/screens/onboarding/steps/LanguageStep.tsx
index c9e0923b5..c2917bc22 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/LanguageStep.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/LanguageStep.tsx
@@ -1,3 +1,4 @@
+import { useOnboardingStep } from '@/hooks/useOnboardingStep';
import { useCallback, useMemo, useState } from 'react';
import { FlatList, Modal, Pressable, TextInput, View } from 'react-native';
import { Text } from '@/components/ui/Text';
@@ -5,7 +6,7 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { OnboardingShell } from '@/components/onboarding/OnboardingShell';
import { SystemIcon } from '@/components/ui/SystemIcon';
import { SpaceGrotesk } from '@/lib/fonts';
-import { getStepProgress, useOnboardingStore } from '@/store/useOnboardingStore';
+import { saveOnboardingConfig } from '@/lib/onboardingMode';
import { useConfigStore } from '@/store/useConfigStore';
import { detectPreferredLanguages } from '@/lib/deviceLanguages';
// TODO: extract this registry into a shared @openwhispr/language-registry package
@@ -14,8 +15,6 @@ import { detectPreferredLanguages } from '@/lib/deviceLanguages';
// adds new Whisper languages until the shared package exists.
import registry from '@/config/languageRegistry.json';
-const STEP_ID = 'language';
-
interface RegistryEntry {
code: string;
label: string;
@@ -132,12 +131,11 @@ const WHISPER_LANGUAGES: SupportedLanguage[] = (registry.languages as RegistryEn
const LANGUAGE_BY_CODE = new Map(WHISPER_LANGUAGES.map((l) => [l.code, l]));
export function LanguageStep() {
- const goNext = useOnboardingStore((s) => s.goNext);
- const goToStep = useOnboardingStore((s) => s.goToStep);
- const updateConfig = useConfigStore((s) => s.updateConfig);
+ const { goNext, progress, goBack } = useOnboardingStep('language');
+ const savedLanguages = useConfigStore((s) => s.config?.languages);
const detectedCodes = useMemo(detectPreferredLanguages, []);
- const [selected, setSelected] = useState<string[]>(() => detectedCodes);
+ const [selected, setSelected] = useState<string[]>(() => savedLanguages ?? detectedCodes);
const [sheetVisible, setSheetVisible] = useState(false);
const selectedLanguages = useMemo(
@@ -155,17 +153,10 @@ export function LanguageStep() {
setSheetVisible(false);
}, []);
- const handleContinue = useCallback(async () => {
- await updateConfig({ languages: selected });
- // The mode picked on the previous step decides what's next: private users download the
- // model their languages route to; cloud users skip the download step entirely.
- const mode = useConfigStore.getState().config?.defaultMode;
- if (mode === 'private') {
- await goNext(); // → 'private-download'
- } else {
- await goToStep('notifications');
- }
- }, [selected, updateConfig, goNext, goToStep]);
+ const handleContinue = useCallback(async (): Promise<void> => {
+ await saveOnboardingConfig({ languages: selected });
+ await goNext();
+ }, [selected, goNext]);
const subtitle = detectedCodes.length
? 'We picked these from your keyboard. Add or remove based on your preference.'
@@ -174,7 +165,8 @@ export function LanguageStep() {
return (
<>
<OnboardingShell
- progress={getStepProgress(STEP_ID)}
+ progress={progress}
+ onBack={goBack}
title="Choose your languages"
titleAccent="languages"
subtitle={subtitle}
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/MicrophoneStep.tsx b/openwhispr-mobile/src/screens/onboarding/steps/MicrophoneStep.tsx
index d07519585..3f5c490f0 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/MicrophoneStep.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/MicrophoneStep.tsx
@@ -1,22 +1,23 @@
+import { useOnboardingStep } from '@/hooks/useOnboardingStep';
import { useCallback, useEffect, useRef, useState } from 'react';
import { ActivityIndicator, Alert, AppState, Linking, View } from 'react-native';
import { OnboardingShell } from '@/components/onboarding/OnboardingShell';
import { SystemIcon } from '@/components/ui/SystemIcon';
-import { getStepProgress, useOnboardingStore } from '@/store/useOnboardingStore';
+import { useOnboardingStore } from '@/store/useOnboardingStore';
import { getExpoAudioModule } from '@/utils/expoAudio';
+import { describeOnboardingError } from '@/lib/onboardingErrors';
import { AppGroupStorage } from '../../../../modules/app-group-storage/src';
-const STEP_ID = 'microphone';
-
type PermissionState = 'checking' | 'undetermined' | 'granted' | 'denied' | 'unavailable';
type RecordingPermissionStatus = { granted: boolean; canAskAgain: boolean };
export function MicrophoneStep() {
- const goNext = useOnboardingStore((s) => s.goNext);
+ const { goNext, progress } = useOnboardingStep('microphone');
const setPermissionGranted = useOnboardingStore((s) => s.setPermissionGranted);
const [state, setState] = useState<PermissionState>('checking');
const [requesting, setRequesting] = useState(false);
+ const [advanceError, setAdvanceError] = useState<string | null>(null);
const requestingRef = useRef(false);
const advancedRef = useRef(false);
@@ -25,12 +26,18 @@ export function MicrophoneStep() {
const advance = useCallback(async () => {
if (advancedRef.current) return;
advancedRef.current = true;
+ setAdvanceError(null);
// The native side refuses to warm the dictation mic without permission, so
// a just-granted permission has to be announced — otherwise warming waits
// for the next foreground and the keyboard stays "not ready" until then.
AppGroupStorage.armWarmMic();
- await setPermissionGranted('microphone', true);
- await goNext();
+ try {
+ await setPermissionGranted('microphone', true);
+ await goNext();
+ } catch (error) {
+ advancedRef.current = false;
+ setAdvanceError(describeOnboardingError(error, 'Could not save progress.'));
+ }
}, [goNext, setPermissionGranted]);
const applyStatus = useCallback(
@@ -96,7 +103,17 @@ export function MicrophoneStep() {
'Open Settings to grant OpenWhispr access. You can continue setup for now.',
[
{ text: 'Open Settings', onPress: () => Linking.openSettings() },
- { text: 'Continue', style: 'cancel', onPress: () => goNext() },
+ {
+ text: 'Continue',
+ style: 'cancel',
+ onPress: () =>
+ goNext().catch((error: unknown) =>
+ Alert.alert(
+ 'Could not continue',
+ describeOnboardingError(error, 'Could not save progress.'),
+ ),
+ ),
+ },
],
);
return;
@@ -117,7 +134,19 @@ export function MicrophoneStep() {
await goNext();
}, [goNext]);
- const progress = getStepProgress(STEP_ID);
+ if (advanceError) {
+ return (
+ <OnboardingShell
+ progress={progress}
+ title="Microphone is ready"
+ subtitle={advanceError}
+ ctaLabel="Retry"
+ onCta={advance}
+ >
+ <View className="flex-1" />
+ </OnboardingShell>
+ );
+ }
if (state === 'checking') {
return (
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/NotificationsStep.tsx b/openwhispr-mobile/src/screens/onboarding/steps/NotificationsStep.tsx
index c894c73d8..2c0bf45f3 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/NotificationsStep.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/NotificationsStep.tsx
@@ -1,14 +1,14 @@
+import { useOnboardingStep } from '@/hooks/useOnboardingStep';
import { useCallback, useEffect, useRef, useState } from 'react';
-import { ActivityIndicator, Linking, View } from 'react-native';
+import { ActivityIndicator, View } from 'react-native';
import { Text } from '@/components/ui/Text';
import { OnboardingShell } from '@/components/onboarding/OnboardingShell';
import { SystemIcon, type LucideIconName } from '@/components/ui/SystemIcon';
-import { getStepProgress, useOnboardingStore } from '@/store/useOnboardingStore';
+import { useOnboardingStore } from '@/store/useOnboardingStore';
import { getNotificationStatus, requestNotifications } from '@/lib/notifications';
+import { describeOnboardingError } from '@/lib/onboardingErrors';
-const STEP_ID = 'notifications';
-
-type PermissionState = 'checking' | 'undetermined' | 'granted' | 'denied' | 'unavailable';
+type PermissionState = 'checking' | 'undetermined' | 'unavailable';
interface Benefit {
icon: string;
@@ -22,57 +22,76 @@ const BENEFITS: Benefit[] = [
];
export function NotificationsStep() {
- const goNext = useOnboardingStore((s) => s.goNext);
+ const { goNext, progress } = useOnboardingStep('notifications');
const setPermissionGranted = useOnboardingStore((s) => s.setPermissionGranted);
const [state, setState] = useState<PermissionState>('checking');
const [requesting, setRequesting] = useState(false);
+ const [advanceError, setAdvanceError] = useState<string | null>(null);
+ const grantedRef = useRef(false);
const checkedRef = useRef(false);
+ const advance = useCallback(
+ async (granted: boolean): Promise<void> => {
+ grantedRef.current = granted;
+ setAdvanceError(null);
+ try {
+ await setPermissionGranted('notifications', granted);
+ await goNext();
+ } catch (error) {
+ setAdvanceError(describeOnboardingError(error, 'Could not save progress.'));
+ }
+ },
+ [goNext, setPermissionGranted],
+ );
+
useEffect(() => {
if (checkedRef.current) return;
checkedRef.current = true;
getNotificationStatus()
.then((status) => {
- if (status === 'granted') {
- return setPermissionGranted('notifications', true).then(() => goNext());
+ if (status === 'granted' || status === 'denied') {
+ return advance(status === 'granted');
}
if (status === 'unavailable') {
setState('unavailable');
return;
}
- setState(status === 'denied' ? 'denied' : 'undetermined');
+ setState('undetermined');
})
.catch(() => setState('undetermined'));
- }, [goNext, setPermissionGranted]);
+ }, [advance]);
const handleAllow = useCallback(async () => {
setRequesting(true);
try {
const result = await requestNotifications();
- await setPermissionGranted('notifications', result === 'granted');
- if (result === 'denied') {
- setState('denied');
- return;
- }
- await goNext();
+ await advance(result === 'granted');
} finally {
setRequesting(false);
}
- }, [goNext, setPermissionGranted]);
-
- const handleOpenSettings = useCallback(() => {
- Linking.openSettings();
- }, []);
+ }, [advance]);
const handleSkip = useCallback(async () => {
await goNext();
}, [goNext]);
+ if (advanceError) {
+ return (
+ <OnboardingShell
+ progress={progress}
+ title="Continue setup"
+ subtitle={advanceError}
+ ctaLabel="Retry"
+ onCta={() => advance(grantedRef.current)}
+ />
+ );
+ }
+
if (state === 'checking') {
return (
<OnboardingShell
- progress={getStepProgress(STEP_ID)}
+ progress={progress}
title="Checking permissions…"
ctaLabel="Continue"
ctaDisabled
@@ -85,30 +104,10 @@ export function NotificationsStep() {
);
}
- if (state === 'denied') {
- return (
- <OnboardingShell
- progress={getStepProgress(STEP_ID)}
- title="Notifications are off"
- subtitle="Open Settings to allow OpenWhispr notifications."
- ctaLabel="Open Settings"
- onCta={handleOpenSettings}
- secondaryCtaLabel="Continue anyway"
- onSecondaryCta={handleSkip}
- >
- <View className="flex-1 items-center justify-center">
- <View className="h-28 w-28 items-center justify-center rounded-2xl bg-secondarySystemGroupedBackground">
- <SystemIcon name="bell.slash.fill" mdName="BellOff" size={48} color="secondaryLabel" />
- </View>
- </View>
- </OnboardingShell>
- );
- }
-
if (state === 'unavailable') {
return (
<OnboardingShell
- progress={getStepProgress(STEP_ID)}
+ progress={progress}
title="Notifications unavailable"
subtitle="Notification support isn't enabled in this build. You can continue setup."
ctaLabel="Continue"
@@ -121,7 +120,7 @@ export function NotificationsStep() {
return (
<OnboardingShell
- progress={getStepProgress(STEP_ID)}
+ progress={progress}
title="Stay in the loop"
titleAccent="loop"
subtitle="You can opt out anytime."
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/PaywallStep.tsx b/openwhispr-mobile/src/screens/onboarding/steps/PaywallStep.tsx
index d34742853..640543910 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/PaywallStep.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/PaywallStep.tsx
@@ -1,13 +1,14 @@
+import { useOnboardingStep } from '@/hooks/useOnboardingStep';
import { useCallback, useEffect, useRef, useState } from 'react';
import { View } from 'react-native';
import { Text } from '@/components/ui/Text';
import { OnboardingShell } from '@/components/onboarding/OnboardingShell';
import { SystemIcon, type LucideIconName } from '@/components/ui/SystemIcon';
-import { useOnboardingStore } from '@/store/useOnboardingStore';
import { useAuthStore } from '@/store/useAuthStore';
import { useUsageStore } from '@/store/useUsageStore';
import { useSuperwallGate } from '@/hooks/useSuperwallGate';
import { SUPERWALL_PLACEMENTS } from '@/lib/superwall';
+import { describeOnboardingError } from '@/lib/onboardingErrors';
const HIGHLIGHTS: { icon: string; mdIcon: LucideIconName; label: string }[] = [
{ icon: 'cloud', mdIcon: 'Cloud', label: 'Cloud transcription with no word limit' },
@@ -26,31 +27,43 @@ export const PAYWALL_READY_GRACE_MS = 3_000;
export const PAYWALL_ESCAPE_MS = 8_000;
/**
- * Presents the Superwall paywall, then hands off to the account step whether or
+ * Presents the Superwall paywall, then resumes setup whether or
* not anything was purchased. This screen is only a backdrop — Superwall's own
* paywall is the real surface — so its job is to never become a dead end.
*/
export function PaywallStep() {
- const goNext = useOnboardingStore((s) => s.goNext);
+ const { goNext } = useOnboardingStep('paywall');
const user = useAuthStore((s) => s.user);
const isSubscribed = useUsageStore((s) => s.usage?.isSubscribed ?? false);
const { register, state, isConfigured } = useSuperwallGate();
const hasPresentedRef = useRef(false);
const hasAdvancedRef = useRef(false);
const unmountedRef = useRef(false);
+ const registrationRef = useRef<AbortController | null>(null);
const [readyGraceElapsed, setReadyGraceElapsed] = useState(false);
const [presenting, setPresenting] = useState(false);
const [escapeElapsed, setEscapeElapsed] = useState(false);
- const advance = useCallback(() => {
+ const [advanceError, setAdvanceError] = useState<string | null>(null);
+ const advance = useCallback(async (): Promise<void> => {
if (hasAdvancedRef.current) return;
hasAdvancedRef.current = true;
- goNext();
+ hasPresentedRef.current = true;
+ registrationRef.current?.abort();
+ setAdvanceError(null);
+ try {
+ await goNext();
+ } catch (error) {
+ hasAdvancedRef.current = false;
+ setAdvanceError(describeOnboardingError(error, 'Could not save progress. Try again.'));
+ }
}, [goNext]);
useEffect(() => {
+ unmountedRef.current = false;
return () => {
unmountedRef.current = true;
+ registrationRef.current?.abort();
};
}, []);
@@ -77,7 +90,7 @@ export function PaywallStep() {
// buy. Either way there is no paywall worth presenting.
if (!user || isSubscribed) {
hasPresentedRef.current = true;
- advance();
+ void advance();
return;
}
@@ -87,30 +100,37 @@ export function PaywallStep() {
// Failures are already reported by SuperwallGateProvider. Swallowing here is
// what keeps a missing campaign, a bad API key or an SDK error from stopping
- // onboarding — the user just continues to the account step. Unmount is the
+ // onboarding — the user just continues setup. Unmount is the
// only thing that cancels the advance; effect re-runs must not.
- register({ placement: SUPERWALL_PLACEMENTS.onboardingPaywall })
+ const controller = new AbortController();
+ registrationRef.current = controller;
+ register({ placement: SUPERWALL_PLACEMENTS.onboardingPaywall, signal: controller.signal })
.catch(() => {})
.finally(() => {
- if (!unmountedRef.current) advance();
+ if (!unmountedRef.current) void advance();
});
}, [advance, isConfigured, isSubscribed, readyGraceElapsed, register, user]);
// Between registering and the SDK presenting, this backdrop looks like an
- // ordinary screen with a primary button; tapping it would mount the account
+ // ordinary screen with a primary button; tapping it would mount the next
// step underneath a paywall that then presents on top of it.
- const ctaDisabled = presenting && state.status === 'idle' && !escapeElapsed;
+ const ctaDisabled = !advanceError && presenting && state.status === 'idle' && !escapeElapsed;
return (
<OnboardingShell
title="Go further with OpenWhispr Pro."
titleAccent="Pro"
- subtitle="You've seen what it can do. Unlock the whole thing."
+ subtitle="Unlock more with Pro, or close the offer to keep using Cloud with your current limits."
ctaLabel="Continue"
ctaDisabled={ctaDisabled}
onCta={advance}
>
<View className="gap-4 pt-2">
+ {advanceError ? (
+ <Text accessibilityRole="alert" className="text-systemRed">
+ {advanceError}
+ </Text>
+ ) : null}
{HIGHLIGHTS.map((item) => (
<View key={item.label} className="flex-row items-center gap-3">
<SystemIcon name={item.icon} mdName={item.mdIcon} size={20} />
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/PrivacyModeStep.tsx b/openwhispr-mobile/src/screens/onboarding/steps/PrivacyModeStep.tsx
index 02ba7df94..b443dd840 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/PrivacyModeStep.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/PrivacyModeStep.tsx
@@ -1,100 +1,52 @@
-import { useCallback, useEffect, useState, type ReactNode } from 'react';
-import { Alert, Pressable, ScrollView, View } from 'react-native';
+import type { ReactElement, ReactNode } from 'react';
+import { ScrollView, View } from 'react-native';
import { Text } from '@/components/ui/Text';
import { OnboardingShell } from '@/components/onboarding/OnboardingShell';
import { SystemIcon } from '@/components/ui/SystemIcon';
import { OpenWhisprMark } from '@/components/ui/OpenWhisprMark';
import { BRAND } from '@/config/colors';
-import { useConfigStore } from '@/store/useConfigStore';
-import { useAuthStore } from '@/store/useAuthStore';
-import { accountRequiredForCloud } from '@/lib/accountAccess';
-import { getStepProgress, useOnboardingStore } from '@/store/useOnboardingStore';
-import type { ProcessingMode } from '@/types';
+import { useOnboardingStep } from '@/hooks/useOnboardingStep';
+import { chooseOnboardingMode } from '@/lib/onboardingMode';
+import { useModelDownloadStore } from '@/store/useModelDownloadStore';
+import { useOnboardingStore } from '@/store/useOnboardingStore';
-const STEP_ID = 'privacy-mode';
+export function PrivacyModeStep(): ReactElement {
+ const { goBack, progress } = useOnboardingStep('privacy-mode');
+ const selectedMode = useOnboardingStore((state) => state.selectedMode);
+ const cancelActiveDownloads = useModelDownloadStore((state) => state.cancelActiveDownloads);
-export function PrivacyModeStep() {
- const goNext = useOnboardingStore((s) => s.goNext);
- const config = useConfigStore((s) => s.config);
- const loadConfig = useConfigStore((s) => s.loadConfig);
- const updateConfig = useConfigStore((s) => s.updateConfig);
- const user = useAuthStore((s) => s.user);
- const isGuest = useAuthStore((s) => s.isGuest);
- const ensureAnonymousSession = useAuthStore((s) => s.ensureAnonymousSession);
- const cloudNeedsAccount = accountRequiredForCloud(user);
- const [selected, setSelected] = useState<ProcessingMode>('private');
-
- useEffect(() => {
- if (!config) loadConfig();
- }, [config, loadConfig]);
-
- useEffect(() => {
- // Without a session cloud can't run, so never restore it as the selection.
- if (config?.defaultMode && !(cloudNeedsAccount && config.defaultMode === 'cloud')) {
- setSelected(config.defaultMode);
- }
- }, [config?.defaultMode, cloudNeedsAccount]);
-
- const handleSelectCloud = useCallback(async () => {
- if (!cloudNeedsAccount) {
- setSelected('cloud');
- return;
- }
-
- // A guest chose to continue without an account on an earlier build; no
- // session is going to be minted for them, and they have a connection, so
- // blaming the network would be wrong.
- if (isGuest) {
- Alert.alert(
- 'Cloud needs an account',
- 'You chose to continue without an account, so Cloud is off for now. Finish setup in Private mode and sign in from the Account tab whenever you want Cloud.',
- [{ text: 'OK' }],
- );
- return;
- }
-
- // Onboarding normally already holds an anonymous session, so reaching here
- // means opening it failed — almost always no connection. Retry once before
- // refusing, rather than leaving Cloud permanently unselectable.
- await ensureAnonymousSession();
- if (!accountRequiredForCloud(useAuthStore.getState().user)) {
- setSelected('cloud');
- return;
- }
-
- Alert.alert(
- 'Cloud is unavailable',
- 'OpenWhispr Cloud needs a connection to set up. Continue with Private mode for now — you can switch later in Settings.',
- [{ text: 'OK' }],
- );
- }, [cloudNeedsAccount, ensureAnonymousSession, isGuest]);
-
- const handleContinue = useCallback(async () => {
- await updateConfig({ defaultMode: selected });
- // Everyone picks languages next (cloud transcription uses them too); the language
- // step then routes cloud users past the model download.
- await goNext();
- }, [selected, updateConfig, goNext]);
+ const chooseCloud = async (): Promise<void> => {
+ const choseLocalEarlier = selectedMode === 'private';
+ await chooseOnboardingMode('cloud', 'privacy-mode');
+ // Back from the download step leaves its model transferring; Cloud has no use for it. Without
+ // an earlier Local choice, a running download was started from Settings and isn't ours to stop.
+ if (choseLocalEarlier) await cancelActiveDownloads();
+ };
return (
<OnboardingShell
- progress={getStepProgress(STEP_ID)}
+ progress={progress}
+ onBack={goBack}
title="How should we transcribe?"
titleAccent="transcribe"
subtitle="Your voice stays yours. Pick a mode — you can change it anytime."
- ctaLabel="Continue"
- onCta={handleContinue}
+ ctaLabel="Use Cloud"
+ onCta={chooseCloud}
+ secondaryCtaLabel="Use Local"
+ secondaryCtaVariant="card"
+ onSecondaryCta={() => chooseOnboardingMode('private', 'privacy-mode')}
>
<ScrollView
- className="flex-1"
showsVerticalScrollIndicator={false}
contentContainerStyle={{ gap: 12, paddingTop: 4, paddingBottom: 8 }}
>
+ {selectedMode ? (
+ <Text className="text-[14px] font-medium text-primary">
+ {selectedMode === 'cloud' ? 'Cloud is selected' : 'Local is selected'}
+ </Text>
+ ) : null}
<ModeCard
- selected={selected === 'private'}
- onPress={() => setSelected('private')}
- accessibilityLabel="Private mode"
- title="Private mode"
+ title="Local · Private mode"
icon={<SystemIcon name="lock.fill" mdName="Lock" size={18} color="brand" />}
>
<Text className="mt-1 text-[14px] leading-[19px] text-secondaryLabel">
@@ -113,14 +65,7 @@ export function PrivacyModeStep() {
One-time ~140–461 MB download, depending on language
</Text>
</ModeCard>
-
- <ModeCard
- selected={selected === 'cloud'}
- onPress={handleSelectCloud}
- accessibilityLabel="OpenWhispr Cloud"
- title="OpenWhispr Cloud"
- icon={<OpenWhisprMark size={20} color={BRAND} />}
- >
+ <ModeCard title="OpenWhispr Cloud" icon={<OpenWhisprMark size={20} color={BRAND} />}>
<Bullet text="Faster transcription" />
<Bullet text="Higher quality" />
<Bullet text="Automatic cleanup & formatting" />
@@ -130,7 +75,7 @@ export function PrivacyModeStep() {
);
}
-function Bullet({ text }: { text: string }) {
+function Bullet({ text }: { text: string }): ReactElement {
return (
<View className="mt-1.5 flex-row items-center gap-1.5">
<SystemIcon name="checkmark" mdName="Check" size={13} color="systemGreen" />
@@ -140,42 +85,21 @@ function Bullet({ text }: { text: string }) {
}
function ModeCard({
- selected,
- onPress,
- icon,
title,
- accessibilityLabel,
+ icon,
children,
}: {
- selected: boolean;
- onPress: () => void;
- icon: ReactNode;
title: string;
- accessibilityLabel: string;
+ icon: ReactNode;
children: ReactNode;
-}) {
+}): ReactElement {
return (
- <Pressable
- onPress={onPress}
- accessibilityRole="radio"
- accessibilityState={{ selected }}
- accessibilityLabel={accessibilityLabel}
- className={`flex-row items-start gap-3 rounded-xl border bg-secondarySystemGroupedBackground px-4 py-4 active:opacity-90 ${
- selected ? 'border-primary' : 'border-separator'
- }`}
- >
+ <View className="flex-row items-start gap-3 rounded-xl border border-separator bg-secondarySystemGroupedBackground px-4 py-4">
<View className="mt-0.5 h-8 w-8 items-center justify-center">{icon}</View>
<View className="flex-1">
<Text className="text-[16px] font-semibold text-label">{title}</Text>
{children}
</View>
- <View className="mt-0.5 h-[20px] w-[20px] items-center justify-center">
- {selected ? (
- <SystemIcon name="checkmark.circle.fill" mdName="CheckCircle2" size={20} color="brand" />
- ) : (
- <View className="h-[20px] w-[20px] rounded-full border border-separator" />
- )}
- </View>
- </Pressable>
+ </View>
);
}
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/PrivateDownloadStep.tsx b/openwhispr-mobile/src/screens/onboarding/steps/PrivateDownloadStep.tsx
index 876a441d6..52f01caa5 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/PrivateDownloadStep.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/PrivateDownloadStep.tsx
@@ -1,10 +1,10 @@
+import { useOnboardingStep } from '@/hooks/useOnboardingStep';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { View, ActivityIndicator, Pressable } from 'react-native';
import { Text } from '@/components/ui/Text';
import { OnboardingShell } from '@/components/onboarding/OnboardingShell';
import { SystemIcon } from '@/components/ui/SystemIcon';
-import { getStepProgress, useOnboardingStore } from '@/store/useOnboardingStore';
-import { useConfigStore } from '@/store/useConfigStore';
+import { chooseOnboardingMode } from '@/lib/onboardingMode';
import { useModelDownloadStore, type LocalModelKey } from '@/store/useModelDownloadStore';
import { LocalTranscriptionService } from '@/services/transcription/LocalTranscriptionService';
import { getPreferredTranscriptionLanguages } from '@/lib/transcriptionLanguage';
@@ -12,8 +12,6 @@ import { getLocalModelCatalog, type LocalModelCatalogEntry } from '@/lib/localMo
import { getPrivateModeUnavailableMessage } from '@/lib/privateMode';
import { SlowDownloadSheet } from './SlowDownloadSheet';
-// Reuse the language step's progress so the conditional step doesn't jump the bar.
-const PROGRESS_ID = 'language';
// Show the "taking a while?" sheet only if the download is still under halfway
// after this delay — fast connections finish first and never see it.
const SLOW_AFTER_MS = 8000;
@@ -24,11 +22,11 @@ function formatModelSize(bytes: number): string {
}
export function PrivateDownloadStep() {
- const goNext = useOnboardingStore((s) => s.goNext);
- const updateConfig = useConfigStore((s) => s.updateConfig);
+ const { progress: stepProgress, goBack } = useOnboardingStep('private-download');
const downloads = useModelDownloadStore((s) => s.downloads);
const startDownload = useModelDownloadStore((s) => s.startDownload);
const cancelDownload = useModelDownloadStore((s) => s.cancelDownload);
+ const cancelActiveDownloads = useModelDownloadStore((s) => s.cancelActiveDownloads);
const available = LocalTranscriptionService.isAvailable();
// The language step just ran, so the selection is settled; pick the model it routes to.
@@ -36,24 +34,31 @@ export function PrivateDownloadStep() {
const [recommended, setRecommended] = useState<LocalModelCatalogEntry | null>(null);
const [sheetVisible, setSheetVisible] = useState(false);
const startedRef = useRef(false);
+ const mountedRef = useRef(true);
+ const [discoveryAttempt, setDiscoveryAttempt] = useState(0);
+ const [discoveryError, setDiscoveryError] = useState<string | null>(null);
useEffect(() => {
if (!available) return;
let cancelled = false;
+ setDiscoveryError(null);
LocalTranscriptionService.getAvailability()
.then((availability) => {
if (cancelled) return;
// Catalog is sorted recommended-first; on platforms without Parakeet the first
// visible entry is the Whisper fallback.
- setRecommended(getLocalModelCatalog(languages, availability)[0] ?? null);
+ const model = getLocalModelCatalog(languages, availability)[0];
+ if (!model) throw new Error('No local model is available for these languages.');
+ setRecommended(model);
})
.catch(() => {
- if (!cancelled) setRecommended(null);
+ if (!cancelled)
+ setDiscoveryError('Could not find a local model. Check your connection and try again.');
});
return () => {
cancelled = true;
};
- }, [available, languages]);
+ }, [available, languages, discoveryAttempt]);
const modelKey: LocalModelKey | null = recommended?.key ?? null;
const download = modelKey ? downloads[modelKey] : null;
@@ -62,17 +67,22 @@ export function PrivateDownloadStep() {
const error = download?.error;
useEffect(() => {
- if (
- available &&
- modelKey &&
- !recommended?.downloaded &&
- !startedRef.current &&
- status === 'idle'
- ) {
- startedRef.current = true;
- startDownload(modelKey);
- }
- }, [available, modelKey, recommended?.downloaded, status, startDownload]);
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ };
+ }, []);
+
+ useEffect(() => {
+ if (!available || !modelKey || startedRef.current) return;
+ startedRef.current = true;
+ const needsDownload = !recommended?.downloaded && status === 'idle';
+ // Going back to change languages can leave the previous recommendation transferring. It's no
+ // longer needed, and startDownload refuses to run beside it.
+ cancelActiveDownloads(modelKey).then(() => {
+ if (needsDownload && mountedRef.current) startDownload(modelKey);
+ });
+ }, [available, modelKey, recommended?.downloaded, status, startDownload, cancelActiveDownloads]);
useEffect(() => {
if (!available || !modelKey) return;
@@ -83,23 +93,14 @@ export function PrivateDownloadStep() {
return () => clearTimeout(timer);
}, [available, modelKey]);
- const continuePrivate = useCallback(async () => {
- // The CTA is gated on status === 'completed', which means the model is on disk (and for
- // Parakeet, prepared). If it ever isn't, the Home toggle's readiness check re-prompts a
- // download — so we trust the store's completed status here rather than re-checking disk.
- await updateConfig({ defaultMode: 'private' });
- await goNext();
- }, [updateConfig, goNext]);
-
- const switchToCloud = useCallback(async () => {
- await updateConfig({ defaultMode: 'cloud' });
- await goNext();
- }, [updateConfig, goNext]);
+ const switchToCloud = useCallback(async (): Promise<void> => {
+ await chooseOnboardingMode('cloud', 'private-download');
+ }, []);
const continueCloudKeepDownloading = useCallback(async () => {
- setSheetVisible(false);
// Download keeps running in the background (store not reset).
await switchToCloud();
+ setSheetVisible(false);
}, [switchToCloud]);
// The auto-start effect only fires once, from idle, so a retry has to start the download itself.
@@ -107,18 +108,19 @@ export function PrivateDownloadStep() {
if (modelKey) startDownload(modelKey);
}, [modelKey, startDownload]);
- const switchToCloudStop = useCallback(async () => {
- // A failed attempt still has its partial download staged; cancelling reclaims it.
+ const switchToCloudStop = useCallback(async (): Promise<void> => {
+ // Validate Cloud and save the choice before discarding the local download.
+ await switchToCloud();
if (modelKey && (status === 'downloading' || status === 'preparing' || status === 'error')) {
await cancelDownload(modelKey);
}
- await switchToCloud();
}, [cancelDownload, modelKey, status, switchToCloud]);
if (!available) {
return (
<OnboardingShell
- progress={getStepProgress(PROGRESS_ID)}
+ progress={stepProgress}
+ onBack={goBack}
title="Private mode needs the full app"
subtitle={getPrivateModeUnavailableMessage()}
ctaLabel="Use Cloud instead"
@@ -133,6 +135,21 @@ export function PrivateDownloadStep() {
);
}
+ if (discoveryError) {
+ return (
+ <OnboardingShell
+ progress={stepProgress}
+ onBack={goBack}
+ title="Local setup needs another try"
+ subtitle={discoveryError}
+ ctaLabel="Retry model selection"
+ onCta={() => setDiscoveryAttempt((attempt) => attempt + 1)}
+ secondaryCtaLabel="Use Cloud instead"
+ onSecondaryCta={switchToCloud}
+ />
+ );
+ }
+
const done = recommended?.downloaded === true || status === 'completed';
const preparing = status === 'preparing';
const percent = done ? 100 : Math.round(progress * 100);
@@ -142,7 +159,8 @@ export function PrivateDownloadStep() {
return (
<>
<OnboardingShell
- progress={getStepProgress(PROGRESS_ID)}
+ progress={stepProgress}
+ onBack={goBack}
title="Set up Private mode"
titleAccent="Private"
subtitle={`Private runs entirely on your device. It needs a one-time ${
@@ -150,7 +168,7 @@ export function PrivateDownloadStep() {
} download, matched to your languages.`}
ctaLabel={done ? 'Continue with Private' : 'Continue · available when ready'}
ctaDisabled={!done}
- onCta={continuePrivate}
+ onCta={() => chooseOnboardingMode('private', 'private-download')}
secondaryCtaLabel={done ? 'Use Cloud instead' : "Don't use Private — switch to Cloud"}
onSecondaryCta={switchToCloudStop}
>
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/SecurityFirstStep.tsx b/openwhispr-mobile/src/screens/onboarding/steps/SecurityFirstStep.tsx
index b488c3891..ef3d72637 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/SecurityFirstStep.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/SecurityFirstStep.tsx
@@ -1,8 +1,8 @@
+import { useOnboardingStep } from '@/hooks/useOnboardingStep';
import { View } from 'react-native';
import { OnboardingShell } from '@/components/onboarding/OnboardingShell';
import { SystemIcon } from '@/components/ui/SystemIcon';
import { Text } from '@/components/ui/Text';
-import { useOnboardingStore } from '@/store/useOnboardingStore';
const TRUST_POINTS = [
'No selling your data',
@@ -11,7 +11,7 @@ const TRUST_POINTS = [
];
export function SecurityFirstStep() {
- const goNext = useOnboardingStore((s) => s.goNext);
+ const { goNext } = useOnboardingStep('security-first');
return (
<OnboardingShell
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/SlowDownloadSheet.tsx b/openwhispr-mobile/src/screens/onboarding/steps/SlowDownloadSheet.tsx
index afda0e6f5..9961f80f0 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/SlowDownloadSheet.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/SlowDownloadSheet.tsx
@@ -1,54 +1,100 @@
+import { useRef, useState, type ReactElement } from 'react';
import { Modal, Pressable, View } from 'react-native';
+import { GestureDetector, GestureHandlerRootView } from 'react-native-gesture-handler';
+import Animated from 'react-native-reanimated';
import { Text } from '@/components/ui/Text';
import { Button } from '@/components/ui/Button';
import { SystemIcon } from '@/components/ui/SystemIcon';
+import { useSheetDragToDismiss } from '@/hooks/useSheetDragToDismiss';
+import { describeOnboardingError } from '@/lib/onboardingErrors';
interface Props {
visible: boolean;
- onContinueCloud: () => void;
+ onContinueCloud: () => Promise<void>;
onKeepWaiting: () => void;
}
-export function SlowDownloadSheet({ visible, onContinueCloud, onKeepWaiting }: Props) {
+export function SlowDownloadSheet({
+ visible,
+ onContinueCloud,
+ onKeepWaiting,
+}: Props): ReactElement {
+ const inFlight = useRef(false);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const continueCloud = async (): Promise<void> => {
+ if (inFlight.current) return;
+ inFlight.current = true;
+ setBusy(true);
+ setError(null);
+ try {
+ await onContinueCloud();
+ } catch (cause) {
+ setError(describeOnboardingError(cause, 'Cloud is unavailable. Try again.'));
+ } finally {
+ inFlight.current = false;
+ setBusy(false);
+ }
+ };
+ const keepWaiting = (): void => {
+ if (!inFlight.current) {
+ setError(null);
+ onKeepWaiting();
+ }
+ };
+ // Pulling the sheet down means the same as Keep waiting.
+ const { dragGesture, sheetStyle } = useSheetDragToDismiss(visible, keepWaiting);
return (
- <Modal visible={visible} transparent animationType="slide" onRequestClose={onKeepWaiting}>
- <Pressable className="flex-1 justify-end bg-black/40" onPress={onKeepWaiting}>
+ <Modal visible={visible} transparent animationType="slide" onRequestClose={keepWaiting}>
+ <GestureHandlerRootView className="flex-1">
<Pressable
- onPress={(e) => e.stopPropagation()}
- className="rounded-t-3xl bg-systemBackground px-6 pb-8 pt-3"
- >
- <View className="mb-4 h-1 w-9 self-center rounded-full bg-separator" />
- <Text className="text-[22px] font-bold text-label">Download taking a while?</Text>
- <Text className="mt-1.5 text-[15px] leading-[20px] text-secondaryLabel">
- No need to wait. Continue setup on Cloud now — we&apos;ll finish your Private download
- in the background.
- </Text>
+ accessibilityLabel="Dismiss"
+ onPress={keepWaiting}
+ className="absolute inset-0 bg-black/40"
+ />
+ <GestureDetector gesture={dragGesture}>
+ <Animated.View
+ style={sheetStyle}
+ className="absolute bottom-0 left-0 right-0 rounded-t-3xl bg-systemBackground px-6 pb-8 pt-3"
+ >
+ <View className="mb-4 h-1 w-9 self-center rounded-full bg-separator" />
+ <Text className="text-[22px] font-bold text-label">Download taking a while?</Text>
+ <Text className="mt-1.5 text-[15px] leading-[20px] text-secondaryLabel">
+ No need to wait. Continue setup on Cloud now — we&apos;ll finish your Private download
+ in the background.
+ </Text>
- <View className="mt-4 rounded-2xl border border-separator bg-secondarySystemGroupedBackground p-4">
- <View className="flex-row items-center gap-2">
- <SystemIcon name="cloud.fill" mdName="Cloud" size={16} color="brand" />
- <Text className="flex-1 text-[13px] leading-[18px] text-secondaryLabel">
- Turn the Cloud toggle <Text className="font-semibold text-label">off</Text> on the
- home screen to switch to Private once it&apos;s ready.
- </Text>
+ <View className="mt-4 rounded-2xl border border-separator bg-secondarySystemGroupedBackground p-4">
+ <View className="flex-row items-center gap-2">
+ <SystemIcon name="cloud.fill" mdName="Cloud" size={16} color="brand" />
+ <Text className="flex-1 text-[13px] leading-[18px] text-secondaryLabel">
+ Turn the Cloud toggle <Text className="font-semibold text-label">off</Text> on the
+ home screen to switch to Private once it&apos;s ready.
+ </Text>
+ </View>
</View>
- </View>
- <View className="mt-5">
- <Button onPress={onContinueCloud} size="lg">
- Continue with Cloud for now
- </Button>
- <Pressable
- onPress={onKeepWaiting}
- className="mt-3 items-center py-2"
- accessibilityRole="button"
- accessibilityLabel="Keep waiting for download"
- >
- <Text className="text-[15px] font-medium text-secondaryLabel">Keep waiting</Text>
- </Pressable>
- </View>
- </Pressable>
- </Pressable>
+ <View className="mt-5">
+ {error ? (
+ <Text accessibilityRole="alert" className="mb-3 text-systemRed">
+ {error}
+ </Text>
+ ) : null}
+ <Button onPress={() => void continueCloud()} loading={busy} size="lg">
+ Continue with Cloud for now
+ </Button>
+ <Pressable
+ onPress={keepWaiting}
+ className="mt-3 items-center py-2"
+ accessibilityRole="button"
+ accessibilityLabel="Keep waiting for download"
+ >
+ <Text className="text-[15px] font-medium text-secondaryLabel">Keep waiting</Text>
+ </Pressable>
+ </View>
+ </Animated.View>
+ </GestureDetector>
+ </GestureHandlerRootView>
</Modal>
);
}
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/ToneStep.tsx b/openwhispr-mobile/src/screens/onboarding/steps/ToneStep.tsx
new file mode 100644
index 000000000..e0eefa5ab
--- /dev/null
+++ b/openwhispr-mobile/src/screens/onboarding/steps/ToneStep.tsx
@@ -0,0 +1,96 @@
+import { useState, type ReactElement } from 'react';
+import { Pressable, ScrollView, View } from 'react-native';
+import { OnboardingShell } from '@/components/onboarding/OnboardingShell';
+import { Text } from '@/components/ui/Text';
+import { SystemIcon } from '@/components/ui/SystemIcon';
+import { useOnboardingStep } from '@/hooks/useOnboardingStep';
+import { KEYBOARD_TONES, DEFAULT_KEYBOARD_TONE } from '@/lib/keyboardTone';
+import { saveOnboardingConfig } from '@/lib/onboardingMode';
+import { useConfigStore } from '@/store/useConfigStore';
+import type { KeyboardTone } from '@/types';
+
+const EXAMPLES: Record<KeyboardTone, string> = {
+ default: 'Hey Sam, are you free for lunch tomorrow? Let’s meet at noon if that works for you.',
+ formal:
+ 'Hi Sam, would you be available for lunch tomorrow at noon? Please let me know if that time is convenient.',
+ casual: 'Hey Sam, want to grab lunch tomorrow? Let’s do noon if that works for you.',
+ very_casual: 'hey sam, lunch tomorrow? noon work for you?',
+ excited: 'Hey Sam! Want to grab lunch tomorrow? Let’s meet at noon if that works for you!',
+};
+
+export function ToneStep(): ReactElement {
+ const { goNext, goBack, progress } = useOnboardingStep('tone');
+ const savedTone = useConfigStore((state) => state.config?.keyboardTone ?? DEFAULT_KEYBOARD_TONE);
+ const [selected, setSelected] = useState<KeyboardTone>(savedTone);
+ const [saving, setSaving] = useState(false);
+
+ const handleContinue = async (): Promise<void> => {
+ setSaving(true);
+ try {
+ // Config subscriptions mirror this saved choice into the keyboard's App Group.
+ await saveOnboardingConfig({ keyboardTone: selected });
+ await goNext();
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <OnboardingShell
+ title="Make it sound like you."
+ titleAccent="you"
+ subtitle="Choose how your keyboard dictation sounds. You can change your tone anytime."
+ progress={progress}
+ onBack={goBack}
+ onSkip={goNext}
+ ctaLabel="Continue"
+ onCta={handleContinue}
+ >
+ <ScrollView
+ showsVerticalScrollIndicator={false}
+ // Tight spacing lets the third tone peek above Continue, showing the list scrolls.
+ contentContainerStyle={{ gap: 10, paddingBottom: 16 }}
+ >
+ <View className="rounded-xl bg-secondarySystemGroupedBackground px-4 py-3">
+ <Text className="text-[13px] font-semibold text-secondaryLabel">Compare the tones</Text>
+ <Text className="mt-1 text-[15px] leading-[21px] text-label">
+ The same lunch invitation, written five different ways.
+ </Text>
+ <Text className="mt-1.5 text-[12px] leading-[17px] text-secondaryLabel">
+ Live tones need Cloud, Dictation Cleanup, and an account.
+ </Text>
+ </View>
+ {KEYBOARD_TONES.map((tone) => (
+ <Pressable
+ key={tone.value}
+ accessibilityRole="radio"
+ accessibilityLabel={`${tone.label}. ${tone.description}. Example: ${EXAMPLES[tone.value]}`}
+ accessibilityState={{ selected: selected === tone.value, disabled: saving }}
+ disabled={saving}
+ onPress={() => setSelected(tone.value)}
+ className={`rounded-2xl border px-4 py-3 bg-secondarySystemGroupedBackground ${selected === tone.value ? 'border-primary' : 'border-separator'}`}
+ >
+ <View className="flex-row items-center justify-between gap-3">
+ <Text className="flex-1 text-[18px] font-semibold text-label">{tone.label}</Text>
+ <SystemIcon
+ name={selected === tone.value ? 'checkmark.circle.fill' : 'circle'}
+ mdName={selected === tone.value ? 'CheckCircle2' : 'Circle'}
+ size={22}
+ color={selected === tone.value ? 'brand' : 'tertiaryLabel'}
+ />
+ </View>
+ <Text className="mt-0.5 text-[14px] text-secondaryLabel">{tone.description}</Text>
+ <View className="mt-3 flex-row items-start gap-3 rounded-xl bg-primary/5 px-3 py-2.5">
+ <View className="h-7 w-7 items-center justify-center rounded-full bg-primary/15">
+ <Text className="text-[13px] font-semibold text-primary">S</Text>
+ </View>
+ <Text className="flex-1 text-[15px] leading-[20px] text-label">
+ {EXAMPLES[tone.value]}
+ </Text>
+ </View>
+ </Pressable>
+ ))}
+ </ScrollView>
+ </OnboardingShell>
+ );
+}
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/TrackingPermissionStep.tsx b/openwhispr-mobile/src/screens/onboarding/steps/TrackingPermissionStep.tsx
index de89e02de..50587e862 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/TrackingPermissionStep.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/TrackingPermissionStep.tsx
@@ -1,3 +1,4 @@
+import { useOnboardingStep } from '@/hooks/useOnboardingStep';
import { useCallback, useEffect, useRef, useState, type ReactElement } from 'react';
import { ActivityIndicator, ScrollView, View } from 'react-native';
import { OnboardingShell } from '@/components/onboarding/OnboardingShell';
@@ -11,6 +12,7 @@ import {
requestTrackingAuthorization,
} from '@/lib/trackingTransparency';
import { useOnboardingStore } from '@/store/useOnboardingStore';
+import { describeOnboardingError } from '@/lib/onboardingErrors';
type ScreenState = 'checking' | 'ready';
@@ -26,7 +28,7 @@ const BENEFITS: Benefit[] = [
];
export function TrackingPermissionStep(): ReactElement {
- const finish = useOnboardingStore((state) => state.finish);
+ const { goNext } = useOnboardingStep('tracking-permission');
const markRequestAttempted = useOnboardingStore(
(state) => state.markTrackingAuthorizationRequestAttempted,
);
@@ -35,21 +37,23 @@ export function TrackingPermissionStep(): ReactElement {
);
const [screenState, setScreenState] = useState<ScreenState>('checking');
const [requesting, setRequesting] = useState(false);
+ const [advanceError, setAdvanceError] = useState<string | null>(null);
const checkedRef = useRef(false);
const requestInFlightRef = useRef(false);
const finishingRef = useRef(false);
- const finishOnboarding = useCallback(async (): Promise<void> => {
+ const continueToCompletion = useCallback(async (): Promise<void> => {
if (finishingRef.current) return;
finishingRef.current = true;
+ setAdvanceError(null);
try {
- await finish();
+ await goNext();
} catch (error) {
finishingRef.current = false;
- Sentry.captureException(error);
+ setAdvanceError(describeOnboardingError(error, 'Could not save progress.'));
}
- }, [finish]);
+ }, [goNext]);
useEffect(() => {
if (checkedRef.current) return;
@@ -61,21 +65,21 @@ export function TrackingPermissionStep(): ReactElement {
setAppsFlyerTrackingAuthorizationStatus(status);
if (status !== 'notDetermined' || requestAttempted) {
- await finishOnboarding();
+ await continueToCompletion();
return;
}
setScreenState('ready');
} catch (error) {
Sentry.captureException(error);
- await finishOnboarding();
+ await continueToCompletion();
}
};
checkAuthorization().catch((error: unknown): void => {
Sentry.captureException(error);
});
- }, [finishOnboarding, requestAttempted]);
+ }, [continueToCompletion, requestAttempted]);
const handleContinue = useCallback(async (): Promise<void> => {
if (requestInFlightRef.current || finishingRef.current) return;
@@ -88,7 +92,7 @@ export function TrackingPermissionStep(): ReactElement {
await markRequestAttempted();
} catch (error) {
Sentry.captureException(error);
- await finishOnboarding();
+ await continueToCompletion();
return;
}
@@ -99,12 +103,25 @@ export function TrackingPermissionStep(): ReactElement {
Sentry.captureException(error);
}
- await finishOnboarding();
+ await continueToCompletion();
} finally {
requestInFlightRef.current = false;
setRequesting(false);
}
- }, [finishOnboarding, markRequestAttempted]);
+ }, [continueToCompletion, markRequestAttempted]);
+
+ if (advanceError) {
+ return (
+ <OnboardingShell
+ title="Your privacy choice is saved"
+ subtitle={advanceError}
+ ctaLabel="Retry"
+ onCta={continueToCompletion}
+ >
+ <View className="flex-1" />
+ </OnboardingShell>
+ );
+ }
if (screenState === 'checking') {
return (
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/VoiceAgentStep.tsx b/openwhispr-mobile/src/screens/onboarding/steps/VoiceAgentStep.tsx
new file mode 100644
index 000000000..631a1bb83
--- /dev/null
+++ b/openwhispr-mobile/src/screens/onboarding/steps/VoiceAgentStep.tsx
@@ -0,0 +1,253 @@
+import { useEffect, useRef, useState, type ReactElement, type ReactNode } from 'react';
+import { Keyboard, PlatformColor, ScrollView, StyleSheet, TextInput, View } from 'react-native';
+import Animated, {
+ useAnimatedStyle,
+ useSharedValue,
+ withSequence,
+ withTiming,
+} from 'react-native-reanimated';
+import { OnboardingShell } from '@/components/onboarding/OnboardingShell';
+import { Text } from '@/components/ui/Text';
+import { SystemIcon } from '@/components/ui/SystemIcon';
+import { useOnboardingPracticeMode } from '@/hooks/useOnboardingPracticeMode';
+import { useOnboardingStep } from '@/hooks/useOnboardingStep';
+import { BRAND } from '@/config/colors';
+import { SpaceGrotesk } from '@/lib/fonts';
+import { safeHaptics } from '@/lib/utils';
+import { useAuthStore } from '@/store/useAuthStore';
+import { addKeyboardStatusChangedListener } from '../../../../modules/app-group-storage/src';
+
+type Phase = 'start' | 'asking' | 'first-draft' | 'refined' | 'done';
+
+// What users say in the live try, and what the example shows when the live try can't run.
+const REQUEST =
+ 'I cancelled my subscription last month but got charged again. Draft an email asking them to refund it.';
+const EXAMPLE_DRAFT =
+ 'Hi,\n\nI cancelled my subscription last month, but I was charged again this month. Could you please refund this charge?\n\nThanks';
+
+// The field is focused on arrival, so the first instruction points straight at the keyboard's agent
+// button, drawn with the same glyph the keyboard uses.
+const INSTRUCTIONS: Record<Phase, ReactNode> = {
+ start: (
+ <>
+ Tap the <SystemIcon name="wand.and.stars" mdName="WandSparkles" size={17} color="label" />{' '}
+ button on your keyboard.
+ </>
+ ),
+ asking: `Say: “${REQUEST}”`,
+ 'first-draft': 'Now tap Ask for changes and say: “Make it firmer.”',
+ refined: 'Tap ✓ to insert it.',
+ done: 'That’s your voice assistant.',
+};
+
+// Errors a retry can't clear: the server wants an account (the free tries are used up, the guest
+// word quota is spent, or the server has no live try yet; only an account clears it) or the weekly
+// word limit is reached (only its reset clears it).
+const FINAL_ERROR_NOTES: Record<string, string> = {
+ account_required: 'The live try isn’t available. Sign in at the end to use the voice assistant.',
+ usage_limit:
+ 'You’ve reached the weekly word limit. Try the voice assistant again once it resets.',
+};
+
+export function VoiceAgentStep(): ReactElement {
+ const { goNext, goBack, progress } = useOnboardingStep('voice-agent');
+ const { localSelected } = useOnboardingPracticeMode();
+ const user = useAuthStore((state) => state.user);
+ const input = useRef<TextInput>(null);
+ const draftsReady = useRef(0);
+ const lastDraftAt = useRef<string | undefined>(undefined);
+ // Once a draft is inserted the step is finished, so a later agent error (another regenerate, a
+ // refused try) must not take it away.
+ const inserted = useRef(false);
+ const [phase, setPhase] = useState<Phase>('start');
+ const [value, setValue] = useState('');
+ const [agentError, setAgentError] = useState<string | null>(null);
+ // A failed refinement leaves the earlier draft on the keyboard's card, so the field stays up for
+ // inserting it.
+ const hasDraft = phase === 'first-draft' || phase === 'refined';
+ const liveAvailable = !localSelected && !!user && (!agentError || hasDraft);
+ const errorIsFinal = !!agentError && agentError in FINAL_ERROR_NOTES;
+ const pulse = useSharedValue(0);
+ const pulseStyle = useAnimatedStyle(() => ({ transform: [{ scale: 1 + pulse.value * 0.04 }] }));
+ const flashStyle = useAnimatedStyle(() => ({ opacity: pulse.value * 0.18 }));
+
+ // Eyes are on the keyboard during the try, so each new instruction pulses the card and taps the
+ // phone to draw them back up.
+ useEffect(() => {
+ if (phase === 'start') return;
+ pulse.value = withSequence(withTiming(1, { duration: 160 }), withTiming(0, { duration: 700 }));
+ safeHaptics(phase === 'done' ? 'success' : 'light');
+ }, [phase, pulse]);
+
+ useEffect(() => {
+ const subscription = addKeyboardStatusChangedListener((event) => {
+ if (event.status === 'recording') {
+ setPhase((current) => (current === 'start' ? 'asking' : current));
+ } else if (event.status === 'agent_ready') {
+ // The native module emits each status directly and again from its own Darwin notification;
+ // both copies carry the same updatedAtMs.
+ if (event.updatedAtMs && event.updatedAtMs === lastDraftAt.current) return;
+ lastDraftAt.current = event.updatedAtMs;
+ draftsReady.current += 1;
+ const next: Phase = draftsReady.current >= 2 ? 'refined' : 'first-draft';
+ setPhase((current) => (current === 'done' ? current : next));
+ setAgentError(null);
+ } else if (event.status === 'agent_error') {
+ if (inserted.current) return;
+ setAgentError(event.error || 'agent_error');
+ if (draftsReady.current === 0) Keyboard.dismiss();
+ }
+ });
+ return () => subscription?.remove();
+ }, []);
+
+ const retry = (): void => {
+ draftsReady.current = 0;
+ setAgentError(null);
+ setPhase('start');
+ setValue('');
+ input.current?.focus();
+ };
+
+ const errorNote = agentError
+ ? (FINAL_ERROR_NOTES[agentError] ??
+ (hasDraft
+ ? 'The change didn’t go through. You can still insert this draft.'
+ : 'The voice assistant couldn’t finish. Try again or skip for now.'))
+ : null;
+ const fallbackNote = localSelected
+ ? 'The voice assistant uses Cloud. Here’s an example instead.'
+ : !user
+ ? 'The voice assistant needs a connection. Here’s an example instead.'
+ : errorNote;
+
+ return (
+ <OnboardingShell
+ title="Meet your voice assistant."
+ titleAccent="voice assistant"
+ subtitle="Say what you need, and it writes it for you in any app."
+ progress={progress}
+ onBack={goBack}
+ onSkip={goNext}
+ ctaLabel="Continue"
+ onCta={goNext}
+ secondaryCtaLabel={agentError && !errorIsFinal ? 'Retry' : undefined}
+ onSecondaryCta={retry}
+ >
+ <ScrollView
+ keyboardShouldPersistTaps="handled"
+ showsVerticalScrollIndicator={false}
+ contentContainerClassName="gap-4 pb-4"
+ >
+ {liveAvailable ? (
+ <>
+ <Animated.View
+ style={pulseStyle}
+ className="flex-row items-center gap-3 overflow-hidden rounded-2xl bg-primary/5 p-4"
+ >
+ <Animated.View
+ pointerEvents="none"
+ style={[StyleSheet.absoluteFill, { backgroundColor: BRAND }, flashStyle]}
+ />
+ <SystemIcon
+ name={phase === 'done' ? 'checkmark.circle.fill' : 'sparkles'}
+ mdName={phase === 'done' ? 'CheckCircle2' : 'Sparkles'}
+ size={20}
+ color="brand"
+ />
+ <Text
+ accessibilityLiveRegion="polite"
+ accessibilityLabel={
+ phase === 'start' && !agentError
+ ? 'Tap the voice assistant button, the wand, on your keyboard.'
+ : undefined
+ }
+ className="flex-1 text-[16px] leading-[22px] text-label"
+ >
+ {INSTRUCTIONS[agentError ? 'refined' : phase]}
+ </Text>
+ </Animated.View>
+ {errorNote ? (
+ <Text
+ accessibilityRole="alert"
+ className={`text-[14px] leading-[20px] ${
+ errorIsFinal ? 'text-secondaryLabel' : 'text-systemRed'
+ }`}
+ >
+ {errorNote}
+ </Text>
+ ) : null}
+ <View className="rounded-2xl border border-separator bg-secondarySystemGroupedBackground px-4 pb-4 pt-3">
+ <Text className="mb-2 text-[11px] font-bold uppercase tracking-wider text-tertiaryLabel">
+ To: Support
+ </Text>
+ <TextInput
+ ref={input}
+ accessibilityLabel="Your message"
+ value={value}
+ onChangeText={(text) => {
+ setValue(text);
+ // Only an inserted agent draft finishes the try; plain dictation into the field
+ // doesn't count.
+ if (text.trim() && draftsReady.current > 0 && phase !== 'done') {
+ inserted.current = true;
+ setPhase('done');
+ setAgentError(null);
+ Keyboard.dismiss();
+ }
+ }}
+ autoFocus
+ multiline
+ placeholder="Your draft appears here"
+ placeholderTextColor="#9CA3AF"
+ style={styles.messageInput}
+ textAlignVertical="top"
+ autoCorrect={false}
+ />
+ </View>
+ </>
+ ) : (
+ <>
+ <Text
+ accessibilityRole={agentError ? 'alert' : undefined}
+ className={`text-[14px] leading-[20px] ${
+ agentError && !errorIsFinal ? 'text-systemRed' : 'text-secondaryLabel'
+ }`}
+ >
+ {fallbackNote}
+ </Text>
+ <View className="rounded-2xl border border-separator bg-secondarySystemGroupedBackground p-4">
+ <View className="flex-row items-center gap-2">
+ <SystemIcon name="mic.fill" mdName="Mic" size={18} color="brand" />
+ <Text className="text-[13px] font-semibold text-secondaryLabel">
+ Example request
+ </Text>
+ </View>
+ <Text className="mt-3 text-[17px] leading-[24px] text-label">“{REQUEST}”</Text>
+ </View>
+ <View className="rounded-2xl bg-primary/5 p-4">
+ <View className="flex-row items-center gap-2">
+ <SystemIcon name="sparkles" mdName="Sparkles" size={18} color="brand" />
+ <Text className="text-[13px] font-semibold text-secondaryLabel">
+ Example response
+ </Text>
+ </View>
+ <Text className="mt-3 text-[17px] leading-[24px] text-label">{EXAMPLE_DRAFT}</Text>
+ </View>
+ </>
+ )}
+ </ScrollView>
+ </OnboardingShell>
+ );
+}
+
+const styles = StyleSheet.create({
+ messageInput: {
+ minHeight: 120,
+ color: PlatformColor('label') as unknown as string,
+ fontFamily: SpaceGrotesk.regular,
+ fontSize: 16,
+ fontWeight: '400',
+ lineHeight: 22,
+ },
+});
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/WelcomeStep.tsx b/openwhispr-mobile/src/screens/onboarding/steps/WelcomeStep.tsx
index 865fd877f..1d730f1e3 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/WelcomeStep.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/WelcomeStep.tsx
@@ -1,8 +1,8 @@
+import { useOnboardingStep } from '@/hooks/useOnboardingStep';
import { useEffect } from 'react';
import { StyleSheet, View, type StyleProp, type ViewStyle } from 'react-native';
import { OnboardingShell } from '@/components/onboarding/OnboardingShell';
import { AnimatedKeyboardPreview } from '@/components/onboarding/AnimatedKeyboardPreview';
-import { useOnboardingStore } from '@/store/useOnboardingStore';
const WELCOME_VIDEO = require('../../../../assets/onboarding/videos/welcome-setup.mp4');
const WELCOME_VIDEO_ASPECT_RATIO = 720 / 630;
@@ -43,7 +43,7 @@ function getExpoVideoModule(): ExpoVideoModule | null {
}
export function WelcomeStep() {
- const goNext = useOnboardingStore((s) => s.goNext);
+ const { goNext } = useOnboardingStep('welcome');
return (
<OnboardingShell
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/CreateAccountStep.test.tsx b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/CreateAccountStep.test.tsx
index acc70f16e..d20adc22d 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/CreateAccountStep.test.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/CreateAccountStep.test.tsx
@@ -1,11 +1,16 @@
import { fireEvent, render, waitFor } from '@testing-library/react-native';
+jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
+jest.mock('react-native-safe-area-context', () => ({ SafeAreaView: require('react-native').View }));
+jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
+
const mockGoNext = jest.fn();
const mockCaptureException = jest.fn();
jest.mock('@/lib/sentry', () => ({
Sentry: { captureException: (...args: unknown[]) => mockCaptureException(...args) },
}));
jest.mock('@/store/useOnboardingStore', () => ({
+ getStepProgress: () => undefined,
useOnboardingStore: (selector: (s: { goNext: () => Promise<void> }) => unknown) =>
selector({ goNext: mockGoNext }),
}));
@@ -95,12 +100,38 @@ describe('CreateAccountStep', () => {
mockAuthState = { user: { id: 'anon-user', isAnonymous: true }, isGuest: false };
mockGoNext.mockRejectedValueOnce(new Error('keychain unavailable'));
- const { getByText } = render(<CreateAccountStep />);
+ const { findByText, getByText } = render(<CreateAccountStep />);
fireEvent.press(getByText('skip'));
await waitFor(() => expect(mockCaptureException).toHaveBeenCalledTimes(1));
- fireEvent.press(getByText('skip'));
+ fireEvent.press(await findByText('Retry'));
+
+ await waitFor(() => expect(mockGoNext).toHaveBeenCalledTimes(2));
+ });
+
+ // The sign-in that ends this step doesn't happen again, so a failed save needs its own retry.
+ it('offers a retry when saving progress fails after signing in', async () => {
+ mockAuthState = { user: { id: 'real-user', isAnonymous: false }, isGuest: false };
+ mockGoNext.mockRejectedValueOnce(new Error('keychain unavailable'));
+
+ const { findByText } = render(<CreateAccountStep />);
+ expect(await findByText('Could not save your progress. Try again.')).toBeTruthy();
+ fireEvent.press(await findByText('Retry'));
+
+ await waitFor(() => expect(mockGoNext).toHaveBeenCalledTimes(2));
+ });
+
+ it('keeps the retry screen up while the retry is saving', async () => {
+ mockAuthState = { user: { id: 'real-user', isAnonymous: false }, isGuest: false };
+ mockGoNext
+ .mockRejectedValueOnce(new Error('keychain unavailable'))
+ .mockReturnValueOnce(new Promise<void>(() => undefined));
+
+ const { findByText, queryByText } = render(<CreateAccountStep />);
+ fireEvent.press(await findByText('Retry'));
- expect(mockGoNext).toHaveBeenCalledTimes(2);
+ await waitFor(() => expect(mockGoNext).toHaveBeenCalledTimes(2));
+ expect(queryByText('skip')).toBeNull();
+ expect(queryByText('Could not save your progress. Try again.')).toBeTruthy();
});
it('advances only once when signup lands after a skip', () => {
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/DictationEmailStep.test.tsx b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/DictationEmailStep.test.tsx
new file mode 100644
index 000000000..7bbe4152e
--- /dev/null
+++ b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/DictationEmailStep.test.tsx
@@ -0,0 +1,159 @@
+import { Keyboard, KeyboardAvoidingView } from 'react-native';
+import { act, fireEvent, render, waitFor } from '@testing-library/react-native';
+import { DictationEmailStep } from '../DictationEmailStep';
+
+jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
+jest.mock('@/lib/sentry', () => ({ Sentry: { captureException: jest.fn() } }));
+jest.mock('react-native-safe-area-context', () => ({ SafeAreaView: require('react-native').View }));
+jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
+let mockListener: (event: { status?: string; error?: string }) => void;
+jest.mock('../../../../../modules/app-group-storage/src', () => ({
+ addKeyboardStatusChangedListener: (listener: typeof mockListener) => {
+ mockListener = listener;
+ return { remove: jest.fn() };
+ },
+}));
+const mockNext = jest.fn();
+let mockMode: 'private' | 'cloud' | null = null;
+const mockSetMode = jest.fn();
+jest.mock('@/store/useOnboardingStore', () => ({
+ useOnboardingStore: (selector: (s: unknown) => unknown) =>
+ selector({ goNext: mockNext, selectedMode: mockMode }),
+ getStepProgress: () => ({ current: 4, total: 8 }),
+}));
+jest.mock('@/store/useProcessingModeStore', () => ({
+ useProcessingModeStore: {
+ getState: () => ({ activeMode: 'private', isUserOverride: false, setActiveMode: mockSetMode }),
+ },
+}));
+let mockUser: { id: string } | null = { id: 'anon' };
+const mockEnsureSession = jest.fn();
+jest.mock('@/store/useAuthStore', () => ({
+ useAuthStore: Object.assign(
+ (selector: (s: unknown) => unknown) =>
+ selector({ user: mockUser, ensureAnonymousSession: mockEnsureSession }),
+ { getState: () => ({ user: mockUser }) },
+ ),
+}));
+let mockSavedMode: 'private' | 'cloud' = 'cloud';
+jest.mock('@/store/useConfigStore', () => ({
+ useConfigStore: (selector: (s: unknown) => unknown) =>
+ selector({ config: { defaultMode: mockSavedMode } }),
+}));
+jest.mock('@/store/useHandoffStore', () => ({
+ useHandoffStore: (selector: (s: unknown) => unknown) => selector({ isTranscribing: false }),
+}));
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockMode = null;
+ mockSavedMode = 'cloud';
+ mockUser = { id: 'anon' };
+ mockNext.mockResolvedValue(undefined);
+ mockEnsureSession.mockResolvedValue(undefined);
+});
+
+const SAMPLE_EMAIL =
+ 'Hey Tim, excited to chat. Are you free next Friday at 3pm… actually, 4pm? Thanks, Chad';
+
+it('lays the practice out as an email to Tim with the sample as the placeholder', () => {
+ const screen = render(<DictationEmailStep />);
+ for (const text of ['To', 'Tim', 'Subject', 'Quick sync', 'Read this aloud']) {
+ expect(screen.getByText(text)).toBeTruthy();
+ }
+ expect(screen.getByLabelText('Your dictated email').props.placeholder).toBe(SAMPLE_EMAIL);
+ expect(screen.getByText('works in any email app')).toBeTruthy();
+});
+
+it('shows recording and processing state, then displays the inserted result', async () => {
+ const screen = render(<DictationEmailStep />);
+ act(() => mockListener({ status: 'recording' }));
+ expect(screen.getByText('Listening…')).toBeTruthy();
+ act(() => mockListener({ status: 'transcribing' }));
+ expect(screen.getByText('Transcribing…')).toBeTruthy();
+ act(() => mockListener({ status: 'ready' }));
+ fireEvent.changeText(screen.getByLabelText('Your dictated email'), 'Hello Tim, see you at four.');
+ expect(screen.getByText('Your email is ready')).toBeTruthy();
+});
+
+it('offers retry after a recording failure, without an example', async () => {
+ const screen = render(<DictationEmailStep />);
+ act(() => mockListener({ status: 'error', error: 'Network unavailable' }));
+ expect(screen.getByText('Network unavailable')).toBeTruthy();
+ expect(screen.queryByText('Show an example')).toBeNull();
+ expect(screen.queryByText(/Example/)).toBeNull();
+ fireEvent.press(screen.getByText('Retry'));
+ await waitFor(() => expect(mockEnsureSession).toHaveBeenCalledTimes(1));
+});
+
+it('keeps Local selected when revisiting practice', () => {
+ mockMode = 'private';
+ const screen = render(<DictationEmailStep />);
+ expect(mockSetMode).not.toHaveBeenCalled();
+ expect(screen.getByLabelText('Your dictated email').props.editable).toBe(false);
+ expect(screen.getByText('Practice uses Cloud. Skip it to keep Local.')).toBeTruthy();
+ expect(screen.queryByText(/Example/)).toBeNull();
+});
+
+it('keeps offline practice skippable', async () => {
+ mockUser = null;
+ const screen = render(<DictationEmailStep />);
+ fireEvent.press(screen.getByText('Skip'));
+ await waitFor(() => expect(mockNext).toHaveBeenCalledWith('dictation-email'));
+});
+
+it('does not dismiss the keyboard until the pending transcript has actually been inserted', () => {
+ const dismiss = jest.spyOn(Keyboard, 'dismiss');
+ const screen = render(<DictationEmailStep />);
+ act(() => mockListener({ status: 'recording' }));
+ act(() => mockListener({ status: 'ready' }));
+ expect(dismiss).not.toHaveBeenCalled();
+ fireEvent.changeText(screen.getByLabelText('Your dictated email'), 'Hello Tim.');
+ expect(dismiss).toHaveBeenCalledTimes(1);
+ dismiss.mockRestore();
+});
+
+it('lets the user edit the inserted email without the keyboard closing on every keystroke', () => {
+ const dismiss = jest.spyOn(Keyboard, 'dismiss');
+ const screen = render(<DictationEmailStep />);
+ const field = screen.getByLabelText('Your dictated email');
+ act(() => mockListener({ status: 'recording' }));
+ act(() => mockListener({ status: 'ready' }));
+ fireEvent.changeText(field, 'Hello Tim.');
+ fireEvent.changeText(field, 'Hello Tim!');
+ fireEvent.changeText(field, 'Hello Tim!!');
+ expect(dismiss).toHaveBeenCalledTimes(1);
+ dismiss.mockRestore();
+});
+
+// After no speech the keyboard settles back to idle a couple of seconds later.
+it('keeps the no-speech error until the next recording starts', () => {
+ const screen = render(<DictationEmailStep />);
+ act(() => mockListener({ status: 'no_speech' }));
+ act(() => mockListener({ status: 'idle' }));
+ expect(screen.getByText('No speech detected. Try again.')).toBeTruthy();
+ act(() => mockListener({ status: 'recording' }));
+ expect(screen.queryByText('No speech detected. Try again.')).toBeNull();
+});
+
+// Replaying onboarding starts with no choice made, but the saved Local default still stands.
+it('keeps a saved Local default when replaying onboarding', () => {
+ mockSavedMode = 'private';
+ const screen = render(<DictationEmailStep />);
+ expect(mockSetMode).not.toHaveBeenCalled();
+ expect(screen.getByText('Practice uses Cloud. Skip it to keep Local.')).toBeTruthy();
+});
+
+it('explains why Cloud practice could not be retried', async () => {
+ mockUser = null;
+ const screen = render(<DictationEmailStep />);
+ fireEvent.press(screen.getByText('Retry'));
+ expect(
+ await screen.findByText('Still no connection. Check it and try again, or skip for now.'),
+ ).toBeTruthy();
+});
+
+it('lets the keyboard cover the buttons', () => {
+ const screen = render(<DictationEmailStep />);
+ expect(screen.UNSAFE_queryByType(KeyboardAvoidingView)).toBeNull();
+});
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/KeyboardSwitchHelpSheet.test.tsx b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/KeyboardSwitchHelpSheet.test.tsx
new file mode 100644
index 000000000..b0c977662
--- /dev/null
+++ b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/KeyboardSwitchHelpSheet.test.tsx
@@ -0,0 +1,69 @@
+import type React from 'react';
+import { Linking } from 'react-native';
+import { fireEvent, render, screen } from '@testing-library/react-native';
+import { KeyboardSwitchHelpSheet } from '../KeyboardSwitchHelpSheet';
+
+jest.mock('@/lib/sentry', () => ({ Sentry: { captureException: jest.fn() } }));
+// The drag rule is covered by useSheetDragToDismiss's own test; the sheet only needs to render.
+jest.mock('react-native-gesture-handler', () => {
+ const { View } = require('react-native');
+ return {
+ GestureHandlerRootView: View,
+ GestureDetector: ({ children }: { children: React.ReactNode }) => children,
+ };
+});
+const mockDrag = jest.fn((_visible: boolean, _onClose: () => void) => ({
+ dragGesture: {},
+ sheetStyle: {},
+}));
+jest.mock('@/hooks/useSheetDragToDismiss', () => ({
+ useSheetDragToDismiss: (visible: boolean, onClose: () => void) => mockDrag(visible, onClose),
+}));
+jest.mock('react-native-reanimated', () => ({
+ __esModule: true,
+ default: { View: require('react-native').View },
+}));
+jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
+jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
+
+const renderSheet = (onClose = jest.fn()) =>
+ render(<KeyboardSwitchHelpSheet visible onClose={onClose} onDismissed={jest.fn()} />);
+
+beforeEach(() => jest.restoreAllMocks());
+
+it('lists the fixes for the common ways switching gets stuck', () => {
+ renderSheet();
+ expect(screen.getByText('Can’t switch to OpenWhispr?')).toBeTruthy();
+ expect(screen.getByText(/Turn on OpenWhispr in Settings → Keyboards/)).toBeTruthy();
+ expect(screen.getByText(/It’s below the letters, bottom left/)).toBeTruthy();
+ expect(screen.getByText(/Turn on Allow Full Access in Settings → Keyboards\./)).toBeTruthy();
+});
+
+it('opens OpenWhispr’s page in iOS Settings', () => {
+ const openSettings = jest.spyOn(Linking, 'openSettings').mockResolvedValue(undefined);
+ renderSheet();
+ fireEvent.press(screen.getByText('Open Settings'));
+ expect(openSettings).toHaveBeenCalledTimes(1);
+});
+
+// The app can't be used without the keyboard, and debugging it after onboarding is much harder,
+// so help never offers a way past the step.
+it('offers no way past the step', () => {
+ renderSheet();
+ expect(screen.queryByText(/Continue/)).toBeNull();
+ expect(screen.queryByText(/later/i)).toBeNull();
+});
+
+it('closes', () => {
+ const onClose = jest.fn();
+ renderSheet(onClose);
+ fireEvent.press(screen.getByText('Close'));
+ expect(onClose).toHaveBeenCalledTimes(1);
+});
+
+it('closes when pulled down', () => {
+ const onClose = jest.fn();
+ renderSheet(onClose);
+ mockDrag.mock.calls.at(-1)![1]();
+ expect(onClose).toHaveBeenCalledTimes(1);
+});
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/LanguageStep.test.tsx b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/LanguageStep.test.tsx
new file mode 100644
index 000000000..6d1097ac2
--- /dev/null
+++ b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/LanguageStep.test.tsx
@@ -0,0 +1,53 @@
+import { fireEvent, render, waitFor } from '@testing-library/react-native';
+import { LanguageStep } from '../LanguageStep';
+
+jest.mock('@/lib/sentry', () => ({ Sentry: { captureException: jest.fn() } }));
+jest.mock('react-native-safe-area-context', () => ({
+ SafeAreaView: require('react-native').View,
+ useSafeAreaInsets: () => ({ top: 0, right: 0, bottom: 0, left: 0 }),
+}));
+jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
+jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
+jest.mock('@/lib/deviceLanguages', () => ({ detectPreferredLanguages: () => ['en'] }));
+const mockNext = jest.fn();
+const mockBack = jest.fn();
+const mockSave = jest.fn();
+jest.mock('@/hooks/useOnboardingStep', () => ({
+ useOnboardingStep: () => ({ goNext: mockNext, goBack: mockBack }),
+}));
+jest.mock('@/lib/onboardingMode', () => ({
+ saveOnboardingConfig: (updates: unknown) => mockSave(updates),
+}));
+jest.mock('@/store/useConfigStore', () => ({
+ useConfigStore: (selector: (state: unknown) => unknown) =>
+ selector({ config: { languages: ['es', 'fr'] } }),
+}));
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockNext.mockResolvedValue(undefined);
+ mockBack.mockResolvedValue(undefined);
+ mockSave.mockResolvedValue(undefined);
+});
+
+it('restores confirmed languages and goes back without saving edits', async () => {
+ const screen = render(<LanguageStep />);
+ expect(screen.getByLabelText('Remove Spanish')).toBeTruthy();
+ expect(screen.queryByLabelText('Remove English')).toBeNull();
+ fireEvent.press(screen.getByLabelText('Remove French'));
+ fireEvent.press(screen.getByLabelText('Back'));
+ await waitFor(() => expect(mockBack).toHaveBeenCalledTimes(1));
+ expect(mockSave).not.toHaveBeenCalled();
+});
+
+it('stays on languages after a failed save and retries the selected values', async () => {
+ mockSave.mockRejectedValueOnce(new Error('Storage unavailable'));
+ const screen = render(<LanguageStep />);
+ fireEvent.press(screen.getByLabelText('Remove French'));
+ fireEvent.press(screen.getByText('Continue'));
+ expect(await screen.findByText('Could not save your progress. Try again.')).toBeTruthy();
+ expect(mockNext).not.toHaveBeenCalled();
+ fireEvent.press(screen.getByText('Retry'));
+ await waitFor(() => expect(mockNext).toHaveBeenCalledTimes(1));
+ expect(mockSave).toHaveBeenLastCalledWith({ languages: ['es'] });
+});
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/OnboardingTransitions.test.tsx b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/OnboardingTransitions.test.tsx
new file mode 100644
index 000000000..fb175ef13
--- /dev/null
+++ b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/OnboardingTransitions.test.tsx
@@ -0,0 +1,273 @@
+import type React from 'react';
+import { act, fireEvent, render, waitFor } from '@testing-library/react-native';
+import {
+ Alert,
+ AppState,
+ Keyboard,
+ KeyboardAvoidingView,
+ Linking,
+ Modal,
+ TextInput,
+} from 'react-native';
+import { NotificationsStep } from '../NotificationsStep';
+import { KeyboardIntroStep } from '../KeyboardIntroStep';
+import { MicrophoneStep } from '../MicrophoneStep';
+import { GraduationStep } from '../GraduationStep';
+import { KeyboardSwitchStep } from '../KeyboardSwitchStep';
+import { GetStartedStep } from '../GetStartedStep';
+
+jest.mock('@/lib/sentry', () => ({ Sentry: { captureException: jest.fn() } }));
+// The drag rule is covered by useSheetDragToDismiss's own test; the sheet only needs to render.
+jest.mock('react-native-gesture-handler', () => {
+ const { View } = require('react-native');
+ return {
+ GestureHandlerRootView: View,
+ GestureDetector: ({ children }: { children: React.ReactNode }) => children,
+ };
+});
+jest.mock('@/hooks/useSheetDragToDismiss', () => ({
+ useSheetDragToDismiss: () => ({ dragGesture: {}, sheetStyle: {} }),
+}));
+jest.mock('react-native-reanimated', () => ({
+ __esModule: true,
+ default: { View: require('react-native').View, Text: require('react-native').Text },
+ Easing: { out: jest.fn(), cubic: jest.fn() },
+ useAnimatedStyle: () => ({}),
+ useSharedValue: () => ({ value: 0 }),
+ withDelay: jest.fn(),
+ withRepeat: jest.fn(),
+ withSequence: jest.fn(),
+ withTiming: jest.fn(),
+}));
+
+let mockHeartbeatConfirmation: () => void;
+jest.mock('@/hooks/useKeyboardHeartbeat', () => ({
+ useKeyboardHeartbeat: (onConfirmed: () => void) => {
+ mockHeartbeatConfirmation = onConfirmed;
+ return false;
+ },
+}));
+
+jest.mock('react-native-safe-area-context', () => ({ SafeAreaView: require('react-native').View }));
+jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
+jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
+jest.mock('@/components/onboarding/AnimatedKeyboardPreview', () => ({
+ AnimatedKeyboardPreview: () => null,
+}));
+jest.mock('@/components/onboarding/FullAccessReasons', () => ({ FullAccessReasons: () => null }));
+jest.mock('@/components/onboarding/InstructionOverlay', () => ({ InstructionOverlay: () => null }));
+jest.mock('@/lib/keyboardPipTutorial', () => ({
+ startKeyboardPipTutorial: jest.fn(),
+ stopKeyboardPipTutorial: jest.fn(),
+}));
+const mockMicPermission = jest.fn();
+const mockRequestMicPermission = jest.fn();
+jest.mock('@/utils/expoAudio', () => ({
+ getExpoAudioModule: () => ({
+ AudioModule: {
+ getRecordingPermissionsAsync: () => mockMicPermission(),
+ requestRecordingPermissionsAsync: () => mockRequestMicPermission(),
+ },
+ }),
+}));
+jest.mock('@/components/ui/OpenWhisprMark', () => ({ OpenWhisprMark: () => null }));
+jest.mock('../../../../../modules/app-group-storage/src', () => ({
+ AppGroupStorage: { armWarmMic: jest.fn() },
+}));
+const mockNext = jest.fn();
+const mockFinish = jest.fn();
+const mockPermission = jest.fn();
+const mockKeyboardInstalled = jest.fn();
+const mockIsInstalled = jest.fn();
+const mockStatus = jest.fn();
+const mockRequest = jest.fn();
+jest.mock('@/store/useOnboardingStore', () => ({
+ useOnboardingStore: (selector: (state: unknown) => unknown) =>
+ selector({
+ goNext: mockNext,
+ finish: mockFinish,
+ setPermissionGranted: mockPermission,
+ setKeyboardInstalled: mockKeyboardInstalled,
+ }),
+ getStepProgress: () => ({ current: 1, total: 8 }),
+}));
+jest.mock('@/lib/keyboardInstallation', () => ({ isKeyboardInstalled: () => mockIsInstalled() }));
+jest.mock('@/lib/notifications', () => ({
+ getNotificationStatus: () => mockStatus(),
+ requestNotifications: () => mockRequest(),
+}));
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockNext.mockResolvedValue(undefined);
+ mockFinish.mockResolvedValue(undefined);
+ mockPermission.mockResolvedValue(undefined);
+ mockMicPermission.mockResolvedValue({ granted: true, canAskAgain: true });
+ mockRequestMicPermission.mockResolvedValue({ granted: true, canAskAgain: true });
+ mockKeyboardInstalled.mockResolvedValue(undefined);
+ mockIsInstalled.mockReturnValue(false);
+ mockStatus.mockResolvedValue('undetermined');
+ mockRequest.mockResolvedValue('denied');
+ jest.spyOn(Linking, 'canOpenURL').mockResolvedValue(false);
+ jest.spyOn(Linking, 'openURL').mockResolvedValue(undefined);
+});
+afterEach(() => {
+ jest.restoreAllMocks();
+ jest.useRealTimers();
+});
+
+it('accepts notification denial without showing another permission screen', async () => {
+ const screen = render(<NotificationsStep />);
+ fireEvent.press(await screen.findByText('Allow notifications'));
+ await waitFor(() => expect(mockNext).toHaveBeenCalledWith('notifications'));
+ expect(mockPermission).toHaveBeenCalledWith('notifications', false);
+ expect(screen.queryByText('Notifications are off')).toBeNull();
+});
+
+it('retries saving notification denial without asking for permission again', async () => {
+ mockStatus.mockResolvedValueOnce('denied');
+ mockNext.mockRejectedValueOnce(
+ new Error("Calling the 'setValueWithKeyAsync' function has failed"),
+ );
+ const screen = render(<NotificationsStep />);
+ expect(await screen.findByText('Could not save progress.')).toBeTruthy();
+ fireEvent.press(screen.getByText('Retry'));
+ await waitFor(() => expect(mockNext).toHaveBeenCalledTimes(2));
+ expect(mockRequest).not.toHaveBeenCalled();
+ expect(screen.queryByText('Allow notifications')).toBeNull();
+});
+
+it('does not keep polling after detecting the keyboard on Settings return', async () => {
+ jest.useFakeTimers();
+ let onState: ((state: 'background' | 'active') => void) | undefined;
+ jest.spyOn(AppState, 'addEventListener').mockImplementation((_event, listener) => {
+ onState = listener;
+ return { remove: jest.fn() };
+ });
+ render(<KeyboardIntroStep />);
+ act(() => onState?.('background'));
+ mockIsInstalled.mockReturnValue(true);
+ await act(async () => {
+ onState?.('active');
+ });
+ await act(async () => {
+ jest.advanceTimersByTime(1200);
+ });
+ expect(mockNext).toHaveBeenCalledTimes(1);
+ expect(mockNext).toHaveBeenCalledWith('keyboard-intro');
+});
+
+it('explains a failed keyboard continuation without native error text', async () => {
+ const alert = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined);
+ mockIsInstalled.mockReturnValue(true);
+ mockNext.mockRejectedValueOnce(
+ new Error("Calling the 'setValueWithKeyAsync' function has failed"),
+ );
+ render(<KeyboardIntroStep />);
+ await waitFor(() => expect(alert).toHaveBeenCalledWith('Could not continue', 'Try again.'));
+ alert.mockRestore();
+});
+
+it('finishes setup before launching an external app', async () => {
+ let resolveFinish: () => void = () => undefined;
+ mockFinish.mockReturnValue(
+ new Promise<void>((resolve) => {
+ resolveFinish = resolve;
+ }),
+ );
+ const screen = render(<GraduationStep />);
+ fireEvent.press(screen.getByLabelText('Messages'));
+ expect(Linking.openURL).not.toHaveBeenCalled();
+ await act(async () => resolveFinish());
+ await waitFor(() => expect(Linking.openURL).toHaveBeenCalledWith('sms:'));
+ expect(mockFinish).toHaveBeenCalledTimes(1);
+});
+
+it('does not launch an app when persisting completion fails', async () => {
+ mockFinish.mockRejectedValueOnce(
+ new Error("Calling the 'setValueWithKeyAsync' function has failed"),
+ );
+ const screen = render(<GraduationStep />);
+ fireEvent.press(screen.getByLabelText('Messages'));
+ expect(await screen.findByText('Could not finish setup. Try again.')).toBeTruthy();
+ expect(screen.queryByText(/setValueWithKeyAsync/)).toBeNull();
+ expect(Linking.openURL).not.toHaveBeenCalled();
+});
+
+it('allows a granted microphone step to retry a failed progress save', async () => {
+ mockNext.mockRejectedValueOnce(
+ new Error("Calling the 'setValueWithKeyAsync' function has failed"),
+ );
+ const screen = render(<MicrophoneStep />);
+ expect(await screen.findByText('Could not save progress.')).toBeTruthy();
+ fireEvent.press(screen.getByText('Retry'));
+ await waitFor(() => expect(mockNext).toHaveBeenCalledTimes(2));
+});
+
+it('shows a retry if detected keyboard continuation cannot save progress', async () => {
+ mockNext.mockRejectedValueOnce(
+ new Error("Calling the 'setValueWithKeyAsync' function has failed"),
+ );
+ const screen = render(<KeyboardSwitchStep />);
+ await act(async () => mockHeartbeatConfirmation());
+ expect((await screen.findAllByText('Could not save progress.')).length).toBeGreaterThan(0);
+ expect(screen.queryByText(/setValueWithKeyAsync/)).toBeNull();
+ fireEvent.press(screen.getByText('Retry'));
+ await waitFor(() => expect(mockNext).toHaveBeenCalledTimes(2));
+});
+
+it('shows a retryable error when Get Started cannot save progress', async () => {
+ mockNext.mockRejectedValueOnce(
+ new Error("Calling the 'setValueWithKeyAsync' function has failed"),
+ );
+ const screen = render(<GetStartedStep />);
+ fireEvent.press(screen.getByText('Get Started'));
+ expect(await screen.findByText('Could not save your progress. Try again.')).toBeTruthy();
+ fireEvent.press(screen.getByText('Get Started'));
+ await waitFor(() => expect(mockNext).toHaveBeenCalledTimes(2));
+});
+
+it('explains a failed continue from the blocked-microphone alert', async () => {
+ const alert = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined);
+ mockMicPermission.mockResolvedValue({ granted: false, canAskAgain: true });
+ mockRequestMicPermission.mockResolvedValue({ granted: false, canAskAgain: false });
+ mockNext.mockRejectedValueOnce(
+ new Error("Calling the 'setValueWithKeyAsync' function has failed"),
+ );
+ const screen = render(<MicrophoneStep />);
+ await screen.findByText('Allow microphone access');
+ fireEvent.press(screen.getByText('Continue'));
+ await waitFor(() => expect(alert).toHaveBeenCalledTimes(1));
+ const buttons = alert.mock.calls[0][2] ?? [];
+ await act(async () => buttons.find((button) => button.text === 'Continue')?.onPress?.());
+ expect(alert).toHaveBeenLastCalledWith('Could not continue', 'Could not save progress.');
+});
+
+it('lets the keyboard cover the switch step’s button, with help to get unstuck', () => {
+ const screen = render(<KeyboardSwitchStep />);
+ expect(screen.UNSAFE_queryByType(KeyboardAvoidingView)).toBeNull();
+
+ // iOS keeps the keyboard above a modal, so help has to put it away first.
+ const dismiss = jest.spyOn(Keyboard, 'dismiss');
+ fireEvent.press(screen.getByLabelText('Help'));
+ expect(dismiss).toHaveBeenCalled();
+ expect(screen.getByText('Can’t switch to OpenWhispr?')).toBeTruthy();
+ expect(screen.queryByText('Continue anyway')).toBeNull();
+});
+
+// iOS ignores a focus request while the sheet is still presented, so the keyboard comes back only
+// once the sheet has fully gone.
+it('brings the keyboard back after the help sheet has closed', async () => {
+ jest.useFakeTimers();
+ const screen = render(<KeyboardSwitchStep />);
+ act(() => jest.advanceTimersByTime(200));
+ const focus = jest.mocked(TextInput.prototype.focus);
+ focus.mockClear();
+
+ fireEvent.press(screen.getByLabelText('Help'));
+ fireEvent.press(screen.getByText('Close'));
+ expect(focus).not.toHaveBeenCalled();
+
+ act(() => screen.UNSAFE_getByType(Modal).props.onDismiss());
+ expect(focus).toHaveBeenCalledTimes(1);
+});
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/PaywallStep.test.tsx b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/PaywallStep.test.tsx
index b4577a014..8ee051037 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/PaywallStep.test.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/PaywallStep.test.tsx
@@ -1,5 +1,6 @@
import { act, fireEvent, render, waitFor } from '@testing-library/react-native';
+jest.mock('@/lib/sentry', () => ({ Sentry: { captureException: jest.fn() } }));
jest.mock('react-native-safe-area-context', () => ({
SafeAreaView: require('react-native').View,
useSafeAreaInsets: () => ({ top: 0, right: 0, bottom: 0, left: 0 }),
@@ -57,14 +58,14 @@ describe('PaywallStep', () => {
expect(mockRegister.mock.calls[0][0].placement).toBe(SUPERWALL_PLACEMENTS.onboardingPaywall);
});
- it('advances to the account step once the paywall closes', async () => {
+ it('advances to the saved setup destination once the paywall closes', async () => {
render(<PaywallStep />);
await waitFor(() => expect(mockGoNext).toHaveBeenCalledTimes(1));
});
// The property that matters most here: nothing about Superwall may strand a
- // first run. A rejected register still has to hand off to the account step.
+ // first run. A rejected register still has to hand off to the saved setup destination.
it('advances even when the paywall fails to present', async () => {
mockRegister.mockRejectedValue(new Error('Superwall unavailable'));
@@ -78,33 +79,40 @@ describe('PaywallStep', () => {
mockRegister.mockReturnValue(new Promise<boolean>(() => {}));
const { getByText } = render(<PaywallStep />);
- act(() => {
+ await act(async () => {
jest.advanceTimersByTime(PAYWALL_ESCAPE_MS);
});
- fireEvent.press(getByText('Continue'));
+ await act(async () => {
+ fireEvent.press(getByText('Continue'));
+ });
expect(mockGoNext).toHaveBeenCalledTimes(1);
+ expect(mockRegister.mock.calls[0][0].signal.aborted).toBe(true);
});
// Between register and the SDK actually presenting, the backdrop is a
// normal-looking screen with a primary button. Tapping it would mount the
// account step underneath a paywall that then presents on top of it.
- it('keeps Continue inert while the paywall is still being presented', () => {
+ it('keeps Continue inert while the paywall is still being presented', async () => {
mockRegister.mockReturnValue(new Promise<boolean>(() => {}));
const { getByText } = render(<PaywallStep />);
- fireEvent.press(getByText('Continue'));
+ await act(async () => {
+ fireEvent.press(getByText('Continue'));
+ });
expect(mockGoNext).not.toHaveBeenCalled();
});
- it('re-enables Continue once the SDK reports the paywall failed to present', () => {
+ it('re-enables Continue once the SDK reports the paywall failed to present', async () => {
mockRegister.mockReturnValue(new Promise<boolean>(() => {}));
const { getByText, rerender } = render(<PaywallStep />);
mockGate = { isConfigured: true, state: { status: 'error' } };
rerender(<PaywallStep />);
- fireEvent.press(getByText('Continue'));
+ await act(async () => {
+ fireEvent.press(getByText('Continue'));
+ });
expect(mockGoNext).toHaveBeenCalledTimes(1);
});
@@ -124,12 +132,12 @@ describe('PaywallStep', () => {
await waitFor(() => expect(mockRegister).toHaveBeenCalledTimes(1));
});
- it('presents anyway once the readiness grace period elapses', () => {
+ it('presents anyway once the readiness grace period elapses', async () => {
jest.useFakeTimers();
mockGate = { isConfigured: false, state: { status: 'idle' } };
render(<PaywallStep />);
- act(() => {
+ await act(async () => {
jest.advanceTimersByTime(PAYWALL_READY_GRACE_MS);
});
@@ -145,7 +153,9 @@ describe('PaywallStep', () => {
);
const { getByText } = render(<PaywallStep />);
- fireEvent.press(getByText('Continue'));
+ await act(async () => {
+ fireEvent.press(getByText('Continue'));
+ });
releaseRegister(true);
await waitFor(() => expect(mockGoNext).toHaveBeenCalled());
@@ -188,3 +198,15 @@ describe('PaywallStep', () => {
expect(mockGoNext).not.toHaveBeenCalled();
});
});
+
+it('allows retrying continuation after a progress save fails', async () => {
+ mockGoNext.mockRejectedValueOnce(
+ new Error("Calling the 'setValueWithKeyAsync' function has failed"),
+ );
+ const screen = render(<PaywallStep />);
+ expect(await screen.findByText('Could not save progress. Try again.')).toBeTruthy();
+ expect(screen.queryByText(/setValueWithKeyAsync/)).toBeNull();
+ fireEvent.press(screen.getByText('Continue'));
+ await waitFor(() => expect(mockGoNext).toHaveBeenCalledTimes(2));
+ expect(mockRegister).toHaveBeenCalledTimes(1);
+});
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/PrivacyModeStep.test.tsx b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/PrivacyModeStep.test.tsx
index 069bd47b6..0533a9cda 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/PrivacyModeStep.test.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/PrivacyModeStep.test.tsx
@@ -1,92 +1,84 @@
-import { Alert } from 'react-native';
import { fireEvent, render, waitFor } from '@testing-library/react-native';
-
-// accountAccess pulls in the router for its sign-in alert; stub it here.
-jest.mock('expo-router', () => ({ router: { push: jest.fn() } }));
-jest.mock('react-native-safe-area-context', () => ({
- SafeAreaView: require('react-native').View,
- useSafeAreaInsets: () => ({ top: 0, right: 0, bottom: 0, left: 0 }),
-}));
-jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
-jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
-jest.mock('@/components/ui/OpenWhisprMark', () => ({ OpenWhisprMark: () => null }));
-
+import { PrivacyModeStep } from '../PrivacyModeStep';
+import { chooseOnboardingMode } from '@/lib/onboardingMode';
+import { OnboardingError } from '@/lib/onboardingErrors';
+let mockSelectedMode: string | null = null;
+jest.mock('@/lib/sentry', () => ({ Sentry: { captureException: jest.fn() } }));
jest.mock('@/store/useOnboardingStore', () => ({
- useOnboardingStore: (selector: (s: { goNext: () => Promise<void> }) => unknown) =>
- selector({ goNext: jest.fn() }),
- getStepProgress: () => ({ current: 1, total: 1 }),
+ useOnboardingStore: (selector: (state: unknown) => unknown) =>
+ selector({ selectedMode: mockSelectedMode }),
}));
-jest.mock('@/store/useConfigStore', () => ({
- useConfigStore: (
- selector: (s: {
- config: { defaultMode: string };
- loadConfig: () => void;
- updateConfig: () => Promise<void>;
- }) => unknown,
- ) =>
- selector({
- config: { defaultMode: 'private' },
- loadConfig: jest.fn(),
- updateConfig: jest.fn().mockResolvedValue(undefined),
- }),
+jest.mock('@/lib/onboardingMode', () => ({ chooseOnboardingMode: jest.fn() }));
+const mockCancelActiveDownloads = jest.fn();
+jest.mock('@/store/useModelDownloadStore', () => ({
+ useModelDownloadStore: (selector: (state: unknown) => unknown) =>
+ selector({ cancelActiveDownloads: mockCancelActiveDownloads }),
}));
-
-const mockEnsureAnonymousSession = jest.fn().mockResolvedValue(undefined);
-type MockAuthState = {
- user: { id: string; isAnonymous: boolean } | null;
- isGuest: boolean;
- ensureAnonymousSession: jest.Mock;
-};
-let mockAuthState: MockAuthState = {
- user: null,
- isGuest: false,
- ensureAnonymousSession: mockEnsureAnonymousSession,
-};
-jest.mock('@/store/useAuthStore', () => ({
- useAuthStore: Object.assign(
- (selector: (s: MockAuthState) => unknown) => selector(mockAuthState),
- { getState: () => mockAuthState },
- ),
+jest.mock('@/hooks/useOnboardingStep', () => ({
+ useOnboardingStep: () => ({ goBack: jest.fn(), progress: { current: 6, total: 8 } }),
}));
-
-import { PrivacyModeStep } from '../PrivacyModeStep';
-
-const alertSpy = jest.spyOn(Alert, 'alert');
+jest.mock('react-native-safe-area-context', () => ({ SafeAreaView: require('react-native').View }));
+jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
+jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
+jest.mock('@/components/ui/OpenWhisprMark', () => ({ OpenWhisprMark: () => null }));
beforeEach(() => {
jest.clearAllMocks();
- mockAuthState = {
- user: null,
- isGuest: false,
- ensureAnonymousSession: mockEnsureAnonymousSession,
- };
+ mockSelectedMode = null;
+ jest.mocked(chooseOnboardingMode).mockResolvedValue(undefined);
+ mockCancelActiveDownloads.mockResolvedValue(undefined);
});
-
-describe('PrivacyModeStep cloud card without a session', () => {
- it('explains a missing connection when the anonymous session never opened', async () => {
- const { getByLabelText } = render(<PrivacyModeStep />);
-
- fireEvent.press(getByLabelText('OpenWhispr Cloud'));
-
- await waitFor(() => expect(alertSpy).toHaveBeenCalled());
- expect(alertSpy.mock.calls[0][0]).toBe('Cloud is unavailable');
- });
-
- // A guest chose to continue without an account on an earlier build; they
- // have a connection and no session is going to be minted for them, so
- // blaming the network would be wrong.
- it('tells a guest that Cloud needs an account, not a connection', async () => {
- mockAuthState = {
- user: null,
- isGuest: true,
- ensureAnonymousSession: mockEnsureAnonymousSession,
- };
- const { getByLabelText } = render(<PrivacyModeStep />);
-
- fireEvent.press(getByLabelText('OpenWhispr Cloud'));
-
- await waitFor(() => expect(alertSpy).toHaveBeenCalled());
- expect(alertSpy.mock.calls[0][0]).toBe('Cloud needs an account');
- expect(mockEnsureAnonymousSession).not.toHaveBeenCalled();
- });
+it('describes each mode in a few short lines', () => {
+ const screen = render(<PrivacyModeStep />);
+ for (const text of [
+ 'Everything runs on your device. Nothing is ever uploaded.',
+ 'Works fully offline',
+ 'Faster transcription',
+ 'Higher quality',
+ 'Automatic cleanup & formatting',
+ ]) {
+ expect(screen.getByText(text)).toBeTruthy();
+ }
+ expect(screen.queryByText(/tone/i)).toBeNull();
+ expect(screen.queryByText(/voice agent/i)).toBeNull();
+ expect(screen.queryByText(/Pro offer/i)).toBeNull();
+});
+it('shows the confirmed mode when revisiting the choice', () => {
+ mockSelectedMode = 'private';
+ const screen = render(<PrivacyModeStep />);
+ expect(screen.getByText('Local is selected')).toBeTruthy();
+});
+it.each([
+ ['Use Cloud', 'cloud'],
+ ['Use Local', 'private'],
+] as const)('commits %s without an extra Continue tap', async (label, mode) => {
+ const screen = render(<PrivacyModeStep />);
+ fireEvent.press(screen.getByText(label));
+ await waitFor(() => expect(chooseOnboardingMode).toHaveBeenCalledWith(mode, 'privacy-mode'));
+ expect(screen.queryByText('Continue')).toBeNull();
+});
+it('keeps the choices available after a failed Cloud attempt', async () => {
+ jest
+ .mocked(chooseOnboardingMode)
+ .mockRejectedValueOnce(new OnboardingError('Cloud is unavailable'));
+ const screen = render(<PrivacyModeStep />);
+ fireEvent.press(screen.getByText('Use Cloud'));
+ expect(await screen.findByText('Cloud is unavailable')).toBeTruthy();
+ fireEvent.press(screen.getByText('Use Local'));
+ await waitFor(() => expect(chooseOnboardingMode).toHaveBeenCalledWith('private', 'privacy-mode'));
+ expect(mockCancelActiveDownloads).not.toHaveBeenCalled();
+});
+// Back from the download step leaves its model transferring; Cloud has no use for it.
+it('stops a Local download left running once Cloud is chosen', async () => {
+ mockSelectedMode = 'private';
+ const screen = render(<PrivacyModeStep />);
+ fireEvent.press(screen.getByText('Use Cloud'));
+ await waitFor(() => expect(mockCancelActiveDownloads).toHaveBeenCalledTimes(1));
+});
+// Reset onboarding shows setup straight away, so a model downloading from Settings is not ours.
+it('leaves other downloads alone when Local was not chosen in this setup', async () => {
+ const screen = render(<PrivacyModeStep />);
+ fireEvent.press(screen.getByText('Use Cloud'));
+ await waitFor(() => expect(chooseOnboardingMode).toHaveBeenCalledWith('cloud', 'privacy-mode'));
+ expect(mockCancelActiveDownloads).not.toHaveBeenCalled();
});
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/PrivateDownloadStep.test.tsx b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/PrivateDownloadStep.test.tsx
index c3c354621..84971ad5c 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/PrivateDownloadStep.test.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/PrivateDownloadStep.test.tsx
@@ -1,10 +1,26 @@
import type React from 'react';
-import { fireEvent, render, screen, waitFor } from '@testing-library/react-native';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react-native';
// nativewind's cssInterop breaks jest's transform; same stub the other screen suites use.
jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
-jest.mock('../SlowDownloadSheet', () => ({ SlowDownloadSheet: () => null }));
+jest.mock('../SlowDownloadSheet', () => {
+ const { Pressable, Text } = require('react-native');
+ return {
+ SlowDownloadSheet: ({
+ visible,
+ onContinueCloud,
+ }: {
+ visible: boolean;
+ onContinueCloud: () => Promise<void>;
+ }) =>
+ visible ? (
+ <Pressable onPress={onContinueCloud}>
+ <Text>Keep downloading with Cloud</Text>
+ </Pressable>
+ ) : null,
+ };
+});
interface MockShellProps {
ctaLabel: string;
ctaDisabled?: boolean;
@@ -39,9 +55,11 @@ jest.mock('@/components/onboarding/OnboardingShell', () => {
),
};
});
+jest.mock('@/lib/onboardingMode', () => ({ chooseOnboardingMode: jest.fn(async () => undefined) }));
jest.mock('@/lib/privateMode', () => ({ getPrivateModeUnavailableMessage: () => '' }));
+let mockLanguages = ['en'];
jest.mock('@/lib/transcriptionLanguage', () => ({
- getPreferredTranscriptionLanguages: () => ['en'],
+ getPreferredTranscriptionLanguages: () => mockLanguages,
}));
jest.mock('@/store/useOnboardingStore', () => ({
useOnboardingStore: (selector: (s: { goNext: () => Promise<void> }) => unknown) =>
@@ -90,7 +108,9 @@ jest.mock('@/services/transcription/LocalTranscriptionService', () => ({
},
}));
-import { useConfigStore } from '@/store/useConfigStore';
+import { chooseOnboardingMode } from '@/lib/onboardingMode';
+import { LocalParakeetService } from '@/services/transcription/LocalParakeetService';
+import { LocalTranscriptionService } from '@/services/transcription/LocalTranscriptionService';
import {
useModelDownloadStore,
type LocalModelKey,
@@ -98,7 +118,11 @@ import {
} from '@/store/useModelDownloadStore';
import { PrivateDownloadStep } from '../PrivateDownloadStep';
-const mockUpdateConfig = useConfigStore.getState().updateConfig as jest.Mock;
+const mockChooseMode = jest.mocked(chooseOnboardingMode);
+const realDownloadActions = {
+ startDownload: useModelDownloadStore.getState().startDownload,
+ cancelDownload: useModelDownloadStore.getState().cancelDownload,
+};
const mockStartDownload = jest.fn(async () => undefined);
const mockCancelDownload = jest.fn(async () => undefined);
@@ -109,12 +133,53 @@ const setDownload = (key: LocalModelKey, entry: ModelDownloadEntry): void =>
beforeEach(() => {
jest.clearAllMocks();
+ mockLanguages = ['en'];
+ jest.mocked(LocalTranscriptionService.isAvailable).mockReturnValue(true);
useModelDownloadStore.getState().reset();
useModelDownloadStore.setState({
startDownload: mockStartDownload,
cancelDownload: mockCancelDownload,
});
});
+afterEach(() => jest.useRealTimers());
+
+it('uses the same Cloud choice from the slow-download sheet and keeps the download', async () => {
+ jest.useFakeTimers();
+ setDownload('parakeet-v2', { status: 'downloading', progress: 0.2 });
+ render(<PrivateDownloadStep />);
+ await screen.findByText('Parakeet v2');
+ await act(async () => {
+ jest.advanceTimersByTime(8000);
+ });
+ await act(async () => {
+ fireEvent.press(screen.getByText('Keep downloading with Cloud'));
+ });
+ expect(mockChooseMode).toHaveBeenCalledWith('cloud', 'private-download');
+ expect(mockCancelDownload).not.toHaveBeenCalled();
+});
+
+it('uses the same Cloud choice when local recording is unavailable', async () => {
+ jest.mocked(LocalTranscriptionService.isAvailable).mockReturnValue(false);
+ render(<PrivateDownloadStep />);
+ fireEvent.press(screen.getByText('Use Cloud instead'));
+ await waitFor(() => expect(mockChooseMode).toHaveBeenCalledWith('cloud', 'private-download'));
+});
+
+it('uses the same Cloud choice when model discovery fails', async () => {
+ jest
+ .mocked(LocalTranscriptionService.getAvailability)
+ .mockRejectedValueOnce(new Error('Unavailable'));
+ render(<PrivateDownloadStep />);
+ fireEvent.press(await screen.findByText('Use Cloud instead'));
+ await waitFor(() => expect(mockChooseMode).toHaveBeenCalledWith('cloud', 'private-download'));
+});
+
+it('reasserts Local before continuing with a completed model', async () => {
+ setDownload('parakeet-v2', { status: 'completed', progress: 1 });
+ render(<PrivateDownloadStep />);
+ fireEvent.press(await screen.findByText('Continue with Private'));
+ await waitFor(() => expect(mockChooseMode).toHaveBeenCalledWith('private', 'private-download'));
+});
describe('PrivateDownloadStep — switching to Cloud', () => {
// A failed attempt leaves its partial download staged. Leaving Private behind is the last
@@ -127,7 +192,7 @@ describe('PrivateDownloadStep — switching to Cloud', () => {
fireEvent.press(screen.getByText("Don't use Private — switch to Cloud"));
await waitFor(() => expect(mockCancelDownload).toHaveBeenCalledWith('parakeet-v2'));
- expect(mockUpdateConfig).toHaveBeenCalledWith({ defaultMode: 'cloud' });
+ expect(mockChooseMode).toHaveBeenCalledWith('cloud', 'private-download');
});
it('keeps a completed model when switching to Cloud', async () => {
@@ -137,7 +202,7 @@ describe('PrivateDownloadStep — switching to Cloud', () => {
fireEvent.press(screen.getByText('Use Cloud instead'));
- await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalledWith({ defaultMode: 'cloud' }));
+ await waitFor(() => expect(mockChooseMode).toHaveBeenCalledWith('cloud', 'private-download'));
expect(mockCancelDownload).not.toHaveBeenCalled();
});
});
@@ -162,3 +227,67 @@ describe('PrivateDownloadStep — retrying after an error', () => {
expect(screen.queryByText('Try again')).toBeNull();
});
});
+
+it('offers retry when model discovery fails instead of spinning forever', async () => {
+ jest
+ .mocked(LocalTranscriptionService.getAvailability)
+ .mockRejectedValueOnce(new Error('Model lookup failed'));
+ render(<PrivateDownloadStep />);
+ fireEvent.press(await screen.findByText('Retry model selection'));
+ expect(await screen.findByText('Parakeet v2')).toBeTruthy();
+});
+
+// Back → a language change → Continue re-enters with a different recommendation while the old
+// one is still transferring. startDownload refuses to run beside it, which used to leave the
+// step on a download that never started.
+it('replaces a stale download when going back changed the recommended model', async () => {
+ useModelDownloadStore.setState(realDownloadActions);
+ setDownload('parakeet-v2', { status: 'downloading', progress: 0.3 });
+ mockLanguages = ['en', 'es'];
+
+ render(<PrivateDownloadStep />);
+
+ await screen.findByText('Parakeet v3');
+ await waitFor(() =>
+ expect(LocalParakeetService.downloadModel).toHaveBeenCalledWith('v3', expect.any(Function)),
+ );
+ expect(LocalParakeetService.cancelModelDownload).toHaveBeenCalledWith('v2');
+ expect(useModelDownloadStore.getState().downloads['parakeet-v2'].status).toBe('idle');
+});
+
+it('stops a stale download even when the new recommendation is already installed', async () => {
+ useModelDownloadStore.setState(realDownloadActions);
+ setDownload('parakeet-v2', { status: 'downloading', progress: 0.3 });
+ mockLanguages = ['en', 'es'];
+ jest.mocked(LocalTranscriptionService.getAvailability).mockResolvedValueOnce({
+ parakeetSupported: true,
+ parakeetV2Downloaded: false,
+ parakeetV3Downloaded: true,
+ whisperDownloaded: false,
+ });
+
+ render(<PrivateDownloadStep />);
+
+ await screen.findByText('Continue with Private');
+ await waitFor(() =>
+ expect(useModelDownloadStore.getState().downloads['parakeet-v2'].status).toBe('idle'),
+ );
+ expect(LocalParakeetService.downloadModel).not.toHaveBeenCalled();
+});
+
+it('does not start the new download once the user has left the step', async () => {
+ useModelDownloadStore.setState(realDownloadActions);
+ setDownload('parakeet-v2', { status: 'downloading', progress: 0.3 });
+ mockLanguages = ['en', 'es'];
+ let finishCancel!: () => void;
+ jest
+ .mocked(LocalParakeetService.cancelModelDownload)
+ .mockImplementationOnce(() => new Promise<void>((resolve) => (finishCancel = resolve)));
+
+ const view = render(<PrivateDownloadStep />);
+ await waitFor(() => expect(LocalParakeetService.cancelModelDownload).toHaveBeenCalledWith('v2'));
+ view.unmount();
+ await act(async () => finishCancel());
+
+ expect(LocalParakeetService.downloadModel).not.toHaveBeenCalled();
+});
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/SlowDownloadSheet.test.tsx b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/SlowDownloadSheet.test.tsx
new file mode 100644
index 000000000..5146a7d42
--- /dev/null
+++ b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/SlowDownloadSheet.test.tsx
@@ -0,0 +1,68 @@
+import type React from 'react';
+import { act, fireEvent, render, waitFor } from '@testing-library/react-native';
+import { OnboardingError } from '@/lib/onboardingErrors';
+import { SlowDownloadSheet } from '../SlowDownloadSheet';
+jest.mock('@/lib/sentry', () => ({ Sentry: { captureException: jest.fn() } }));
+jest.mock('react-native-gesture-handler', () => {
+ const { View } = require('react-native');
+ return {
+ GestureHandlerRootView: View,
+ GestureDetector: ({ children }: { children: React.ReactNode }) => children,
+ };
+});
+jest.mock('react-native-reanimated', () => ({
+ __esModule: true,
+ default: { View: require('react-native').View },
+}));
+const mockDrag = jest.fn((_visible: boolean, _onClose: () => void) => ({
+ dragGesture: {},
+ sheetStyle: {},
+}));
+jest.mock('@/hooks/useSheetDragToDismiss', () => ({
+ useSheetDragToDismiss: (visible: boolean, onClose: () => void) => mockDrag(visible, onClose),
+}));
+jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
+jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
+
+it('shows a Cloud failure without losing the ability to keep downloading locally', async () => {
+ const onContinueCloud = jest
+ .fn()
+ .mockRejectedValue(new OnboardingError('Cloud needs a connection'));
+ const onKeepWaiting = jest.fn();
+ const screen = render(
+ <SlowDownloadSheet visible onContinueCloud={onContinueCloud} onKeepWaiting={onKeepWaiting} />,
+ );
+ fireEvent.press(screen.getByText('Continue with Cloud for now'));
+ expect(await screen.findByText('Cloud needs a connection')).toBeTruthy();
+ fireEvent.press(screen.getByText('Keep waiting'));
+ expect(onKeepWaiting).toHaveBeenCalledTimes(1);
+});
+it('does not start two Cloud transitions on repeated taps', async () => {
+ const onContinueCloud = jest.fn().mockReturnValue(new Promise<void>(() => undefined));
+ const screen = render(
+ <SlowDownloadSheet visible onContinueCloud={onContinueCloud} onKeepWaiting={jest.fn()} />,
+ );
+ const button = screen.getByText('Continue with Cloud for now');
+ fireEvent.press(button);
+ fireEvent.press(button);
+ await waitFor(() => expect(onContinueCloud).toHaveBeenCalledTimes(1));
+});
+it('does not show the text of an unexpected Cloud failure', async () => {
+ const onContinueCloud = jest
+ .fn()
+ .mockRejectedValue(new Error("Calling the 'setValueWithKeyAsync' function has failed"));
+ const screen = render(
+ <SlowDownloadSheet visible onContinueCloud={onContinueCloud} onKeepWaiting={jest.fn()} />,
+ );
+ fireEvent.press(screen.getByText('Continue with Cloud for now'));
+ expect(await screen.findByText('Cloud is unavailable. Try again.')).toBeTruthy();
+ expect(screen.queryByText(/setValueWithKeyAsync/)).toBeNull();
+});
+
+it('treats pulling the sheet down as keep waiting', () => {
+ const onKeepWaiting = jest.fn();
+ render(<SlowDownloadSheet visible onContinueCloud={jest.fn()} onKeepWaiting={onKeepWaiting} />);
+ const pulledDown = mockDrag.mock.calls.at(-1)![1];
+ act(() => pulledDown());
+ expect(onKeepWaiting).toHaveBeenCalledTimes(1);
+});
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/ToneStep.test.tsx b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/ToneStep.test.tsx
new file mode 100644
index 000000000..6aabd4c0a
--- /dev/null
+++ b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/ToneStep.test.tsx
@@ -0,0 +1,120 @@
+import { fireEvent, render, waitFor } from '@testing-library/react-native';
+import { ToneStep } from '../ToneStep';
+
+jest.mock('@/lib/sentry', () => ({ Sentry: { captureException: jest.fn() } }));
+jest.mock('react-native-safe-area-context', () => ({ SafeAreaView: require('react-native').View }));
+jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
+jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
+jest.mock('@/components/ui/Button', () => {
+ const { Pressable, Text } = require('react-native');
+ return {
+ Button: ({
+ children,
+ onPress,
+ disabled,
+ loading,
+ }: {
+ children: React.ReactNode;
+ onPress: () => void;
+ disabled?: boolean;
+ loading?: boolean;
+ }) => (
+ <Pressable onPress={onPress} disabled={disabled || loading}>
+ <Text>{children}</Text>
+ </Pressable>
+ ),
+ };
+});
+const mockGoNext = jest.fn();
+const mockGoBack = jest.fn();
+jest.mock('@/store/useOnboardingStore', () => ({
+ useOnboardingStore: (selector: (s: unknown) => unknown) =>
+ selector({ goNext: mockGoNext, goBack: mockGoBack, selectedMode: null }),
+ getStepProgress: () => ({ current: 6, total: 9 }),
+}));
+const mockUpdateConfig = jest.fn();
+const mockConfigState = {
+ config: { keyboardTone: 'default' },
+ error: null as string | null,
+ updateConfig: mockUpdateConfig,
+};
+jest.mock('@/store/useConfigStore', () => ({
+ useConfigStore: Object.assign((selector: (s: unknown) => unknown) => selector(mockConfigState), {
+ getState: () => mockConfigState,
+ }),
+}));
+jest.mock('@/store/useAuthStore', () => ({ useAuthStore: { getState: jest.fn() } }));
+jest.mock('@/store/useProcessingModeStore', () => ({
+ useProcessingModeStore: { getState: jest.fn() },
+}));
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockConfigState.config.keyboardTone = 'default';
+ mockConfigState.error = null;
+ mockUpdateConfig.mockResolvedValue(undefined);
+ mockGoNext.mockResolvedValue(undefined);
+});
+
+it('shows illustrative examples and saves a selected tone only on Continue', async () => {
+ const screen = render(<ToneStep />);
+ expect(screen.getAllByRole('radio')).toHaveLength(5);
+ expect(screen.getByRole('radio', { name: /^Default\./ })).toBeSelected();
+ fireEvent.press(screen.getByRole('radio', { name: /^Formal\./ }));
+ expect(screen.getByRole('radio', { name: /^Formal\./ })).toBeSelected();
+ expect(mockUpdateConfig).not.toHaveBeenCalled();
+ fireEvent.press(screen.getByText('Continue'));
+ await waitFor(() => expect(mockGoNext).toHaveBeenCalledWith('tone'));
+ expect(mockUpdateConfig).toHaveBeenCalledWith({ keyboardTone: 'formal' });
+});
+
+it('preserves the saved tone when skipping', async () => {
+ mockConfigState.config.keyboardTone = 'casual';
+ const screen = render(<ToneStep />);
+ expect(screen.getByRole('radio', { name: /^Casual\./ })).toBeSelected();
+ fireEvent.press(screen.getByRole('radio', { name: /^Excited\./ }));
+ fireEvent.press(screen.getByText('Skip'));
+ await waitFor(() => expect(mockGoNext).toHaveBeenCalledWith('tone'));
+ expect(mockUpdateConfig).not.toHaveBeenCalled();
+});
+
+it('stays on the preview and allows retry when saving fails', async () => {
+ mockUpdateConfig.mockImplementationOnce(async () => {
+ mockConfigState.error = 'Disk unavailable';
+ });
+ const screen = render(<ToneStep />);
+ fireEvent.press(screen.getByText('Continue'));
+ expect(await screen.findByText('Could not save your progress. Try again.')).toBeTruthy();
+ expect(mockGoNext).not.toHaveBeenCalled();
+ mockConfigState.error = null;
+ fireEvent.press(screen.getByRole('radio', { name: /^Excited\./ }));
+ fireEvent.press(screen.getByText('Retry'));
+ await waitFor(() => expect(mockGoNext).toHaveBeenCalledTimes(1));
+ expect(mockUpdateConfig).toHaveBeenLastCalledWith({ keyboardTone: 'excited' });
+});
+
+// Tones only change keyboard dictation; in-app recordings are never toned.
+it('says the tone applies to keyboard dictation', () => {
+ const screen = render(<ToneStep />);
+ expect(screen.getByText(/keyboard dictation/)).toBeTruthy();
+});
+
+it('reads each tone with its description and example to screen readers', () => {
+ const screen = render(<ToneStep />);
+ expect(
+ screen.getByRole('radio', {
+ name: 'Formal. Professional and polished. Example: Hi Sam, would you be available for lunch tomorrow at noon? Please let me know if that time is convenient.',
+ }),
+ ).toBeTruthy();
+});
+
+it('keeps the intro to the comparison and what live tones need', () => {
+ const screen = render(<ToneStep />);
+ expect(screen.getByText('Compare the tones')).toBeTruthy();
+ expect(screen.getByText('The same lunch invitation, written five different ways.')).toBeTruthy();
+ expect(
+ screen.getByText('Live tones need Cloud, Dictation Cleanup, and an account.'),
+ ).toBeTruthy();
+ expect(screen.queryByText(/illustrative/)).toBeNull();
+ expect(screen.queryByText(/choose Local/)).toBeNull();
+});
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/TrackingPermissionStep.test.tsx b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/TrackingPermissionStep.test.tsx
index 91af38e66..1aae19296 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/TrackingPermissionStep.test.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/TrackingPermissionStep.test.tsx
@@ -1,7 +1,7 @@
import { fireEvent, render, waitFor } from '@testing-library/react-native';
import type { TrackingAuthorizationStatus } from '@/lib/trackingTransparency';
-const mockFinish = jest.fn();
+const mockGoNext = jest.fn();
const mockMarkRequestAttempted = jest.fn();
const mockGetTrackingAuthorizationStatus = jest.fn();
const mockRequestTrackingAuthorization = jest.fn();
@@ -49,15 +49,16 @@ jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
jest.mock('@/components/ui/OpenWhisprMark', () => ({ OpenWhisprMark: () => null }));
jest.mock('@/store/useOnboardingStore', () => ({
+ getStepProgress: () => undefined,
useOnboardingStore: (
selector: (state: {
- finish: () => Promise<void>;
+ goNext: () => Promise<void>;
markTrackingAuthorizationRequestAttempted: () => Promise<void>;
trackingAuthorizationRequestAttempted: boolean;
}) => unknown,
) =>
selector({
- finish: mockFinish,
+ goNext: mockGoNext,
markTrackingAuthorizationRequestAttempted: mockMarkRequestAttempted,
trackingAuthorizationRequestAttempted: mockTrackingAuthorizationRequestAttempted,
}),
@@ -95,7 +96,7 @@ function deferred<T>(): {
beforeEach(() => {
jest.clearAllMocks();
mockTrackingAuthorizationRequestAttempted = false;
- mockFinish.mockResolvedValue(undefined);
+ mockGoNext.mockResolvedValue(undefined);
mockMarkRequestAttempted.mockResolvedValue(undefined);
mockGetTrackingAuthorizationStatus.mockResolvedValue('notDetermined');
mockRequestTrackingAuthorization.mockResolvedValue('authorized');
@@ -107,7 +108,7 @@ describe('TrackingPermissionStep', () => {
expect(await findByRole('header')).toBeTruthy();
expect(getByText('Continue')).toBeTruthy();
- expect(mockFinish).not.toHaveBeenCalled();
+ expect(mockGoNext).not.toHaveBeenCalled();
});
it('omits the decorative OpenWhispr logo from the education content', async () => {
@@ -124,7 +125,8 @@ describe('TrackingPermissionStep', () => {
const { queryByText } = render(<TrackingPermissionStep />);
- await waitFor(() => expect(mockFinish).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(mockGoNext).toHaveBeenCalledWith('tracking-permission'));
+ expect(mockGoNext).toHaveBeenCalledTimes(1);
expect(queryByText('Continue')).toBeNull();
expect(mockRequestTrackingAuthorization).not.toHaveBeenCalled();
},
@@ -135,7 +137,8 @@ describe('TrackingPermissionStep', () => {
render(<TrackingPermissionStep />);
- await waitFor(() => expect(mockFinish).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(mockGoNext).toHaveBeenCalledWith('tracking-permission'));
+ expect(mockGoNext).toHaveBeenCalledTimes(1);
expect(mockRequestTrackingAuthorization).not.toHaveBeenCalled();
});
@@ -144,7 +147,8 @@ describe('TrackingPermissionStep', () => {
render(<TrackingPermissionStep />);
- await waitFor(() => expect(mockFinish).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(mockGoNext).toHaveBeenCalledWith('tracking-permission'));
+ expect(mockGoNext).toHaveBeenCalledTimes(1);
expect(mockRequestTrackingAuthorization).not.toHaveBeenCalled();
});
@@ -161,30 +165,33 @@ describe('TrackingPermissionStep', () => {
expect(mockMarkRequestAttempted).toHaveBeenCalledTimes(1);
authorization.resolve('authorized');
- await waitFor(() => expect(mockFinish).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(mockGoNext).toHaveBeenCalledWith('tracking-permission'));
+ expect(mockGoNext).toHaveBeenCalledTimes(1);
});
it.each(['authorized', 'denied', 'notDetermined', 'notSupported'] as const)(
- 'finishes onboarding after the native request returns %s',
+ 'advances to completion after the native request returns %s',
async (status) => {
mockRequestTrackingAuthorization.mockResolvedValue(status);
const { findByText } = render(<TrackingPermissionStep />);
fireEvent.press(await findByText('Continue'));
- await waitFor(() => expect(mockFinish).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(mockGoNext).toHaveBeenCalledWith('tracking-permission'));
+ expect(mockGoNext).toHaveBeenCalledTimes(1);
expect(mockSetAppsFlyerTrackingAuthorizationStatus).toHaveBeenCalledWith(status);
},
);
- it('fails open and finishes onboarding when the native request errors', async () => {
+ it('fails open and advances to completion when the native request errors', async () => {
const error = new Error('native ATT request failed');
mockRequestTrackingAuthorization.mockRejectedValue(error);
const { findByText } = render(<TrackingPermissionStep />);
fireEvent.press(await findByText('Continue'));
- await waitFor(() => expect(mockFinish).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(mockGoNext).toHaveBeenCalledWith('tracking-permission'));
+ expect(mockGoNext).toHaveBeenCalledTimes(1);
expect(mockCaptureException).toHaveBeenCalledWith(error);
});
@@ -194,17 +201,32 @@ describe('TrackingPermissionStep', () => {
fireEvent.press(await findByText('Continue'));
- await waitFor(() => expect(mockFinish).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(mockGoNext).toHaveBeenCalledWith('tracking-permission'));
+ expect(mockGoNext).toHaveBeenCalledTimes(1);
expect(mockRequestTrackingAuthorization).not.toHaveBeenCalled();
});
- it('fails open and finishes onboarding when checking authorization errors', async () => {
+ it('fails open and advances to completion when checking authorization errors', async () => {
const error = new Error('ATT status unavailable');
mockGetTrackingAuthorizationStatus.mockRejectedValue(error);
render(<TrackingPermissionStep />);
- await waitFor(() => expect(mockFinish).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(mockGoNext).toHaveBeenCalledWith('tracking-permission'));
+ expect(mockGoNext).toHaveBeenCalledTimes(1);
expect(mockCaptureException).toHaveBeenCalledWith(error);
});
});
+
+it('offers continuation retry when auto-skipping ATT fails to save progress', async () => {
+ mockGetTrackingAuthorizationStatus.mockResolvedValue('authorized');
+ mockGoNext.mockRejectedValueOnce(
+ new Error("Calling the 'setValueWithKeyAsync' function has failed"),
+ );
+ const screen = render(<TrackingPermissionStep />);
+ expect(await screen.findByText('Could not save progress.')).toBeTruthy();
+ fireEvent.press(screen.getByText('Retry'));
+ expect(mockCaptureException).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(mockGoNext).toHaveBeenCalledTimes(2));
+ expect(mockRequestTrackingAuthorization).not.toHaveBeenCalled();
+});
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/VoiceAgentStep.test.tsx b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/VoiceAgentStep.test.tsx
new file mode 100644
index 000000000..6d55b9444
--- /dev/null
+++ b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/VoiceAgentStep.test.tsx
@@ -0,0 +1,335 @@
+import { KeyboardAvoidingView } from 'react-native';
+import { act, fireEvent, render } from '@testing-library/react-native';
+import { safeHaptics } from '@/lib/utils';
+import { VoiceAgentStep } from '../VoiceAgentStep';
+
+jest.mock('@/lib/sentry', () => ({ Sentry: { captureException: jest.fn() } }));
+jest.mock('@/lib/utils', () => ({ ...jest.requireActual('@/lib/utils'), safeHaptics: jest.fn() }));
+jest.mock('react-native-reanimated', () => ({
+ __esModule: true,
+ default: { View: require('react-native').View },
+ useAnimatedStyle: () => ({}),
+ useSharedValue: (value: number) => ({ value }),
+ withSequence: jest.fn(),
+ withTiming: jest.fn(),
+}));
+jest.mock('react-native-safe-area-context', () => ({ SafeAreaView: require('react-native').View }));
+jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
+// Renders the symbol name so a test can tell which glyph an instruction shows.
+jest.mock('@/components/ui/SystemIcon', () => {
+ const { Text } = require('react-native');
+ return { SystemIcon: ({ name }: { name: string }) => <Text>{`[${name}]`}</Text> };
+});
+let mockListener: (event: { status?: string; error?: string; updatedAtMs?: string }) => void;
+jest.mock('../../../../../modules/app-group-storage/src', () => ({
+ addKeyboardStatusChangedListener: (listener: typeof mockListener) => {
+ mockListener = listener;
+ return { remove: jest.fn() };
+ },
+}));
+const mockNext = jest.fn();
+const mockBack = jest.fn();
+jest.mock('@/hooks/useOnboardingStep', () => ({
+ useOnboardingStep: () => ({
+ goNext: mockNext,
+ goBack: mockBack,
+ progress: { current: 5, total: 9 },
+ }),
+}));
+let mockMode: 'private' | 'cloud' | null = null;
+jest.mock('@/store/useOnboardingStore', () => ({
+ useOnboardingStore: (selector: (s: unknown) => unknown) => selector({ selectedMode: mockMode }),
+}));
+const mockSetMode = jest.fn();
+jest.mock('@/store/useProcessingModeStore', () => ({
+ useProcessingModeStore: {
+ getState: () => ({ activeMode: 'private', isUserOverride: false, setActiveMode: mockSetMode }),
+ },
+}));
+let mockSavedMode: 'private' | 'cloud' = 'cloud';
+jest.mock('@/store/useConfigStore', () => ({
+ useConfigStore: (selector: (s: unknown) => unknown) =>
+ selector({ config: { defaultMode: mockSavedMode } }),
+}));
+let mockUser: { id: string } | null = { id: 'anon' };
+jest.mock('@/store/useAuthStore', () => ({
+ useAuthStore: (selector: (s: unknown) => unknown) => selector({ user: mockUser }),
+}));
+
+// The field is focused on arrival, and the glyph is the keyboard's own agent button.
+const START = 'Tap the [wand.and.stars] button on your keyboard.';
+const ASK =
+ 'Say: “I cancelled my subscription last month but got charged again. Draft an email asking them to refund it.”';
+const FOLLOW_UP = 'Now tap Ask for changes and say: “Make it firmer.”';
+const INSERT = 'Tap ✓ to insert it.';
+const DONE = 'That’s your voice assistant.';
+const ACCOUNT_REQUIRED =
+ 'The live try isn’t available. Sign in at the end to use the voice assistant.';
+
+const emit = (status: string, error?: string, updatedAtMs?: string): void => {
+ act(() => mockListener({ status, error, updatedAtMs }));
+};
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockMode = null;
+ mockSavedMode = 'cloud';
+ mockUser = { id: 'anon' };
+ mockNext.mockResolvedValue(undefined);
+ mockBack.mockResolvedValue(undefined);
+});
+
+it('starts by pointing to the agent button on the keyboard', () => {
+ const screen = render(<VoiceAgentStep />);
+ expect(screen.getByText('Meet your voice assistant.')).toBeTruthy();
+ expect(screen.getByText(START)).toBeTruthy();
+ expect(screen.getByLabelText('Your message')).toBeTruthy();
+ expect(screen.queryByText('Example request')).toBeNull();
+});
+
+it('says what the agent does in one line', () => {
+ const screen = render(<VoiceAgentStep />);
+ expect(screen.getByText('Say what you need, and it writes it for you in any app.')).toBeTruthy();
+});
+
+// The keyboard is up for the whole try, so the buttons stay put and it covers them; Skip at the
+// top is the way out until the draft is inserted and the keyboard closes.
+it('lets the keyboard cover the buttons', () => {
+ const screen = render(<VoiceAgentStep />);
+ expect(screen.UNSAFE_queryByType(KeyboardAvoidingView)).toBeNull();
+});
+
+it('nudges with a haptic each time the instruction changes', () => {
+ const screen = render(<VoiceAgentStep />);
+ expect(safeHaptics).not.toHaveBeenCalled();
+ emit('recording');
+ expect(safeHaptics).toHaveBeenLastCalledWith('light');
+ emit('agent_ready', undefined, '1000');
+ emit('agent_ready', undefined, '2000');
+ expect(safeHaptics).toHaveBeenCalledTimes(3);
+ fireEvent.changeText(
+ screen.getByLabelText('Your message'),
+ 'Hi, please refund this charge and confirm my subscription is cancelled.',
+ );
+ expect(safeHaptics).toHaveBeenLastCalledWith('success');
+});
+
+it('addresses the practice email to Support', () => {
+ const screen = render(<VoiceAgentStep />);
+ expect(screen.getByText('To: Support')).toBeTruthy();
+});
+
+it('shows the refund request and a drafted email when the live try is unavailable', () => {
+ mockUser = null;
+ const screen = render(<VoiceAgentStep />);
+ expect(
+ screen.getByText(
+ '“I cancelled my subscription last month but got charged again. Draft an email asking them to refund it.”',
+ ),
+ ).toBeTruthy();
+ expect(screen.getByText(/Could you please refund this charge\?/)).toBeTruthy();
+ expect(screen.queryByText(/confirm/)).toBeNull();
+ expect(screen.queryByText(/lunch/)).toBeNull();
+});
+
+it('walks through a request, a spoken follow-up and inserting the result', () => {
+ const screen = render(<VoiceAgentStep />);
+ emit('recording');
+ expect(screen.getByText(ASK)).toBeTruthy();
+ emit('agent_generating');
+ emit('agent_ready');
+ expect(screen.getByText(FOLLOW_UP)).toBeTruthy();
+ // Recording the follow-up keeps the follow-up instruction on screen.
+ emit('recording');
+ expect(screen.getByText(FOLLOW_UP)).toBeTruthy();
+ emit('agent_ready');
+ expect(screen.getByText(INSERT)).toBeTruthy();
+ fireEvent.changeText(
+ screen.getByLabelText('Your message'),
+ 'Hi, please refund this charge and confirm my subscription is cancelled.',
+ );
+ expect(screen.getByText(DONE)).toBeTruthy();
+});
+
+it('does not count ordinary dictation as trying the agent', () => {
+ const screen = render(<VoiceAgentStep />);
+ emit('recording');
+ emit('ready');
+ fireEvent.changeText(screen.getByLabelText('Your message'), 'Please refund the charge.');
+ expect(screen.queryByText(DONE)).toBeNull();
+ expect(screen.getByText(ASK)).toBeTruthy();
+});
+
+it('counts a draft once when the keyboard reports it twice', () => {
+ // The native module emits each status directly and again from its own Darwin
+ // notification; both copies carry the same updatedAtMs.
+ const screen = render(<VoiceAgentStep />);
+ emit('recording');
+ emit('agent_ready', undefined, '1000');
+ emit('agent_ready', undefined, '1000');
+ expect(screen.getByText(FOLLOW_UP)).toBeTruthy();
+ emit('agent_ready', undefined, '2000');
+ expect(screen.getByText(INSERT)).toBeTruthy();
+});
+
+it('keeps the first draft insertable when the refinement fails', () => {
+ // The keyboard keeps the first draft on its card after a failed refinement.
+ const screen = render(<VoiceAgentStep />);
+ emit('recording');
+ emit('agent_ready', undefined, '1000');
+ emit('recording');
+ emit('agent_error', 'Network request failed');
+ expect(
+ screen.getByText('The change didn’t go through. You can still insert this draft.'),
+ ).toBeTruthy();
+ expect(screen.getByText(INSERT)).toBeTruthy();
+ expect(screen.getByText('Retry')).toBeTruthy();
+ expect(screen.queryByText('Example request')).toBeNull();
+ fireEvent.changeText(
+ screen.getByLabelText('Your message'),
+ 'Hi, please refund this charge and confirm my subscription is cancelled.',
+ );
+ expect(screen.getByText(DONE)).toBeTruthy();
+ expect(screen.queryByText('Retry')).toBeNull();
+});
+
+it('keeps the draft insertable when the refinement needs an account', () => {
+ const screen = render(<VoiceAgentStep />);
+ emit('recording');
+ emit('agent_ready', undefined, '1000');
+ emit('agent_error', 'account_required');
+ expect(screen.getByText(ACCOUNT_REQUIRED)).toBeTruthy();
+ expect(screen.getByLabelText('Your message')).toBeTruthy();
+ expect(screen.getByText(INSERT)).toBeTruthy();
+ expect(screen.queryByText('Retry')).toBeNull();
+});
+
+it('keeps the finished step when an agent error arrives after inserting the draft', () => {
+ // Tapping regenerate again after inserting can hit a refused try.
+ const screen = render(<VoiceAgentStep />);
+ emit('recording');
+ emit('agent_ready', undefined, '1000');
+ fireEvent.changeText(
+ screen.getByLabelText('Your message'),
+ 'Hi, please refund this charge and confirm my subscription is cancelled.',
+ );
+ emit('agent_error', 'account_required');
+ expect(screen.getByText(DONE)).toBeTruthy();
+ expect(
+ screen.getByDisplayValue(
+ 'Hi, please refund this charge and confirm my subscription is cancelled.',
+ ),
+ ).toBeTruthy();
+ expect(screen.queryByText(ACCOUNT_REQUIRED)).toBeNull();
+ expect(screen.queryByText('Example request')).toBeNull();
+});
+
+it('clears a failed refinement once another draft arrives', () => {
+ const screen = render(<VoiceAgentStep />);
+ emit('recording');
+ emit('agent_ready', undefined, '1000');
+ emit('agent_error', 'Network request failed');
+ emit('agent_ready', undefined, '2000');
+ expect(screen.getByText(INSERT)).toBeTruthy();
+ expect(
+ screen.queryByText('The change didn’t go through. You can still insert this draft.'),
+ ).toBeNull();
+ expect(screen.queryByText('Retry')).toBeNull();
+});
+
+it('does not offer a retry once the weekly word limit is reached', () => {
+ const screen = render(<VoiceAgentStep />);
+ emit('recording');
+ emit('agent_error', 'usage_limit');
+ expect(
+ screen.getByText(
+ 'You’ve reached the weekly word limit. Try the voice assistant again once it resets.',
+ ),
+ ).toBeTruthy();
+ expect(screen.getByText('Example request')).toBeTruthy();
+ expect(screen.queryByText('Retry')).toBeNull();
+});
+
+it('uses Cloud for the live try before a mode is chosen', () => {
+ render(<VoiceAgentStep />);
+ expect(mockSetMode).toHaveBeenCalledWith('cloud', true);
+});
+
+it('falls back to the example when the live try needs an account', () => {
+ // Used-up tries, the word limit, or a server without the live try all look the same here, so the
+ // note must not claim the user spent anything.
+ const screen = render(<VoiceAgentStep />);
+ emit('recording');
+ emit('agent_error', 'account_required');
+ expect(screen.getByText(ACCOUNT_REQUIRED)).toBeTruthy();
+ expect(screen.getByText('Example request')).toBeTruthy();
+ expect(screen.queryByText('Retry')).toBeNull();
+});
+
+it('offers a retry and the example when the agent fails before a draft', async () => {
+ const screen = render(<VoiceAgentStep />);
+ emit('recording');
+ emit('agent_error', 'Network request failed');
+ expect(
+ screen.getByText('The voice assistant couldn’t finish. Try again or skip for now.'),
+ ).toBeTruthy();
+ expect(screen.getByText('Example request')).toBeTruthy();
+ await act(async () => {
+ fireEvent.press(screen.getByText('Retry'));
+ });
+ expect(screen.getByText(START)).toBeTruthy();
+ expect(screen.getByLabelText('Your message')).toBeTruthy();
+});
+
+it('starts the try over when retrying after a failed refinement', async () => {
+ const screen = render(<VoiceAgentStep />);
+ emit('recording');
+ emit('agent_ready', undefined, '1000');
+ emit('agent_error', 'Network request failed');
+ await act(async () => {
+ fireEvent.press(screen.getByText('Retry'));
+ });
+ expect(screen.getByText(START)).toBeTruthy();
+ // A draft from before the retry no longer counts toward the follow-up.
+ emit('agent_ready', undefined, '2000');
+ expect(screen.getByText(FOLLOW_UP)).toBeTruthy();
+});
+
+it.each([
+ ['a Local choice', () => (mockMode = 'private')],
+ ['a saved Local default', () => (mockSavedMode = 'private')],
+])('shows the example instead of a live try for %s', (_label, arrange) => {
+ arrange();
+ const screen = render(<VoiceAgentStep />);
+ expect(
+ screen.getByText('The voice assistant uses Cloud. Here’s an example instead.'),
+ ).toBeTruthy();
+ expect(screen.getByText('Example request')).toBeTruthy();
+ expect(screen.queryByText(START)).toBeNull();
+ expect(mockSetMode).not.toHaveBeenCalled();
+});
+
+it('shows the example when there is no session to try the agent with', () => {
+ mockUser = null;
+ const screen = render(<VoiceAgentStep />);
+ expect(
+ screen.getByText('The voice assistant needs a connection. Here’s an example instead.'),
+ ).toBeTruthy();
+ expect(screen.getByText('Example request')).toBeTruthy();
+});
+
+it.each(['Continue', 'Skip'])('leaves the voice-agent step using %s', async (action) => {
+ const screen = render(<VoiceAgentStep />);
+ await act(async () => {
+ fireEvent.press(screen.getByText(action));
+ });
+ expect(mockNext).toHaveBeenCalledTimes(1);
+});
+
+it('can return to dictation practice', async () => {
+ const screen = render(<VoiceAgentStep />);
+ await act(async () => {
+ fireEvent.press(screen.getByLabelText('Back'));
+ });
+ expect(mockBack).toHaveBeenCalledTimes(1);
+});
diff --git a/openwhispr-mobile/src/services/agent/AgentStreamClient.ts b/openwhispr-mobile/src/services/agent/AgentStreamClient.ts
index 002dc5692..509551d4c 100644
--- a/openwhispr-mobile/src/services/agent/AgentStreamClient.ts
+++ b/openwhispr-mobile/src/services/agent/AgentStreamClient.ts
@@ -12,7 +12,8 @@ import { withRetry } from '@/lib/retry';
// Single budget for the entire streaming call: connect + receive.
const AGENT_STREAM_TIMEOUT_MS = 55_000;
-// Max 1 retry — words are billed at /api/transcribe, not here.
+// Max 1 retry. Words are billed at /api/transcribe, not here, but each attempt
+// spends one of an anonymous session's five agent tries.
const AGENT_MAX_RETRIES = 1;
export interface AgentMessage {
diff --git a/openwhispr-mobile/src/store/__tests__/useModelDownloadStore.test.ts b/openwhispr-mobile/src/store/__tests__/useModelDownloadStore.test.ts
index ef78b8338..7d70d3cb3 100644
--- a/openwhispr-mobile/src/store/__tests__/useModelDownloadStore.test.ts
+++ b/openwhispr-mobile/src/store/__tests__/useModelDownloadStore.test.ts
@@ -161,6 +161,36 @@ describe('useModelDownloadStore', () => {
await first;
});
+ it('cancels every active download except the one being kept', async () => {
+ const set = (key: 'parakeet-v2' | 'parakeet-v3' | 'whisper-base', status: string): void =>
+ useModelDownloadStore.setState((state) => ({
+ downloads: { ...state.downloads, [key]: { status, progress: 0.3 } as never },
+ }));
+ set('parakeet-v2', 'downloading');
+ set('parakeet-v3', 'downloading');
+ set('whisper-base', 'completed');
+
+ await useModelDownloadStore.getState().cancelActiveDownloads('parakeet-v3');
+
+ const { downloads } = useModelDownloadStore.getState();
+ expect(mockParakeet.cancelModelDownload).toHaveBeenCalledWith('v2');
+ expect(mockParakeet.cancelModelDownload).not.toHaveBeenCalledWith('v3');
+ expect(downloads['parakeet-v2'].status).toBe('idle');
+ expect(downloads['parakeet-v3'].status).toBe('downloading');
+ expect(downloads['whisper-base'].status).toBe('completed');
+ });
+
+ it('treats a model still preparing as active', async () => {
+ useModelDownloadStore.setState((state) => ({
+ downloads: { ...state.downloads, 'whisper-base': { status: 'preparing', progress: 1 } },
+ }));
+
+ await useModelDownloadStore.getState().cancelActiveDownloads('parakeet-v3');
+
+ expect(mockWhisper.cancelModelDownload).toHaveBeenCalledWith('base');
+ expect(useModelDownloadStore.getState().downloads['whisper-base'].status).toBe('idle');
+ });
+
it('surfaces download failures as per-key errors', async () => {
mockParakeet.downloadModel.mockRejectedValue(new Error('network down'));
await useModelDownloadStore.getState().startDownload('parakeet-v3');
diff --git a/openwhispr-mobile/src/store/__tests__/useOnboardingStore.appsflyer.test.ts b/openwhispr-mobile/src/store/__tests__/useOnboardingStore.appsflyer.test.ts
index 6f2f95d60..79215975f 100644
--- a/openwhispr-mobile/src/store/__tests__/useOnboardingStore.appsflyer.test.ts
+++ b/openwhispr-mobile/src/store/__tests__/useOnboardingStore.appsflyer.test.ts
@@ -1,8 +1,13 @@
const mockCompleteOnboarding = jest.fn();
const mockLogTutorialCompletion = jest.fn();
+jest.mock('@/store/useConfigStore', () => ({
+ useConfigStore: { getState: () => ({ config: { defaultMode: 'cloud' } }) },
+}));
+
jest.mock('@/utils/onboarding', () => ({
FIRST_ONBOARDING_STEP: 'get-started',
+ ONBOARDING_VERSION: 3,
OnboardingService: {
isOnboardingComplete: jest.fn(),
getProgress: jest.fn(),
@@ -37,7 +42,8 @@ beforeEach(() => {
useOnboardingStore.setState({
hydrated: true,
finished: false,
- currentStep: 'graduation',
+ currentStep: 'tone',
+ tutorialCompleted: false,
keyboardInstalled: true,
permissionsGranted: {
microphone: false,
@@ -47,30 +53,26 @@ beforeEach(() => {
});
describe('useOnboardingStore AppsFlyer events', () => {
- // The tutorial ends at graduation. The paywall and account steps that follow
- // are a different funnel, so the event fires when the user leaves graduation
- // rather than when onboarding is finally persisted — otherwise everyone who
- // drops at the paywall or the account screen would read as never having
- // finished the tutorial.
- it('logs tutorial completion when leaving graduation with the setup state', async () => {
- await useOnboardingStore.getState().goNext();
-
- expect(useOnboardingStore.getState().currentStep).toBe('paywall');
+ it('logs tutorial completion when leaving the tone preview with the setup state', async () => {
+ await useOnboardingStore.getState().goNext('tone');
+
+ expect(useOnboardingStore.getState().currentStep).toBe('privacy-mode');
expect(mockLogTutorialCompletion).toHaveBeenCalledWith({
keyboardInstalled: true,
microphonePermissionGranted: false,
});
});
- it('logs it once, not again on the steps after graduation', async () => {
- await useOnboardingStore.getState().goNext();
- await useOnboardingStore.getState().goNext();
+ it('logs it once, not again on the duplicate callbacks', async () => {
+ await useOnboardingStore.getState().goNext('tone');
+ await useOnboardingStore.getState().goNext('tone');
- expect(useOnboardingStore.getState().currentStep).toBe('create-account');
+ expect(useOnboardingStore.getState().currentStep).toBe('privacy-mode');
expect(mockLogTutorialCompletion).toHaveBeenCalledTimes(1);
});
it('does not log completion when onboarding is persisted', async () => {
+ useOnboardingStore.setState({ currentStep: 'graduation' });
await useOnboardingStore.getState().finish();
expect(mockCompleteOnboarding).toHaveBeenCalledTimes(1);
@@ -79,7 +81,9 @@ describe('useOnboardingStore AppsFlyer events', () => {
});
it('does not persist completion again once onboarding is finished', async () => {
+ useOnboardingStore.setState({ currentStep: 'graduation' });
await useOnboardingStore.getState().finish();
+ useOnboardingStore.setState({ currentStep: 'graduation' });
await useOnboardingStore.getState().finish();
expect(mockCompleteOnboarding).toHaveBeenCalledTimes(1);
@@ -89,6 +93,7 @@ describe('useOnboardingStore AppsFlyer events', () => {
const deferredPersistence = createDeferredPromise();
mockCompleteOnboarding.mockReturnValueOnce(deferredPersistence.promise);
+ useOnboardingStore.setState({ currentStep: 'graduation' });
const firstCompletion = useOnboardingStore.getState().finish();
const secondCompletion = useOnboardingStore.getState().finish();
@@ -103,6 +108,7 @@ describe('useOnboardingStore AppsFlyer events', () => {
it('does not log a failed completion and allows a later retry', async () => {
mockCompleteOnboarding.mockRejectedValueOnce(new Error('secure storage unavailable'));
+ useOnboardingStore.setState({ currentStep: 'graduation' });
await expect(useOnboardingStore.getState().finish()).rejects.toThrow(
'secure storage unavailable',
);
@@ -111,6 +117,7 @@ describe('useOnboardingStore AppsFlyer events', () => {
mockCompleteOnboarding.mockResolvedValueOnce(undefined);
+ useOnboardingStore.setState({ currentStep: 'graduation' });
await useOnboardingStore.getState().finish();
expect(mockCompleteOnboarding).toHaveBeenCalledTimes(2);
diff --git a/openwhispr-mobile/src/store/__tests__/useOnboardingStore.test.ts b/openwhispr-mobile/src/store/__tests__/useOnboardingStore.test.ts
index e045f307a..190059a3f 100644
--- a/openwhispr-mobile/src/store/__tests__/useOnboardingStore.test.ts
+++ b/openwhispr-mobile/src/store/__tests__/useOnboardingStore.test.ts
@@ -1,188 +1,332 @@
-import {
- STEP_ORDER,
- getStepProgress,
- useOnboardingStore,
- type OnboardingStepId,
-} from '@/store/useOnboardingStore';
-import { FIRST_ONBOARDING_STEP, OnboardingService } from '@/utils/onboarding';
-
-// The tutorial milestone reports to AppsFlyer, whose module pulls in the
-// SQLite-backed config store; the event itself has its own focused suite.
-jest.mock('@/lib/appsflyer', () => ({ logTutorialCompletion: jest.fn() }));
+import { getStepProgress, useOnboardingStore } from '../useOnboardingStore';
+import { OnboardingService } from '@/utils/onboarding';
+import { logTutorialCompletion } from '@/lib/appsflyer';
+jest.mock('@/lib/appsflyer', () => ({ logTutorialCompletion: jest.fn() }));
+let mockConfig = { defaultMode: 'cloud' };
+jest.mock('@/store/useConfigStore', () => ({
+ useConfigStore: { getState: () => ({ config: mockConfig }) },
+}));
jest.mock('@/utils/onboarding', () => ({
FIRST_ONBOARDING_STEP: 'get-started',
+ ONBOARDING_VERSION: 3,
OnboardingService: {
isOnboardingComplete: jest.fn(),
completeOnboarding: jest.fn(),
- resetOnboarding: jest.fn(),
hasAttemptedTrackingAuthorizationRequest: jest.fn(),
markTrackingAuthorizationRequestAttempted: jest.fn(),
getProgress: jest.fn(),
setProgress: jest.fn(),
+ resetOnboarding: jest.fn(),
},
}));
+const service = jest.mocked(OnboardingService);
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockConfig = { defaultMode: 'cloud' };
+ service.setProgress.mockResolvedValue();
+ service.completeOnboarding.mockResolvedValue();
+ service.isOnboardingComplete.mockResolvedValue(false);
+ service.hasAttemptedTrackingAuthorizationRequest.mockResolvedValue(false);
+ useOnboardingStore.setState(useOnboardingStore.getInitialState());
+});
-const mockedService = OnboardingService as jest.Mocked<typeof OnboardingService>;
-
-async function advanceTo(step: OnboardingStepId): Promise<void> {
- await useOnboardingStore.getState().goToStep(step);
-}
-
-describe('useOnboardingStore step order', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- mockedService.setProgress.mockResolvedValue();
- mockedService.completeOnboarding.mockResolvedValue();
- mockedService.hasAttemptedTrackingAuthorizationRequest.mockResolvedValue(false);
- mockedService.markTrackingAuthorizationRequestAttempted.mockResolvedValue(undefined);
- useOnboardingStore.setState({
- currentStep: 'security-first',
- finished: false,
- trackingAuthorizationRequestAttempted: false,
- });
- });
+it('ignores a late callback from a step that has already advanced', async () => {
+ await useOnboardingStore.getState().goToStep('keyboard-intro');
+ await Promise.all([
+ useOnboardingStore.getState().goNext('keyboard-intro'),
+ useOnboardingStore.getState().goNext('keyboard-intro'),
+ ]);
+ expect(useOnboardingStore.getState().currentStep).toBe('keyboard-switch');
+});
- it('opens on Get Started and ends with account creation then tracking permission', () => {
- expect(STEP_ORDER[0]).toBe('get-started');
- expect(STEP_ORDER.slice(-4)).toEqual([
- 'graduation',
- 'paywall',
- 'create-account',
- 'tracking-permission',
- ]);
+it.each([
+ ['get-started', 'get-started'],
+ ['unknown-old-step', 'get-started'],
+ ['keyboard-switch', 'keyboard-switch'],
+] as const)('resumes %s at %s without replaying earlier content', async (step, expected) => {
+ service.getProgress.mockResolvedValue({
+ step,
+ keyboardInstalled: false,
+ permissionsGranted: { microphone: false, notifications: false },
});
-
- it('starts a fresh install at the first step', async () => {
- mockedService.isOnboardingComplete.mockResolvedValue(false);
- mockedService.getProgress.mockResolvedValue({
- step: FIRST_ONBOARDING_STEP,
- keyboardInstalled: false,
- permissionsGranted: { microphone: false, notifications: false },
- });
-
- await useOnboardingStore.getState().hydrate();
-
- expect(useOnboardingStore.getState().currentStep).toBe('get-started');
+ service.hasAttemptedTrackingAuthorizationRequest.mockResolvedValue(true);
+ await useOnboardingStore.getState().hydrate();
+ expect(useOnboardingStore.getState()).toMatchObject({
+ currentStep: expected,
+ hydrated: true,
+ finished: false,
+ trackingAuthorizationRequestAttempted: true,
});
+});
- it('falls back to the first step when saved progress names an unknown step', async () => {
- mockedService.isOnboardingComplete.mockResolvedValue(false);
- mockedService.getProgress.mockResolvedValue({
- step: 'a-step-that-was-removed',
- keyboardInstalled: false,
- permissionsGranted: { microphone: false, notifications: false },
- });
+it('marks tracking permission attempted only after its marker is saved', async () => {
+ service.markTrackingAuthorizationRequestAttempted.mockRejectedValueOnce(
+ new Error('Storage unavailable'),
+ );
+ await expect(
+ useOnboardingStore.getState().markTrackingAuthorizationRequestAttempted(),
+ ).rejects.toThrow();
+ expect(useOnboardingStore.getState().trackingAuthorizationRequestAttempted).toBe(false);
+ await useOnboardingStore.getState().markTrackingAuthorizationRequestAttempted();
+ expect(useOnboardingStore.getState().trackingAuthorizationRequestAttempted).toBe(true);
+});
- await useOnboardingStore.getState().hydrate();
+it('does not leave a step when persisting the transition fails', async () => {
+ service.setProgress.mockRejectedValueOnce(new Error('Keychain unavailable'));
+ await expect(useOnboardingStore.getState().goNext('get-started')).rejects.toThrow();
+ expect(useOnboardingStore.getState().currentStep).toBe('get-started');
+ await useOnboardingStore.getState().goNext('get-started');
+ expect(useOnboardingStore.getState().currentStep).toBe('security-first');
+});
- expect(useOnboardingStore.getState().currentStep).toBe(FIRST_ONBOARDING_STEP);
+it('shows the paywall immediately for Cloud, then resumes languages only once', async () => {
+ await useOnboardingStore.getState().goToStep('privacy-mode');
+ await useOnboardingStore.getState().chooseMode('cloud', 'privacy-mode');
+ expect(useOnboardingStore.getState().currentStep).toBe('paywall');
+ await useOnboardingStore.getState().goNext('paywall');
+ await useOnboardingStore.getState().goNext('paywall');
+ expect(useOnboardingStore.getState()).toMatchObject({
+ currentStep: 'language',
+ paywallHandled: true,
});
+ await useOnboardingStore.getState().goBack('language');
+ expect(useOnboardingStore.getState().currentStep).toBe('privacy-mode');
+ await useOnboardingStore.getState().chooseMode('cloud', 'privacy-mode');
+ expect(useOnboardingStore.getState().currentStep).toBe('language');
+ await useOnboardingStore.getState().goNext('language');
+ expect(useOnboardingStore.getState().currentStep).toBe('notifications');
+});
- it('resumes mid-onboarding installs where they left off', async () => {
- mockedService.isOnboardingComplete.mockResolvedValue(false);
- mockedService.getProgress.mockResolvedValue({
- step: 'language',
- keyboardInstalled: true,
- permissionsGranted: { microphone: true, notifications: false },
- });
+it('routes Local through languages and download without a paywall', async () => {
+ await useOnboardingStore.getState().goToStep('privacy-mode');
+ await useOnboardingStore.getState().chooseMode('private', 'privacy-mode');
+ expect(useOnboardingStore.getState().currentStep).toBe('language');
+ await useOnboardingStore.getState().goNext('language');
+ expect(useOnboardingStore.getState().currentStep).toBe('private-download');
+ await useOnboardingStore.getState().goBack('private-download');
+ expect(useOnboardingStore.getState().currentStep).toBe('language');
+});
- await useOnboardingStore.getState().hydrate();
+it('resumes a download-to-Cloud paywall at notifications after relaunch', async () => {
+ await useOnboardingStore.getState().goToStep('private-download');
+ await useOnboardingStore.getState().chooseMode('cloud', 'private-download');
+ const saved = service.setProgress.mock.calls.at(-1)?.[0];
+ service.getProgress.mockResolvedValue(saved!);
+ useOnboardingStore.setState(useOnboardingStore.getInitialState());
+ await useOnboardingStore.getState().hydrate();
+ expect(useOnboardingStore.getState().currentStep).toBe('paywall');
+ await useOnboardingStore.getState().goNext('paywall');
+ expect(useOnboardingStore.getState().currentStep).toBe('notifications');
+});
- expect(useOnboardingStore.getState().currentStep).toBe('language');
- });
+const legacyProgress = (step: string) => ({
+ step,
+ keyboardInstalled: true,
+ permissionsGranted: { microphone: true, notifications: false },
+});
- it('restores a persisted ATT request attempt when resuming onboarding', async () => {
- mockedService.isOnboardingComplete.mockResolvedValue(false);
- mockedService.hasAttemptedTrackingAuthorizationRequest.mockResolvedValue(true);
- mockedService.getProgress.mockResolvedValue({
- step: 'tracking-permission',
- keyboardInstalled: true,
- permissionsGranted: { microphone: true, notifications: true },
+// Main offered the paywall and logged the tutorial after graduation, so installs that update
+// before reaching it still owe both.
+it.each([
+ ['language', 'paywall', 'language', false, false],
+ ['notifications', 'paywall', 'notifications', false, false],
+ ['graduation', 'paywall', 'create-account', false, false],
+ ['paywall', 'paywall', 'create-account', false, true],
+ ['create-account', 'create-account', 'language', true, true],
+ ['tracking-permission', 'tracking-permission', 'language', true, true],
+] as const)(
+ 'resumes a legacy Cloud install at %s on %s, next %s',
+ async (step, currentStep, paywallNextStep, paywallHandled, tutorialCompleted) => {
+ service.getProgress.mockResolvedValue(legacyProgress(step));
+ await useOnboardingStore.getState().hydrate();
+ expect(useOnboardingStore.getState()).toMatchObject({
+ currentStep,
+ selectedMode: 'cloud',
+ paywallNextStep,
+ paywallHandled,
+ tutorialCompleted,
});
-
+ },
+);
+
+it.each([
+ ['language', 'language', false],
+ ['notifications', 'notifications', false],
+ ['graduation', 'create-account', false],
+ ['paywall', 'create-account', true],
+] as const)(
+ 'resumes a legacy Local install at %s on %s without an offer',
+ async (step, currentStep, tutorialCompleted) => {
+ mockConfig = { defaultMode: 'private' };
+ service.getProgress.mockResolvedValue(legacyProgress(step));
await useOnboardingStore.getState().hydrate();
-
expect(useOnboardingStore.getState()).toMatchObject({
- currentStep: 'tracking-permission',
- trackingAuthorizationRequestAttempted: true,
+ currentStep,
+ selectedMode: 'private',
+ tutorialCompleted,
});
- });
+ },
+);
+
+it('sends a legacy install from its owed offer on to the account step, logging the tutorial once', async () => {
+ service.getProgress.mockResolvedValue(legacyProgress('graduation'));
+ await useOnboardingStore.getState().hydrate();
+ await useOnboardingStore.getState().goNext('paywall');
+ await useOnboardingStore.getState().goNext('create-account');
+ expect(useOnboardingStore.getState().currentStep).toBe('tracking-permission');
+ expect(logTutorialCompletion).toHaveBeenCalledTimes(1);
+});
- it('walks graduation into the paywall rather than finishing', async () => {
- await advanceTo('graduation');
- await useOnboardingStore.getState().goNext();
+it('logs the tutorial for a legacy install that resumes past the tone preview', async () => {
+ service.getProgress.mockResolvedValue(legacyProgress('privacy-mode'));
+ await useOnboardingStore.getState().hydrate();
+ await useOnboardingStore.getState().chooseMode('private', 'privacy-mode');
+ await useOnboardingStore.getState().goNext('language');
+ expect(logTutorialCompletion).toHaveBeenCalledTimes(1);
+});
- expect(useOnboardingStore.getState().currentStep).toBe('paywall');
- expect(useOnboardingStore.getState().finished).toBe(false);
- expect(mockedService.completeOnboarding).not.toHaveBeenCalled();
+it('preserves a legacy local download and does not replay earlier steps', async () => {
+ service.getProgress.mockResolvedValue({
+ step: 'private-download',
+ keyboardInstalled: true,
+ permissionsGranted: { microphone: true, notifications: false },
});
-
- it('walks the paywall into account creation', async () => {
- await advanceTo('paywall');
- await useOnboardingStore.getState().goNext();
-
- expect(useOnboardingStore.getState().currentStep).toBe('create-account');
- expect(useOnboardingStore.getState().finished).toBe(false);
+ await useOnboardingStore.getState().hydrate();
+ expect(useOnboardingStore.getState()).toMatchObject({
+ currentStep: 'private-download',
+ selectedMode: 'private',
+ paywallHandled: false,
});
+});
- it('walks account creation into tracking permission without finishing', async () => {
- await advanceTo('create-account');
- await useOnboardingStore.getState().goNext();
-
- expect(useOnboardingStore.getState().currentStep).toBe('tracking-permission');
- expect(useOnboardingStore.getState().finished).toBe(false);
- expect(mockedService.completeOnboarding).not.toHaveBeenCalled();
+it('resumes an owed offer that leads to the account step after a relaunch', async () => {
+ service.getProgress.mockResolvedValue({
+ version: 3,
+ step: 'paywall',
+ selectedMode: 'cloud',
+ paywallNextStep: 'create-account',
+ keyboardInstalled: true,
+ permissionsGranted: { microphone: true, notifications: false },
});
+ await useOnboardingStore.getState().hydrate();
+ await useOnboardingStore.getState().goNext('paywall');
+ expect(useOnboardingStore.getState().currentStep).toBe('create-account');
+});
- it('only completes onboarding once the tracking step finishes', async () => {
- await advanceTo('tracking-permission');
- await useOnboardingStore.getState().goNext();
-
- // tracking-permission is terminal: goNext is a no-op, finish() is the only exit.
- expect(useOnboardingStore.getState().currentStep).toBe('tracking-permission');
- expect(useOnboardingStore.getState().finished).toBe(false);
+it('does not restart completed installs', async () => {
+ service.isOnboardingComplete.mockResolvedValue(true);
+ await useOnboardingStore.getState().hydrate();
+ expect(useOnboardingStore.getState().finished).toBe(true);
+ expect(service.getProgress).not.toHaveBeenCalled();
+});
- await useOnboardingStore.getState().finish();
+// The optional download shares the language step's number, so choosing Local never grows the total.
+it('counts only teaching screens and gives the local download the language step number', () => {
+ expect(getStepProgress('microphone')).toEqual({ current: 1, total: 9 });
+ expect(getStepProgress('voice-agent')).toEqual({ current: 5, total: 9 });
+ expect(getStepProgress('tone')).toEqual({ current: 6, total: 9 });
+ expect(getStepProgress('language')).toEqual({ current: 8, total: 9 });
+ expect(getStepProgress('private-download')).toEqual({ current: 8, total: 9 });
+ expect(getStepProgress('notifications')).toEqual({ current: 9, total: 9 });
+ expect(getStepProgress('paywall')).toBeUndefined();
+});
- expect(mockedService.completeOnboarding).toHaveBeenCalledTimes(1);
- expect(useOnboardingStore.getState().finished).toBe(true);
+it.each([
+ ['voice-agent', 'tone'],
+ ['privacy-mode', 'privacy-mode'],
+ ['paywall', 'paywall'],
+ ['graduation', 'graduation'],
+] as const)('preserves version 2 progress at %s as %s', async (step, expected) => {
+ service.getProgress.mockResolvedValue({
+ version: 2,
+ step,
+ selectedMode: 'private',
+ paywallHandled: false,
+ paywallNextStep: 'notifications',
+ keyboardInstalled: true,
+ permissionsGranted: { microphone: true, notifications: false },
});
-
- it('persists the ATT attempt before the system request can run', async () => {
- await advanceTo('tracking-permission');
-
- await useOnboardingStore.getState().markTrackingAuthorizationRequestAttempted();
-
- expect(useOnboardingStore.getState().trackingAuthorizationRequestAttempted).toBe(true);
- expect(mockedService.markTrackingAuthorizationRequestAttempted).toHaveBeenCalledTimes(1);
+ await useOnboardingStore.getState().hydrate();
+ expect(useOnboardingStore.getState()).toMatchObject({
+ currentStep: expected,
+ selectedMode: 'private',
+ paywallHandled: false,
+ paywallNextStep: 'notifications',
});
+});
- it('keeps the ATT request attempt when onboarding is reset', async () => {
- mockedService.hasAttemptedTrackingAuthorizationRequest.mockResolvedValue(true);
- useOnboardingStore.setState({ trackingAuthorizationRequestAttempted: false });
-
- await useOnboardingStore.getState().reset();
-
- expect(useOnboardingStore.getState().trackingAuthorizationRequestAttempted).toBe(true);
- expect(mockedService.hasAttemptedTrackingAuthorizationRequest).toHaveBeenCalledTimes(1);
+it('completes teaching once at the preview, but only finishes onboarding at graduation', async () => {
+ await useOnboardingStore.getState().goToStep('voice-agent');
+ await useOnboardingStore.getState().goNext('voice-agent');
+ expect(useOnboardingStore.getState().currentStep).toBe('tone');
+ expect(logTutorialCompletion).not.toHaveBeenCalled();
+ await useOnboardingStore.getState().goNext('tone');
+ await useOnboardingStore.getState().goBack('privacy-mode');
+ await useOnboardingStore.getState().goNext('tone');
+ expect(logTutorialCompletion).toHaveBeenCalledTimes(1);
+ await useOnboardingStore.getState().goToStep('tracking-permission');
+ await useOnboardingStore.getState().goNext('tracking-permission');
+ expect(useOnboardingStore.getState()).toMatchObject({
+ currentStep: 'graduation',
+ finished: false,
});
+ await useOnboardingStore.getState().finish();
+ expect(useOnboardingStore.getState().finished).toBe(true);
+});
- it('counts only the teaching steps, not the intro or closing screens', () => {
- const total = getStepProgress('welcome').total;
-
- expect(getStepProgress('welcome').current).toBe(1);
- expect(getStepProgress('notifications').current).toBe(total);
- // Uncounted screens clamp to 1 rather than reporting a bogus position.
- for (const step of [
- 'get-started',
- 'security-first',
- 'graduation',
- 'paywall',
- 'create-account',
- 'tracking-permission',
- ] as const) {
- expect(getStepProgress(step).current).toBe(1);
+it.each(['cloud', 'private'] as const)(
+ 'completes the %s route through optional account and tracking',
+ async (mode) => {
+ await useOnboardingStore.getState().goToStep('privacy-mode');
+ await useOnboardingStore.getState().chooseMode(mode, 'privacy-mode');
+ if (mode === 'cloud') await useOnboardingStore.getState().goNext('paywall');
+ await useOnboardingStore.getState().goNext('language');
+ if (mode === 'private') await useOnboardingStore.getState().goNext('private-download');
+ for (const from of ['notifications', 'create-account', 'tracking-permission'] as const) {
+ expect(useOnboardingStore.getState().currentStep).toBe(from);
+ await useOnboardingStore.getState().goNext(from);
}
+ expect(useOnboardingStore.getState().currentStep).toBe('graduation');
+ expect(service.completeOnboarding).not.toHaveBeenCalled();
+ },
+);
+
+it('keeps resolved offers and confirmed choices across a relaunch and backward navigation', async () => {
+ await useOnboardingStore.getState().goToStep('privacy-mode');
+ await useOnboardingStore.getState().chooseMode('cloud', 'privacy-mode');
+ await useOnboardingStore.getState().goNext('paywall');
+ service.getProgress.mockResolvedValue(service.setProgress.mock.calls.at(-1)![0]);
+ useOnboardingStore.setState(useOnboardingStore.getInitialState());
+ await useOnboardingStore.getState().hydrate();
+ await useOnboardingStore.getState().goBack('language');
+ await useOnboardingStore.getState().goBack('privacy-mode');
+ await useOnboardingStore.getState().goBack('tone');
+ await useOnboardingStore.getState().goBack('voice-agent');
+ expect(useOnboardingStore.getState()).toMatchObject({
+ currentStep: 'dictation-email',
+ selectedMode: 'cloud',
+ paywallHandled: true,
+ });
+ await useOnboardingStore.getState().goToStep('privacy-mode');
+ await useOnboardingStore.getState().chooseMode('cloud', 'privacy-mode');
+ expect(useOnboardingStore.getState().currentStep).toBe('language');
+});
+
+it('preserves the tracking request marker when resetting setup', async () => {
+ useOnboardingStore.setState({
+ finished: true,
+ paywallHandled: true,
+ selectedMode: 'private',
+ trackingAuthorizationRequestAttempted: true,
+ });
+ await useOnboardingStore.getState().reset();
+ expect(useOnboardingStore.getState()).toMatchObject({
+ currentStep: 'get-started',
+ finished: false,
+ selectedMode: null,
+ paywallHandled: false,
+ trackingAuthorizationRequestAttempted: true,
});
});
diff --git a/openwhispr-mobile/src/store/useModelDownloadStore.ts b/openwhispr-mobile/src/store/useModelDownloadStore.ts
index 0e57d1d52..6d739bdcb 100644
--- a/openwhispr-mobile/src/store/useModelDownloadStore.ts
+++ b/openwhispr-mobile/src/store/useModelDownloadStore.ts
@@ -23,11 +23,15 @@ interface ModelDownloadState {
completedCount: number;
startDownload: (key?: LocalModelKey) => Promise<void>;
cancelDownload: (key: LocalModelKey) => Promise<void>;
+ cancelActiveDownloads: (except?: LocalModelKey) => Promise<void>;
reset: (key?: LocalModelKey) => void;
}
const idleEntry = (): ModelDownloadEntry => ({ status: 'idle', progress: 0, error: undefined });
+const isActive = (entry: ModelDownloadEntry): boolean =>
+ entry.status === 'downloading' || entry.status === 'preparing';
+
const idleDownloads = (): Record<LocalModelKey, ModelDownloadEntry> => ({
'whisper-base': idleEntry(),
'parakeet-v2': idleEntry(),
@@ -165,10 +169,7 @@ export const useModelDownloadStore = create<ModelDownloadState>((set, get) => {
completedCount: 0,
startDownload: async (key = 'whisper-base') => {
- const busy = Object.values(get().downloads).some(
- (entry) => entry.status === 'downloading' || entry.status === 'preparing',
- );
- if (busy) {
+ if (Object.values(get().downloads).some(isActive)) {
return;
}
const requestId = beginRequest(key);
@@ -203,6 +204,14 @@ export const useModelDownloadStore = create<ModelDownloadState>((set, get) => {
}
},
+ cancelActiveDownloads: async (except) => {
+ const { downloads, cancelDownload } = get();
+ const active = (Object.keys(downloads) as LocalModelKey[]).filter(
+ (key) => key !== except && isActive(downloads[key]),
+ );
+ await Promise.all(active.map(cancelDownload));
+ },
+
reset: (key) => {
if (key) {
beginRequest(key);
diff --git a/openwhispr-mobile/src/store/useOnboardingStore.ts b/openwhispr-mobile/src/store/useOnboardingStore.ts
index 37abbd7d5..eca385edc 100644
--- a/openwhispr-mobile/src/store/useOnboardingStore.ts
+++ b/openwhispr-mobile/src/store/useOnboardingStore.ts
@@ -1,10 +1,13 @@
import { create } from 'zustand';
import {
FIRST_ONBOARDING_STEP,
+ ONBOARDING_VERSION,
OnboardingService,
type OnboardingProgress,
} from '@/utils/onboarding';
import { logTutorialCompletion } from '@/lib/appsflyer';
+import { useConfigStore } from './useConfigStore';
+import type { ProcessingMode } from '@/types';
export type OnboardingStepId =
| 'get-started'
@@ -14,21 +17,17 @@ export type OnboardingStepId =
| 'keyboard-intro'
| 'keyboard-switch'
| 'dictation-email'
+ | 'voice-agent'
+ | 'tone'
| 'privacy-mode'
+ | 'paywall'
| 'language'
| 'private-download'
| 'notifications'
- | 'graduation'
- | 'paywall'
| 'create-account'
- | 'tracking-permission';
-
-// Language comes BEFORE the model download so the download step can pick the right
-// on-device model (Parakeet v2/v3 vs Whisper) from the user's language selection.
-//
-// The closing sequence is deliberate: the user experiences the whole product
-// first, then sees the paywall and account screen. Tracking permission is the
-// final optional system decision before onboarding is persisted.
+ | 'tracking-permission'
+ | 'graduation';
+
export const STEP_ORDER: readonly OnboardingStepId[] = [
'get-started',
'security-first',
@@ -37,43 +36,107 @@ export const STEP_ORDER: readonly OnboardingStepId[] = [
'keyboard-intro',
'keyboard-switch',
'dictation-email',
+ 'voice-agent',
+ 'tone',
'privacy-mode',
+ 'paywall',
'language',
'private-download',
'notifications',
+ 'create-account',
+ 'tracking-permission',
'graduation',
+];
+
+const UNCOUNTED_STEPS = new Set<OnboardingStepId>([
+ 'get-started',
+ 'security-first',
+ 'welcome',
'paywall',
'create-account',
'tracking-permission',
-] as const;
-
-// The "Step N of M" counter covers the teaching steps only. The intro screens
-// and the closing sequence (graduation → paywall → account → tracking) stay
-// uncounted, so the range is pinned to named endpoints rather than offsets.
-const MIDDLE_STEPS = STEP_ORDER.slice(
- STEP_ORDER.indexOf('welcome'),
- STEP_ORDER.indexOf('graduation'),
+ 'graduation',
+]);
+const BACK_DESTINATIONS: Partial<Record<OnboardingStepId, OnboardingStepId>> = {
+ 'voice-agent': 'dictation-email',
+ tone: 'voice-agent',
+ 'privacy-mode': 'tone',
+ language: 'privacy-mode',
+ 'private-download': 'language',
+};
+
+export function getOnboardingRoute(mode: ProcessingMode | null): OnboardingStepId[] {
+ return STEP_ORDER.filter((step) =>
+ step === 'private-download' ? mode === 'private' : step !== 'paywall',
+ );
+}
+
+// The optional download shares the language step's number so choosing Local doesn't grow the total.
+const COUNTED_STEPS = STEP_ORDER.filter(
+ (step) => !UNCOUNTED_STEPS.has(step) && step !== 'private-download',
);
-export function getStepProgress(stepId: OnboardingStepId): { current: number; total: number } {
- const idx = MIDDLE_STEPS.indexOf(stepId);
- return { current: Math.max(idx + 1, 1), total: MIDDLE_STEPS.length };
+export function getStepProgress(
+ stepId: OnboardingStepId,
+): { current: number; total: number } | undefined {
+ const index = COUNTED_STEPS.indexOf(stepId === 'private-download' ? 'language' : stepId);
+ return index < 0 ? undefined : { current: index + 1, total: COUNTED_STEPS.length };
+}
+
+const PAYWALL_NEXT_STEPS = ['language', 'notifications', 'create-account'] as const;
+export type PaywallNextStep = (typeof PAYWALL_NEXT_STEPS)[number];
+
+function isPaywallNextStep(step: string | undefined): step is PaywallNextStep {
+ return (PAYWALL_NEXT_STEPS as readonly (string | undefined)[]).includes(step);
+}
+
+// Main ran privacy-mode → language → [private-download] → notifications → graduation → paywall →
+// create-account → tracking-permission, and logged the tutorial and offered the paywall only after
+// graduation. Installs that update partway resume on the new route still owed both.
+const LEGACY_POST_CHOICE_STEPS: readonly OnboardingStepId[] = [
+ 'language',
+ 'private-download',
+ 'notifications',
+ 'graduation',
+ 'paywall',
+ 'create-account',
+ 'tracking-permission',
+];
+
+function resumeLegacyChoice(
+ step: OnboardingStepId,
+ mode: ProcessingMode,
+): Pick<
+ OnboardingStore,
+ 'currentStep' | 'paywallHandled' | 'paywallNextStep' | 'tutorialCompleted'
+> {
+ const tutorialCompleted =
+ step === 'paywall' || step === 'create-account' || step === 'tracking-permission';
+ const paywallHandled = tutorialCompleted && step !== 'paywall';
+ const resume = step === 'graduation' || step === 'paywall' ? 'create-account' : step;
+ if (mode === 'cloud' && !paywallHandled && isPaywallNextStep(resume)) {
+ return { currentStep: 'paywall', paywallNextStep: resume, paywallHandled, tutorialCompleted };
+ }
+ return { currentStep: resume, paywallNextStep: 'language', paywallHandled, tutorialCompleted };
}
interface OnboardingStore {
hydrated: boolean;
finished: boolean;
+ transitioning: boolean;
currentStep: OnboardingStepId;
+ selectedMode: ProcessingMode | null;
+ paywallHandled: boolean;
+ paywallNextStep: PaywallNextStep;
+ tutorialCompleted: boolean;
keyboardInstalled: boolean;
trackingAuthorizationRequestAttempted: boolean;
- permissionsGranted: {
- microphone: boolean;
- notifications: boolean;
- };
-
+ permissionsGranted: { microphone: boolean; notifications: boolean };
hydrate: () => Promise<void>;
goToStep: (step: OnboardingStepId) => Promise<void>;
- goNext: () => Promise<void>;
+ goNext: (from: OnboardingStepId) => Promise<void>;
+ goBack: (from: OnboardingStepId) => Promise<void>;
+ chooseMode: (mode: ProcessingMode, from: 'privacy-mode' | 'private-download') => Promise<void>;
setKeyboardInstalled: (installed: boolean) => Promise<void>;
markTrackingAuthorizationRequestAttempted: () => Promise<void>;
setPermissionGranted: (
@@ -86,7 +149,12 @@ interface OnboardingStore {
function snapshot(state: OnboardingStore): OnboardingProgress {
return {
+ version: ONBOARDING_VERSION,
step: state.currentStep,
+ selectedMode: state.selectedMode,
+ paywallHandled: state.paywallHandled,
+ paywallNextStep: state.paywallNextStep,
+ tutorialCompleted: state.tutorialCompleted,
keyboardInstalled: state.keyboardInstalled,
permissionsGranted: state.permissionsGranted,
};
@@ -94,111 +162,156 @@ function snapshot(state: OnboardingStore): OnboardingProgress {
let finishInFlight: Promise<void> | null = null;
-export const useOnboardingStore = create<OnboardingStore>((set, get) => ({
- hydrated: false,
- finished: false,
- currentStep: FIRST_ONBOARDING_STEP,
- keyboardInstalled: false,
- trackingAuthorizationRequestAttempted: false,
- permissionsGranted: {
- microphone: false,
- notifications: false,
- },
-
- hydrate: async () => {
- const [finished, trackingAuthorizationRequestAttempted] = await Promise.all([
- OnboardingService.isOnboardingComplete(),
- OnboardingService.hasAttemptedTrackingAuthorizationRequest(),
- ]);
- if (finished) {
- set({ hydrated: true, finished: true, trackingAuthorizationRequestAttempted });
- return;
+export const useOnboardingStore = create<OnboardingStore>((set, get) => {
+ const transition = async (
+ from: OnboardingStepId,
+ updates: Partial<OnboardingStore>,
+ ): Promise<void> => {
+ if (get().currentStep !== from || get().transitioning || get().finished) return;
+ set({ transitioning: true });
+ try {
+ await OnboardingService.setProgress(snapshot({ ...get(), ...updates }));
+ set(updates);
+ } finally {
+ set({ transitioning: false });
}
- const progress = await OnboardingService.getProgress();
- const step = (STEP_ORDER as readonly string[]).includes(progress.step)
- ? (progress.step as OnboardingStepId)
- : FIRST_ONBOARDING_STEP;
- set({
- hydrated: true,
- finished: false,
- currentStep: step,
- keyboardInstalled: progress.keyboardInstalled,
- trackingAuthorizationRequestAttempted,
- permissionsGranted: progress.permissionsGranted,
- });
- },
-
- goToStep: async (step) => {
- set({ currentStep: step });
- await OnboardingService.setProgress(snapshot(get()));
- },
-
- goNext: async () => {
- const { currentStep, keyboardInstalled, permissionsGranted } = get();
- const idx = STEP_ORDER.indexOf(currentStep);
- if (idx === -1 || idx === STEP_ORDER.length - 1) return;
- const next = STEP_ORDER[idx + 1];
- set({ currentStep: next });
- await OnboardingService.setProgress(snapshot(get()));
- // The tutorial ends at graduation. The paywall and account steps after it
- // are a different funnel, so the AppsFlyer milestone fires here rather
- // than on finish() — otherwise everyone who drops at the paywall or the
- // account screen would read as never having finished the tutorial.
- if (currentStep === 'graduation') {
- logTutorialCompletion({
- keyboardInstalled,
- microphonePermissionGranted: permissionsGranted.microphone,
+ };
+
+ return {
+ hydrated: false,
+ finished: false,
+ transitioning: false,
+ currentStep: FIRST_ONBOARDING_STEP,
+ selectedMode: null,
+ paywallHandled: false,
+ paywallNextStep: 'language',
+ tutorialCompleted: false,
+ keyboardInstalled: false,
+ trackingAuthorizationRequestAttempted: false,
+ permissionsGranted: { microphone: false, notifications: false },
+
+ hydrate: async () => {
+ const [finished, trackingAuthorizationRequestAttempted] = await Promise.all([
+ OnboardingService.isOnboardingComplete(),
+ OnboardingService.hasAttemptedTrackingAuthorizationRequest(),
+ ]);
+ if (finished) {
+ set({ hydrated: true, finished: true, trackingAuthorizationRequestAttempted });
+ return;
+ }
+ const progress = await OnboardingService.getProgress();
+ let step = STEP_ORDER.includes(progress.step as OnboardingStepId)
+ ? (progress.step as OnboardingStepId)
+ : FIRST_ONBOARDING_STEP;
+ const legacy = (progress.version ?? 1) < 2;
+ // Version 2 used this identifier for the combined agent/tone preview.
+ if (progress.version === 2 && step === 'voice-agent') step = 'tone';
+ const resumed = {
+ hydrated: true,
+ finished: false,
+ currentStep: step,
+ selectedMode: progress.selectedMode ?? null,
+ paywallHandled: progress.paywallHandled === true,
+ paywallNextStep: isPaywallNextStep(progress.paywallNextStep)
+ ? progress.paywallNextStep
+ : 'language',
+ tutorialCompleted: progress.tutorialCompleted === true,
+ keyboardInstalled: progress.keyboardInstalled,
+ trackingAuthorizationRequestAttempted,
+ permissionsGranted: progress.permissionsGranted,
+ };
+ if (legacy && LEGACY_POST_CHOICE_STEPS.includes(step)) {
+ if (!useConfigStore.getState().config) await useConfigStore.getState().loadConfig();
+ const mode =
+ step === 'private-download'
+ ? 'private'
+ : (useConfigStore.getState().config?.defaultMode ?? 'cloud');
+ set({ ...resumed, selectedMode: mode, ...resumeLegacyChoice(step, mode) });
+ return;
+ }
+ set(resumed);
+ },
+
+ goToStep: async (step) => transition(get().currentStep, { currentStep: step }),
+
+ goNext: async (from) => {
+ const state = get();
+ if (state.currentStep !== from || state.transitioning) return;
+ const route = getOnboardingRoute(state.selectedMode);
+ const next = from === 'paywall' ? state.paywallNextStep : route[route.indexOf(from) + 1];
+ if (!next || from === 'graduation') return;
+ // Legacy installs can resume past the tone preview, so leaving it or any later step counts.
+ const completesTutorial =
+ !state.tutorialCompleted && STEP_ORDER.indexOf(from) >= STEP_ORDER.indexOf('tone');
+ await transition(from, {
+ currentStep: next,
+ paywallHandled: state.paywallHandled || from === 'paywall',
+ tutorialCompleted: state.tutorialCompleted || completesTutorial,
});
- }
- },
-
- setKeyboardInstalled: async (installed) => {
- set({ keyboardInstalled: installed });
- await OnboardingService.setProgress(snapshot(get()));
- },
-
- markTrackingAuthorizationRequestAttempted: async () => {
- set({ trackingAuthorizationRequestAttempted: true });
- await OnboardingService.markTrackingAuthorizationRequestAttempted();
- },
-
- setPermissionGranted: async (key, granted) => {
- set((state) => ({
- permissionsGranted: { ...state.permissionsGranted, [key]: granted },
- }));
- await OnboardingService.setProgress(snapshot(get()));
- },
-
- finish: () => {
- if (get().finished) return Promise.resolve();
- if (finishInFlight) return finishInFlight;
-
- finishInFlight = (async (): Promise<void> => {
- try {
- await OnboardingService.completeOnboarding();
- set({ finished: true });
- } finally {
- finishInFlight = null;
+ if (completesTutorial) {
+ logTutorialCompletion({
+ keyboardInstalled: state.keyboardInstalled,
+ microphonePermissionGranted: state.permissionsGranted.microphone,
+ });
}
- })();
-
- return finishInFlight;
- },
-
- reset: async () => {
- await OnboardingService.resetOnboarding();
- const trackingAuthorizationRequestAttempted =
- get().trackingAuthorizationRequestAttempted ||
- (await OnboardingService.hasAttemptedTrackingAuthorizationRequest());
- set({
- finished: false,
- currentStep: FIRST_ONBOARDING_STEP,
- keyboardInstalled: false,
- trackingAuthorizationRequestAttempted,
- permissionsGranted: {
- microphone: false,
- notifications: false,
- },
- });
- },
-}));
+ },
+
+ goBack: async (from) => {
+ const previous = BACK_DESTINATIONS[from];
+ if (previous) await transition(from, { currentStep: previous });
+ },
+
+ chooseMode: async (mode, from) => {
+ const next = from === 'private-download' ? 'notifications' : 'language';
+ await transition(from, {
+ selectedMode: mode,
+ paywallNextStep: next,
+ currentStep: mode === 'cloud' && !get().paywallHandled ? 'paywall' : next,
+ });
+ },
+
+ setKeyboardInstalled: async (installed) => {
+ set({ keyboardInstalled: installed });
+ await OnboardingService.setProgress(snapshot(get()));
+ },
+ markTrackingAuthorizationRequestAttempted: async () => {
+ await OnboardingService.markTrackingAuthorizationRequestAttempted();
+ set({ trackingAuthorizationRequestAttempted: true });
+ },
+ setPermissionGranted: async (key, granted) => {
+ set((state) => ({ permissionsGranted: { ...state.permissionsGranted, [key]: granted } }));
+ await OnboardingService.setProgress(snapshot(get()));
+ },
+ finish: () => {
+ if (get().finished || get().currentStep !== 'graduation') return Promise.resolve();
+ if (finishInFlight) return finishInFlight;
+ finishInFlight = (async (): Promise<void> => {
+ try {
+ await OnboardingService.completeOnboarding();
+ set({ finished: true });
+ } finally {
+ finishInFlight = null;
+ }
+ })();
+ return finishInFlight;
+ },
+ reset: async () => {
+ await OnboardingService.resetOnboarding();
+ const attempted =
+ get().trackingAuthorizationRequestAttempted ||
+ (await OnboardingService.hasAttemptedTrackingAuthorizationRequest());
+ set({
+ finished: false,
+ transitioning: false,
+ currentStep: FIRST_ONBOARDING_STEP,
+ selectedMode: null,
+ paywallHandled: false,
+ paywallNextStep: 'language',
+ tutorialCompleted: false,
+ keyboardInstalled: false,
+ trackingAuthorizationRequestAttempted: attempted,
+ permissionsGranted: { microphone: false, notifications: false },
+ });
+ },
+ };
+});
diff --git a/openwhispr-mobile/src/utils/onboarding.ts b/openwhispr-mobile/src/utils/onboarding.ts
index 76b81ba30..f8b70a2cb 100644
--- a/openwhispr-mobile/src/utils/onboarding.ts
+++ b/openwhispr-mobile/src/utils/onboarding.ts
@@ -1,7 +1,10 @@
import * as SecureStore from 'expo-secure-store';
// Type-only, so this does not create a runtime cycle with the store, which
// imports this module for values.
-import type { OnboardingStepId } from '@/store/useOnboardingStore';
+import type { OnboardingStepId, PaywallNextStep } from '@/store/useOnboardingStore';
+import type { ProcessingMode } from '@/types';
+
+export const ONBOARDING_VERSION = 3;
const ONBOARDING_COMPLETE_KEY = 'onboarding_complete';
const ONBOARDING_PROGRESS_KEY = 'onboarding_progress';
@@ -11,7 +14,12 @@ const TRACKING_AUTHORIZATION_REQUEST_ATTEMPTED_KEY = 'tracking_authorization_req
export const FIRST_ONBOARDING_STEP: OnboardingStepId = 'get-started';
export interface OnboardingProgress {
+ version?: number;
step: string;
+ selectedMode?: ProcessingMode | null;
+ paywallHandled?: boolean;
+ paywallNextStep?: PaywallNextStep;
+ tutorialCompleted?: boolean;
keyboardInstalled: boolean;
permissionsGranted: {
microphone: boolean;