Skip to content

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

fix(mobile): finish the On-Device switch once Apple Intelligence is ready (#2772)

Chad Piha85cbe3283480
diff --git a/openwhispr-mobile/src/components/settings/InferenceModePicker.tsx b/openwhispr-mobile/src/components/settings/InferenceModePicker.tsx
index e6f54e2f0..8f88f77fb 100644
--- a/openwhispr-mobile/src/components/settings/InferenceModePicker.tsx
+++ b/openwhispr-mobile/src/components/settings/InferenceModePicker.tsx
@@ -11,9 +11,18 @@ type Props = {
onSelect: (mode: InferenceMode) => void;
// Modes this phone can never run, each with the reason shown in place of its description.
unavailable?: Partial<Record<InferenceMode, string>>;
+ // Modes waiting on something outside the app, each with its status shown in place of its
+ // description. They stay tappable.
+ statuses?: Partial<Record<InferenceMode, string>>;
};
-export function InferenceModePicker({ scope, selectedMode, onSelect, unavailable }: Props) {
+export function InferenceModePicker({
+ scope,
+ selectedMode,
+ onSelect,
+ unavailable,
+ statuses,
+}: Props) {
const modes = getInferenceModes(scope);
return (
<SettingsSection title="Mode">
@@ -24,7 +33,7 @@ export function InferenceModePicker({ scope, selectedMode, onSelect, unavailable
icon={opt.icon}
mdIcon={opt.mdIcon}
title={opt.title}
- description={unavailable?.[opt.mode] ?? opt.description}
+ description={unavailable?.[opt.mode] ?? statuses?.[opt.mode] ?? opt.description}
disabled={!!unavailable?.[opt.mode]}
onPress={() => onSelect(opt.mode)}
selected={selectedMode === opt.mode}
diff --git a/openwhispr-mobile/src/lib/__tests__/transcribeAndCleanup.onDeviceCleanup.test.ts b/openwhispr-mobile/src/lib/__tests__/transcribeAndCleanup.onDeviceCleanup.test.ts
index eb3dea242..43c5be727 100644
--- a/openwhispr-mobile/src/lib/__tests__/transcribeAndCleanup.onDeviceCleanup.test.ts
+++ b/openwhispr-mobile/src/lib/__tests__/transcribeAndCleanup.onDeviceCleanup.test.ts
@@ -232,10 +232,13 @@ it('keeps an On-Device transcript raw when cleanup is turned off', async () => {
it.each([
[
'appleIntelligenceOff',
- "Apple Intelligence is turned off in iOS Settings, so this can't run on-device.",
+ "Apple Intelligence is turned off, so this can't run on-device. Turn it on in Settings → Apple Intelligence & Siri.",
],
['disabled', 'Local Apple Intelligence is turned off in AI Models.'],
- ['modelNotReady', 'Apple Intelligence is still preparing its local model. Try again later.'],
+ [
+ 'modelNotReady',
+ 'Apple Intelligence is still downloading its model. Check Settings → Apple Intelligence & Siri, and keep your iPhone on Wi-Fi and charging.',
+ ],
['unavailable', 'Local Apple Intelligence is unavailable on this device.'],
])('says why On-Device cleanup could not run when readiness is %s', async (status, reason) => {
mockReadiness.mockResolvedValue({ status, tokenCounting: false });
diff --git a/openwhispr-mobile/src/lib/__tests__/workflowModeSwitch.test.ts b/openwhispr-mobile/src/lib/__tests__/workflowModeSwitch.test.ts
index 726c1dcaa..34e794be2 100644
--- a/openwhispr-mobile/src/lib/__tests__/workflowModeSwitch.test.ts
+++ b/openwhispr-mobile/src/lib/__tests__/workflowModeSwitch.test.ts
@@ -28,6 +28,7 @@ jest.mock('@/lib/privateMode', () => ({
getPrivateModeUnavailableMessage: () => 'Native modules are missing.',
}));
jest.mock('@/lib/localReasoning', () => ({
+ ...jest.requireActual('@/lib/localReasoning'),
getLocalReasoningReadiness: () => mockLocalReasoningReadiness(),
getLocalReasoningUnavailableMessage: () => 'Apple Intelligence is turned off.',
}));
@@ -112,12 +113,33 @@ it('switches uploads to On-Device with the model picked for them before', async
expect(mockSetActiveMode).not.toHaveBeenCalled();
});
-it('explains why a text workflow cannot run on-device', async () => {
- mockLocalReasoningReadiness.mockResolvedValue({ status: 'appleIntelligenceOff' });
- await expect(switchWorkflowMode('cleanup', 'local')).resolves.toBe('refused');
- expect(alert).toHaveBeenCalledWith('On-Device Unavailable', 'Apple Intelligence is turned off.');
- expect(mockUpdateConfig).not.toHaveBeenCalled();
-});
+// Settings can fix these, so the page finishes the switch once Apple Intelligence is ready.
+it.each(['appleIntelligenceOff', 'modelNotReady'])(
+ 'waits for Apple Intelligence when it is %s',
+ async (status) => {
+ mockLocalReasoningReadiness.mockResolvedValue({ status });
+ await expect(switchWorkflowMode('cleanup', 'local')).resolves.toBe('not-ready');
+ expect(alert).toHaveBeenCalledWith(
+ 'On-Device Unavailable',
+ 'Apple Intelligence is turned off. Keep this page open and On-Device turns on once Apple Intelligence is ready.',
+ );
+ expect(mockUpdateConfig).not.toHaveBeenCalled();
+ },
+);
+
+// Nothing in iOS Settings makes these ready, so the page must not wait for them.
+it.each(['unsupportedDevice', 'disabled', 'unavailable'])(
+ 'refuses a text workflow on-device when Apple Intelligence is %s',
+ async (status) => {
+ mockLocalReasoningReadiness.mockResolvedValue({ status });
+ await expect(switchWorkflowMode('cleanup', 'local')).resolves.toBe('refused');
+ expect(alert).toHaveBeenCalledWith(
+ 'On-Device Unavailable',
+ 'Apple Intelligence is turned off.',
+ );
+ expect(mockUpdateConfig).not.toHaveBeenCalled();
+ },
+);
it('switches a text workflow to On-Device when Apple Intelligence is ready', async () => {
await expect(switchWorkflowMode('notes', 'local')).resolves.toBe('switched');
diff --git a/openwhispr-mobile/src/lib/localReasoning.ts b/openwhispr-mobile/src/lib/localReasoning.ts
index 1251bb365..c37a2d844 100644
--- a/openwhispr-mobile/src/lib/localReasoning.ts
+++ b/openwhispr-mobile/src/lib/localReasoning.ts
@@ -221,9 +221,9 @@ export function getLocalReasoningUnavailableMessage(readiness?: LocalReasoningRe
case 'disabled':
return 'Local Apple Intelligence is turned off in AI Models.';
case 'appleIntelligenceOff':
- return "Apple Intelligence is turned off in iOS Settings, so this can't run on-device.";
+ return "Apple Intelligence is turned off, so this can't run on-device. Turn it on in Settings → Apple Intelligence & Siri.";
case 'modelNotReady':
- return 'Apple Intelligence is still preparing its local model. Try again later.';
+ return 'Apple Intelligence is still downloading its model. Check Settings → Apple Intelligence & Siri, and keep your iPhone on Wi-Fi and charging.';
case 'unavailable':
default:
return 'Local Apple Intelligence is unavailable on this device.';
diff --git a/openwhispr-mobile/src/lib/workflowModeSwitch.ts b/openwhispr-mobile/src/lib/workflowModeSwitch.ts
index 7b09aa8fd..9bc3a6364 100644
--- a/openwhispr-mobile/src/lib/workflowModeSwitch.ts
+++ b/openwhispr-mobile/src/lib/workflowModeSwitch.ts
@@ -10,6 +10,7 @@ import {
} from '@/lib/accountAccess';
import { workflowSaveConfig } from '@/lib/inferenceModes';
import {
+ canRunLocalReasoning,
getLocalReasoningReadiness,
getLocalReasoningUnavailableMessage,
} from '@/lib/localReasoning';
@@ -20,7 +21,8 @@ import { getPrivateModeReadiness, getPrivateModeUnavailableMessage } from '@/lib
type SpeechScope = 'dictation' | 'upload';
// 'needs-model' means the model list was opened because nothing on this phone can run it yet.
-export type ModeSwitchResult = 'switched' | 'needs-model' | 'refused';
+// 'not-ready' means Apple Intelligence is off in iOS Settings or still downloading its model.
+export type ModeSwitchResult = 'switched' | 'needs-model' | 'not-ready' | 'refused';
function isSpeechScope(scope: MobileInferenceScope): scope is SpeechScope {
return scope === 'dictation' || scope === 'upload';
@@ -45,11 +47,19 @@ async function transcriptionModelReady(): Promise<ModeSwitchResult | null> {
return null;
}
-async function appleIntelligenceReady(): Promise<boolean> {
+async function appleIntelligenceReady(): Promise<ModeSwitchResult | null> {
const readiness = await getLocalReasoningReadiness({ refresh: true });
- if (readiness.status === 'ready') return true;
- Alert.alert('On-Device Unavailable', getLocalReasoningUnavailableMessage(readiness));
- return false;
+ if (readiness.status === 'ready') return null;
+ const message = getLocalReasoningUnavailableMessage(readiness);
+ if (!canRunLocalReasoning(readiness)) {
+ Alert.alert('On-Device Unavailable', message);
+ return 'refused';
+ }
+ Alert.alert(
+ 'On-Device Unavailable',
+ `${message} Keep this page open and On-Device turns on once Apple Intelligence is ready.`,
+ );
+ return 'not-ready';
}
// Applies OpenWhispr Cloud or On-Device to a workflow as soon as it is tapped, after its sign-in
@@ -76,9 +86,7 @@ export async function switchWorkflowMode(
if (mode === 'local') {
const blocked = isSpeechScope(scope)
? await transcriptionModelReady()
- : (await appleIntelligenceReady())
- ? null
- : 'refused';
+ : await appleIntelligenceReady();
if (blocked) return blocked;
}
diff --git a/openwhispr-mobile/src/screens/AIModelsScreen.tsx b/openwhispr-mobile/src/screens/AIModelsScreen.tsx
index 9864ace91..3b23d5f41 100644
--- a/openwhispr-mobile/src/screens/AIModelsScreen.tsx
+++ b/openwhispr-mobile/src/screens/AIModelsScreen.tsx
@@ -41,7 +41,7 @@ function localReasoningStatusLabel(readiness: LocalReasoningReadiness | null): s
case 'appleIntelligenceOff':
return 'Apple Intelligence off';
case 'modelNotReady':
- return 'Model not ready';
+ return 'Downloading model';
case 'unavailable':
return 'Not eligible';
case 'unsupportedDevice':
diff --git a/openwhispr-mobile/src/screens/WorkflowSettingsScreen.tsx b/openwhispr-mobile/src/screens/WorkflowSettingsScreen.tsx
index 7ba9ae4ff..9aff7d988 100644
--- a/openwhispr-mobile/src/screens/WorkflowSettingsScreen.tsx
+++ b/openwhispr-mobile/src/screens/WorkflowSettingsScreen.tsx
@@ -1,5 +1,13 @@
import React, { useCallback, useEffect, useRef, useState } from 'react';
-import { ActivityIndicator, Keyboard, Linking, Platform, Pressable, View } from 'react-native';
+import {
+ ActivityIndicator,
+ AppState,
+ Keyboard,
+ Linking,
+ Platform,
+ Pressable,
+ View,
+} from 'react-native';
import { router, useFocusEffect, useLocalSearchParams } from 'expo-router';
import { useHeaderHeight } from '@react-navigation/elements';
import { useNavigation, usePreventRemove } from '@react-navigation/native';
@@ -21,7 +29,7 @@ import { resolveCustomPrompt } from '@/config/prompts/registry';
import { useAuthStore } from '@/store/useAuthStore';
import { useConfigStore } from '@/store/useConfigStore';
import { useProcessingModeStore } from '@/store/useProcessingModeStore';
-import type { UserConfig } from '@/types';
+import type { LocalReasoningReadiness, UserConfig } from '@/types';
import {
type ProviderCredential,
getProviderCredential,
@@ -55,7 +63,7 @@ import {
} from '@/lib/dictationAgent';
import { safeHaptics } from '@/lib/utils';
import { SystemIcon, type LucideIconName } from '@/components/ui/SystemIcon';
-import { switchWorkflowMode } from '@/lib/workflowModeSwitch';
+import { type ModeSwitchResult, switchWorkflowMode } from '@/lib/workflowModeSwitch';
import { getPrivateModeReadiness } from '@/lib/privateMode';
import {
getLocalReasoningReadiness,
@@ -84,6 +92,13 @@ import {
} from '@/lib/mobileProviders';
type Picker = 'provider' | 'model';
+// How often an open page checks whether Apple Intelligence finished downloading its model.
+const APPLE_INTELLIGENCE_POLL_MS = 10_000;
+// Shown on the On-Device row while iOS Settings has Apple Intelligence to finish.
+const APPLE_INTELLIGENCE_STATUSES: Partial<Record<LocalReasoningReadiness['status'], string>> = {
+ appleIntelligenceOff: 'Apple Intelligence is turned off in iOS Settings.',
+ modelNotReady: 'Apple Intelligence is downloading its model.',
+};
const PROVIDER_SETUP_URLS: Record<string, string> = {
openai: 'https://platform.openai.com/api-keys',
groq: 'https://console.groq.com/keys',
@@ -312,7 +327,8 @@ function WorkflowSettings({ scope }: { scope: MobileInferenceScope }): React.JSX
const [configured, setConfigured] = useState(false);
const [busy, setBusy] = useState(false);
const [checking, setChecking] = useState<'test' | 'discover' | null>(null);
- // Set when On-Device was tapped with no model on this phone and the model list opened.
+ // Set when On-Device was tapped with no model on this phone and the model list opened, or
+ // before Apple Intelligence was ready.
const [onDeviceWanted, setOnDeviceWanted] = useState(false);
const [discoveredModels, setDiscoveredModels] = useState<{ id: string; name: string }[]>([]);
const { toast, showToast } = useToast();
@@ -332,29 +348,39 @@ function WorkflowSettings({ scope }: { scope: MobileInferenceScope }): React.JSX
const providerId = provider?.id;
const models = provider?.models.length ? provider.models : discoveredModels;
const speechScope = scope === 'dictation' || scope === 'upload' ? scope : null;
- // On-Device text workflows run on Apple Intelligence, which some iPhones can never run.
- const [onDeviceUnsupported, setOnDeviceUnsupported] = useState<string | null>(null);
+ // On-Device text workflows run on Apple Intelligence, which some iPhones can never run and
+ // others have to finish setting up in iOS Settings, so it's checked again on return to the app.
+ const [appleIntelligence, setAppleIntelligence] = useState<LocalReasoningReadiness | null>(null);
useEffect(() => {
if (speechScope) return undefined;
let cancelled = false;
- getLocalReasoningReadiness()
- .then((readiness) => {
- if (cancelled) return;
- setOnDeviceUnsupported(
- isLocalReasoningUnsupported(readiness)
- ? getLocalReasoningUnavailableMessage(readiness)
- : null,
- );
- })
- .catch(() => undefined);
+ const check = (): void => {
+ getLocalReasoningReadiness({ refresh: true })
+ .then((readiness) => {
+ if (!cancelled) setAppleIntelligence(readiness);
+ })
+ .catch(() => undefined);
+ };
+ check();
+ const appStateSubscription = AppState.addEventListener('change', (state) => {
+ if (state === 'active') check();
+ });
return (): void => {
cancelled = true;
+ appStateSubscription.remove();
};
}, [speechScope]);
+ const onDeviceUnsupported = isLocalReasoningUnsupported(appleIntelligence)
+ ? getLocalReasoningUnavailableMessage(appleIntelligence ?? undefined)
+ : null;
+ const onDeviceStatus = appleIntelligence && APPLE_INTELLIGENCE_STATUSES[appleIntelligence.status];
// Nothing is shown as picked when the On-Device text workflow can never run on this iPhone.
const pickedMode =
!speechScope && onDeviceUnsupported && selection.mode === 'local' ? null : selection.mode;
const modeNote =
+ (onDeviceWanted && !speechScope
+ ? 'Switches to On-Device once Apple Intelligence is ready, while this page stays open.'
+ : undefined) ??
(scope === 'cleanup' && selection.mode === 'local' && onDeviceUnsupported
? ON_DEVICE_CLEANUP_UNSUPPORTED_NOTE
: undefined) ??
@@ -378,6 +404,9 @@ function WorkflowSettings({ scope }: { scope: MobileInferenceScope }): React.JSX
const modeUnavailable: Partial<Record<InferenceMode, string>> = onDeviceUnsupported
? { local: onDeviceUnsupported }
: {};
+ const modeStatuses: Partial<Record<InferenceMode, string>> = onDeviceStatus
+ ? { local: onDeviceStatus }
+ : {};
// Keys are stored per provider (per server for Custom), so every workflow on it shares one.
const keyOwner =
provider?.id === 'custom' ? 'this server' : providerDisplayName(provider?.id ?? '');
@@ -456,23 +485,55 @@ function WorkflowSettings({ scope }: { scope: MobileInferenceScope }): React.JSX
}
// Coming back from the model list with a model downloaded finishes the On-Device switch.
+ // Apple Intelligence is turned on and downloads its model outside the app, so it is also
+ // checked on return to the app and while this page stays open.
useFocusEffect(
useCallback(() => {
if (!onDeviceWanted) return undefined;
let cancelled = false;
- getPrivateModeReadiness()
- .then(async (readiness) => {
- if (cancelled || readiness.status !== 'ready') return;
- setOnDeviceWanted(false);
- if ((await switchWorkflowMode(scope, 'local')) !== 'switched') return;
- setSelection(useConfigStore.getState().config?.inference?.[scope] ?? { mode: 'local' });
- showToast('Switched to On-Device.', 'success');
- })
- .catch(() => undefined);
+ let switching = false;
+ const finishWhenReady = async (): Promise<void> => {
+ let ready: boolean;
+ if (speechScope) {
+ ready = (await getPrivateModeReadiness()).status === 'ready';
+ } else {
+ const readiness = await getLocalReasoningReadiness({ refresh: true });
+ if (!cancelled) setAppleIntelligence(readiness);
+ ready = readiness.status === 'ready';
+ }
+ if (cancelled || switching || !ready) return;
+ switching = true;
+ const result = await switchWorkflowMode(scope, 'local').catch(
+ (): ModeSwitchResult => 'refused',
+ );
+ switching = false;
+ // The switch checks Apple Intelligence again and can find it not ready after all. Its
+ // alert says the page keeps waiting, so the request stays.
+ if (result === 'not-ready') return;
+ setOnDeviceWanted(false);
+ if (result !== 'switched') return;
+ setSelection(useConfigStore.getState().config?.inference?.[scope] ?? { mode: 'local' });
+ showToast('Switched to On-Device.', 'success');
+ };
+ const check = (): void => {
+ finishWhenReady().catch(() => undefined);
+ };
+ check();
+ if (speechScope) {
+ return (): void => {
+ cancelled = true;
+ };
+ }
+ const appStateSubscription = AppState.addEventListener('change', (state) => {
+ if (state === 'active') check();
+ });
+ const poll = setInterval(check, APPLE_INTELLIGENCE_POLL_MS);
return (): void => {
cancelled = true;
+ appStateSubscription.remove();
+ clearInterval(poll);
};
- }, [onDeviceWanted, scope, showToast]),
+ }, [onDeviceWanted, scope, speechScope, showToast]),
);
async function chooseMode(mode: InferenceMode): Promise<void> {
@@ -500,7 +561,7 @@ function WorkflowSettings({ scope }: { scope: MobileInferenceScope }): React.JSX
if (result === 'switched') {
setSelection(useConfigStore.getState().config?.inference?.[scope] ?? { mode });
}
- setOnDeviceWanted(result === 'needs-model');
+ setOnDeviceWanted(result === 'needs-model' || result === 'not-ready');
} finally {
setBusy(false);
}
@@ -766,6 +827,7 @@ function WorkflowSettings({ scope }: { scope: MobileInferenceScope }): React.JSX
selectedMode={pickedMode}
onSelect={chooseMode}
unavailable={modeUnavailable}
+ statuses={modeStatuses}
/>
{modeNote ? <SectionFooter>{modeNote}</SectionFooter> : null}
{selection.mode === 'local' && speechScope ? (
diff --git a/openwhispr-mobile/src/screens/__tests__/AIModelsScreen.test.tsx b/openwhispr-mobile/src/screens/__tests__/AIModelsScreen.test.tsx
index a15974137..03cd6bde2 100644
--- a/openwhispr-mobile/src/screens/__tests__/AIModelsScreen.test.tsx
+++ b/openwhispr-mobile/src/screens/__tests__/AIModelsScreen.test.tsx
@@ -104,6 +104,12 @@ it('keeps the meeting speaker model with the other on-device settings', async ()
await screen.findByText(/Status: Ready/);
});
+it('says Apple Intelligence is downloading its model while it is not ready', async () => {
+ mockReadiness.mockResolvedValue({ status: 'modelNotReady', tokenCounting: false });
+ render(<AIModelsScreen />);
+ await screen.findByText(/Status: Downloading model/);
+});
+
it('removes every saved provider key after confirmation', async () => {
jest
.spyOn(Alert, 'alert')
diff --git a/openwhispr-mobile/src/screens/__tests__/WorkflowSettingsScreen.test.tsx b/openwhispr-mobile/src/screens/__tests__/WorkflowSettingsScreen.test.tsx
index 0f8245de9..88f16b309 100644
--- a/openwhispr-mobile/src/screens/__tests__/WorkflowSettingsScreen.test.tsx
+++ b/openwhispr-mobile/src/screens/__tests__/WorkflowSettingsScreen.test.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { Alert, Keyboard, ScrollView } from 'react-native';
+import { Alert, AppState, Keyboard, ScrollView } from 'react-native';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react-native';
const mockUpdateConfig = jest.fn().mockResolvedValue(undefined);
@@ -23,7 +23,7 @@ let mockStoredPrompt = '';
const mockPush = jest.fn();
const mockSwitchMode = jest.fn();
const mockPrivateReadiness = jest.fn();
-let mockFocusEffect: (() => void) | undefined;
+let mockFocusEffect: (() => (() => void) | undefined) | undefined;
const MockText = require('react-native').Text;
jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
@@ -33,7 +33,7 @@ jest.mock('expo-router', () => ({
router: { push: (...args: unknown[]) => mockPush(...args) },
useLocalSearchParams: () => ({ scope: mockScope }),
// Tests call the latest effect to act out returning to the page.
- useFocusEffect: (effect: () => void) => {
+ useFocusEffect: (effect: () => (() => void) | undefined) => {
mockFocusEffect = effect;
},
}));
@@ -624,6 +624,117 @@ it('forgets a pending On-Device switch once another mode is chosen', async () =>
expect(selectedMode()).toBe('OpenWhispr Cloud');
});
+describe('a text workflow waiting on Apple Intelligence', () => {
+ const WAITING_NOTE =
+ 'Switches to On-Device once Apple Intelligence is ready, while this page stays open.';
+ let appStateListeners: ((state: string) => void)[];
+ let leavePage: (() => void) | undefined;
+
+ beforeEach(() => {
+ appStateListeners = [];
+ jest.spyOn(AppState, 'addEventListener').mockImplementation((_type, listener) => {
+ appStateListeners.push(listener as (state: string) => void);
+ return { remove: jest.fn() } as unknown as ReturnType<typeof AppState.addEventListener>;
+ });
+ mockConfig = { defaultMode: 'cloud', inference: { cleanup: { mode: 'openwhispr' } } };
+ mockScope = 'cleanup';
+ mockSwitchMode.mockResolvedValueOnce('not-ready');
+ mockLocalReadiness.mockResolvedValue({ status: 'modelNotReady', tokenCounting: false });
+ });
+
+ afterEach(() => {
+ leavePage?.();
+ leavePage = undefined;
+ jest.useRealTimers();
+ });
+
+ async function tapOnDevice(): Promise<void> {
+ render(<WorkflowSettingsScreen />);
+ fireEvent.press(screen.getByText('On-Device'));
+ await waitFor(() => expect(mockSwitchMode).toHaveBeenCalledTimes(1));
+ await act(async () => {
+ leavePage = mockFocusEffect?.();
+ });
+ }
+
+ it('says the switch finishes by itself', async () => {
+ await tapOnDevice();
+ expect(screen.getByText(WAITING_NOTE)).toBeTruthy();
+ expect(mockSwitchMode).toHaveBeenCalledTimes(1);
+ expect(selectedMode()).toBe('OpenWhispr Cloud');
+ });
+
+ // Apple Intelligence is turned on and downloads its model in iOS Settings.
+ it('switches once it is ready on return from Settings', async () => {
+ await tapOnDevice();
+ mockLocalReadiness.mockResolvedValue({ status: 'ready', tokenCounting: true });
+ await act(async () => appStateListeners.forEach((listener) => listener('active')));
+ await waitFor(() => expect(mockSwitchMode).toHaveBeenCalledTimes(2));
+ expect(mockSwitchMode).toHaveBeenLastCalledWith('cleanup', 'local');
+ expect(mockLocalReadiness).toHaveBeenLastCalledWith({ refresh: true });
+ expect(await screen.findByTestId('toast-success')).toHaveTextContent('Switched to On-Device.');
+ expect(selectedMode()).toBe('On-Device');
+ });
+
+ it('switches once it is ready while the page stays open', async () => {
+ jest.useFakeTimers();
+ await tapOnDevice();
+ mockLocalReadiness.mockResolvedValue({ status: 'ready', tokenCounting: true });
+ await act(async () => {
+ jest.advanceTimersByTime(10_000);
+ });
+ await waitFor(() => expect(mockSwitchMode).toHaveBeenCalledTimes(2));
+ expect(selectedMode()).toBe('On-Device');
+ });
+
+ // The switch checks Apple Intelligence again, and its alert promises the page keeps waiting.
+ it('keeps waiting when Apple Intelligence is not ready by the time it switches', async () => {
+ await tapOnDevice();
+ mockLocalReadiness.mockResolvedValue({ status: 'ready', tokenCounting: true });
+ mockSwitchMode.mockResolvedValueOnce('not-ready');
+ await act(async () => appStateListeners.forEach((listener) => listener('active')));
+ await waitFor(() => expect(mockSwitchMode).toHaveBeenCalledTimes(2));
+ expect(screen.getByText(WAITING_NOTE)).toBeTruthy();
+ expect(screen.queryByTestId('toast-success')).toBeNull();
+ expect(selectedMode()).toBe('OpenWhispr Cloud');
+
+ await act(async () => appStateListeners.forEach((listener) => listener('active')));
+ await waitFor(() => expect(mockSwitchMode).toHaveBeenCalledTimes(3));
+ expect(await screen.findByTestId('toast-success')).toHaveTextContent('Switched to On-Device.');
+ expect(selectedMode()).toBe('On-Device');
+ expect(screen.queryByText(WAITING_NOTE)).toBeNull();
+ });
+
+ it('stops checking once the page is left', async () => {
+ jest.useFakeTimers();
+ await tapOnDevice();
+ leavePage?.();
+ leavePage = undefined;
+ mockLocalReadiness.mockResolvedValue({ status: 'ready', tokenCounting: true });
+ await act(async () => {
+ appStateListeners.forEach((listener) => listener('active'));
+ jest.advanceTimersByTime(10_000);
+ });
+ expect(mockSwitchMode).toHaveBeenCalledTimes(1);
+ });
+
+ it('stops waiting once another mode is chosen', async () => {
+ await tapOnDevice();
+ await act(async () => {
+ fireEvent.press(screen.getByText('OpenWhispr Cloud'));
+ });
+ expect(screen.queryByText(WAITING_NOTE)).toBeNull();
+
+ // React cleans up the waiting effect and runs the current one, which no longer waits.
+ leavePage?.();
+ leavePage = mockFocusEffect?.();
+ expect(leavePage).toBeUndefined();
+ mockLocalReadiness.mockResolvedValue({ status: 'ready', tokenCounting: true });
+ await act(async () => appStateListeners.forEach((listener) => listener('active')));
+ expect(mockSwitchMode).toHaveBeenCalledTimes(1);
+ });
+});
+
it('shows the on-device model list once On-Device is applied', async () => {
mockConfig = { defaultMode: 'cloud', inference: { upload: { mode: 'openwhispr' } } };
mockScope = 'upload';
@@ -1260,15 +1371,47 @@ describe('an iPhone that cannot run Apple Intelligence', () => {
expect(modeRow('On-Device').props.accessibilityState?.disabled).toBeFalsy();
});
- it('keeps On-Device available while Apple Intelligence is only turned off', async () => {
- mockLocalReadiness.mockResolvedValue({ status: 'appleIntelligenceOff', tokenCounting: false });
+ it.each([
+ ['appleIntelligenceOff', 'Apple Intelligence is turned off in iOS Settings.'],
+ ['modelNotReady', 'Apple Intelligence is downloading its model.'],
+ ])('keeps On-Device available and says why while it is %s', async (status, reason) => {
+ mockLocalReadiness.mockResolvedValue({ status, tokenCounting: false });
mockScope = 'cleanup';
render(<WorkflowSettingsScreen />);
- await act(async () => {});
+ expect(await screen.findByText(reason)).toBeTruthy();
+ expect(screen.queryByText('Text never leaves this phone.')).not.toBeOnTheScreen();
expect(modeRow('On-Device').props.accessibilityState?.disabled).toBeFalsy();
});
+ it('checks again on return to the app, as Apple Intelligence is set up in iOS Settings', async () => {
+ const appStateListeners: ((state: string) => void)[] = [];
+ jest.spyOn(AppState, 'addEventListener').mockImplementation((_type, listener) => {
+ appStateListeners.push(listener as (state: string) => void);
+ return { remove: jest.fn() } as unknown as ReturnType<typeof AppState.addEventListener>;
+ });
+ mockLocalReadiness.mockResolvedValue({ status: 'modelNotReady', tokenCounting: false });
+ mockScope = 'cleanup';
+ render(<WorkflowSettingsScreen />);
+ expect(await screen.findByText('Apple Intelligence is downloading its model.')).toBeTruthy();
+
+ mockLocalReadiness.mockResolvedValue({ status: 'ready', tokenCounting: true });
+ await act(async () => appStateListeners.forEach((listener) => listener('active')));
+ expect(await screen.findByText('Text never leaves this phone.')).toBeTruthy();
+ expect(mockLocalReadiness).toHaveBeenLastCalledWith({ refresh: true });
+ });
+
+ it('shows no Apple Intelligence status on Dictation, which runs its own speech model', async () => {
+ mockLocalReadiness.mockResolvedValue({ status: 'modelNotReady', tokenCounting: false });
+ mockScope = 'dictation';
+ render(<WorkflowSettingsScreen />);
+
+ await act(async () => {});
+ expect(
+ screen.queryByText('Apple Intelligence is downloading its model.'),
+ ).not.toBeOnTheScreen();
+ });
+
it('says Local Mode cleanup is skipped, shows nothing picked and points at Cloud', async () => {
mockActiveMode = 'private';
mockConfig = { defaultMode: 'private', inference: {} };