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): Set every workflow's mode from AI Models (#2344)

Chad Pihae05b6694e7a6
diff --git a/openwhispr-mobile/README.md b/openwhispr-mobile/README.md
index 54135ea2e..0f811eb6a 100644
--- a/openwhispr-mobile/README.md
+++ b/openwhispr-mobile/README.md
@@ -50,7 +50,7 @@ See [CONTRIBUTING.md](./CONTRIBUTING.md) for platform prerequisites, configurati
## Personal provider setup (iOS)
-Open **AI Models → Bring Your Own Key** and tap a workflow. Each workflow (dictation/keyboard, uploads, cleanup, note formatting/titles, and chat/voice assistant) has its own mode; choose **Bring Your Own Key**, then a provider and model. The list shows what each workflow currently runs. This release supports OpenAI, Groq, OpenRouter (text), and any OpenAI-compatible Custom server. Other providers are not offered on mobile yet.
+Open **AI Models** and tap a workflow. Each workflow (dictation/keyboard, uploads, cleanup, note formatting/titles, and chat/voice assistant) has its own mode; choose **Bring Your Own Key**, then a provider and model, and save. The list shows what each workflow currently runs. OpenWhispr Cloud and On-Device apply as soon as you tap them, and On-Device dictation and uploads can each use a specific downloaded model or Automatic. This release supports OpenAI, Groq, OpenRouter (text), and any OpenAI-compatible Custom server. Other providers are not offered on mobile yet.
Enter a provider API key and save. No OpenWhispr account or Pro subscription is required for personal provider use; your provider bills requests separately. Hosted inference and sync retain their existing account requirements. Provider credentials live in device-local secure storage, are not synced, and survive sign-out. Deleting your OpenWhispr account removes them. Remove credential deletes one key; Remove all provider keys deletes every saved key, including keys for Custom endpoints you no longer use. Deleting the app leaves them in the Keychain until the app is installed again; the first launch after a reinstall erases them. After a member of a managed organization signs out, that organization's provider policy keeps applying until another account (not a guest session) signs in and its policy loads, or until Remove all provider keys is used. Removing keys one at a time does not lift it.
diff --git a/openwhispr-mobile/app/(account)/_layout.tsx b/openwhispr-mobile/app/(account)/_layout.tsx
index f3877cf6b..70b441673 100644
--- a/openwhispr-mobile/app/(account)/_layout.tsx
+++ b/openwhispr-mobile/app/(account)/_layout.tsx
@@ -3,7 +3,7 @@ import { Pressable } from 'react-native';
import { SystemIcon } from '@/components/ui/SystemIcon';
import { safeHaptics } from '@/lib/utils';
import { customHeaderStackOptions, glassStackOptions } from '@/config/navigation';
-import { WORKFLOW_LABELS, parseWorkflow } from '@/lib/byokWorkflows';
+import { WORKFLOW_LABELS, parseWorkflow } from '@/lib/aiWorkflows';
// iOS 26 wraps custom header buttons in their own liquid-glass capsule, so this
// back button is a bare chevron — the native bar supplies the glass. Adding our
@@ -44,11 +44,7 @@ export default function AccountLayout() {
<Stack.Screen name="profile" options={{ title: 'Profile', headerLargeTitle: false }} />
<Stack.Screen name="ai-models" options={{ title: 'AI Models', headerLargeTitle: false }} />
<Stack.Screen
- name="providers"
- options={{ title: 'Bring Your Own Key', headerLargeTitle: false }}
- />
- <Stack.Screen
- name="provider-workflow"
+ name="ai-workflow"
options={({ route }) => {
const scope = parseWorkflow((route.params as { scope?: string })?.scope);
return { title: scope ? WORKFLOW_LABELS[scope] : '', headerLargeTitle: false };
@@ -62,22 +58,10 @@ export default function AccountLayout() {
name="keyboard-tone"
options={{ title: 'Keyboard Tone', headerLargeTitle: false }}
/>
- <Stack.Screen
- name="speech-to-text"
- options={{ title: 'Speech to Text', headerLargeTitle: false }}
- />
- <Stack.Screen
- name="dictation-cleanup"
- options={{ title: 'Dictation Cleanup', headerLargeTitle: false }}
- />
<Stack.Screen
name="cleanup-prompt"
options={{ title: 'Cleanup Prompt', headerLargeTitle: false }}
/>
- <Stack.Screen
- name="note-formatting"
- options={{ title: 'Note Formatting', headerLargeTitle: false }}
- />
<Stack.Screen
name="preferences"
options={{ title: 'Preferences', headerLargeTitle: false }}
diff --git a/openwhispr-mobile/app/(account)/ai-workflow.tsx b/openwhispr-mobile/app/(account)/ai-workflow.tsx
new file mode 100644
index 000000000..d68d6f19e
--- /dev/null
+++ b/openwhispr-mobile/app/(account)/ai-workflow.tsx
@@ -0,0 +1 @@
+export { WorkflowSettingsScreen as default } from '@/screens/WorkflowSettingsScreen';
diff --git a/openwhispr-mobile/app/(account)/dictation-cleanup.tsx b/openwhispr-mobile/app/(account)/dictation-cleanup.tsx
deleted file mode 100644
index 35e5de0dd..000000000
--- a/openwhispr-mobile/app/(account)/dictation-cleanup.tsx
+++ /dev/null
@@ -1,2 +0,0 @@
-import DictationCleanupScreen from '@/screens/DictationCleanupScreen';
-export default DictationCleanupScreen;
diff --git a/openwhispr-mobile/app/(account)/note-formatting.tsx b/openwhispr-mobile/app/(account)/note-formatting.tsx
deleted file mode 100644
index c2264511a..000000000
--- a/openwhispr-mobile/app/(account)/note-formatting.tsx
+++ /dev/null
@@ -1,2 +0,0 @@
-import NoteFormattingScreen from '@/screens/NoteFormattingScreen';
-export default NoteFormattingScreen;
diff --git a/openwhispr-mobile/app/(account)/provider-workflow.tsx b/openwhispr-mobile/app/(account)/provider-workflow.tsx
deleted file mode 100644
index 4f0a39f42..000000000
--- a/openwhispr-mobile/app/(account)/provider-workflow.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { ProviderSettingsScreen as default } from '@/screens/ProviderSettingsScreen';
diff --git a/openwhispr-mobile/app/(account)/providers.tsx b/openwhispr-mobile/app/(account)/providers.tsx
deleted file mode 100644
index ed0dc3c6a..000000000
--- a/openwhispr-mobile/app/(account)/providers.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { ByokWorkflowsScreen as default } from '@/screens/ByokWorkflowsScreen';
diff --git a/openwhispr-mobile/app/(account)/speech-to-text.tsx b/openwhispr-mobile/app/(account)/speech-to-text.tsx
deleted file mode 100644
index 1eac2cbd9..000000000
--- a/openwhispr-mobile/app/(account)/speech-to-text.tsx
+++ /dev/null
@@ -1,2 +0,0 @@
-import SpeechToTextScreen from '@/screens/SpeechToTextScreen';
-export default SpeechToTextScreen;
diff --git a/openwhispr-mobile/src/components/notes/NoteActionsMenu.tsx b/openwhispr-mobile/src/components/notes/NoteActionsMenu.tsx
index df17c1caf..843f30512 100644
--- a/openwhispr-mobile/src/components/notes/NoteActionsMenu.tsx
+++ b/openwhispr-mobile/src/components/notes/NoteActionsMenu.tsx
@@ -16,7 +16,7 @@ interface NoteActionsMenuProps {
processing: boolean;
onRunAction: (action: Action) => void;
onManageActions: () => void;
- onAskNote: () => void;
+ onAskNote?: () => void;
askNoteDisabled?: boolean;
onCopyGeneratedNote?: () => void;
onCopyTranscript?: () => void;
@@ -69,13 +69,17 @@ export function NoteActionsMenu({
image: 'slider.horizontal.3',
imageColor: iconColor,
},
- {
- id: ASK_NOTE_ID,
- title: 'Ask about this note',
- image: 'message',
- imageColor: iconColor,
- attributes: { disabled: !hasContent || askNoteDisabled },
- },
+ ...(onAskNote
+ ? [
+ {
+ id: ASK_NOTE_ID,
+ title: 'Ask about this note',
+ image: 'message',
+ imageColor: iconColor,
+ attributes: { disabled: !hasContent || askNoteDisabled },
+ },
+ ]
+ : []),
...(onCopyGeneratedNote
? [
{
@@ -130,7 +134,7 @@ export function NoteActionsMenu({
return;
}
if (id === ASK_NOTE_ID) {
- onAskNote();
+ onAskNote?.();
return;
}
if (id === COPY_GENERATED_NOTE_ID) {
diff --git a/openwhispr-mobile/src/components/settings/InferenceModePicker.tsx b/openwhispr-mobile/src/components/settings/InferenceModePicker.tsx
index 9c237fc23..e239cdd41 100644
--- a/openwhispr-mobile/src/components/settings/InferenceModePicker.tsx
+++ b/openwhispr-mobile/src/components/settings/InferenceModePicker.tsx
@@ -8,18 +8,12 @@ type Props = {
scope: InferenceScope;
selectedMode: InferenceMode;
onSelect: (mode: InferenceMode) => void;
- title?: string;
};
-export function InferenceModePicker({
- scope,
- selectedMode,
- onSelect,
- title = 'Inference Mode',
-}: Props) {
+export function InferenceModePicker({ scope, selectedMode, onSelect }: Props) {
const modes = getInferenceModes(scope);
return (
- <SettingsSection title={title}>
+ <SettingsSection title="Mode">
{modes.map((opt) => (
<SettingsRow
key={opt.mode}
diff --git a/openwhispr-mobile/src/components/settings/ModelLanguagesButton.tsx b/openwhispr-mobile/src/components/settings/ModelLanguagesButton.tsx
new file mode 100644
index 000000000..0fa55d7fb
--- /dev/null
+++ b/openwhispr-mobile/src/components/settings/ModelLanguagesButton.tsx
@@ -0,0 +1,163 @@
+import React, { useState } from 'react';
+import { Modal, Pressable, ScrollView, StyleSheet, View } from 'react-native';
+import { GroupedList } from '@/components/notes/GroupedList';
+import { GlassIconButton } from '@/components/ui/GlassIconButton';
+import { SearchField } from '@/components/ui/SearchField';
+import { SystemIcon } from '@/components/ui/SystemIcon';
+import { Text } from '@/components/ui/Text';
+import {
+ languageByCode,
+ localModelLanguages,
+ LOCAL_MODEL_TITLES,
+ type LocalModelKey,
+} from '@/lib/localModelCatalog';
+import { getPreferredTranscriptionLanguages } from '@/lib/transcriptionLanguage';
+import { localModelCoversLanguages } from '@/services/transcription/localEngine';
+
+// Long enough that finding one language by scrolling is a chore.
+const SEARCH_THRESHOLD = 30;
+
+function SectionTitle({ children }: { children: string }): React.JSX.Element {
+ return (
+ <Text className="px-1 text-[13px] uppercase tracking-wider text-secondaryLabel">
+ {children}
+ </Text>
+ );
+}
+
+function Flag({ flag }: { flag: string }): React.JSX.Element {
+ return <Text className="text-[20px]">{flag}</Text>;
+}
+
+function ModelLanguagesSheet({
+ model,
+ onClose,
+}: {
+ model: LocalModelKey;
+ onClose: () => void;
+}): React.JSX.Element {
+ const [query, setQuery] = useState('');
+ const title = LOCAL_MODEL_TITLES[model];
+ const languages = localModelLanguages(model);
+ const yours = getPreferredTranscriptionLanguages().map(languageByCode);
+ const searchable = languages.length > SEARCH_THRESHOLD;
+ const needle = query.trim().toLowerCase();
+ const shown = needle
+ ? languages.filter((language) => language.label.toLowerCase().includes(needle))
+ : languages;
+
+ return (
+ <Modal visible animationType="slide" presentationStyle="pageSheet" onRequestClose={onClose}>
+ <View className="flex-1 bg-systemBackground">
+ <View className="flex-row items-center justify-between px-6 pb-4 pt-8">
+ <Text className="text-[22px] font-bold text-label">{`${title} Languages`}</Text>
+ <GlassIconButton onPress={onClose} accessibilityLabel="Close">
+ <SystemIcon name="xmark" mdName="X" size={15} color="secondaryLabel" />
+ </GlassIconButton>
+ </View>
+ <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled">
+ {yours.length ? (
+ <View className="gap-2">
+ <SectionTitle>{yours.length > 1 ? 'Your Languages' : 'Your Language'}</SectionTitle>
+ <GroupedList>
+ {yours.map((language) => {
+ const supported = localModelCoversLanguages(model, [language.code]);
+ return (
+ <GroupedList.Row
+ key={language.code}
+ leadingIconSlot={<Flag flag={language.flag} />}
+ accessibilityLabel={`${language.label}, ${supported ? 'supported' : 'not supported'}`}
+ >
+ <View className="flex-row items-center justify-between gap-3">
+ <Text className="text-[17px] text-label">{language.label}</Text>
+ {supported ? (
+ <SystemIcon
+ name="checkmark.circle.fill"
+ mdName="CircleCheck"
+ size={18}
+ color="systemGreen"
+ />
+ ) : (
+ <Text className="text-[15px] text-secondaryLabel">Not supported</Text>
+ )}
+ </View>
+ </GroupedList.Row>
+ );
+ })}
+ </GroupedList>
+ </View>
+ ) : null}
+ <View className="gap-2">
+ <SectionTitle>{`All ${languages.length} Languages`}</SectionTitle>
+ {searchable ? (
+ <View className="flex-row">
+ <SearchField
+ value={query}
+ onChangeText={setQuery}
+ placeholder="Search languages"
+ accessibilityLabel="Search languages"
+ returnKeyType="done"
+ />
+ </View>
+ ) : null}
+ {shown.length ? (
+ <GroupedList>
+ {shown.map((language) => (
+ <GroupedList.Row
+ key={language.code}
+ leadingIconSlot={<Flag flag={language.flag} />}
+ >
+ <Text className="text-[17px] text-label">{language.label}</Text>
+ </GroupedList.Row>
+ ))}
+ </GroupedList>
+ ) : (
+ <Text className="px-1 text-[15px] text-secondaryLabel">No matching languages.</Text>
+ )}
+ {model === 'whisper-base' ? (
+ <Text className="px-1 text-[13px] text-secondaryLabel">
+ Whisper base also detects the spoken language automatically, including many
+ languages not listed here.
+ </Text>
+ ) : null}
+ </View>
+ </ScrollView>
+ </View>
+ </Modal>
+ );
+}
+
+// A small "?" beside a model's language note that lists the languages it covers.
+export function ModelLanguagesButton({
+ model,
+}: {
+ model: LocalModelKey;
+}): React.JSX.Element | null {
+ const [open, setOpen] = useState(false);
+ const bases = new Set(localModelLanguages(model).map(({ code }) => code.split('-')[0]));
+ // A single-language model says so in its note already.
+ if (bases.size < 2) return null;
+ return (
+ <>
+ <Pressable
+ hitSlop={10}
+ accessibilityRole="button"
+ accessibilityLabel={`${LOCAL_MODEL_TITLES[model]} languages`}
+ onPress={() => setOpen(true)}
+ style={({ pressed }) => ({ opacity: pressed ? 0.5 : 1 })}
+ >
+ <SystemIcon
+ name="questionmark.circle"
+ mdName="CircleHelp"
+ size={15}
+ color="secondaryLabel"
+ />
+ </Pressable>
+ {open ? <ModelLanguagesSheet model={model} onClose={() => setOpen(false)} /> : null}
+ </>
+ );
+}
+
+const styles = StyleSheet.create({
+ content: { paddingHorizontal: 24, paddingBottom: 40, gap: 16 },
+});
diff --git a/openwhispr-mobile/src/components/settings/OnDeviceModelSection.tsx b/openwhispr-mobile/src/components/settings/OnDeviceModelSection.tsx
new file mode 100644
index 000000000..07253069b
--- /dev/null
+++ b/openwhispr-mobile/src/components/settings/OnDeviceModelSection.tsx
@@ -0,0 +1,122 @@
+import React, { useCallback, useState } from 'react';
+import { router, useFocusEffect } from 'expo-router';
+import { SettingsRow, SettingsSection } from '@/components/ui/SettingsSection';
+import { ModelLanguagesButton } from '@/components/settings/ModelLanguagesButton';
+import {
+ getLocalModelCatalog,
+ LOCAL_MODEL_TITLES,
+ type LocalModelKey,
+} from '@/lib/localModelCatalog';
+import { getPreferredTranscriptionLanguages } from '@/lib/transcriptionLanguage';
+import { pickLocalModel } from '@/lib/workflowModeSwitch';
+import { LocalTranscriptionService } from '@/services/transcription/LocalTranscriptionService';
+import {
+ localModelCoversLanguages,
+ selectLocalEngine,
+ type LocalEngineAvailability,
+ type LocalEngineChoice,
+} from '@/services/transcription/localEngine';
+import { useModelDownloadStore } from '@/store/useModelDownloadStore';
+
+type Props = {
+ scope: 'dictation' | 'upload';
+ picked: LocalModelKey | undefined;
+};
+
+function modelInUse(choice: LocalEngineChoice): string {
+ if (choice.engine === 'none') return 'No model is downloaded yet.';
+ const key: LocalModelKey =
+ choice.engine === 'whisper' ? 'whisper-base' : `parakeet-${choice.version}`;
+ return `Using ${LOCAL_MODEL_TITLES[key]}.`;
+}
+
+function radio(selected: boolean): { icon: string; mdIcon: 'CircleCheck' | 'Circle' } {
+ return selected
+ ? { icon: 'checkmark.circle.fill', mdIcon: 'CircleCheck' }
+ : { icon: 'circle', mdIcon: 'Circle' };
+}
+
+export function OnDeviceModelSection({ scope, picked }: Props): React.JSX.Element | null {
+ const [availability, setAvailability] = useState<LocalEngineAvailability | null>(null);
+ const completedCount = useModelDownloadStore((state) => state.completedCount);
+
+ // Refresh on return from the download screen, where models are added or deleted.
+ useFocusEffect(
+ useCallback(() => {
+ let cancelled = false;
+ LocalTranscriptionService.getAvailability()
+ .then((next) => {
+ if (!cancelled) setAvailability(next);
+ })
+ .catch(() => {
+ /* The list stays hidden; switching modes already checked the model. */
+ });
+ return (): void => {
+ cancelled = true;
+ };
+ // completedCount re-runs this when a download finishes while this page is open.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [completedCount]),
+ );
+
+ if (!availability) return null;
+ const languages = getPreferredTranscriptionLanguages();
+ const catalog = getLocalModelCatalog(languages, availability);
+ const usable = (key: LocalModelKey): boolean =>
+ !!catalog.find((entry) => entry.key === key)?.downloaded &&
+ localModelCoversLanguages(key, languages);
+ // A pick that is deleted or misses a language runs as Automatic, so show it that way.
+ const effectivePick = picked && usable(picked) ? picked : undefined;
+
+ return (
+ <SettingsSection title="On-Device Model">
+ <SettingsRow
+ {...radio(!effectivePick)}
+ iconStyle="line"
+ title="Automatic"
+ description={`Best downloaded model for your languages. ${modelInUse(selectLocalEngine(languages, availability))}`}
+ selected={!effectivePick}
+ showChevron={false}
+ onPress={() => pickLocalModel(scope, undefined)}
+ />
+ {catalog.map((entry) =>
+ entry.downloaded ? (
+ <SettingsRow
+ key={entry.key}
+ {...radio(effectivePick === entry.key)}
+ iconStyle="line"
+ title={entry.title}
+ description={
+ usable(entry.key)
+ ? entry.languagesNote
+ : `${entry.languagesNote} · Doesn't cover your languages`
+ }
+ descriptionAccessory={<ModelLanguagesButton model={entry.key} />}
+ selected={effectivePick === entry.key}
+ showChevron={false}
+ onPress={usable(entry.key) ? () => pickLocalModel(scope, entry.key) : undefined}
+ />
+ ) : (
+ <SettingsRow
+ key={entry.key}
+ icon="arrow.down.circle"
+ mdIcon="Download"
+ iconStyle="line"
+ title={entry.title}
+ description={entry.languagesNote}
+ descriptionAccessory={<ModelLanguagesButton model={entry.key} />}
+ subtitle="Download"
+ onPress={() => router.push('/(account)/model-download')}
+ />
+ ),
+ )}
+ <SettingsRow
+ icon="externaldrive"
+ mdIcon="HardDrive"
+ iconStyle="line"
+ title="Manage downloads"
+ onPress={() => router.push('/(account)/model-download')}
+ />
+ </SettingsSection>
+ );
+}
diff --git a/openwhispr-mobile/src/components/settings/__tests__/ModelLanguagesButton.test.tsx b/openwhispr-mobile/src/components/settings/__tests__/ModelLanguagesButton.test.tsx
new file mode 100644
index 000000000..73b5ebfae
--- /dev/null
+++ b/openwhispr-mobile/src/components/settings/__tests__/ModelLanguagesButton.test.tsx
@@ -0,0 +1,81 @@
+import React from 'react';
+import { fireEvent, render, screen } from '@testing-library/react-native';
+
+let mockLanguages: string[] = ['fr'];
+
+jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
+jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
+jest.mock('@/components/ui/GlassIconButton', () => ({
+ GlassIconButton: ({
+ onPress,
+ accessibilityLabel,
+ }: {
+ onPress: () => void;
+ accessibilityLabel: string;
+ }) => {
+ const { Pressable } = require('react-native');
+ return <Pressable accessibilityLabel={accessibilityLabel} onPress={onPress} />;
+ },
+}));
+jest.mock('@/lib/transcriptionLanguage', () => ({
+ getPreferredTranscriptionLanguages: () => mockLanguages,
+}));
+
+import { ModelLanguagesButton } from '../ModelLanguagesButton';
+
+beforeEach(() => {
+ mockLanguages = ['fr'];
+});
+
+function openSheet(label: string): void {
+ fireEvent.press(screen.getByLabelText(label));
+}
+
+it('opens the model language list from the question mark', () => {
+ render(<ModelLanguagesButton model="parakeet-v3" />);
+ expect(screen.queryByText('Parakeet v3 Languages')).toBeNull();
+ openSheet('Parakeet v3 languages');
+ expect(screen.getByText('Parakeet v3 Languages')).toBeTruthy();
+ expect(screen.getByText('German')).toBeTruthy();
+ expect(screen.getByText('All 26 Languages')).toBeTruthy();
+});
+
+it('puts the chosen language first and says whether the model supports it', () => {
+ mockLanguages = ['fr', 'he'];
+ render(<ModelLanguagesButton model="parakeet-v3" />);
+ openSheet('Parakeet v3 languages');
+ const page = JSON.stringify(screen.toJSON());
+ expect(page.indexOf('Your Languages')).toBeLessThan(page.indexOf('All 26 Languages'));
+ expect(screen.getByLabelText('French, supported')).toBeTruthy();
+ expect(screen.getByLabelText('Hebrew, not supported')).toBeTruthy();
+});
+
+it('has no chosen-language section for Auto-detect', () => {
+ mockLanguages = [];
+ render(<ModelLanguagesButton model="parakeet-v3" />);
+ openSheet('Parakeet v3 languages');
+ expect(screen.queryByText('Your Language')).toBeNull();
+ expect(screen.queryByText('Your Languages')).toBeNull();
+});
+
+it('searches the long Whisper list and notes its auto-detect', () => {
+ render(<ModelLanguagesButton model="whisper-base" />);
+ openSheet('Whisper base languages');
+ expect(screen.getByText(/also detects the spoken language/)).toBeTruthy();
+ fireEvent.changeText(screen.getByLabelText('Search languages'), 'heb');
+ expect(screen.getByText('Hebrew')).toBeTruthy();
+ expect(screen.queryByText('German')).toBeNull();
+});
+
+it('has no search on a short list', () => {
+ render(<ModelLanguagesButton model="parakeet-v3" />);
+ openSheet('Parakeet v3 languages');
+ expect(screen.queryByLabelText('Search languages')).toBeNull();
+});
+
+it('closes the sheet', () => {
+ render(<ModelLanguagesButton model="parakeet-v3" />);
+ openSheet('Parakeet v3 languages');
+ fireEvent.press(screen.getByLabelText('Close'));
+ expect(screen.queryByText('Parakeet v3 Languages')).toBeNull();
+});
diff --git a/openwhispr-mobile/src/components/settings/__tests__/OnDeviceModelSection.test.tsx b/openwhispr-mobile/src/components/settings/__tests__/OnDeviceModelSection.test.tsx
new file mode 100644
index 000000000..6476984ff
--- /dev/null
+++ b/openwhispr-mobile/src/components/settings/__tests__/OnDeviceModelSection.test.tsx
@@ -0,0 +1,95 @@
+import React from 'react';
+import { fireEvent, render, screen } from '@testing-library/react-native';
+
+const mockPush = jest.fn();
+const mockPickLocalModel = jest.fn().mockResolvedValue(undefined);
+let mockLanguages: string[] = ['en'];
+let mockAvailability = {
+ parakeetSupported: true,
+ parakeetV2Downloaded: true,
+ parakeetV3Downloaded: true,
+ whisperDownloaded: false,
+};
+
+jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
+jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
+jest.mock('expo-router', () => ({
+ router: { push: (...args: unknown[]) => mockPush(...args) },
+ useFocusEffect: (effect: () => void) => require('react').useEffect(effect, [effect]),
+}));
+jest.mock('@/store/useModelDownloadStore', () => ({
+ useModelDownloadStore: (selector: (state: unknown) => unknown) => selector({ completedCount: 0 }),
+}));
+jest.mock('@/lib/transcriptionLanguage', () => ({
+ getPreferredTranscriptionLanguages: () => mockLanguages,
+}));
+jest.mock('@/services/transcription/LocalTranscriptionService', () => ({
+ LocalTranscriptionService: { getAvailability: async () => mockAvailability },
+}));
+jest.mock('@/lib/workflowModeSwitch', () => ({
+ pickLocalModel: (...args: unknown[]) => mockPickLocalModel(...args),
+}));
+
+import { OnDeviceModelSection } from '../OnDeviceModelSection';
+
+function isSelected(title: string): boolean {
+ let row = screen.getByText(title).parent;
+ while (row && !row.props.accessibilityState) row = row.parent;
+ return !!row?.props.accessibilityState?.selected;
+}
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockLanguages = ['en'];
+ mockAvailability = {
+ parakeetSupported: true,
+ parakeetV2Downloaded: true,
+ parakeetV3Downloaded: true,
+ whisperDownloaded: false,
+ };
+});
+
+it('offers the language list for multi-language models only', async () => {
+ render(<OnDeviceModelSection scope="dictation" picked={undefined} />);
+ await screen.findByText('Parakeet v3');
+ expect(screen.getByLabelText('Parakeet v3 languages')).toBeTruthy();
+ expect(screen.getByLabelText('Whisper base languages')).toBeTruthy();
+ expect(screen.queryByLabelText('Parakeet v2 languages')).toBeNull();
+});
+
+it('defaults to Automatic and names the model it is using', async () => {
+ render(<OnDeviceModelSection scope="dictation" picked={undefined} />);
+ expect(await screen.findByText(/Using Parakeet v2/)).toBeTruthy();
+ expect(isSelected('Automatic')).toBe(true);
+});
+
+it('picks a downloaded model for the workflow', async () => {
+ render(<OnDeviceModelSection scope="upload" picked={undefined} />);
+ fireEvent.press(await screen.findByText('Parakeet v3'));
+ expect(mockPickLocalModel).toHaveBeenCalledWith('upload', 'parakeet-v3');
+});
+
+it('shows the picked model as selected and can go back to Automatic', async () => {
+ render(<OnDeviceModelSection scope="dictation" picked="parakeet-v3" />);
+ await screen.findByText('Parakeet v3');
+ expect(isSelected('Parakeet v3')).toBe(true);
+ expect(isSelected('Automatic')).toBe(false);
+ fireEvent.press(screen.getByText('Automatic'));
+ expect(mockPickLocalModel).toHaveBeenCalledWith('dictation', undefined);
+});
+
+it('sends a model that is not downloaded to the download screen', async () => {
+ render(<OnDeviceModelSection scope="dictation" picked={undefined} />);
+ fireEvent.press(await screen.findByText('Whisper base'));
+ expect(mockPush).toHaveBeenCalledWith('/(account)/model-download');
+ expect(mockPickLocalModel).not.toHaveBeenCalled();
+});
+
+it('does not let a model that misses a language be picked, and falls back to Automatic', async () => {
+ mockLanguages = ['fr'];
+ render(<OnDeviceModelSection scope="dictation" picked="parakeet-v2" />);
+ expect(await screen.findByText(/Doesn't cover your languages/)).toBeTruthy();
+ fireEvent.press(screen.getByText('Parakeet v2'));
+ expect(mockPickLocalModel).not.toHaveBeenCalled();
+ expect(isSelected('Automatic')).toBe(true);
+});
diff --git a/openwhispr-mobile/src/components/ui/SettingsSection.tsx b/openwhispr-mobile/src/components/ui/SettingsSection.tsx
index bf02c188d..c5897827d 100644
--- a/openwhispr-mobile/src/components/ui/SettingsSection.tsx
+++ b/openwhispr-mobile/src/components/ui/SettingsSection.tsx
@@ -1,8 +1,9 @@
import React from 'react';
-import { View, Pressable, StyleSheet } from 'react-native';
+import { View, Pressable, StyleSheet, TextInput, type TextInputProps } from 'react-native';
import { Text } from '@/components/ui/Text';
import { SystemIcon, type LucideIconName } from './SystemIcon';
-import { BRAND } from '@/config/colors';
+import { BRAND, iosColor } from '@/config/colors';
+import { SpaceGrotesk } from '@/lib/fonts';
type SettingsRowProps = {
icon: string;
@@ -17,6 +18,8 @@ type SettingsRowProps = {
destructive?: boolean;
showChevron?: boolean;
selected?: boolean;
+ // Shown right after the description, such as a help button.
+ descriptionAccessory?: React.ReactNode;
};
export function SettingsRow({
@@ -32,6 +35,7 @@ export function SettingsRow({
destructive = false,
showChevron = true,
selected = false,
+ descriptionAccessory,
}: SettingsRowProps) {
const isLine = iconStyle === 'line';
return (
@@ -73,7 +77,12 @@ export function SettingsRow({
>
{title}
</Text>
- {description ? (
+ {description && descriptionAccessory ? (
+ <View className="mt-0.5 flex-row items-center gap-1.5">
+ <Text className="flex-shrink text-[13px] text-secondaryLabel">{description}</Text>
+ {descriptionAccessory}
+ </View>
+ ) : description ? (
<Text className="mt-0.5 text-[13px] text-secondaryLabel">{description}</Text>
) : null}
</View>
@@ -94,6 +103,42 @@ export function SettingsRow({
);
}
+type SettingsTextFieldRowProps = TextInputProps & {
+ icon: string;
+ mdIcon?: LucideIconName;
+ label?: string;
+ trailing?: React.ReactNode;
+};
+
+// A text field laid out like a SettingsRow, so it sits in the same card with aligned separators.
+export function SettingsTextFieldRow({
+ icon,
+ mdIcon,
+ label,
+ trailing,
+ editable = true,
+ style,
+ ...inputProps
+}: SettingsTextFieldRowProps) {
+ return (
+ <View className="min-h-[50px] flex-row items-center gap-4 px-4">
+ <View className="h-6 w-6 items-center justify-center">
+ <SystemIcon name={icon} mdName={mdIcon} size={22} color="label" />
+ </View>
+ {label ? <Text className="w-[84px] text-[17px] text-label">{label}</Text> : null}
+ <TextInput
+ placeholderTextColor={iosColor('tertiaryLabel')}
+ autoCorrect={false}
+ editable={editable}
+ className={`flex-1 py-3 text-[17px] text-label ${editable ? '' : 'opacity-40'}`}
+ style={[{ fontFamily: SpaceGrotesk.regular }, style]}
+ {...inputProps}
+ />
+ {trailing}
+ </View>
+ );
+}
+
type SettingsSectionProps = {
title?: string;
borderless?: boolean;
diff --git a/openwhispr-mobile/src/hooks/useToast.ts b/openwhispr-mobile/src/hooks/useToast.ts
new file mode 100644
index 000000000..c8555c10b
--- /dev/null
+++ b/openwhispr-mobile/src/hooks/useToast.ts
@@ -0,0 +1,44 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import type { ToastType } from '@/components/ui/Toast';
+
+const TOAST_MS = 3000;
+// Errors carry something to act on, so they stay long enough to read.
+const ERROR_TOAST_MS = 6000;
+
+export interface ToastState {
+ message: string;
+ type: ToastType;
+ visible: boolean;
+ // Changes on every show, so the same message shown twice still replays.
+ showId: number;
+}
+
+export function useToast(): {
+ toast: ToastState;
+ showToast: (message: string, type: ToastType) => void;
+} {
+ const [toast, setToast] = useState<ToastState>({
+ message: '',
+ type: 'info',
+ visible: false,
+ showId: 0,
+ });
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ useEffect(
+ () => (): void => {
+ if (timer.current) clearTimeout(timer.current);
+ },
+ [],
+ );
+
+ const showToast = useCallback((message: string, type: ToastType): void => {
+ if (timer.current) clearTimeout(timer.current);
+ setToast((current) => ({ message, type, visible: true, showId: current.showId + 1 }));
+ timer.current = setTimeout(
+ () => setToast((current) => ({ ...current, visible: false })),
+ type === 'error' ? ERROR_TOAST_MS : TOAST_MS,
+ );
+ }, []);
+
+ return { toast, showToast };
+}
diff --git a/openwhispr-mobile/src/lib/__tests__/inferenceModes.test.ts b/openwhispr-mobile/src/lib/__tests__/inferenceModes.test.ts
index 171c92d24..8beac0445 100644
--- a/openwhispr-mobile/src/lib/__tests__/inferenceModes.test.ts
+++ b/openwhispr-mobile/src/lib/__tests__/inferenceModes.test.ts
@@ -178,3 +178,17 @@ describe('getInferenceModes', () => {
expect(getInferenceModes('speech').map((mode) => mode.mode)).toEqual(['openwhispr', 'local']);
});
});
+
+it('switches dictation back to On-Device with the model the user picked', () => {
+ const config = {
+ defaultMode: 'cloud' as const,
+ inference: { dictation: { mode: 'openwhispr' as const } },
+ rememberedInference: {
+ dictation: { local: { mode: 'local' as const, modelId: 'parakeet-v3' } },
+ },
+ };
+ expect(dictationModeConfig(config, 'private').inference?.dictation).toEqual({
+ mode: 'local',
+ modelId: 'parakeet-v3',
+ });
+});
diff --git a/openwhispr-mobile/src/lib/__tests__/localModelCatalog.test.ts b/openwhispr-mobile/src/lib/__tests__/localModelCatalog.test.ts
new file mode 100644
index 000000000..6d515f1b1
--- /dev/null
+++ b/openwhispr-mobile/src/lib/__tests__/localModelCatalog.test.ts
@@ -0,0 +1,30 @@
+import { localModelLanguages } from '../localModelCatalog';
+
+const labels = (model: Parameters<typeof localModelLanguages>[0]): string[] =>
+ localModelLanguages(model).map((language) => language.label);
+
+describe('localModelLanguages', () => {
+ it('lists the 25 Parakeet v3 languages, with each English variant the app offers', () => {
+ const languages = localModelLanguages('parakeet-v3');
+ expect(new Set(languages.map((language) => language.code.split('-')[0])).size).toBe(25);
+ expect(labels('parakeet-v3')).toEqual(
+ expect.arrayContaining(['French', 'German', 'English (US)', 'English (UK)']),
+ );
+ expect(labels('parakeet-v3')).not.toContain('Hebrew');
+ });
+
+ it('lists only English for Parakeet v2', () => {
+ expect(labels('parakeet-v2')).toEqual(['English (UK)', 'English (US)']);
+ });
+
+ it('lists every language the app offers for Whisper base, without Auto-detect', () => {
+ expect(labels('whisper-base')).toContain('Hebrew');
+ expect(labels('whisper-base')).not.toContain('Auto-detect');
+ expect(localModelLanguages('whisper-base')).toHaveLength(59);
+ });
+
+ it('sorts languages by name', () => {
+ const names = labels('whisper-base');
+ expect(names).toEqual([...names].sort((a, b) => a.localeCompare(b)));
+ });
+});
diff --git a/openwhispr-mobile/src/lib/__tests__/workflowModeSwitch.test.ts b/openwhispr-mobile/src/lib/__tests__/workflowModeSwitch.test.ts
new file mode 100644
index 000000000..70000613c
--- /dev/null
+++ b/openwhispr-mobile/src/lib/__tests__/workflowModeSwitch.test.ts
@@ -0,0 +1,152 @@
+import { Alert } from 'react-native';
+
+const mockUpdateConfig = jest.fn().mockResolvedValue(undefined);
+const mockSetActiveMode = jest.fn();
+const mockPush = jest.fn();
+const mockPrivateReadiness = jest.fn();
+const mockLocalReasoningReadiness = jest.fn();
+let mockConfig: Record<string, unknown> | null = null;
+let mockUser: Record<string, unknown> | null = { id: 'user-1' };
+
+jest.mock('expo-router', () => ({ router: { push: (...args: unknown[]) => mockPush(...args) } }));
+jest.mock('@/store/useConfigStore', () => ({
+ useConfigStore: {
+ getState: () => ({ config: mockConfig, updateConfig: mockUpdateConfig }),
+ },
+}));
+jest.mock('@/store/useProcessingModeStore', () => ({
+ useProcessingModeStore: { getState: () => ({ setActiveMode: mockSetActiveMode }) },
+}));
+jest.mock('@/store/useAuthStore', () => ({
+ useAuthStore: { getState: () => ({ user: mockUser }) },
+}));
+jest.mock('@/lib/privateMode', () => ({
+ getPrivateModeReadiness: () => mockPrivateReadiness(),
+ getPrivateModeUnavailableMessage: () => 'Native modules are missing.',
+}));
+jest.mock('@/lib/localReasoning', () => ({
+ getLocalReasoningReadiness: () => mockLocalReasoningReadiness(),
+ getLocalReasoningUnavailableMessage: () => 'Apple Intelligence is turned off.',
+}));
+
+import { pickLocalModel, switchWorkflowMode } from '../workflowModeSwitch';
+
+let alert: jest.SpyInstance;
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockConfig = { defaultMode: 'cloud', inference: { dictation: { mode: 'openwhispr' } } };
+ mockUser = { id: 'user-1' };
+ mockPrivateReadiness.mockResolvedValue({ status: 'ready', modelName: 'Parakeet v2' });
+ mockLocalReasoningReadiness.mockResolvedValue({ status: 'ready', tokenCounting: false });
+ alert = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined);
+});
+
+it('asks a signed-out user to sign in before switching to Cloud', async () => {
+ mockUser = null;
+ mockConfig = { defaultMode: 'private' };
+ await expect(switchWorkflowMode('cleanup', 'openwhispr')).resolves.toBe('refused');
+ expect(alert).toHaveBeenCalledWith('Sign in required', expect.any(String), expect.any(Array));
+ expect(mockUpdateConfig).not.toHaveBeenCalled();
+});
+
+it('switches dictation to On-Device along with the app mode', async () => {
+ await expect(switchWorkflowMode('dictation', 'local')).resolves.toBe('switched');
+ expect(mockSetActiveMode).toHaveBeenCalledWith('private', true);
+ expect(mockUpdateConfig).toHaveBeenCalledWith({
+ defaultMode: 'private',
+ inference: { dictation: { mode: 'local' } },
+ });
+});
+
+it('opens the model list when no on-device transcription model is downloaded', async () => {
+ mockPrivateReadiness.mockResolvedValue({ status: 'missing', modelName: 'Parakeet v2' });
+ await expect(switchWorkflowMode('upload', 'local')).resolves.toBe('needs-model');
+ // Every model is offered there, not just the one recommended for the language.
+ expect(alert).not.toHaveBeenCalled();
+ expect(mockPush).toHaveBeenCalledWith('/(account)/model-download');
+ expect(mockUpdateConfig).not.toHaveBeenCalled();
+});
+
+it('switches uploads to On-Device with the model picked for them before', async () => {
+ mockConfig = {
+ defaultMode: 'cloud',
+ inference: { dictation: { mode: 'openwhispr' } },
+ rememberedInference: { upload: { local: { mode: 'local', modelId: 'whisper-base' } } },
+ };
+ await expect(switchWorkflowMode('upload', 'local')).resolves.toBe('switched');
+ expect(mockUpdateConfig).toHaveBeenCalledWith({
+ inference: {
+ dictation: { mode: 'openwhispr' },
+ upload: { mode: 'local', modelId: 'whisper-base' },
+ },
+ });
+ 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();
+});
+
+it('switches a text workflow to On-Device when Apple Intelligence is ready', async () => {
+ await expect(switchWorkflowMode('notes', 'local')).resolves.toBe('switched');
+ expect(mockUpdateConfig).toHaveBeenCalledWith({
+ inference: { dictation: { mode: 'openwhispr' }, notes: { mode: 'local' } },
+ });
+});
+
+it('saves a picked model for the workflow and remembers it for the next switch', async () => {
+ mockConfig = { defaultMode: 'private', inference: { dictation: { mode: 'local' } } };
+ await pickLocalModel('dictation', 'parakeet-v3');
+ expect(mockUpdateConfig).toHaveBeenCalledWith({
+ inference: { dictation: { mode: 'local', modelId: 'parakeet-v3' } },
+ rememberedInference: {
+ dictation: { local: { mode: 'local', modelId: 'parakeet-v3' } },
+ },
+ });
+});
+
+it('picking Automatic clears the model', async () => {
+ mockConfig = {
+ defaultMode: 'private',
+ inference: { dictation: { mode: 'local', modelId: 'parakeet-v3' } },
+ };
+ await pickLocalModel('dictation', undefined);
+ expect(mockUpdateConfig).toHaveBeenCalledWith({
+ inference: { dictation: { mode: 'local' } },
+ rememberedInference: { dictation: { local: { mode: 'local' } } },
+ });
+});
+
+describe('a workflow held on its old mode when dictation moved to your own key', () => {
+ beforeEach(() => {
+ mockConfig = {
+ defaultMode: 'providers',
+ inference: {
+ dictation: { mode: 'providers', providerId: 'openai', modelId: 'whisper-1' },
+ upload: { mode: 'local' },
+ notes: { mode: 'local' },
+ },
+ pinnedInference: ['upload', 'notes'],
+ };
+ });
+
+ it('becomes the user choice once a mode is tapped for it', async () => {
+ await expect(switchWorkflowMode('upload', 'openwhispr')).resolves.toBe('switched');
+ expect(mockUpdateConfig.mock.calls[0][0]).toMatchObject({
+ inference: { upload: { mode: 'openwhispr' } },
+ pinnedInference: ['notes'],
+ });
+ });
+
+ it('becomes the user choice once a model is picked for it', async () => {
+ await pickLocalModel('upload', 'whisper-base');
+ expect(mockUpdateConfig.mock.calls[0][0]).toMatchObject({
+ inference: { upload: { mode: 'local', modelId: 'whisper-base' } },
+ pinnedInference: ['notes'],
+ });
+ });
+});
diff --git a/openwhispr-mobile/src/lib/byokWorkflows.ts b/openwhispr-mobile/src/lib/aiWorkflows.ts
similarity index 66%
rename from openwhispr-mobile/src/lib/byokWorkflows.ts
rename to openwhispr-mobile/src/lib/aiWorkflows.ts
index 335c6b494..03938eef0 100644
--- a/openwhispr-mobile/src/lib/byokWorkflows.ts
+++ b/openwhispr-mobile/src/lib/aiWorkflows.ts
@@ -1,15 +1,11 @@
-import { Alert } from 'react-native';
-import { router } from 'expo-router';
-import { accountRequiredForCloud, showAccountRequiredAlert } from '@/lib/accountAccess';
-import type { AuthUser } from '@/lib/authClient';
-import { getPrivateModeReadiness, getPrivateModeUnavailableMessage } from '@/lib/privateMode';
import type { InferenceSelection } from '@/lib/mobileProviders';
import { MODE_LABELS } from '@/lib/inferenceModes';
+import { isLocalModelKey, LOCAL_MODEL_TITLES } from '@/lib/localModelCatalog';
import { providerDisplayName, type MobileInferenceScope } from '@/lib/mobileProviders';
import type { ProcessingMode, UserConfig } from '@/types';
export const WORKFLOW_LABELS: Record<MobileInferenceScope, string> = {
- dictation: 'Dictation & Keyboard',
+ dictation: 'Dictation',
upload: 'Uploads',
cleanup: 'Text Cleanup',
notes: 'Note Formatting & Titles',
@@ -66,45 +62,14 @@ export function workflowSummary(
if (activeMode === 'private') {
if (scope === 'cleanup') return 'Skipped';
const chatOnCloud = (config?.inference?.agent?.mode ?? 'openwhispr') === 'openwhispr';
- return scope === 'agent' && chatOnCloud ? MODE_LABELS.openwhispr : MODE_LABELS.local;
+ if (scope === 'agent' && chatOnCloud) return MODE_LABELS.openwhispr;
}
const selection = config?.inference?.[scope] ?? unsetSelection(scope, activeMode);
+ if (selection.mode === 'local' && isLocalModelKey(selection.modelId))
+ return LOCAL_MODEL_TITLES[selection.modelId];
+ if (activeMode === 'private') return MODE_LABELS.local;
if (selection.mode !== 'providers') return MODE_LABELS[selection.mode];
if (!selection.providerId) return 'Not set';
const name = providerDisplayName(selection.providerId);
return keyMissing ? `${name} · Key missing` : name;
}
-
-// Every control that moves speech to Cloud or On-Device runs these checks, so none can
-// save a mode that fails on the next recording.
-export async function confirmSpeechModeReady(
- mode: 'cloud' | 'private',
- user: AuthUser | null,
-): Promise<boolean> {
- if (mode === 'cloud') {
- if (!accountRequiredForCloud(user)) return true;
- showAccountRequiredAlert('cloud transcription');
- return false;
- }
- const readiness = await getPrivateModeReadiness().catch(() => null);
- if (!readiness) {
- Alert.alert('On-Device Unavailable', 'Unable to check the local model right now.');
- return false;
- }
- if (readiness.status === 'unavailable') {
- Alert.alert('On-Device Unavailable', getPrivateModeUnavailableMessage());
- return false;
- }
- if (readiness.status === 'missing') {
- Alert.alert(
- 'Download required',
- `Download the on-device model (${readiness.modelName}) before switching to on-device.`,
- [
- { text: 'Cancel', style: 'cancel' },
- { text: 'Download', onPress: () => router.push('/(account)/model-download') },
- ],
- );
- return false;
- }
- return true;
-}
diff --git a/openwhispr-mobile/src/lib/inferenceModes.ts b/openwhispr-mobile/src/lib/inferenceModes.ts
index 54245035f..6f07f43db 100644
--- a/openwhispr-mobile/src/lib/inferenceModes.ts
+++ b/openwhispr-mobile/src/lib/inferenceModes.ts
@@ -70,7 +70,7 @@ function scopesToPin(leavingMode: ProcessingMode): MobileInferenceScope[] {
return leavingMode === 'private' ? ['upload', 'notes', 'agent'] : ['upload', 'notes'];
}
-// The Home toggle and the Speech-to-Text picker both own the dictation mode;
+// The Home toggle and the Dictation page both own the dictation mode;
// writing the scope selection alongside defaultMode keeps routing and UI in step.
export function dictationModeConfig(
config: UserConfig | null,
@@ -86,7 +86,14 @@ export function dictationModeConfig(
);
return {
defaultMode: mode,
- inference: { ...inference, dictation: { mode: mode === 'private' ? 'local' : 'openwhispr' } },
+ inference: {
+ ...inference,
+ // On-Device restores the model picked on the Dictation page.
+ dictation:
+ mode === 'private'
+ ? (config?.rememberedInference?.dictation?.local ?? { mode: 'local' })
+ : { mode: 'openwhispr' },
+ },
...(config?.pinnedInference ? { pinnedInference: undefined } : {}),
};
}
diff --git a/openwhispr-mobile/src/lib/inferenceRouting.ts b/openwhispr-mobile/src/lib/inferenceRouting.ts
index e67f64d23..77d9295fb 100644
--- a/openwhispr-mobile/src/lib/inferenceRouting.ts
+++ b/openwhispr-mobile/src/lib/inferenceRouting.ts
@@ -8,6 +8,7 @@ import {
resolveMobileInferenceRoute,
} from '@/lib/mobileProviders';
import type { TranscriptionProvider, TranscriptionRequest, TextInferenceSnapshot } from '@/types';
+import { isLocalModelKey, type LocalModelKey } from '@/lib/localModelCatalog';
export type ProviderRoute = Extract<InferenceRoute, { mode: 'providers' }>;
@@ -15,6 +16,14 @@ export function getInferenceSelection(scope: InferenceScope): InferenceSelection
return useConfigStore.getState().config?.inference?.[scope];
}
+// The on-device model the user picked for a workflow; undefined means Automatic.
+export function getPickedLocalModel(scope: 'dictation' | 'upload'): LocalModelKey | undefined {
+ const selection = getInferenceSelection(scope);
+ return selection?.mode === 'local' && isLocalModelKey(selection.modelId)
+ ? selection.modelId
+ : undefined;
+}
+
export function getTranscriptionProvider(scope: InferenceScope): TranscriptionProvider {
if (useProcessingModeStore.getState().activeMode === 'private') return 'local';
const selection = getInferenceSelection(scope);
diff --git a/openwhispr-mobile/src/lib/localModelCatalog.ts b/openwhispr-mobile/src/lib/localModelCatalog.ts
index 05c90d78e..94569ba4f 100644
--- a/openwhispr-mobile/src/lib/localModelCatalog.ts
+++ b/openwhispr-mobile/src/lib/localModelCatalog.ts
@@ -1,10 +1,51 @@
+import registry from '@/config/languageRegistry.json';
import {
+ PARAKEET_V3_LANGUAGES,
preferredEngineForLanguages,
type LocalEngineAvailability,
} from '@/services/transcription/localEngine';
export type LocalModelKey = 'whisper-base' | 'parakeet-v2' | 'parakeet-v3';
+export const LOCAL_MODEL_TITLES: Record<LocalModelKey, string> = {
+ 'parakeet-v2': 'Parakeet v2',
+ 'parakeet-v3': 'Parakeet v3',
+ 'whisper-base': 'Whisper base',
+};
+
+export interface ModelLanguage {
+ code: string;
+ label: string;
+ flag: string;
+}
+
+// The languages the app offers in Transcription Language that a model can transcribe.
+export function localModelLanguages(model: LocalModelKey): ModelLanguage[] {
+ return (registry.languages as (ModelLanguage & { whisper?: boolean })[])
+ .filter(({ code, whisper }) => {
+ if (code === 'auto') return false;
+ if (model === 'whisper-base') return !!whisper;
+ const base = code.split('-')[0];
+ return model === 'parakeet-v2' ? base === 'en' : PARAKEET_V3_LANGUAGES.has(base);
+ })
+ .map(({ code, label, flag }) => ({ code, label, flag }))
+ .sort((a, b) => a.label.localeCompare(b.label));
+}
+
+// A registry entry for a base language code; English exists only as regional variants.
+export function languageByCode(code: string): ModelLanguage {
+ const languages = registry.languages as ModelLanguage[];
+ const entry =
+ languages.find((language) => language.code === code) ??
+ languages.find((language) => language.code.startsWith(`${code}-`));
+ if (!entry) return { code, label: code, flag: '🌐' };
+ return { code, label: entry.label.replace(/ \(.*\)$/, ''), flag: entry.flag };
+}
+
+export function isLocalModelKey(value: unknown): value is LocalModelKey {
+ return typeof value === 'string' && Object.keys(LOCAL_MODEL_TITLES).includes(value);
+}
+
/**
* Nominal on-disk sizes shown before download (whisper from its published ggml size; Parakeet
* measured on-device by the benchmark spike). Used for display and the pre-download
@@ -49,7 +90,7 @@ export function getLocalModelCatalog(
{
key: 'parakeet-v2',
engineName: 'Parakeet',
- title: 'Parakeet v2',
+ title: LOCAL_MODEL_TITLES['parakeet-v2'],
description: 'Fastest and most accurate for English dictation.',
languagesNote: 'English only',
sizeBytes: LOCAL_MODEL_SIZE_BYTES['parakeet-v2'],
@@ -59,7 +100,7 @@ export function getLocalModelCatalog(
{
key: 'parakeet-v3',
engineName: 'Parakeet',
- title: 'Parakeet v3',
+ title: LOCAL_MODEL_TITLES['parakeet-v3'],
description: 'Fast transcription with automatic language detection.',
languagesNote: '25 European languages',
sizeBytes: LOCAL_MODEL_SIZE_BYTES['parakeet-v3'],
@@ -69,7 +110,7 @@ export function getLocalModelCatalog(
{
key: 'whisper-base',
engineName: 'Whisper',
- title: 'Whisper base',
+ title: LOCAL_MODEL_TITLES['whisper-base'],
description: 'Broad language coverage — the fallback for everything Parakeet doesn’t cover.',
languagesNote: '~99 languages incl. auto-detect',
sizeBytes: LOCAL_MODEL_SIZE_BYTES['whisper-base'],
diff --git a/openwhispr-mobile/src/lib/localReasoning.ts b/openwhispr-mobile/src/lib/localReasoning.ts
index 33f6b2355..8c0f69c9b 100644
--- a/openwhispr-mobile/src/lib/localReasoning.ts
+++ b/openwhispr-mobile/src/lib/localReasoning.ts
@@ -174,9 +174,9 @@ export async function fitsLocalReasoningBudget(input: {
export function getLocalReasoningUnavailableMessage(readiness?: LocalReasoningReadiness): string {
switch (readiness?.status) {
case 'disabled':
- return 'Local Apple Intelligence is turned off in Account settings.';
+ return 'Local Apple Intelligence is turned off in AI Models.';
case 'appleIntelligenceOff':
- return "Apple Intelligence is turned off in iOS Settings, so on-device AI can't run.";
+ return "Apple Intelligence is turned off in iOS Settings, so this can't run on-device.";
case 'modelNotReady':
return 'Apple Intelligence is still preparing its local model. Try again later.';
case 'unavailable':
diff --git a/openwhispr-mobile/src/lib/workflowModeSwitch.ts b/openwhispr-mobile/src/lib/workflowModeSwitch.ts
new file mode 100644
index 000000000..d31e2aa09
--- /dev/null
+++ b/openwhispr-mobile/src/lib/workflowModeSwitch.ts
@@ -0,0 +1,102 @@
+import { Alert } from 'react-native';
+import { router } from 'expo-router';
+import { useAuthStore } from '@/store/useAuthStore';
+import { useConfigStore } from '@/store/useConfigStore';
+import { useProcessingModeStore } from '@/store/useProcessingModeStore';
+import { accountRequiredForCloud, showAccountRequiredAlert } from '@/lib/accountAccess';
+import { workflowSaveConfig } from '@/lib/inferenceModes';
+import {
+ getLocalReasoningReadiness,
+ getLocalReasoningUnavailableMessage,
+} from '@/lib/localReasoning';
+import type { LocalModelKey } from '@/lib/localModelCatalog';
+import type { InferenceSelection, MobileInferenceScope } from '@/lib/mobileProviders';
+import { getPrivateModeReadiness, getPrivateModeUnavailableMessage } from '@/lib/privateMode';
+
+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';
+
+function isSpeechScope(scope: MobileInferenceScope): scope is SpeechScope {
+ return scope === 'dictation' || scope === 'upload';
+}
+
+async function transcriptionModelReady(): Promise<ModeSwitchResult | null> {
+ const readiness = await getPrivateModeReadiness().catch(() => null);
+ if (!readiness) {
+ Alert.alert('On-Device Unavailable', 'Unable to check the local model right now.');
+ return 'refused';
+ }
+ if (readiness.status === 'unavailable') {
+ Alert.alert('On-Device Unavailable', getPrivateModeUnavailableMessage());
+ return 'refused';
+ }
+ // Nothing to run yet: open the model list, where every on-device model can be
+ // downloaded, as the Home toggle does.
+ if (readiness.status === 'missing') {
+ router.push('/(account)/model-download');
+ return 'needs-model';
+ }
+ return null;
+}
+
+async function appleIntelligenceReady(): Promise<boolean> {
+ const readiness = await getLocalReasoningReadiness({ refresh: true });
+ if (readiness.status === 'ready') return true;
+ Alert.alert('On-Device Unavailable', getLocalReasoningUnavailableMessage(readiness));
+ return false;
+}
+
+// Applies OpenWhispr Cloud or On-Device to a workflow as soon as it is tapped, after the same
+// sign-in and model checks the Home toggle runs.
+export async function switchWorkflowMode(
+ scope: MobileInferenceScope,
+ mode: 'openwhispr' | 'local',
+): Promise<ModeSwitchResult> {
+ if (mode === 'openwhispr' && accountRequiredForCloud(useAuthStore.getState().user)) {
+ showAccountRequiredAlert(isSpeechScope(scope) ? 'cloud transcription' : 'cloud AI');
+ return 'refused';
+ }
+ if (mode === 'local') {
+ const blocked = isSpeechScope(scope)
+ ? await transcriptionModelReady()
+ : (await appleIntelligenceReady())
+ ? null
+ : 'refused';
+ if (blocked) return blocked;
+ }
+
+ const { config, updateConfig } = useConfigStore.getState();
+ const { activeMode, setActiveMode } = useProcessingModeStore.getState();
+ if (scope === 'dictation') setActiveMode(mode === 'local' ? 'private' : 'cloud', true);
+ const selection: InferenceSelection =
+ mode === 'local'
+ ? (config?.rememberedInference?.[scope]?.local ?? { mode: 'local' })
+ : { mode: 'openwhispr' };
+ await updateConfig(workflowSaveConfig(config, scope, selection, activeMode));
+ return 'switched';
+}
+
+// Saves the on-device model for a workflow; undefined means Automatic. The pick is also
+// remembered so switching back to On-Device, from here or the Home toggle, restores it.
+export async function pickLocalModel(
+ scope: SpeechScope,
+ model: LocalModelKey | undefined,
+): Promise<void> {
+ const { config, updateConfig } = useConfigStore.getState();
+ const selection: InferenceSelection = model
+ ? { mode: 'local', modelId: model }
+ : { mode: 'local' };
+ await updateConfig({
+ inference: { ...config?.inference, [scope]: selection },
+ rememberedInference: {
+ ...config?.rememberedInference,
+ [scope]: { ...config?.rememberedInference?.[scope], local: selection },
+ },
+ // A picked model is the user's own choice, so leaving Bring Your Own Key keeps it.
+ ...(config?.pinnedInference
+ ? { pinnedInference: config.pinnedInference.filter((pinned) => pinned !== scope) }
+ : {}),
+ });
+}
diff --git a/openwhispr-mobile/src/screens/AIModelsScreen.tsx b/openwhispr-mobile/src/screens/AIModelsScreen.tsx
index 0ebf44831..5a0498570 100644
--- a/openwhispr-mobile/src/screens/AIModelsScreen.tsx
+++ b/openwhispr-mobile/src/screens/AIModelsScreen.tsx
@@ -1,20 +1,36 @@
import React, { useEffect, useState } from 'react';
-import { Platform } from 'react-native';
+import { Platform, View } from 'react-native';
import { router } from 'expo-router';
+import { useHeaderHeight } from '@react-navigation/elements';
import { SettingsRow, SettingsSection } from '@/components/ui/SettingsSection';
import { SettingsScreen } from '@/components/ui/SettingsScreen';
import { SettingsSwitch } from '@/components/ui/SettingsSwitch';
-import { SoonBadge } from '@/components/ui/SoonBadge';
+import type { LucideIconName } from '@/components/ui/SystemIcon';
+import { Text } from '@/components/ui/Text';
+import { Toast } from '@/components/ui/Toast';
import { useConfigToggle } from '@/hooks/useConfigToggle';
-import { useConfigStore } from '@/store/useConfigStore';
-import { useProcessingModeStore } from '@/store/useProcessingModeStore';
-import { MODE_LABELS } from '@/lib/inferenceModes';
+import { useToast } from '@/hooks/useToast';
+import { confirmDestructive } from '@/lib/alerts';
+import { WORKFLOW_LABELS, WORKFLOWS, workflowSummary } from '@/lib/aiWorkflows';
import { getLocalReasoningReadiness } from '@/lib/localReasoning';
+import type { InferenceSelection, MobileInferenceScope } from '@/lib/mobileProviders';
import {
- processingToInferenceMode,
- type InferenceMode,
- type LocalReasoningReadiness,
-} from '@/types';
+ clearProviderCredentials,
+ getProviderCredentialReference,
+ getProviderCredentialStatus,
+ subscribeProviderCredentialChanges,
+} from '@/services/providers/ProviderCredentials';
+import { useConfigStore } from '@/store/useConfigStore';
+import { useProcessingModeStore } from '@/store/useProcessingModeStore';
+import type { LocalReasoningReadiness } from '@/types';
+
+const WORKFLOW_ICONS: Record<MobileInferenceScope, { icon: string; mdIcon: LucideIconName }> = {
+ dictation: { icon: 'waveform', mdIcon: 'AudioLines' },
+ upload: { icon: 'square.and.arrow.up', mdIcon: 'Upload' },
+ cleanup: { icon: 'sparkles', mdIcon: 'Sparkles' },
+ notes: { icon: 'doc.text', mdIcon: 'FileText' },
+ agent: { icon: 'bubble.left.and.bubble.right', mdIcon: 'MessagesSquare' },
+};
function localReasoningStatusLabel(readiness: LocalReasoningReadiness | null): string {
switch (readiness?.status) {
@@ -33,14 +49,55 @@ function localReasoningStatusLabel(readiness: LocalReasoningReadiness | null): s
}
}
-export default function AIModelsScreen() {
+// Same lookup the workflow page uses; a key that exists but cannot be read is not reported missing.
+async function isKeyMissing(selection: InferenceSelection | undefined): Promise<boolean> {
+ if (selection?.mode !== 'providers' || !selection.providerId) return false;
+ // A Custom endpoint may run without a key unless one was saved for it.
+ if (selection.providerId === 'custom' && !selection.credentialRef) return false;
+ try {
+ const reference = await getProviderCredentialReference(
+ selection.providerId,
+ selection.endpoint,
+ );
+ const status = await getProviderCredentialStatus(reference).catch(() => ({
+ isConfigured: true,
+ }));
+ return !status.isConfigured;
+ } catch {
+ return false;
+ }
+}
+
+export default function AIModelsScreen(): React.JSX.Element {
const config = useConfigStore((state) => state.config);
- const { activeMode } = useProcessingModeStore();
+ const activeMode = useProcessingModeStore((state) => state.activeMode);
const [localReadiness, setLocalReadiness] = useState<LocalReasoningReadiness | null>(null);
const localIntelligenceEnabled = config?.appleLocalIntelligenceEnabled ?? true;
const handleToggleLocalIntelligence = useConfigToggle('appleLocalIntelligenceEnabled');
+ const [busy, setBusy] = useState(false);
+ const { toast, showToast } = useToast();
+ const headerHeight = useHeaderHeight();
+ const [missingKeys, setMissingKeys] = useState<MobileInferenceScope[]>([]);
- const currentMode: InferenceMode = processingToInferenceMode(config?.defaultMode ?? activeMode);
+ useEffect(() => {
+ if (Platform.OS !== 'ios') return undefined;
+ let cancelled = false;
+ const check = (): void => {
+ Promise.all(WORKFLOWS.map((scope) => isKeyMissing(config?.inference?.[scope]))).then(
+ (missing) => {
+ if (cancelled) return;
+ const next = WORKFLOWS.filter((_, index) => missing[index]);
+ setMissingKeys((current) => (current.join() === next.join() ? current : next));
+ },
+ );
+ };
+ check();
+ const unsubscribe = subscribeProviderCredentialChanges(check);
+ return (): void => {
+ cancelled = true;
+ unsubscribe();
+ };
+ }, [config]);
useEffect(() => {
let cancelled = false;
@@ -58,69 +115,82 @@ export default function AIModelsScreen() {
};
}, [localIntelligenceEnabled]);
+ function removeAllCredentials(): void {
+ confirmDestructive(
+ 'Remove all provider keys?',
+ 'Every provider key saved on this iPhone is deleted, including keys for Custom endpoints you no longer use. Workflows that use them stop until you add a key again.',
+ async (): Promise<void> => {
+ setBusy(true);
+ try {
+ await clearProviderCredentials();
+ showToast('All provider keys were removed.', 'success');
+ } catch {
+ showToast('Unable to remove every provider key. Please try again.', 'error');
+ } finally {
+ setBusy(false);
+ }
+ },
+ { destructiveLabel: 'Remove' },
+ );
+ }
+
return (
- <SettingsScreen>
- {Platform.OS === 'ios' ? (
- <SettingsSection>
+ <View className="flex-1 bg-systemBackground">
+ <SettingsScreen>
+ <Text className="mb-4 px-8 text-[13px] text-secondaryLabel">
+ Each workflow picks its own mode.
+ </Text>
+ <SettingsSection title="Workflows">
+ {WORKFLOWS.map((scope) => (
+ <SettingsRow
+ key={scope}
+ iconStyle="line"
+ {...WORKFLOW_ICONS[scope]}
+ title={WORKFLOW_LABELS[scope]}
+ subtitle={workflowSummary(config, scope, activeMode, missingKeys.includes(scope))}
+ onPress={() => router.push({ pathname: '/(account)/ai-workflow', params: { scope } })}
+ />
+ ))}
+ </SettingsSection>
+ <SettingsSection title="On-Device">
<SettingsRow
iconStyle="line"
- icon="key"
- mdIcon="KeyRound"
- title="Bring Your Own Key"
- description="Use your own API keys for transcription and text AI."
- onPress={() => router.push('/(account)/providers')}
+ icon="sparkles"
+ mdIcon="Sparkles"
+ title="Local Apple Intelligence"
+ description={`Status: ${localReasoningStatusLabel(localReadiness)}. Runs On-Device text workflows, and private and signed-out note generation.`}
+ rightElement={
+ <SettingsSwitch
+ value={localIntelligenceEnabled}
+ onValueChange={handleToggleLocalIntelligence}
+ />
+ }
+ showChevron={false}
+ />
+ <SettingsRow
+ iconStyle="line"
+ icon="person.2"
+ mdIcon="Users"
+ title="Speaker Separation"
+ description="Required for meeting transcription."
+ onPress={() => router.push('/(account)/diarization-model')}
/>
</SettingsSection>
- ) : null}
- <SettingsSection title="Transcription">
- <SettingsRow
- iconStyle="line"
- icon="waveform"
- mdIcon="AudioLines"
- title="Speech to Text"
- subtitle={MODE_LABELS[currentMode]}
- onPress={() => router.push('/(account)/speech-to-text')}
- />
- </SettingsSection>
-
- <SettingsSection title="LLM Intelligence">
- <SettingsRow
- iconStyle="line"
- icon="sparkles"
- mdIcon="Sparkles"
- title="Dictation Cleanup"
- onPress={() => router.push('/(account)/dictation-cleanup')}
- />
- <SettingsRow
- iconStyle="line"
- icon="doc.text"
- mdIcon="FileText"
- title="Note Formatting"
- onPress={() => router.push('/(account)/note-formatting')}
- />
- <SettingsRow
- iconStyle="line"
- icon="bubble.left.and.bubble.right"
- mdIcon="MessagesSquare"
- title="Chat Intelligence"
- rightElement={<SoonBadge />}
- showChevron={false}
- />
- <SettingsRow
- iconStyle="line"
- icon="sparkles"
- mdIcon="Sparkles"
- title="Local Apple Intelligence"
- description={`Status: ${localReasoningStatusLabel(localReadiness)}. Use Apple Intelligence for private and signed-out note generation when available.`}
- rightElement={
- <SettingsSwitch
- value={localIntelligenceEnabled}
- onValueChange={handleToggleLocalIntelligence}
+ {Platform.OS === 'ios' ? (
+ <SettingsSection>
+ <SettingsRow
+ iconStyle="line"
+ icon="trash"
+ mdIcon="Trash2"
+ title="Remove All Provider Keys"
+ destructive
+ showChevron={false}
+ onPress={busy ? undefined : removeAllCredentials}
/>
- }
- showChevron={false}
- />
- </SettingsSection>
- </SettingsScreen>
+ </SettingsSection>
+ ) : null}
+ </SettingsScreen>
+ <Toast {...toast} topOffset={headerHeight + 8} />
+ </View>
);
}
diff --git a/openwhispr-mobile/src/screens/ByokWorkflowsScreen.tsx b/openwhispr-mobile/src/screens/ByokWorkflowsScreen.tsx
deleted file mode 100644
index 55a33142b..000000000
--- a/openwhispr-mobile/src/screens/ByokWorkflowsScreen.tsx
+++ /dev/null
@@ -1,145 +0,0 @@
-import React, { useEffect, useState } from 'react';
-import { Platform, View } from 'react-native';
-import { router } from 'expo-router';
-import { SettingsScreen } from '@/components/ui/SettingsScreen';
-import { SettingsRow, SettingsSection } from '@/components/ui/SettingsSection';
-import { Button } from '@/components/ui/Button';
-import { Text } from '@/components/ui/Text';
-import { useConfigStore } from '@/store/useConfigStore';
-import { useProcessingModeStore } from '@/store/useProcessingModeStore';
-import {
- clearProviderCredentials,
- getProviderCredentialReference,
- getProviderCredentialStatus,
- subscribeProviderCredentialChanges,
-} from '@/services/providers/ProviderCredentials';
-import { confirmDestructive } from '@/lib/alerts';
-import { WORKFLOW_LABELS, WORKFLOWS, workflowSummary } from '@/lib/byokWorkflows';
-import type { InferenceSelection, MobileInferenceScope } from '@/lib/mobileProviders';
-import type { LucideIconName } from '@/components/ui/SystemIcon';
-
-// Same symbols AI Models uses for these features.
-const WORKFLOW_ICONS: Record<MobileInferenceScope, { icon: string; mdIcon: LucideIconName }> = {
- dictation: { icon: 'waveform', mdIcon: 'AudioLines' },
- upload: { icon: 'square.and.arrow.up', mdIcon: 'Upload' },
- cleanup: { icon: 'sparkles', mdIcon: 'Sparkles' },
- notes: { icon: 'doc.text', mdIcon: 'FileText' },
- agent: { icon: 'bubble.left.and.bubble.right', mdIcon: 'MessagesSquare' },
-};
-
-// Same lookup the workflow page uses; a key that exists but cannot be read is not reported missing.
-async function isKeyMissing(selection: InferenceSelection | undefined): Promise<boolean> {
- if (selection?.mode !== 'providers' || !selection.providerId) return false;
- // A Custom endpoint may run without a key unless one was saved for it.
- if (selection.providerId === 'custom' && !selection.credentialRef) return false;
- try {
- const reference = await getProviderCredentialReference(
- selection.providerId,
- selection.endpoint,
- );
- const status = await getProviderCredentialStatus(reference).catch(() => ({
- isConfigured: true,
- }));
- return !status.isConfigured;
- } catch {
- return false;
- }
-}
-
-export function ByokWorkflowsScreen(): React.JSX.Element {
- const config = useConfigStore((state) => state.config);
- const activeMode = useProcessingModeStore((state) => state.activeMode);
- const [busy, setBusy] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const [notice, setNotice] = useState<string | null>(null);
- const [missingKeys, setMissingKeys] = useState<MobileInferenceScope[]>([]);
-
- useEffect(() => {
- if (Platform.OS !== 'ios') return undefined;
- let cancelled = false;
- const check = (): void => {
- Promise.all(WORKFLOWS.map((scope) => isKeyMissing(config?.inference?.[scope]))).then(
- (missing) => {
- if (cancelled) return;
- const next = WORKFLOWS.filter((_, index) => missing[index]);
- setMissingKeys((current) => (current.join() === next.join() ? current : next));
- },
- );
- };
- check();
- const unsubscribe = subscribeProviderCredentialChanges(check);
- return (): void => {
- cancelled = true;
- unsubscribe();
- };
- }, [config]);
-
- function removeAllCredentials(): void {
- confirmDestructive(
- 'Remove all provider keys?',
- 'Every provider key saved on this iPhone is deleted, including keys for Custom endpoints you no longer use. Workflows that use them stop until you add a key again.',
- async (): Promise<void> => {
- setBusy(true);
- setError(null);
- setNotice(null);
- try {
- await clearProviderCredentials();
- setNotice('All provider keys were removed.');
- } catch {
- setError('Unable to remove every provider key. Please try again.');
- } finally {
- setBusy(false);
- }
- },
- { destructiveLabel: 'Remove' },
- );
- }
-
- if (Platform.OS !== 'ios') {
- return (
- <SettingsScreen>
- <Text className="px-8 text-[15px] text-secondaryLabel">
- Provider setup is available on iOS. Cloud and on-device settings remain available on
- Android.
- </Text>
- </SettingsScreen>
- );
- }
-
- return (
- <SettingsScreen>
- <Text className="mb-4 px-8 text-[13px] text-secondaryLabel">
- Each workflow picks its own mode. Your provider bills usage.
- </Text>
- <SettingsSection title="Workflows">
- {WORKFLOWS.map((scope) => (
- <SettingsRow
- key={scope}
- iconStyle="line"
- {...WORKFLOW_ICONS[scope]}
- title={WORKFLOW_LABELS[scope]}
- subtitle={workflowSummary(config, scope, activeMode, missingKeys.includes(scope))}
- onPress={() =>
- router.push({ pathname: '/(account)/provider-workflow', params: { scope } })
- }
- />
- ))}
- </SettingsSection>
- <View className="gap-3 px-4">
- {error ? (
- <Text accessibilityRole="alert" className="text-[14px] text-systemRed">
- {error}
- </Text>
- ) : null}
- {notice ? (
- <Text accessibilityLiveRegion="polite" className="text-[14px] text-secondaryLabel">
- {notice}
- </Text>
- ) : null}
- <Button variant="ghost" disabled={busy} onPress={removeAllCredentials}>
- Remove all provider keys
- </Button>
- </View>
- </SettingsScreen>
- );
-}
diff --git a/openwhispr-mobile/src/screens/CleanupPromptScreen.tsx b/openwhispr-mobile/src/screens/CleanupPromptScreen.tsx
index 8dee54a85..0fd125dde 100644
--- a/openwhispr-mobile/src/screens/CleanupPromptScreen.tsx
+++ b/openwhispr-mobile/src/screens/CleanupPromptScreen.tsx
@@ -38,7 +38,7 @@ export default function CleanupPromptScreen() {
// On-Device transcripts stay raw, and Bring Your Own Key skips cleanup until it has a selection.
const inactiveNotice = !cleanupEnabled
- ? 'Dictation Cleanup is off. Your prompt is saved and applies once you turn it on.'
+ ? 'Text Cleanup is off. Your prompt is saved and applies once you turn it on.'
: activeMode === 'private'
? 'On-Device mode keeps the raw transcript, so cleanup is skipped. Your prompt is saved and applies when dictation leaves On-Device.'
: activeMode === 'providers' && !cleanupSelected
diff --git a/openwhispr-mobile/src/screens/DictationAgentScreen.tsx b/openwhispr-mobile/src/screens/DictationAgentScreen.tsx
index 185786b24..800e88130 100644
--- a/openwhispr-mobile/src/screens/DictationAgentScreen.tsx
+++ b/openwhispr-mobile/src/screens/DictationAgentScreen.tsx
@@ -75,7 +75,7 @@ export function DictationAgentScreen(): React.JSX.Element {
icon="person.wave.2"
mdIcon="UserRoundCog"
title="Enable Voice Assistant"
- description="Say your assistant’s name while dictating to have OpenWhispr rewrite what you said."
+ description="Say your assistant’s name while dictating to have OpenWhispr rewrite what you said. Also turns note chat on or off."
rightElement={
<SettingsSwitch
value={enabled}
diff --git a/openwhispr-mobile/src/screens/DictationCleanupScreen.tsx b/openwhispr-mobile/src/screens/DictationCleanupScreen.tsx
deleted file mode 100644
index a17b0abfc..000000000
--- a/openwhispr-mobile/src/screens/DictationCleanupScreen.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-import React from 'react';
-import { router } from 'expo-router';
-import { SettingsRow, SettingsSection } from '@/components/ui/SettingsSection';
-import { SettingsScreen } from '@/components/ui/SettingsScreen';
-import { SettingsSwitch } from '@/components/ui/SettingsSwitch';
-import { useConfigStore } from '@/store/useConfigStore';
-import { useCustomPromptsStore } from '@/store/useCustomPromptsStore';
-import { useConfigToggle } from '@/hooks/useConfigToggle';
-import { resolveCustomPrompt } from '@/config/prompts/registry';
-
-export default function DictationCleanupScreen() {
- const config = useConfigStore((state) => state.config);
- const cleanupEnabled = config?.cleanupEnabled ?? true;
- const handleToggleEnabled = useConfigToggle('cleanupEnabled');
- const hasCustomPrompt = useCustomPromptsStore(
- (state) => resolveCustomPrompt(state.customPrompts.cleanup) !== undefined,
- );
-
- return (
- <SettingsScreen>
- <SettingsSection>
- <SettingsRow
- iconStyle="line"
- icon="sparkles"
- mdIcon="Sparkles"
- title="Enable Text Cleanup"
- description="Use AI to remove filler words, fix grammar, and polish punctuation. Runs on cloud dictation only — on-device dictation returns the raw transcript."
- rightElement={
- <SettingsSwitch value={cleanupEnabled} onValueChange={handleToggleEnabled} />
- }
- showChevron={false}
- />
- <SettingsRow
- iconStyle="line"
- icon="text.quote"
- mdIcon="TextQuote"
- title="Cleanup Prompt"
- subtitle={hasCustomPrompt ? 'Custom' : 'Default'}
- onPress={() => router.push('/(account)/cleanup-prompt')}
- />
- </SettingsSection>
- </SettingsScreen>
- );
-}
diff --git a/openwhispr-mobile/src/screens/HomeScreen.tsx b/openwhispr-mobile/src/screens/HomeScreen.tsx
index 540e4e673..9ff3d2905 100644
--- a/openwhispr-mobile/src/screens/HomeScreen.tsx
+++ b/openwhispr-mobile/src/screens/HomeScreen.tsx
@@ -346,7 +346,7 @@ export default function HomeScreen() {
if (isRecording) return;
if (activeMode === 'providers') {
- router.push('/(account)/speech-to-text');
+ router.push({ pathname: '/(account)/ai-workflow', params: { scope: 'dictation' } });
return;
}
if (isPrivateMode) {
@@ -553,7 +553,7 @@ export default function HomeScreen() {
accessibilityRole: 'button',
accessibilityState: { disabled: isRecording },
accessibilityLabel: 'Transcription: Bring Your Own Key',
- accessibilityHint: 'Opens Speech to Text settings.',
+ accessibilityHint: 'Opens Dictation settings.',
}
: {
accessibilityRole: 'switch',
diff --git a/openwhispr-mobile/src/screens/KeyboardToneScreen.tsx b/openwhispr-mobile/src/screens/KeyboardToneScreen.tsx
index 988046bf9..b71a7e357 100644
--- a/openwhispr-mobile/src/screens/KeyboardToneScreen.tsx
+++ b/openwhispr-mobile/src/screens/KeyboardToneScreen.tsx
@@ -37,8 +37,8 @@ export default function KeyboardToneScreen() {
<View className="mx-4 mb-3" style={{ borderCurve: 'continuous' }}>
<View className="rounded-[14px] border border-separator bg-secondarySystemGroupedBackground px-4 py-3">
<Text className="text-[13px] text-secondaryLabel">
- Tone requires Cloud mode with Dictation Cleanup turned on. Your choice is saved and
- will apply once both are active.
+ Tone requires Cloud mode with Text Cleanup turned on. Your choice is saved and will
+ apply once both are active.
</Text>
</View>
</View>
diff --git a/openwhispr-mobile/src/screens/MeetingRecordScreen.tsx b/openwhispr-mobile/src/screens/MeetingRecordScreen.tsx
index a62643aa5..e8c7d27e9 100644
--- a/openwhispr-mobile/src/screens/MeetingRecordScreen.tsx
+++ b/openwhispr-mobile/src/screens/MeetingRecordScreen.tsx
@@ -229,7 +229,7 @@ export const MeetingRecordScreen = (): React.JSX.Element => {
if (!(await isLocalAsrModelReady())) {
Alert.alert(
'Speech model needed',
- 'Download a local speech model in Settings → AI Models → Speech to Text, then try again.',
+ 'Download a local speech model in Settings → AI Models → Dictation, then try again.',
);
setPhase('prompt');
return;
diff --git a/openwhispr-mobile/src/screens/ModelDownloadScreen.tsx b/openwhispr-mobile/src/screens/ModelDownloadScreen.tsx
index d8f86a856..c294f9950 100644
--- a/openwhispr-mobile/src/screens/ModelDownloadScreen.tsx
+++ b/openwhispr-mobile/src/screens/ModelDownloadScreen.tsx
@@ -11,6 +11,7 @@ import { SystemIcon } from '@/components/ui/SystemIcon';
import { useModelDownloadStore, type LocalModelKey } from '@/store/useModelDownloadStore';
import { confirmDestructive } from '@/lib/alerts';
import { safeHaptics } from '@/lib/utils';
+import { ModelLanguagesButton } from '@/components/settings/ModelLanguagesButton';
function formatBytes(bytes: number): string {
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
@@ -197,9 +198,13 @@ export default function ModelDownloadScreen() {
) : null}
</View>
<Text className="text-sm text-secondaryLabel">{model.description}</Text>
- <Text className="mt-0.5 text-xs text-tertiaryLabel">
- {model.languagesNote} · {formatBytes(model.sizeBytes)}
- </Text>
+ <View className="mt-0.5 flex-row items-center gap-1">
+ <Text className="text-xs text-tertiaryLabel">{model.languagesNote}</Text>
+ <ModelLanguagesButton model={model.key} />
+ <Text className="text-xs text-tertiaryLabel">
+ · {formatBytes(model.sizeBytes)}
+ </Text>
+ </View>
{isDownloading ? (
<View className="mt-3">
diff --git a/openwhispr-mobile/src/screens/NoteEditorScreen.tsx b/openwhispr-mobile/src/screens/NoteEditorScreen.tsx
index ba403a216..96556ecc5 100644
--- a/openwhispr-mobile/src/screens/NoteEditorScreen.tsx
+++ b/openwhispr-mobile/src/screens/NoteEditorScreen.tsx
@@ -30,6 +30,7 @@ import { MarkdownRenderer } from '@/components/notes/MarkdownRenderer';
import { NoteActionsMenu } from '@/components/notes/NoteActionsMenu';
import { ConflictBanner } from '@/components/notes/ConflictBanner';
import { NoteChatSheet } from '@/components/notes/NoteChatSheet';
+import { isDictationAgentEnabled } from '@/lib/dictationAgent';
import { SpeakerTranscript } from '@/components/notes/SpeakerTranscript';
import { SpeakerRenameSheet } from '@/components/notes/SpeakerRenameSheet';
import { SpeakerMergeSheet } from '@/components/notes/SpeakerMergeSheet';
@@ -137,6 +138,8 @@ export default function NoteEditorScreen() {
const notesMode = useConfigStore((s) => s.config?.inference?.notes?.mode);
const notesProviderId = useConfigStore((s) => s.config?.inference?.notes?.providerId);
const chatMode = useConfigStore((s) => s.config?.inference?.agent?.mode);
+ // Note chat shares the Chat & Voice Assistant switch with the voice assistant.
+ const chatEnabled = useConfigStore((s) => (s.config ? isDictationAgentEnabled(s.config) : true));
const providerNotes = notesMode === 'providers';
// Only an unset or OpenWhispr chat route reaches Cloud, so only it needs an account and the paywall.
const cloudChat = chatMode !== 'providers' && chatMode !== 'local';
@@ -900,7 +903,7 @@ export default function NoteEditorScreen() {
processing={isEnhancingHeader}
onRunAction={handleRunAction}
onManageActions={handleManageActions}
- onAskNote={handleAskNote}
+ onAskNote={chatEnabled ? handleAskNote : undefined}
askNoteDisabled={isChatProcessing}
onCopyGeneratedNote={note?.enhancedContent ? handleCopyGeneratedNote : undefined}
onCopyTranscript={usesSegmentTranscript ? handleCopyTranscript : undefined}
diff --git a/openwhispr-mobile/src/screens/NoteFormattingScreen.tsx b/openwhispr-mobile/src/screens/NoteFormattingScreen.tsx
deleted file mode 100644
index 4a638a4d4..000000000
--- a/openwhispr-mobile/src/screens/NoteFormattingScreen.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import React from 'react';
-import { SettingsRow, SettingsSection } from '@/components/ui/SettingsSection';
-import { SettingsScreen } from '@/components/ui/SettingsScreen';
-import { SettingsSwitch } from '@/components/ui/SettingsSwitch';
-import { useConfigStore } from '@/store/useConfigStore';
-import { useConfigToggle } from '@/hooks/useConfigToggle';
-
-export default function NoteFormattingScreen() {
- const config = useConfigStore((state) => state.config);
- const autoGenerateTitle = config?.autoGenerateNoteTitle ?? true;
- const handleToggleAutoTitle = useConfigToggle('autoGenerateNoteTitle');
-
- return (
- <SettingsScreen>
- <SettingsSection>
- <SettingsRow
- iconStyle="line"
- icon="textformat"
- mdIcon="Type"
- title="Auto-generate Note Titles"
- description="Use AI to generate a short title for notes after enhancement. Runs in the cloud."
- rightElement={
- <SettingsSwitch value={autoGenerateTitle} onValueChange={handleToggleAutoTitle} />
- }
- showChevron={false}
- />
- </SettingsSection>
- </SettingsScreen>
- );
-}
diff --git a/openwhispr-mobile/src/screens/ProviderSettingsScreen.tsx b/openwhispr-mobile/src/screens/ProviderSettingsScreen.tsx
deleted file mode 100644
index 04678726e..000000000
--- a/openwhispr-mobile/src/screens/ProviderSettingsScreen.tsx
+++ /dev/null
@@ -1,653 +0,0 @@
-import React, { useEffect, useRef, useState } from 'react';
-import { Alert, Keyboard, Linking, Platform, View } from 'react-native';
-import { useLocalSearchParams } from 'expo-router';
-import { useHeaderHeight } from '@react-navigation/elements';
-import { useNavigation, usePreventRemove } from '@react-navigation/native';
-import { SettingsScreen } from '@/components/ui/SettingsScreen';
-import { SettingsRow, SettingsSection } from '@/components/ui/SettingsSection';
-import { Input } from '@/components/ui/Input';
-import { Button } from '@/components/ui/Button';
-import { Text } from '@/components/ui/Text';
-import { Toast, type ToastType } from '@/components/ui/Toast';
-import { confirmDestructive } from '@/lib/alerts';
-import { useConfigStore } from '@/store/useConfigStore';
-import { useProcessingModeStore } from '@/store/useProcessingModeStore';
-import { inferenceToProcessingMode, type UserConfig } from '@/types';
-import {
- type ProviderCredential,
- getProviderCredential,
- getProviderCredentialReference,
- getProviderCredentialStatus,
- removeProviderCredential,
- setProviderCredential,
-} from '@/services/providers/ProviderCredentials';
-import { workflowSaveConfig } from '@/lib/inferenceModes';
-import {
- getLocalReasoningReadiness,
- getLocalReasoningUnavailableMessage,
-} from '@/lib/localReasoning';
-import { useAuthStore } from '@/store/useAuthStore';
-import { InferenceModePicker } from '@/components/settings/InferenceModePicker';
-import {
- ON_DEVICE_MODE_NOTES,
- UNSET_PROVIDER_NOTES,
- confirmSpeechModeReady,
- parseWorkflow,
- unsetSelection,
-} from '@/lib/byokWorkflows';
-import {
- discoverProviderModels,
- testProviderConnection,
- ProviderExecutionError,
-} from '@/services/providers/ProviderExecution';
-import { getProviderPolicy } from '@/services/providers/ProviderPolicy';
-import {
- getModelListBaseCandidates,
- isSecureHttpEndpoint,
- normalizeBaseUrl,
-} from '@/lib/providerEndpoints';
-import {
- defaultModelId,
- getMobileProvidersForScope,
- resolveMobileInferenceRoute,
- type InferenceMode,
- type InferenceSelection,
- type MobileInferenceScope,
-} from '@/lib/mobileProviders';
-
-type Picker = 'provider' | 'model';
-const TOAST_MS = 3000;
-// Errors carry something to act on, so they stay long enough to read.
-const ERROR_TOAST_MS = 6000;
-const PROVIDER_SETUP_URLS: Record<string, string> = {
- openai: 'https://platform.openai.com/api-keys',
- groq: 'https://console.groq.com/keys',
- openrouter: 'https://openrouter.ai/keys',
-};
-
-export function ProviderSettingsScreen(): React.JSX.Element {
- const params = useLocalSearchParams<{ scope?: string; mode?: string }>();
- const scope = parseWorkflow(params.scope);
- if (!scope) {
- return (
- <SettingsScreen>
- <Text className="px-8 text-[15px] text-secondaryLabel">
- This workflow is not available.
- </Text>
- </SettingsScreen>
- );
- }
- return <WorkflowSettings scope={scope} openWithProviders={params.mode === 'providers'} />;
-}
-
-// The provider used last for this workflow, else the first one offered.
-function providerSelection(
- config: UserConfig | null,
- scope: MobileInferenceScope,
-): InferenceSelection {
- const providers = getMobileProvidersForScope(scope);
- const remembered = Object.values(config?.rememberedInference?.[scope] ?? {}).find((saved) =>
- providers.some((candidate) => candidate.id === saved.providerId),
- );
- return (
- remembered ?? {
- mode: 'providers',
- providerId: providers[0]?.id,
- modelId: defaultModelId(providers[0]),
- }
- );
-}
-
-function WorkflowSettings({
- scope,
- openWithProviders,
-}: {
- scope: MobileInferenceScope;
- openWithProviders: boolean;
-}): React.JSX.Element {
- const config = useConfigStore((state) => state.config);
- const updateConfig = useConfigStore((state) => state.updateConfig);
- const setActiveMode = useProcessingModeStore((state) => state.setActiveMode);
- const activeMode = useProcessingModeStore((state) => state.activeMode);
- const user = useAuthStore((state) => state.user);
- const [savedSelection, setSavedSelection] = useState<InferenceSelection>(
- () => config?.inference?.[scope] ?? unsetSelection(scope, activeMode),
- );
- const [selection, setSelection] = useState<InferenceSelection>(() =>
- openWithProviders && savedSelection.mode !== 'providers'
- ? providerSelection(config, scope)
- : savedSelection,
- );
- const remembered = useRef<Record<string, InferenceSelection>>({});
- const [picker, setPicker] = useState<Picker | null>(null);
- const [apiKey, setApiKey] = useState('');
- const [configured, setConfigured] = useState(false);
- const [busy, setBusy] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const [notice, setNotice] = useState<string | null>(null);
- const [discoveredModels, setDiscoveredModels] = useState<{ id: string; name: string }[]>([]);
- const [toast, setToast] = useState<{
- message: string;
- type: ToastType;
- visible: boolean;
- showId: number;
- }>({ message: '', type: 'info', visible: false, showId: 0 });
- const toastTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
- const headerHeight = useHeaderHeight();
- const navigation = useNavigation();
- const diagnosticController = useRef<AbortController | null>(null);
- useEffect(
- () => (): void => {
- diagnosticController.current?.abort();
- if (toastTimer.current) clearTimeout(toastTimer.current);
- },
- [],
- );
- const providers = getMobileProvidersForScope(scope);
- const provider =
- providers.find((candidate) => candidate.id === selection.providerId) ?? providers[0];
- const modelId = selection.modelId ?? defaultModelId(provider);
- const providerId = provider?.id;
- const models = provider?.models.length ? provider.models : discoveredModels;
- const modeNote =
- activeMode === 'private'
- ? ON_DEVICE_MODE_NOTES[scope]
- : activeMode === 'providers' && !config?.inference?.[scope]
- ? UNSET_PROVIDER_NOTES[scope]
- : undefined;
-
- // A passing check looks like finished setup, so leaving must not drop the key silently.
- const hasUnsavedChanges =
- !!apiKey.trim() ||
- selection.mode !== savedSelection.mode ||
- (selection.mode === 'providers' &&
- (selection.providerId !== savedSelection.providerId ||
- modelId !== savedSelection.modelId ||
- (selection.endpoint ?? '') !== (savedSelection.endpoint ?? '')));
- usePreventRemove(hasUnsavedChanges, ({ data }) =>
- confirmDestructive(
- 'Discard unsaved changes?',
- 'Your selection and any key you entered have not been saved.',
- () => navigation.dispatch(data.action),
- { destructiveLabel: 'Discard' },
- ),
- );
-
- function clearInputs(): void {
- setApiKey('');
- setError(null);
- setNotice(null);
- }
-
- useEffect(() => {
- let cancelled = false;
- setConfigured(false);
- if (Platform.OS === 'ios' && selection.mode === 'providers' && providerId) {
- getProviderCredentialReference(providerId, selection.endpoint)
- .then((reference) =>
- // An unreadable saved key still exists, so offer to remove it.
- getProviderCredentialStatus(reference).catch(() => ({ reference, isConfigured: true })),
- )
- .then((status) => {
- if (!cancelled) setConfigured(status.isConfigured);
- })
- .catch(() => {
- /* Invalid custom endpoints are explained when saving. */
- });
- }
- return (): void => {
- cancelled = true;
- };
- }, [providerId, selection.endpoint, selection.mode]);
-
- function showToast(message: string, type: ToastType): void {
- if (toastTimer.current) clearTimeout(toastTimer.current);
- setToast((current) => ({ message, type, visible: true, showId: current.showId + 1 }));
- toastTimer.current = setTimeout(
- () => setToast((current) => ({ ...current, visible: false })),
- type === 'error' ? ERROR_TOAST_MS : TOAST_MS,
- );
- }
-
- function openPicker(next: Picker): void {
- setPicker(picker === next ? null : next);
- }
-
- function chooseMode(mode: InferenceMode): void {
- if (busy) return;
- setSelection(
- mode === 'providers' && !selection.providerId
- ? providerSelection(config, scope)
- : { ...selection, mode },
- );
- setPicker(null);
- clearInputs();
- }
-
- function chooseProvider(nextProviderId: string): void {
- setDiscoveredModels([]);
- if (provider) remembered.current[provider.id] = { ...selection, modelId };
- const next = providers.find((candidate) => candidate.id === nextProviderId);
- setSelection(
- remembered.current[nextProviderId] ??
- config?.rememberedInference?.[scope]?.[nextProviderId] ?? {
- mode: 'providers',
- providerId: nextProviderId,
- modelId: defaultModelId(next),
- },
- );
- setPicker(null);
- clearInputs();
- }
-
- async function prepareSelection(
- requireModel = true,
- saveCredential = true,
- onInvalid: (message: string) => void = setError,
- ): Promise<InferenceSelection | null> {
- let saved: InferenceSelection = { mode: selection.mode };
- if (selection.mode === 'providers') {
- if (!provider || (requireModel && !modelId.trim())) {
- onInvalid('Choose a provider and enter a model ID.');
- return null;
- }
- const endpoint = normalizeBaseUrl(
- provider.id === 'custom' ? selection.endpoint : provider.endpoint,
- );
- if (provider.id === 'custom') {
- if (!isSecureHttpEndpoint(endpoint)) {
- onInvalid('Use HTTPS, or HTTP for a private-network host.');
- return null;
- }
- const parsed = new URL(endpoint);
- if (parsed.username || parsed.password || parsed.search || parsed.hash) {
- onInvalid('Remove credentials, query parameters, and fragments from the endpoint URL.');
- return null;
- }
- }
- const reference = await getProviderCredentialReference(provider.id, endpoint);
- const hasNewCredential = !!apiKey.trim();
- let hasCredential =
- hasNewCredential || (await getProviderCredentialStatus(reference)).isConfigured;
- const carried = !hasCredential && saveCredential && (await savedServerCredential(endpoint));
- if (carried) {
- await setProviderCredential(reference, carried);
- hasCredential = true;
- }
- if (hasNewCredential && saveCredential) {
- await setProviderCredential(reference, { apiKey: apiKey.trim() });
- clearInputs();
- setConfigured(true);
- }
- if (provider.id !== 'custom' && !hasCredential) {
- onInvalid('Enter a credential for this provider.');
- return null;
- }
- saved = {
- mode: 'providers',
- providerId: provider.id,
- modelId: modelId.trim() || 'catalog-probe',
- ...(provider.id === 'custom' ? { endpoint } : {}),
- ...(hasCredential ? { credentialRef: reference } : {}),
- };
- }
- return saved;
- }
-
- // A check can move a saved custom server to the /v1 address it answers on. Its key
- // goes with it, but never to another host.
- async function savedServerCredential(endpoint: string): Promise<ProviderCredential | null> {
- const previous = savedSelection;
- if (
- previous.providerId !== 'custom' ||
- !previous.endpoint ||
- !previous.credentialRef ||
- !getModelListBaseCandidates(previous.endpoint).includes(endpoint)
- )
- return null;
- return getProviderCredential(previous.credentialRef);
- }
-
- // A bare server origin often serves its API under /v1; keep the address that answered.
- function adoptWorkingEndpoint(draft: InferenceSelection, endpoint: string | undefined): void {
- if (draft.providerId !== 'custom' || !endpoint || endpoint === draft.endpoint) return;
- setSelection((current) => ({ ...current, endpoint }));
- }
-
- // The same checks Speech to Text and Home run, plus Apple Intelligence for text workflows.
- async function confirmModeReady(mode: InferenceMode): Promise<boolean> {
- if (mode === 'providers') return true;
- if (scope === 'dictation' || scope === 'upload') {
- return confirmSpeechModeReady(mode === 'local' ? 'private' : 'cloud', user);
- }
- if (mode !== 'local') return true;
- const readiness = await getLocalReasoningReadiness({ refresh: true });
- if (readiness.status === 'ready') return true;
- Alert.alert('On-Device Unavailable', getLocalReasoningUnavailableMessage(readiness));
- return false;
- }
-
- async function save(): Promise<void> {
- setBusy(true);
- setError(null);
- setNotice(null);
- try {
- if (!(await confirmModeReady(selection.mode))) return;
- const saved = await prepareSelection();
- if (!saved) return;
- const processingMode = inferenceToProcessingMode(saved.mode);
- await updateConfig(
- workflowSaveConfig(useConfigStore.getState().config, scope, saved, activeMode),
- );
- if (useConfigStore.getState().error) {
- setError('Unable to save your selection. Please try again.');
- return;
- }
- if (scope === 'dictation') setActiveMode(processingMode, true);
- setSelection(saved);
- setSavedSelection(saved);
- clearInputs();
- setNotice('Selection saved.');
- } catch {
- setError('Unable to save provider settings. Check your configuration and try again.');
- } finally {
- setBusy(false);
- }
- }
-
- async function diagnose(action: 'test' | 'discover'): Promise<void> {
- // Focus moves to the result, so the keyboard has no reason to stay up.
- Keyboard.dismiss();
- setBusy(true);
- setError(null);
- setNotice(null);
- const controller = new AbortController();
- diagnosticController.current = controller;
- const showError = (message: string): void => showToast(message, 'error');
- try {
- const draft = await prepareSelection(action === 'test', false, showError);
- if (!draft) return;
- const resolved = resolveMobileInferenceRoute({
- scope,
- selection: draft,
- // A check sends no user content, so On-Device mode does not block it.
- policy: await getProviderPolicy(),
- });
- if (!resolved.ok || resolved.route.mode !== 'providers') {
- showError(
- !resolved.ok && resolved.code.startsWith('POLICY')
- ? 'Organization policy does not currently permit this provider check.'
- : 'Check your provider, model, and endpoint before testing.',
- );
- return;
- }
- const checkKey =
- apiKey.trim() ||
- (!draft.credentialRef && (await savedServerCredential(draft.endpoint ?? ''))?.apiKey) ||
- undefined;
- if (action === 'discover') {
- const result = await discoverProviderModels({
- route: resolved.route,
- signal: controller.signal,
- apiKey: checkKey,
- });
- if (controller.signal.aborted) return;
- adoptWorkingEndpoint(draft, result.endpoint);
- setDiscoveredModels(result.models);
- showToast(
- result.models.length
- ? 'Model catalog loaded. Inference access has not been verified.'
- : 'No models were listed. You can still enter a model ID manually.',
- 'info',
- );
- } else {
- const result = await testProviderConnection({
- route: resolved.route,
- signal: controller.signal,
- apiKey: checkKey,
- });
- if (controller.signal.aborted) return;
- adoptWorkingEndpoint(draft, result.endpoint);
- if (result.verification === 'inference')
- showToast('Connection works. Save to use it.', 'success');
- else
- showToast(
- 'Model catalog accessible. Transcription and inference access have not been verified.',
- 'info',
- );
- }
- } catch (failure: unknown) {
- if (!controller.signal.aborted)
- showError(
- failure instanceof ProviderExecutionError
- ? failure.message
- : 'Unable to check this provider. Check the endpoint and connection, then try again.',
- );
- } finally {
- diagnosticController.current = null;
- setBusy(false);
- }
- }
-
- async function removeCredential(): Promise<void> {
- if (!provider) return;
- setBusy(true);
- setError(null);
- setNotice(null);
- try {
- const reference = await getProviderCredentialReference(provider.id, selection.endpoint);
- await removeProviderCredential(reference);
- setConfigured(false);
- clearInputs();
- setNotice('Credential removed for every workflow using it.');
- } catch {
- setError('Unable to remove this credential. Please try again.');
- } finally {
- setBusy(false);
- }
- }
-
- function choice(title: string, selected: boolean, onPress: () => void): React.JSX.Element {
- return (
- <SettingsRow
- key={title}
- icon={selected ? 'checkmark.circle.fill' : 'circle'}
- mdIcon={selected ? 'CircleCheck' : 'Circle'}
- iconStyle="line"
- title={title}
- selected={selected}
- showChevron={false}
- onPress={busy ? undefined : onPress}
- />
- );
- }
-
- if (Platform.OS !== 'ios') {
- return (
- <SettingsScreen>
- <Text className="px-8 text-[15px] text-secondaryLabel">
- Provider setup is available on iOS. Cloud and on-device settings remain available on
- Android.
- </Text>
- </SettingsScreen>
- );
- }
-
- return (
- <View className="flex-1 bg-systemBackground">
- <SettingsScreen
- automaticallyAdjustKeyboardInsets
- keyboardShouldPersistTaps="handled"
- keyboardDismissMode="interactive"
- >
- <InferenceModePicker
- scope={scope === 'dictation' || scope === 'upload' ? 'speech' : 'text'}
- title="Mode"
- selectedMode={selection.mode}
- onSelect={chooseMode}
- />
- {modeNote ? (
- <Text className="-mt-4 mb-6 px-8 text-[13px] text-secondaryLabel">{modeNote}</Text>
- ) : null}
- {selection.mode === 'providers' && provider ? (
- <>
- <SettingsSection title="Connection">
- <SettingsRow
- icon="network"
- mdIcon="Network"
- iconStyle="line"
- title="Provider"
- subtitle={provider.name}
- onPress={busy ? undefined : () => openPicker('provider')}
- />
- {picker === 'provider' &&
- providers.map((item) =>
- choice(item.name, item.id === provider.id, () => chooseProvider(item.id)),
- )}
- {models.length > 0 ? (
- <SettingsRow
- icon="square.stack"
- mdIcon="Layers"
- iconStyle="line"
- title="Model"
- subtitle={models.find((model) => model.id === modelId)?.name ?? modelId}
- onPress={busy ? undefined : () => openPicker('model')}
- />
- ) : null}
- {picker === 'model' &&
- models.map((model) =>
- choice(model.name, model.id === modelId, () => {
- setSelection({ ...selection, modelId: model.id });
- setPicker(null);
- setNotice(null);
- }),
- )}
- </SettingsSection>
- <SettingsSection
- borderless
- title={configured ? 'Credential saved on this device' : 'Credentials'}
- >
- <View className="gap-3 p-1">
- {provider.id === 'custom' ? (
- <>
- <Input
- label="Endpoint URL"
- accessibilityLabel="Endpoint URL"
- value={selection.endpoint ?? ''}
- onChangeText={(endpoint) => {
- setSelection({ ...selection, endpoint });
- clearInputs();
- }}
- autoCapitalize="none"
- autoCorrect={false}
- keyboardType="url"
- placeholder="https://your-server.example/v1"
- editable={!busy}
- />
- <Text className="text-[13px] text-secondaryLabel">
- On iPhone, localhost refers to this iPhone. Use your server's LAN address for
- a local server.
- </Text>
- </>
- ) : null}
- {!provider.models.length ? (
- <Input
- label="Model ID"
- accessibilityLabel="Model ID"
- value={modelId}
- onChangeText={(nextModel) => setSelection({ ...selection, modelId: nextModel })}
- autoCapitalize="none"
- autoCorrect={false}
- editable={!busy}
- />
- ) : null}
- <Input
- label={provider.id === 'custom' ? 'API key (optional)' : 'API key'}
- accessibilityLabel="API key"
- value={apiKey}
- onChangeText={(next) => {
- // A paste or password-manager fill arrives as one change; typing adds one character.
- if (next.length - apiKey.length > 1) Keyboard.dismiss();
- setApiKey(next);
- }}
- secureTextEntry
- autoCapitalize="none"
- autoCorrect={false}
- placeholder={
- configured ? 'Leave blank to keep saved credential' : 'Enter API key'
- }
- editable={!busy}
- />
- {PROVIDER_SETUP_URLS[provider.id] ? (
- <Button
- variant="ghost"
- disabled={busy}
- onPress={async (): Promise<void> => {
- try {
- await Linking.openURL(PROVIDER_SETUP_URLS[provider.id]);
- } catch {
- setError('Unable to open the provider website. Please try again.');
- }
- }}
- >
- Get provider credentials
- </Button>
- ) : null}
- {configured ? (
- <Button variant="ghost" disabled={busy} onPress={removeCredential}>
- Remove credential
- </Button>
- ) : null}
- </View>
- </SettingsSection>
- <SettingsSection borderless title="Verify access">
- <View className="gap-3 p-1">
- <Text className="text-[13px] text-secondaryLabel">
- Checks use the key entered above without saving it. Text checks send a short test
- prompt and may incur provider charges; transcription checks verify catalog access
- only.
- </Text>
- <Button variant="outline" disabled={busy} onPress={() => diagnose('test')}>
- Check connection
- </Button>
- {provider.id === 'custom' || provider.id === 'openrouter' ? (
- <Button variant="outline" disabled={busy} onPress={() => diagnose('discover')}>
- Discover models
- </Button>
- ) : null}
- </View>
- </SettingsSection>
- </>
- ) : null}
- <View className="gap-3 px-4">
- {error ? (
- <Text accessibilityRole="alert" className="text-[14px] text-systemRed">
- {error}
- </Text>
- ) : null}
- {notice ? (
- <Text accessibilityLiveRegion="polite" className="text-[14px] text-secondaryLabel">
- {notice}
- </Text>
- ) : null}
- {/* A workflow that was never set is not saved until something is chosen, so the
- default shown here never becomes an explicit choice. */}
- <Button
- loading={busy}
- disabled={!hasUnsavedChanges && !config?.inference?.[scope]}
- onPress={save}
- >
- Save selection
- </Button>
- </View>
- </SettingsScreen>
- <Toast
- message={toast.message}
- visible={toast.visible}
- type={toast.type}
- showId={toast.showId}
- topOffset={headerHeight + 8}
- />
- </View>
- );
-}
diff --git a/openwhispr-mobile/src/screens/SpeechToTextScreen.tsx b/openwhispr-mobile/src/screens/SpeechToTextScreen.tsx
deleted file mode 100644
index 8ea087bde..000000000
--- a/openwhispr-mobile/src/screens/SpeechToTextScreen.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import React, { useCallback } from 'react';
-import { router } from 'expo-router';
-import { SettingsRow, SettingsSection } from '@/components/ui/SettingsSection';
-import { SettingsScreen } from '@/components/ui/SettingsScreen';
-import { InferenceModePicker } from '@/components/settings/InferenceModePicker';
-import { useConfigStore } from '@/store/useConfigStore';
-import { useProcessingModeStore } from '@/store/useProcessingModeStore';
-import { useAuthStore } from '@/store/useAuthStore';
-import { confirmSpeechModeReady } from '@/lib/byokWorkflows';
-import { dictationModeConfig } from '@/lib/inferenceModes';
-import { safeHaptics } from '@/lib/utils';
-import { type InferenceMode, processingToInferenceMode } from '@/types';
-
-export default function SpeechToTextScreen() {
- const config = useConfigStore((state) => state.config);
- const updateConfig = useConfigStore((state) => state.updateConfig);
- const { activeMode, setActiveMode } = useProcessingModeStore();
- const user = useAuthStore((state) => state.user);
-
- const selectedMode: InferenceMode = processingToInferenceMode(config?.defaultMode ?? activeMode);
-
- const handleSelectMode = useCallback(
- async (mode: InferenceMode) => {
- if (mode === 'providers') {
- router.push({
- pathname: '/(account)/provider-workflow',
- params: { scope: 'dictation', mode: 'providers' },
- });
- return;
- }
- if (mode === selectedMode) return;
- safeHaptics('light');
- const nextMode = mode === 'local' ? 'private' : 'cloud';
- if (!(await confirmSpeechModeReady(nextMode, user))) return;
-
- setActiveMode(nextMode, true);
- updateConfig(dictationModeConfig(config ?? null, nextMode));
- },
- [config, selectedMode, setActiveMode, updateConfig, user],
- );
-
- return (
- <SettingsScreen>
- <InferenceModePicker scope="speech" selectedMode={selectedMode} onSelect={handleSelectMode} />
-
- <SettingsSection title="On-Device Models">
- <SettingsRow
- iconStyle="line"
- icon="arrow.down.circle"
- mdIcon="Download"
- title="Transcription Models"
- description="Download on-device models for private mode."
- onPress={() => router.push('/(account)/model-download')}
- />
- <SettingsRow
- iconStyle="line"
- icon="person.2"
- mdIcon="Users"
- title="Speaker Separation"
- description="Required for meeting transcription."
- onPress={() => router.push('/(account)/diarization-model')}
- />
- </SettingsSection>
- </SettingsScreen>
- );
-}
diff --git a/openwhispr-mobile/src/screens/WorkflowSettingsScreen.tsx b/openwhispr-mobile/src/screens/WorkflowSettingsScreen.tsx
new file mode 100644
index 000000000..fbb66b565
--- /dev/null
+++ b/openwhispr-mobile/src/screens/WorkflowSettingsScreen.tsx
@@ -0,0 +1,857 @@
+import React, { useCallback, useEffect, useRef, useState } from 'react';
+import { ActivityIndicator, 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';
+import { SettingsScreen } from '@/components/ui/SettingsScreen';
+import {
+ SettingsRow,
+ SettingsSection,
+ SettingsTextFieldRow,
+} from '@/components/ui/SettingsSection';
+import { Text } from '@/components/ui/Text';
+import { Toast } from '@/components/ui/Toast';
+import { useToast } from '@/hooks/useToast';
+import { confirmDestructive } from '@/lib/alerts';
+import { SettingsSwitch } from '@/components/ui/SettingsSwitch';
+import { OnDeviceModelSection } from '@/components/settings/OnDeviceModelSection';
+import { useConfigToggle } from '@/hooks/useConfigToggle';
+import { useCustomPromptsStore } from '@/store/useCustomPromptsStore';
+import { resolveCustomPrompt } from '@/config/prompts/registry';
+import { useConfigStore } from '@/store/useConfigStore';
+import { useProcessingModeStore } from '@/store/useProcessingModeStore';
+import type { UserConfig } from '@/types';
+import {
+ type ProviderCredential,
+ getProviderCredential,
+ getProviderCredentialReference,
+ getProviderCredentialStatus,
+ removeProviderCredential,
+ setProviderCredential,
+} from '@/services/providers/ProviderCredentials';
+import { workflowSaveConfig } from '@/lib/inferenceModes';
+import { InferenceModePicker } from '@/components/settings/InferenceModePicker';
+import {
+ ON_DEVICE_MODE_NOTES,
+ UNSET_PROVIDER_NOTES,
+ WORKFLOW_LABELS,
+ WORKFLOWS,
+ parseWorkflow,
+ unsetSelection,
+} from '@/lib/aiWorkflows';
+import { isLocalModelKey } from '@/lib/localModelCatalog';
+import { getDictationAgentName, isDictationAgentEnabled } from '@/lib/dictationAgent';
+import { SystemIcon, type LucideIconName } from '@/components/ui/SystemIcon';
+import { switchWorkflowMode } from '@/lib/workflowModeSwitch';
+import { getPrivateModeReadiness } from '@/lib/privateMode';
+import {
+ discoverProviderModels,
+ testProviderConnection,
+ ProviderExecutionError,
+} from '@/services/providers/ProviderExecution';
+import { getProviderPolicy } from '@/services/providers/ProviderPolicy';
+import {
+ getModelListBaseCandidates,
+ isSecureHttpEndpoint,
+ normalizeBaseUrl,
+} from '@/lib/providerEndpoints';
+import {
+ defaultModelId,
+ getMobileProvidersForScope,
+ providerDisplayName,
+ resolveMobileInferenceRoute,
+ type InferenceMode,
+ type InferenceSelection,
+ type MobileInferenceScope,
+} from '@/lib/mobileProviders';
+
+type Picker = 'provider' | 'model';
+const PROVIDER_SETUP_URLS: Record<string, string> = {
+ openai: 'https://platform.openai.com/api-keys',
+ groq: 'https://console.groq.com/keys',
+ openrouter: 'https://openrouter.ai/keys',
+};
+
+function SectionFooter({ children }: { children: string }): React.JSX.Element {
+ return (
+ <View className="mx-4 -mt-5 mb-7 px-4">
+ <Text className="text-[13px] text-secondaryLabel">{children}</Text>
+ </View>
+ );
+}
+
+function joinNames(names: string[]): string {
+ return names.length < 2 ? names.join('') : `${names.slice(0, -1).join(', ')} and ${names.at(-1)}`;
+}
+
+// A workflow that can be turned off: its switch sits above Mode, with the workflow's own
+// settings row under it while it is on.
+function WorkflowSwitchCard({
+ title,
+ description,
+ icon,
+ mdIcon,
+ enabled,
+ onToggle,
+ offNote,
+ children,
+}: {
+ title: string;
+ description: string;
+ icon: string;
+ mdIcon: LucideIconName;
+ enabled: boolean;
+ onToggle: (value: boolean) => void;
+ offNote: string;
+ children: React.ReactNode;
+}): React.JSX.Element {
+ return (
+ <>
+ <SettingsSection>
+ <SettingsRow
+ iconStyle="line"
+ icon={icon}
+ mdIcon={mdIcon}
+ title={title}
+ description={description}
+ rightElement={<SettingsSwitch value={enabled} onValueChange={onToggle} />}
+ showChevron={false}
+ />
+ {enabled ? children : null}
+ </SettingsSection>
+ {enabled ? null : <SectionFooter>{offNote}</SectionFooter>}
+ </>
+ );
+}
+
+function CleanupSettings({ enabled }: { enabled: boolean }): React.JSX.Element {
+ const toggleCleanup = useConfigToggle('cleanupEnabled');
+ const hasCustomPrompt = useCustomPromptsStore(
+ (state) => resolveCustomPrompt(state.customPrompts.cleanup) !== undefined,
+ );
+ return (
+ <WorkflowSwitchCard
+ title="Enable Text Cleanup"
+ description="Use AI to remove filler words, fix grammar, and polish punctuation."
+ icon="sparkles"
+ mdIcon="Sparkles"
+ enabled={enabled}
+ onToggle={toggleCleanup}
+ offNote="Dictation is inserted as spoken, with no AI cleanup."
+ >
+ <SettingsRow
+ iconStyle="line"
+ icon="text.quote"
+ mdIcon="TextQuote"
+ title="Cleanup Prompt"
+ subtitle={hasCustomPrompt ? 'Custom' : 'Default'}
+ onPress={() => router.push('/(account)/cleanup-prompt')}
+ />
+ </WorkflowSwitchCard>
+ );
+}
+
+function AssistantSettings({ enabled }: { enabled: boolean }): React.JSX.Element {
+ const toggleAssistant = useConfigToggle('dictationAgentEnabled');
+ const agentName = useConfigStore((state) =>
+ state.config ? getDictationAgentName(state.config) : undefined,
+ );
+ return (
+ <WorkflowSwitchCard
+ title="Enable Chat & Voice Assistant"
+ description="Chat with your notes, and say your assistant’s name to give it commands."
+ icon="bubble.left.and.bubble.right"
+ mdIcon="MessagesSquare"
+ enabled={enabled}
+ onToggle={toggleAssistant}
+ offNote="Note chat and the voice assistant are off."
+ >
+ <SettingsRow
+ iconStyle="line"
+ icon="person.wave.2"
+ mdIcon="UserRoundCog"
+ title="Voice Assistant"
+ subtitle={agentName}
+ onPress={() => router.push('/(account)/dictation-agent')}
+ />
+ </WorkflowSwitchCard>
+ );
+}
+
+function NoteTitleSettings(): React.JSX.Element {
+ const autoTitle = useConfigStore((state) => state.config?.autoGenerateNoteTitle ?? true);
+ const toggleAutoTitle = useConfigToggle('autoGenerateNoteTitle');
+ return (
+ <SettingsSection title="Settings">
+ <SettingsRow
+ iconStyle="line"
+ icon="textformat"
+ mdIcon="Type"
+ title="Auto-generate Note Titles"
+ description="Use AI to generate a short title for notes after enhancement."
+ rightElement={<SettingsSwitch value={autoTitle} onValueChange={toggleAutoTitle} />}
+ showChevron={false}
+ />
+ </SettingsSection>
+ );
+}
+
+export function WorkflowSettingsScreen(): React.JSX.Element {
+ const scope = parseWorkflow(useLocalSearchParams<{ scope?: string }>().scope);
+ if (!scope) {
+ return (
+ <SettingsScreen>
+ <Text className="px-8 text-[15px] text-secondaryLabel">
+ This workflow is not available.
+ </Text>
+ </SettingsScreen>
+ );
+ }
+ return <WorkflowSettings scope={scope} />;
+}
+
+// The provider used last for this workflow, else the first one offered.
+function providerSelection(
+ config: UserConfig | null,
+ scope: MobileInferenceScope,
+): InferenceSelection {
+ const providers = getMobileProvidersForScope(scope);
+ const remembered = Object.values(config?.rememberedInference?.[scope] ?? {}).find((saved) =>
+ providers.some((candidate) => candidate.id === saved.providerId),
+ );
+ return (
+ remembered ?? {
+ mode: 'providers',
+ providerId: providers[0]?.id,
+ modelId: defaultModelId(providers[0]),
+ }
+ );
+}
+
+function WorkflowSettings({ scope }: { scope: MobileInferenceScope }): React.JSX.Element {
+ const config = useConfigStore((state) => state.config);
+ const updateConfig = useConfigStore((state) => state.updateConfig);
+ const setActiveMode = useProcessingModeStore((state) => state.setActiveMode);
+ const activeMode = useProcessingModeStore((state) => state.activeMode);
+ const savedSelection = config?.inference?.[scope] ?? unsetSelection(scope, activeMode);
+ // Tracks the saved selection, except while a Bring Your Own Key draft is being set up.
+ const [selection, setSelection] = useState<InferenceSelection>(savedSelection);
+ const remembered = useRef<Record<string, InferenceSelection>>({});
+ const [picker, setPicker] = useState<Picker | null>(null);
+ const [apiKey, setApiKey] = useState('');
+ 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.
+ const [onDeviceWanted, setOnDeviceWanted] = useState(false);
+ const [discoveredModels, setDiscoveredModels] = useState<{ id: string; name: string }[]>([]);
+ const { toast, showToast } = useToast();
+ const headerHeight = useHeaderHeight();
+ const navigation = useNavigation();
+ const diagnosticController = useRef<AbortController | null>(null);
+ useEffect(
+ () => (): void => {
+ diagnosticController.current?.abort();
+ },
+ [],
+ );
+ const providers = getMobileProvidersForScope(scope);
+ const provider =
+ providers.find((candidate) => candidate.id === selection.providerId) ?? providers[0];
+ const modelId = selection.modelId ?? defaultModelId(provider);
+ const providerId = provider?.id;
+ const models = provider?.models.length ? provider.models : discoveredModels;
+ const modeNote =
+ (activeMode === 'private' ? ON_DEVICE_MODE_NOTES[scope] : undefined) ??
+ (activeMode === 'providers' && !config?.inference?.[scope]
+ ? UNSET_PROVIDER_NOTES[scope]
+ : undefined) ??
+ (selection.mode === 'providers' && savedSelection.mode !== 'providers'
+ ? 'Save to switch to Bring Your Own Key.'
+ : undefined);
+ const speechScope = scope === 'dictation' || scope === 'upload' ? scope : null;
+ // 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 ?? '');
+ // Text Cleanup and Chat & Voice Assistant can be switched off; then they use no key.
+ const switchedOff = (workflow: MobileInferenceScope): boolean =>
+ (workflow === 'cleanup' && !(config?.cleanupEnabled ?? true)) ||
+ (workflow === 'agent' && !!config && !isDictationAgentEnabled(config));
+ const workflowOff = switchedOff(scope);
+ const sharedWith = WORKFLOWS.filter((other) => {
+ const saved = config?.inference?.[other];
+ return (
+ other !== scope &&
+ !switchedOff(other) &&
+ saved?.mode === 'providers' &&
+ saved.providerId === provider?.id &&
+ (provider?.id !== 'custom' ||
+ normalizeBaseUrl(saved.endpoint) === normalizeBaseUrl(selection.endpoint))
+ );
+ }).map((other) => WORKFLOW_LABELS[other]);
+ const keyFooter = sharedWith.length
+ ? `Stays on this iPhone. Also used by ${joinNames(sharedWith)}.`
+ : provider?.id === 'custom'
+ ? 'Stays on this iPhone. Every workflow using this server uses the same key.'
+ : `Stays on this iPhone. Every workflow set to ${keyOwner} uses the same key.`;
+
+ // A passing check looks like finished setup, so leaving must not drop the key silently.
+ const hasUnsavedChanges =
+ !!apiKey.trim() ||
+ selection.mode !== savedSelection.mode ||
+ (selection.mode === 'providers' &&
+ (selection.providerId !== savedSelection.providerId ||
+ modelId !== savedSelection.modelId ||
+ (selection.endpoint ?? '') !== (savedSelection.endpoint ?? '')));
+ const canSave = hasUnsavedChanges && !busy;
+ usePreventRemove(hasUnsavedChanges, ({ data }) =>
+ confirmDestructive(
+ 'Discard unsaved changes?',
+ 'Your selection and any key you entered have not been saved.',
+ () => navigation.dispatch(data.action),
+ { destructiveLabel: 'Discard' },
+ ),
+ );
+
+ function clearInputs(): void {
+ setApiKey('');
+ }
+
+ useEffect(() => {
+ let cancelled = false;
+ setConfigured(false);
+ if (Platform.OS === 'ios' && selection.mode === 'providers' && providerId) {
+ getProviderCredentialReference(providerId, selection.endpoint)
+ .then((reference) =>
+ // An unreadable saved key still exists, so offer to remove it.
+ getProviderCredentialStatus(reference).catch(() => ({ reference, isConfigured: true })),
+ )
+ .then((status) => {
+ if (!cancelled) setConfigured(status.isConfigured);
+ })
+ .catch(() => {
+ /* Invalid custom endpoints are explained when saving. */
+ });
+ }
+ return (): void => {
+ cancelled = true;
+ };
+ }, [providerId, selection.endpoint, selection.mode]);
+
+ const showError = (message: string): void => showToast(message, 'error');
+
+ function openPicker(next: Picker): void {
+ setPicker(picker === next ? null : next);
+ }
+
+ // Coming back from the model list with a model downloaded finishes the On-Device switch.
+ 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);
+ return (): void => {
+ cancelled = true;
+ };
+ }, [onDeviceWanted, scope, showToast]),
+ );
+
+ async function chooseMode(mode: InferenceMode): Promise<void> {
+ if (busy) return;
+ setOnDeviceWanted(false);
+ setPicker(null);
+ clearInputs();
+ // Bring Your Own Key needs a provider and key, so it switches on Save.
+ if (mode === 'providers') {
+ setSelection(
+ selection.providerId ? { ...selection, mode } : providerSelection(config, scope),
+ );
+ return;
+ }
+ if (mode === savedSelection.mode) {
+ setSelection(savedSelection);
+ return;
+ }
+ setBusy(true);
+ try {
+ const result = await switchWorkflowMode(scope, mode);
+ if (result === 'switched') {
+ setSelection(useConfigStore.getState().config?.inference?.[scope] ?? { mode });
+ }
+ setOnDeviceWanted(result === 'needs-model');
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ function chooseProvider(nextProviderId: string): void {
+ setDiscoveredModels([]);
+ if (provider) remembered.current[provider.id] = { ...selection, modelId };
+ const next = providers.find((candidate) => candidate.id === nextProviderId);
+ setSelection(
+ remembered.current[nextProviderId] ??
+ config?.rememberedInference?.[scope]?.[nextProviderId] ?? {
+ mode: 'providers',
+ providerId: nextProviderId,
+ modelId: defaultModelId(next),
+ },
+ );
+ setPicker(null);
+ clearInputs();
+ }
+
+ async function prepareSelection(
+ requireModel = true,
+ saveCredential = true,
+ onInvalid: (message: string) => void = showError,
+ ): Promise<InferenceSelection | null> {
+ let saved: InferenceSelection = { mode: selection.mode };
+ if (selection.mode === 'providers') {
+ if (!provider || (requireModel && !modelId.trim())) {
+ onInvalid('Choose a provider and enter a model ID.');
+ return null;
+ }
+ const endpoint = normalizeBaseUrl(
+ provider.id === 'custom' ? selection.endpoint : provider.endpoint,
+ );
+ if (provider.id === 'custom') {
+ if (!isSecureHttpEndpoint(endpoint)) {
+ onInvalid('Use HTTPS, or HTTP for a private-network host.');
+ return null;
+ }
+ const parsed = new URL(endpoint);
+ if (parsed.username || parsed.password || parsed.search || parsed.hash) {
+ onInvalid('Remove credentials, query parameters, and fragments from the endpoint URL.');
+ return null;
+ }
+ }
+ const reference = await getProviderCredentialReference(provider.id, endpoint);
+ const hasNewCredential = !!apiKey.trim();
+ let hasCredential =
+ hasNewCredential || (await getProviderCredentialStatus(reference)).isConfigured;
+ const carried = !hasCredential && saveCredential && (await savedServerCredential(endpoint));
+ if (carried) {
+ await setProviderCredential(reference, carried);
+ hasCredential = true;
+ }
+ if (hasNewCredential && saveCredential) {
+ await setProviderCredential(reference, { apiKey: apiKey.trim() });
+ clearInputs();
+ setConfigured(true);
+ }
+ if (provider.id !== 'custom' && !hasCredential) {
+ onInvalid('Enter a credential for this provider.');
+ return null;
+ }
+ saved = {
+ mode: 'providers',
+ providerId: provider.id,
+ modelId: modelId.trim() || 'catalog-probe',
+ ...(provider.id === 'custom' ? { endpoint } : {}),
+ ...(hasCredential ? { credentialRef: reference } : {}),
+ };
+ }
+ return saved;
+ }
+
+ // A check can move a saved custom server to the /v1 address it answers on. Its key
+ // goes with it, but never to another host.
+ async function savedServerCredential(endpoint: string): Promise<ProviderCredential | null> {
+ const previous = savedSelection;
+ if (
+ previous.providerId !== 'custom' ||
+ !previous.endpoint ||
+ !previous.credentialRef ||
+ !getModelListBaseCandidates(previous.endpoint).includes(endpoint)
+ )
+ return null;
+ return getProviderCredential(previous.credentialRef);
+ }
+
+ // A bare server origin often serves its API under /v1; keep the address that answered.
+ function adoptWorkingEndpoint(draft: InferenceSelection, endpoint: string | undefined): void {
+ if (draft.providerId !== 'custom' || !endpoint || endpoint === draft.endpoint) return;
+ setSelection((current) => ({ ...current, endpoint }));
+ }
+
+ async function save(): Promise<void> {
+ Keyboard.dismiss();
+ const enteredKey = !!apiKey.trim();
+ setBusy(true);
+ try {
+ const saved = await prepareSelection();
+ if (!saved) return;
+ await updateConfig(
+ workflowSaveConfig(useConfigStore.getState().config, scope, saved, activeMode),
+ );
+ if (useConfigStore.getState().error) {
+ showError('Unable to save your selection. Please try again.');
+ return;
+ }
+ if (scope === 'dictation') setActiveMode('providers', true);
+ setSelection(saved);
+ clearInputs();
+ showToast(
+ !enteredKey
+ ? 'Saved.'
+ : provider?.id === 'custom'
+ ? 'Saved. Every workflow using this server uses this key.'
+ : `Saved. Every workflow set to ${keyOwner} uses this key.`,
+ 'success',
+ );
+ } catch {
+ showError('Unable to save provider settings. Check your configuration and try again.');
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ async function diagnose(action: 'test' | 'discover'): Promise<void> {
+ // Focus moves to the result, so the keyboard has no reason to stay up.
+ Keyboard.dismiss();
+ setBusy(true);
+ setChecking(action);
+ const controller = new AbortController();
+ diagnosticController.current = controller;
+ try {
+ const draft = await prepareSelection(action === 'test', false, showError);
+ if (!draft) return;
+ const resolved = resolveMobileInferenceRoute({
+ scope,
+ selection: draft,
+ // A check sends no user content, so On-Device mode does not block it.
+ policy: await getProviderPolicy(),
+ });
+ if (!resolved.ok || resolved.route.mode !== 'providers') {
+ showError(
+ !resolved.ok && resolved.code.startsWith('POLICY')
+ ? 'Organization policy does not currently permit this provider check.'
+ : 'Check your provider, model, and endpoint before testing.',
+ );
+ return;
+ }
+ const checkKey =
+ apiKey.trim() ||
+ (!draft.credentialRef && (await savedServerCredential(draft.endpoint ?? ''))?.apiKey) ||
+ undefined;
+ if (action === 'discover') {
+ const result = await discoverProviderModels({
+ route: resolved.route,
+ signal: controller.signal,
+ apiKey: checkKey,
+ });
+ if (controller.signal.aborted) return;
+ adoptWorkingEndpoint(draft, result.endpoint);
+ setDiscoveredModels(result.models);
+ showToast(
+ result.models.length
+ ? 'Model catalog loaded. Inference access has not been verified.'
+ : 'No models were listed. You can still enter a model ID manually.',
+ 'info',
+ );
+ } else {
+ const result = await testProviderConnection({
+ route: resolved.route,
+ signal: controller.signal,
+ apiKey: checkKey,
+ });
+ if (controller.signal.aborted) return;
+ adoptWorkingEndpoint(draft, result.endpoint);
+ if (result.verification === 'inference')
+ showToast('Connection works. Save to use it.', 'success');
+ else
+ showToast(
+ 'Model catalog accessible. Transcription and inference access have not been verified.',
+ 'info',
+ );
+ }
+ } catch (failure: unknown) {
+ if (!controller.signal.aborted)
+ showError(
+ failure instanceof ProviderExecutionError
+ ? failure.message
+ : 'Unable to check this provider. Check the endpoint and connection, then try again.',
+ );
+ } finally {
+ diagnosticController.current = null;
+ setChecking(null);
+ setBusy(false);
+ }
+ }
+
+ function removeCredential(): void {
+ if (!provider) return;
+ const custom = provider.id === 'custom';
+ confirmDestructive(
+ custom ? "Remove this server's key?" : `Remove your ${keyOwner} key?`,
+ custom
+ ? 'Every workflow using this server loses its key until you add one again.'
+ : `Every workflow set to ${keyOwner} stops until you add a key again.`,
+ async (): Promise<void> => {
+ setBusy(true);
+ try {
+ const reference = await getProviderCredentialReference(provider.id, selection.endpoint);
+ await removeProviderCredential(reference);
+ setConfigured(false);
+ clearInputs();
+ showToast(custom ? 'Server key removed.' : `${keyOwner} key removed.`, 'success');
+ } catch {
+ showError('Unable to remove this key. Please try again.');
+ } finally {
+ setBusy(false);
+ }
+ },
+ { destructiveLabel: 'Remove' },
+ );
+ }
+
+ async function openKeyPage(url: string): Promise<void> {
+ try {
+ await Linking.openURL(url);
+ } catch {
+ showError('Unable to open the provider website. Please try again.');
+ }
+ }
+
+ function choice(title: string, selected: boolean, onPress: () => void): React.JSX.Element {
+ return (
+ <SettingsRow
+ key={title}
+ icon={selected ? 'checkmark.circle.fill' : 'circle'}
+ mdIcon={selected ? 'CircleCheck' : 'Circle'}
+ iconStyle="line"
+ title={title}
+ selected={selected}
+ showChevron={false}
+ onPress={busy ? undefined : onPress}
+ />
+ );
+ }
+
+ return (
+ <View className="flex-1 bg-systemBackground">
+ <SettingsScreen
+ automaticallyAdjustKeyboardInsets
+ keyboardShouldPersistTaps="handled"
+ keyboardDismissMode="interactive"
+ >
+ {scope === 'cleanup' ? <CleanupSettings enabled={!workflowOff} /> : null}
+ {scope === 'agent' ? <AssistantSettings enabled={!workflowOff} /> : null}
+ {workflowOff ? null : (
+ <>
+ <InferenceModePicker
+ scope={speechScope ? 'speech' : 'text'}
+ selectedMode={selection.mode}
+ onSelect={chooseMode}
+ />
+ {modeNote ? <SectionFooter>{modeNote}</SectionFooter> : null}
+ {selection.mode === 'local' && speechScope ? (
+ <OnDeviceModelSection
+ scope={speechScope}
+ picked={
+ isLocalModelKey(savedSelection.modelId) ? savedSelection.modelId : undefined
+ }
+ />
+ ) : null}
+ {selection.mode === 'local' && !speechScope ? (
+ <SectionFooter>Runs on Apple Intelligence on this iPhone.</SectionFooter>
+ ) : null}
+ {selection.mode === 'providers' && provider ? (
+ <>
+ <SettingsSection title="Connection">
+ <SettingsRow
+ icon="network"
+ mdIcon="Network"
+ iconStyle="line"
+ title="Provider"
+ subtitle={provider.name}
+ onPress={busy ? undefined : () => openPicker('provider')}
+ />
+ {picker === 'provider' &&
+ providers.map((item) =>
+ choice(item.name, item.id === provider.id, () => chooseProvider(item.id)),
+ )}
+ {models.length > 0 ? (
+ <SettingsRow
+ icon="square.stack"
+ mdIcon="Layers"
+ iconStyle="line"
+ title="Model"
+ subtitle={models.find((model) => model.id === modelId)?.name ?? modelId}
+ onPress={busy ? undefined : () => openPicker('model')}
+ />
+ ) : null}
+ {picker === 'model' &&
+ models.map((model) =>
+ choice(model.name, model.id === modelId, () => {
+ setSelection({ ...selection, modelId: model.id });
+ setPicker(null);
+ }),
+ )}
+ {provider.id === 'custom' ? (
+ <SettingsTextFieldRow
+ icon="server.rack"
+ mdIcon="Server"
+ label="Server"
+ accessibilityLabel="Server URL"
+ value={selection.endpoint ?? ''}
+ onChangeText={(endpoint) => {
+ setSelection({ ...selection, endpoint });
+ clearInputs();
+ }}
+ autoCapitalize="none"
+ keyboardType="url"
+ placeholder="https://your-server.example/v1"
+ editable={!busy}
+ />
+ ) : null}
+ {!provider.models.length ? (
+ <SettingsTextFieldRow
+ icon="square.stack"
+ mdIcon="Layers"
+ label="Model ID"
+ accessibilityLabel="Model ID"
+ value={modelId}
+ onChangeText={(nextModel) =>
+ setSelection({ ...selection, modelId: nextModel })
+ }
+ autoCapitalize="none"
+ placeholder="model-name"
+ editable={!busy}
+ />
+ ) : null}
+ </SettingsSection>
+ {provider.id === 'custom' ? (
+ <SectionFooter>
+ On iPhone, localhost is this iPhone. Use your server's network address.
+ </SectionFooter>
+ ) : null}
+ <SettingsSection title="API Key">
+ <SettingsTextFieldRow
+ icon="key"
+ mdIcon="KeyRound"
+ accessibilityLabel="API key"
+ value={apiKey}
+ onChangeText={(next) => {
+ // A paste or password-manager fill arrives as one change; typing adds one character.
+ if (next.length - apiKey.length > 1) Keyboard.dismiss();
+ setApiKey(next);
+ }}
+ secureTextEntry
+ autoCapitalize="none"
+ placeholder={
+ configured
+ ? '••••••••••••'
+ : provider.id === 'custom'
+ ? 'Optional'
+ : 'Paste your API key'
+ }
+ accessibilityHint={
+ configured ? 'A key is saved. Enter a new key to replace it.' : undefined
+ }
+ trailing={
+ configured && !apiKey ? (
+ <View className="flex-row items-center gap-1">
+ <SystemIcon
+ name="checkmark.circle.fill"
+ mdName="CircleCheck"
+ size={15}
+ color="systemGreen"
+ />
+ <Text className="text-[15px] text-systemGreen">Saved</Text>
+ </View>
+ ) : undefined
+ }
+ editable={!busy}
+ />
+ {PROVIDER_SETUP_URLS[provider.id] ? (
+ <SettingsRow
+ iconStyle="line"
+ icon="arrow.up.right.square"
+ mdIcon="ExternalLink"
+ title="Get an API Key"
+ showChevron={false}
+ onPress={
+ busy ? undefined : () => openKeyPage(PROVIDER_SETUP_URLS[provider.id])
+ }
+ />
+ ) : null}
+ {configured ? (
+ <SettingsRow
+ iconStyle="line"
+ icon="trash"
+ mdIcon="Trash2"
+ title="Remove Key"
+ destructive
+ showChevron={false}
+ onPress={busy ? undefined : removeCredential}
+ />
+ ) : null}
+ </SettingsSection>
+ <SectionFooter>{keyFooter}</SectionFooter>
+ <SettingsSection title="Verify">
+ <SettingsRow
+ iconStyle="line"
+ icon="checkmark.shield"
+ mdIcon="ShieldCheck"
+ title="Check Connection"
+ showChevron={false}
+ rightElement={checking === 'test' ? <ActivityIndicator /> : undefined}
+ onPress={busy ? undefined : () => diagnose('test')}
+ />
+ {provider.id === 'custom' || provider.id === 'openrouter' ? (
+ <SettingsRow
+ iconStyle="line"
+ icon="magnifyingglass"
+ mdIcon="Search"
+ title="Discover Models"
+ showChevron={false}
+ rightElement={checking === 'discover' ? <ActivityIndicator /> : undefined}
+ onPress={busy ? undefined : () => diagnose('discover')}
+ />
+ ) : null}
+ </SettingsSection>
+ <SectionFooter>
+ Checks use the key above without saving it. Text checks send a short test prompt
+ and may cost a little; transcription checks only confirm access to the model list.
+ </SectionFooter>
+ <View className="mx-4 mb-7">
+ <Pressable
+ accessibilityRole="button"
+ accessibilityState={{ disabled: !canSave, busy }}
+ onPress={save}
+ disabled={!canSave}
+ className={
+ 'items-center rounded-[10px] py-3 ' + (canSave ? 'bg-brand' : 'bg-brand/30')
+ }
+ style={({ pressed }) => ({
+ borderCurve: 'continuous',
+ opacity: pressed ? 0.85 : 1,
+ transform: [{ scale: pressed ? 0.98 : 1 }],
+ })}
+ >
+ {busy && !checking ? (
+ <ActivityIndicator color="white" />
+ ) : (
+ <Text className="text-[15px] font-semibold text-white">Save</Text>
+ )}
+ </Pressable>
+ </View>
+ </>
+ ) : null}
+ {scope === 'notes' ? <NoteTitleSettings /> : null}
+ </>
+ )}
+ </SettingsScreen>
+ <Toast {...toast} topOffset={headerHeight + 8} />
+ </View>
+ );
+}
diff --git a/openwhispr-mobile/src/screens/__tests__/AIModelsScreen.test.tsx b/openwhispr-mobile/src/screens/__tests__/AIModelsScreen.test.tsx
index 95207d086..8e162badf 100644
--- a/openwhispr-mobile/src/screens/__tests__/AIModelsScreen.test.tsx
+++ b/openwhispr-mobile/src/screens/__tests__/AIModelsScreen.test.tsx
@@ -1,35 +1,174 @@
import React from 'react';
-import { Platform } from 'react-native';
-import { render, screen } from '@testing-library/react-native';
-import AIModelsScreen from '../AIModelsScreen';
+import { Alert, Platform } from 'react-native';
+import { fireEvent, render, screen } from '@testing-library/react-native';
+
+const mockPush = jest.fn();
+const mockClearCredentials = jest.fn().mockResolvedValue(undefined);
+let mockActiveMode = 'cloud';
+let mockConfig: Record<string, unknown> | null = null;
+const mockCredentialStatus = jest.fn();
+let mockCredentialListener: (() => void) | null = null;
+const MockText = require('react-native').Text;
jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
-jest.mock('expo-router', () => ({ router: { push: jest.fn() } }));
-jest.mock('@/hooks/useConfigToggle', () => ({ useConfigToggle: () => jest.fn() }));
+jest.mock('expo-router', () => ({ router: { push: (...args: unknown[]) => mockPush(...args) } }));
+jest.mock('@react-navigation/elements', () => ({ useHeaderHeight: () => 0 }));
+jest.mock('@/components/ui/Toast', () => ({
+ Toast: ({ message, visible, type }: { message: string; visible: boolean; type: string }) =>
+ visible ? <MockText testID={`toast-${type}`}>{message}</MockText> : null,
+}));
jest.mock('@/store/useConfigStore', () => ({
- useConfigStore: (selector: (state: unknown) => unknown) =>
- selector({ config: { defaultMode: 'cloud', appleLocalIntelligenceEnabled: false } }),
+ useConfigStore: (selector: (state: unknown) => unknown) => selector({ config: mockConfig }),
}));
jest.mock('@/store/useProcessingModeStore', () => ({
- useProcessingModeStore: () => ({ activeMode: 'cloud' }),
+ useProcessingModeStore: (selector: (state: unknown) => unknown) =>
+ selector({ activeMode: mockActiveMode }),
+}));
+jest.mock('@/hooks/useConfigToggle', () => ({ useConfigToggle: () => jest.fn() }));
+jest.mock('@/lib/localReasoning', () => ({
+ getLocalReasoningReadiness: jest.fn(async () => ({ status: 'ready', tokenCounting: false })),
+}));
+jest.mock('@/services/providers/ProviderCredentials', () => ({
+ clearProviderCredentials: (...args: unknown[]) => mockClearCredentials(...args),
+ getProviderCredentialReference: jest.fn(async (providerId: string) => `provider.${providerId}`),
+ getProviderCredentialStatus: (...args: unknown[]) => mockCredentialStatus(...args),
+ subscribeProviderCredentialChanges: (listener: () => void) => {
+ mockCredentialListener = listener;
+ return () => {
+ mockCredentialListener = null;
+ };
+ },
}));
-jest.mock('@/lib/localReasoning', () => ({ getLocalReasoningReadiness: jest.fn() }));
-const originalOS = Platform.OS;
-afterEach(() => {
- Platform.OS = originalOS;
-});
+import AIModelsScreen from '../AIModelsScreen';
-it('offers Bring Your Own Key on iOS', () => {
+const originalPlatform = Platform.OS;
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockActiveMode = 'cloud';
+ mockConfig = null;
Platform.OS = 'ios';
+ mockCredentialStatus.mockResolvedValue({ isConfigured: true });
+});
+
+afterAll(() => {
+ Platform.OS = originalPlatform;
+});
+
+it('shows what each workflow runs, naming the provider or on-device model', async () => {
+ mockActiveMode = 'providers';
+ mockConfig = {
+ defaultMode: 'providers',
+ inference: {
+ dictation: { mode: 'providers', providerId: 'openai', modelId: 'whisper-1' },
+ upload: { mode: 'local', modelId: 'whisper-base' },
+ notes: { mode: 'openwhispr' },
+ agent: { mode: 'providers', providerId: 'custom', modelId: 'llama' },
+ },
+ };
+ render(<AIModelsScreen />);
+ expect(screen.getByText('OpenAI')).toBeTruthy();
+ expect(screen.getByText('Whisper base')).toBeTruthy();
+ // Bring Your Own Key dictation skips cleanup until a provider is saved for it.
+ expect(screen.getByText('Not set')).toBeTruthy();
+ expect(screen.getByText('OpenWhispr Cloud')).toBeTruthy();
+ expect(screen.getByText('Custom server')).toBeTruthy();
+ expect(screen.queryByText(/Meeting/)).toBeNull();
+ await screen.findByText(/Status: Ready/);
+});
+
+it('opens the tapped workflow on its own page', async () => {
render(<AIModelsScreen />);
- expect(screen.getByText('Bring Your Own Key')).toBeOnTheScreen();
+ fireEvent.press(screen.getByText('Text Cleanup'));
+ expect(mockPush).toHaveBeenCalledWith({
+ pathname: '/(account)/ai-workflow',
+ params: { scope: 'cleanup' },
+ });
+ await screen.findByText(/Status: Ready/);
});
-it('never shows Bring Your Own Key on Android', () => {
+it('keeps the meeting speaker model with the other on-device settings', async () => {
+ render(<AIModelsScreen />);
+ fireEvent.press(screen.getByText('Speaker Separation'));
+ expect(mockPush).toHaveBeenCalledWith('/(account)/diarization-model');
+ expect(screen.getByText('Local Apple Intelligence')).toBeTruthy();
+ await screen.findByText(/Status: Ready/);
+});
+
+it('removes every saved provider key after confirmation', async () => {
+ jest
+ .spyOn(Alert, 'alert')
+ .mockImplementation((_title, _message, buttons) => buttons?.[1]?.onPress?.());
+ render(<AIModelsScreen />);
+ fireEvent.press(screen.getByText('Remove All Provider Keys'));
+ expect(await screen.findByTestId('toast-success')).toHaveTextContent(
+ 'All provider keys were removed.',
+ );
+ expect(mockClearCredentials).toHaveBeenCalledTimes(1);
+});
+
+it('has no provider keys to remove on Android', async () => {
Platform.OS = 'android';
render(<AIModelsScreen />);
- expect(screen.getByText('Speech to Text')).toBeOnTheScreen();
- expect(screen.queryByText('Bring Your Own Key')).not.toBeOnTheScreen();
+ expect(screen.getByText('Dictation')).toBeTruthy();
+ expect(screen.queryByText('Remove All Provider Keys')).toBeNull();
+ await screen.findByText(/Status: Ready/);
+});
+
+it('shows what each workflow really does while On-Device mode is on', async () => {
+ mockActiveMode = 'private';
+ mockConfig = {
+ defaultMode: 'private',
+ inference: {
+ dictation: { mode: 'local', modelId: 'whisper-base' },
+ upload: { mode: 'providers', providerId: 'openai', modelId: 'whisper-1' },
+ cleanup: { mode: 'openwhispr' },
+ },
+ };
+ render(<AIModelsScreen />);
+ // A picked model keeps its name; uploads stay on the phone whatever is saved.
+ expect(screen.getByText('Whisper base')).toBeTruthy();
+ expect(screen.queryByText('OpenAI')).toBeNull();
+ // On-Device transcripts stay raw, so cleanup never runs.
+ expect(screen.getByText('Skipped')).toBeTruthy();
+ // Note chat keeps its own selection, which is OpenWhispr Cloud when unset.
+ expect(screen.getByText('OpenWhispr Cloud')).toBeTruthy();
+ await screen.findByText(/Status: Ready/);
+});
+
+it('shows provider note chat as On-Device, which answers it on this iPhone first', async () => {
+ mockActiveMode = 'private';
+ mockCredentialStatus.mockResolvedValue({ isConfigured: true });
+ mockConfig = {
+ defaultMode: 'private',
+ inference: { agent: { mode: 'providers', providerId: 'groq', modelId: 'llama' } },
+ };
+ render(<AIModelsScreen />);
+ expect(screen.queryByText('Groq')).toBeNull();
+ expect(screen.queryByText('OpenWhispr Cloud')).toBeNull();
+ await screen.findByText(/Status: Ready/);
+});
+
+it('flags a provider workflow whose key was removed', async () => {
+ mockActiveMode = 'providers';
+ mockConfig = {
+ defaultMode: 'providers',
+ inference: {
+ dictation: { mode: 'providers', providerId: 'openai', modelId: 'whisper-1' },
+ cleanup: { mode: 'providers', providerId: 'groq', modelId: 'llama' },
+ },
+ };
+ mockCredentialStatus.mockImplementation(async (reference: string) => ({
+ reference,
+ isConfigured: reference !== 'provider.openai',
+ }));
+ render(<AIModelsScreen />);
+ expect(await screen.findByText('OpenAI · Key missing')).toBeTruthy();
+ expect(screen.getByText('Groq')).toBeTruthy();
+
+ mockCredentialStatus.mockResolvedValue({ isConfigured: false });
+ mockCredentialListener?.();
+ expect(await screen.findByText('Groq · Key missing')).toBeTruthy();
});
diff --git a/openwhispr-mobile/src/screens/__tests__/ByokWorkflowsScreen.test.tsx b/openwhispr-mobile/src/screens/__tests__/ByokWorkflowsScreen.test.tsx
deleted file mode 100644
index 360c5bec6..000000000
--- a/openwhispr-mobile/src/screens/__tests__/ByokWorkflowsScreen.test.tsx
+++ /dev/null
@@ -1,150 +0,0 @@
-import React from 'react';
-import { Alert } from 'react-native';
-import { fireEvent, render, screen } from '@testing-library/react-native';
-
-const mockPush = jest.fn();
-const mockClearCredentials = jest.fn().mockResolvedValue(undefined);
-let mockActiveMode = 'cloud';
-let mockConfig: Record<string, unknown> | null = null;
-const mockCredentialStatus = jest.fn();
-let mockCredentialListener: (() => void) | null = null;
-
-jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
-jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
-jest.mock('expo-router', () => ({ router: { push: (...args: unknown[]) => mockPush(...args) } }));
-jest.mock('@/store/useConfigStore', () => ({
- useConfigStore: (selector: (state: unknown) => unknown) => selector({ config: mockConfig }),
-}));
-jest.mock('@/store/useAuthStore', () => ({ useAuthStore: { getState: () => ({ user: null }) } }));
-jest.mock('@/lib/privateMode', () => ({}));
-jest.mock('@/store/useProcessingModeStore', () => ({
- useProcessingModeStore: (selector: (state: unknown) => unknown) =>
- selector({ activeMode: mockActiveMode }),
-}));
-jest.mock('@/services/providers/ProviderCredentials', () => ({
- clearProviderCredentials: (...args: unknown[]) => mockClearCredentials(...args),
- getProviderCredentialReference: jest.fn(async (providerId: string) => `provider.${providerId}`),
- getProviderCredentialStatus: (...args: unknown[]) => mockCredentialStatus(...args),
- subscribeProviderCredentialChanges: (listener: () => void) => {
- mockCredentialListener = listener;
- return () => {
- mockCredentialListener = null;
- };
- },
-}));
-
-import { ByokWorkflowsScreen } from '../ByokWorkflowsScreen';
-
-beforeEach(() => {
- jest.clearAllMocks();
- mockActiveMode = 'cloud';
- mockConfig = null;
- mockCredentialStatus.mockResolvedValue({ isConfigured: true });
-});
-
-it('shows what each workflow runs, naming the provider for Bring Your Own Key', () => {
- mockActiveMode = 'providers';
- mockConfig = {
- defaultMode: 'providers',
- inference: {
- dictation: { mode: 'providers', providerId: 'openai', modelId: 'whisper-1' },
- upload: { mode: 'local' },
- notes: { mode: 'openwhispr' },
- agent: { mode: 'providers', providerId: 'custom', modelId: 'llama' },
- },
- };
- render(<ByokWorkflowsScreen />);
- expect(screen.getByText('OpenAI')).toBeTruthy();
- expect(screen.getByText('On-Device')).toBeTruthy();
- // Bring Your Own Key dictation skips cleanup until a provider is saved for it.
- expect(screen.getByText('Not set')).toBeTruthy();
- expect(screen.getByText('OpenWhispr Cloud')).toBeTruthy();
- expect(screen.getByText('Custom server')).toBeTruthy();
- expect(screen.queryByText(/Meeting/)).toBeNull();
-});
-
-it('opens the tapped workflow on its own page', () => {
- render(<ByokWorkflowsScreen />);
- fireEvent.press(screen.getByText('Text Cleanup'));
- expect(mockPush).toHaveBeenCalledWith({
- pathname: '/(account)/provider-workflow',
- params: { scope: 'cleanup' },
- });
-});
-
-it('removes every saved provider key after confirmation', async () => {
- jest
- .spyOn(Alert, 'alert')
- .mockImplementation((_title, _message, buttons) => buttons?.[1]?.onPress?.());
- render(<ByokWorkflowsScreen />);
- fireEvent.press(screen.getByText('Remove all provider keys'));
- await screen.findByText('All provider keys were removed.');
- expect(mockClearCredentials).toHaveBeenCalledTimes(1);
-});
-
-it('shows what each workflow really does while On-Device mode is on', () => {
- mockActiveMode = 'private';
- mockConfig = {
- defaultMode: 'private',
- inference: {
- dictation: { mode: 'local' },
- upload: { mode: 'providers', providerId: 'openai', modelId: 'whisper-1' },
- cleanup: { mode: 'openwhispr' },
- },
- };
- render(<ByokWorkflowsScreen />);
- // Dictation, uploads and note formatting stay on the phone whatever is saved.
- expect(screen.getAllByText('On-Device')).toHaveLength(3);
- expect(screen.queryByText('OpenAI')).not.toBeOnTheScreen();
- // On-Device transcripts stay raw, so cleanup never runs.
- expect(screen.getByText('Skipped')).toBeTruthy();
- // Note chat keeps its own selection, which is OpenWhispr Cloud when unset.
- expect(screen.getByText('OpenWhispr Cloud')).toBeTruthy();
-});
-
-it('shows provider note chat as On-Device, which answers it on this iPhone first', () => {
- mockActiveMode = 'private';
- mockCredentialStatus.mockResolvedValue({ isConfigured: true });
- mockConfig = {
- defaultMode: 'private',
- inference: { agent: { mode: 'providers', providerId: 'groq', modelId: 'llama' } },
- };
- render(<ByokWorkflowsScreen />);
- expect(screen.getAllByText('On-Device')).toHaveLength(4);
- expect(screen.queryByText('Groq')).not.toBeOnTheScreen();
-});
-
-it('flags a provider workflow whose key was removed', async () => {
- mockActiveMode = 'providers';
- mockConfig = {
- defaultMode: 'providers',
- inference: {
- dictation: { mode: 'providers', providerId: 'openai', modelId: 'whisper-1' },
- cleanup: { mode: 'providers', providerId: 'groq', modelId: 'llama' },
- },
- };
- mockCredentialStatus.mockImplementation(async (reference: string) => ({
- reference,
- isConfigured: reference !== 'provider.openai',
- }));
- render(<ByokWorkflowsScreen />);
- expect(await screen.findByText('OpenAI · Key missing')).toBeTruthy();
- expect(screen.getByText('Groq')).toBeTruthy();
-
- mockCredentialStatus.mockResolvedValue({ isConfigured: false });
- mockCredentialListener?.();
- expect(await screen.findByText('Groq · Key missing')).toBeTruthy();
-});
-
-it('does not list workflows on Android', () => {
- const platform = require('react-native').Platform;
- const original = platform.OS;
- platform.OS = 'android';
- try {
- render(<ByokWorkflowsScreen />);
- expect(screen.queryByText('Remove all provider keys')).not.toBeOnTheScreen();
- expect(screen.getByText(/Provider setup is available on iOS/)).toBeTruthy();
- } finally {
- platform.OS = original;
- }
-});
diff --git a/openwhispr-mobile/src/screens/__tests__/CleanupPromptScreen.test.tsx b/openwhispr-mobile/src/screens/__tests__/CleanupPromptScreen.test.tsx
index 1cdc67434..0e57fcb61 100644
--- a/openwhispr-mobile/src/screens/__tests__/CleanupPromptScreen.test.tsx
+++ b/openwhispr-mobile/src/screens/__tests__/CleanupPromptScreen.test.tsx
@@ -119,7 +119,7 @@ describe('CleanupPromptScreen — guidance', () => {
it('shows the inactive notice when cleanup is turned off', () => {
mockConfig = { defaultMode: 'cloud', cleanupEnabled: false };
render(<CleanupPromptScreen />);
- expect(screen.getByText(/Dictation Cleanup is off/)).toBeTruthy();
+ expect(screen.getByText(/Text Cleanup is off/)).toBeTruthy();
});
it('hides the notice in Cloud mode with cleanup on', () => {
diff --git a/openwhispr-mobile/src/screens/__tests__/DictationCleanupScreen.test.tsx b/openwhispr-mobile/src/screens/__tests__/DictationCleanupScreen.test.tsx
deleted file mode 100644
index 3dff90d7e..000000000
--- a/openwhispr-mobile/src/screens/__tests__/DictationCleanupScreen.test.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-import React from 'react';
-import { fireEvent, render, screen } from '@testing-library/react-native';
-
-const mockRouterPush = jest.fn();
-let mockStoredPrompt = '';
-
-jest.mock('expo-router', () => ({
- router: { push: (...args: unknown[]) => mockRouterPush(...args) },
-}));
-// 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('@/store/useConfigStore', () => ({
- useConfigStore: (selector: (state: unknown) => unknown) => selector({ config: null }),
-}));
-jest.mock('@/hooks/useConfigToggle', () => ({ useConfigToggle: () => jest.fn() }));
-jest.mock('@/store/useCustomPromptsStore', () => ({
- useCustomPromptsStore: (selector: (state: unknown) => unknown) =>
- selector({ customPrompts: { cleanup: mockStoredPrompt } }),
-}));
-
-import DictationCleanupScreen from '../DictationCleanupScreen';
-
-beforeEach(() => {
- jest.clearAllMocks();
- mockStoredPrompt = '';
-});
-
-describe('DictationCleanupScreen — Cleanup Prompt entry point', () => {
- it('shows the prompt row as Default when no override is stored', () => {
- render(<DictationCleanupScreen />);
- expect(screen.getByText('Cleanup Prompt')).toBeTruthy();
- expect(screen.getByText('Default')).toBeTruthy();
- });
-
- it('shows the prompt row as Custom when an override is stored', () => {
- mockStoredPrompt = 'Always use bullet points.';
- render(<DictationCleanupScreen />);
- expect(screen.getByText('Custom')).toBeTruthy();
- });
-
- it('opens the prompt editor', () => {
- render(<DictationCleanupScreen />);
- fireEvent.press(screen.getByText('Cleanup Prompt'));
- expect(mockRouterPush).toHaveBeenCalledWith('/(account)/cleanup-prompt');
- });
-});
diff --git a/openwhispr-mobile/src/screens/__tests__/HomeScreen.proCompletion.test.tsx b/openwhispr-mobile/src/screens/__tests__/HomeScreen.proCompletion.test.tsx
index 760df6959..84ae60002 100644
--- a/openwhispr-mobile/src/screens/__tests__/HomeScreen.proCompletion.test.tsx
+++ b/openwhispr-mobile/src/screens/__tests__/HomeScreen.proCompletion.test.tsx
@@ -1,6 +1,6 @@
import React from 'react';
import { Alert } from 'react-native';
-import { render, screen } from '@testing-library/react-native';
+import { fireEvent, render, screen } from '@testing-library/react-native';
let mockRouteParams: { proCompletion?: string } = {};
const mockRouterSetParams = jest.fn();
@@ -195,13 +195,13 @@ describe('HomeScreen mode control', () => {
mockProcessingModeStoreState.activeMode = 'cloud';
});
- it('is a button that opens Speech to Text in Bring Your Own Key mode', () => {
+ it('is a button that opens the Dictation page in Bring Your Own Key mode', () => {
mockProcessingModeStoreState.activeMode = 'providers';
render(<HomeScreen />);
const control = screen.getByLabelText('Transcription: Bring Your Own Key');
expect(control.props.accessibilityRole).toBe('button');
expect(control.props.accessibilityState?.checked).toBeUndefined();
- expect(control.props.accessibilityHint).toBe('Opens Speech to Text settings.');
+ expect(control.props.accessibilityHint).toBe('Opens Dictation settings.');
});
it('is a Cloud switch otherwise', () => {
@@ -210,4 +210,14 @@ describe('HomeScreen mode control', () => {
expect(control.props.accessibilityRole).toBe('switch');
expect(control.props.accessibilityState).toMatchObject({ checked: true });
});
+
+ it('opens the Dictation page when dictation uses your own key', () => {
+ mockProcessingModeStoreState.activeMode = 'providers';
+ render(<HomeScreen />);
+ fireEvent.press(screen.getByLabelText('Transcription: Bring Your Own Key'));
+ expect(require('expo-router').router.push).toHaveBeenCalledWith({
+ pathname: '/(account)/ai-workflow',
+ params: { scope: 'dictation' },
+ });
+ });
});
diff --git a/openwhispr-mobile/src/screens/__tests__/ModelDownloadScreen.partialDownload.test.tsx b/openwhispr-mobile/src/screens/__tests__/ModelDownloadScreen.partialDownload.test.tsx
index 97bbd563a..501344fed 100644
--- a/openwhispr-mobile/src/screens/__tests__/ModelDownloadScreen.partialDownload.test.tsx
+++ b/openwhispr-mobile/src/screens/__tests__/ModelDownloadScreen.partialDownload.test.tsx
@@ -143,3 +143,14 @@ describe('ModelDownloadScreen — partial Parakeet download', () => {
expect(screen.queryByText(/saved from an earlier attempt/)).toBeNull();
});
});
+
+describe('ModelDownloadScreen — model languages', () => {
+ it('offers the language list beside each multi-language model', async () => {
+ await renderAsync(<ModelDownloadScreen />);
+
+ expect(screen.getByText('Parakeet v3')).toBeTruthy();
+ expect(screen.getByLabelText('Parakeet v3 languages')).toBeTruthy();
+ expect(screen.getByLabelText('Whisper base languages')).toBeTruthy();
+ expect(screen.queryByLabelText('Parakeet v2 languages')).toBeNull();
+ });
+});
diff --git a/openwhispr-mobile/src/screens/__tests__/NoteEditorScreen.calendarContext.test.tsx b/openwhispr-mobile/src/screens/__tests__/NoteEditorScreen.calendarContext.test.tsx
index e4ed8b259..5872e531d 100644
--- a/openwhispr-mobile/src/screens/__tests__/NoteEditorScreen.calendarContext.test.tsx
+++ b/openwhispr-mobile/src/screens/__tests__/NoteEditorScreen.calendarContext.test.tsx
@@ -223,9 +223,11 @@ jest.mock('@/components/notes/NoteActionsMenu', () => ({
NoteActionsMenu: ({
actions,
onRunAction,
+ onAskNote,
}: {
actions: Action[];
onRunAction: (action: Action) => void;
+ onAskNote?: () => void;
}) =>
(() => {
const { Pressable: MockPressable, Text: MockText, View: MockView } = require('react-native');
@@ -240,6 +242,7 @@ jest.mock('@/components/notes/NoteActionsMenu', () => ({
<MockText>{action.name}</MockText>
</MockPressable>
))}
+ {onAskNote ? <MockText>Ask about this note</MockText> : null}
</MockView>
);
})(),
@@ -417,6 +420,7 @@ beforeEach(() => {
mockAppleAvailability = 'available';
mockAuthState.user = { id: 'user-1', email: '[email protected]', emailVerified: true };
mockConfigState.config.inference = undefined;
+ mockConfigState.config.dictationAgentEnabled = undefined;
mockProcessingModeState.activeMode = 'cloud';
mockActions = [defaultAction()];
mockActionsState.actions = mockActions;
@@ -539,6 +543,19 @@ describe('NoteEditorScreen generated meeting context', () => {
});
});
+describe('NoteEditorScreen note chat', () => {
+ it('offers Ask about this note while Chat & Voice Assistant is on', () => {
+ const { getByText } = render(<NoteEditorScreen />);
+ expect(getByText('Ask about this note')).toBeTruthy();
+ });
+
+ it('hides Ask about this note when Chat & Voice Assistant is off', () => {
+ mockConfigState.config.dictationAgentEnabled = false;
+ const { queryByText } = render(<NoteEditorScreen />);
+ expect(queryByText('Ask about this note')).toBeNull();
+ });
+});
+
describe('NoteEditorScreen generated titles', () => {
const personalNote = (title: string): Note =>
note({
diff --git a/openwhispr-mobile/src/screens/__tests__/SpeechToTextScreen.test.tsx b/openwhispr-mobile/src/screens/__tests__/SpeechToTextScreen.test.tsx
deleted file mode 100644
index 588ad79e3..000000000
--- a/openwhispr-mobile/src/screens/__tests__/SpeechToTextScreen.test.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import React from 'react';
-import { Alert } from 'react-native';
-import { fireEvent, render, screen, waitFor } from '@testing-library/react-native';
-import SpeechToTextScreen from '../SpeechToTextScreen';
-
-const mockPush = jest.fn();
-const mockUpdateConfig = jest.fn();
-const mockSetActiveMode = jest.fn();
-const mockPrivateReadiness = jest.fn();
-
-jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
-jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
-jest.mock('@/lib/utils', () => ({ safeHaptics: jest.fn() }));
-jest.mock('expo-router', () => ({ router: { push: (...args: unknown[]) => mockPush(...args) } }));
-jest.mock('@/store/useConfigStore', () => ({
- useConfigStore: (selector: (state: unknown) => unknown) =>
- selector({ config: { defaultMode: 'cloud' }, updateConfig: mockUpdateConfig }),
-}));
-jest.mock('@/store/useProcessingModeStore', () => ({
- useProcessingModeStore: () => ({ activeMode: 'cloud', setActiveMode: mockSetActiveMode }),
-}));
-jest.mock('@/store/useAuthStore', () => ({
- useAuthStore: Object.assign(
- (selector: (state: unknown) => unknown) => selector({ user: { id: 'user-1' } }),
- { getState: () => ({ user: { id: 'user-1' } }) },
- ),
-}));
-jest.mock('@/lib/privateMode', () => ({
- getPrivateModeReadiness: () => mockPrivateReadiness(),
- getPrivateModeUnavailableMessage: () => 'Unavailable.',
-}));
-
-beforeEach(() => jest.clearAllMocks());
-
-it('opens the Dictation workflow with Bring Your Own Key chosen', () => {
- render(<SpeechToTextScreen />);
- fireEvent.press(screen.getByText('Bring Your Own Key'));
- expect(mockPush).toHaveBeenCalledWith({
- pathname: '/(account)/provider-workflow',
- params: { scope: 'dictation', mode: 'providers' },
- });
-});
-
-it('asks for the on-device model before switching to On-Device', async () => {
- const alert = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined);
- mockPrivateReadiness.mockResolvedValue({ status: 'missing', modelName: 'Parakeet v3' });
- render(<SpeechToTextScreen />);
- fireEvent.press(screen.getByText('On-Device'));
- await waitFor(() => expect(alert).toHaveBeenCalled());
- expect(alert.mock.calls[0][0]).toBe('Download required');
- expect(mockUpdateConfig).not.toHaveBeenCalled();
- alert.mockRestore();
-});
-
-it('switches to On-Device once the model is downloaded', async () => {
- mockPrivateReadiness.mockResolvedValue({ status: 'ready', modelName: 'Parakeet v3' });
- render(<SpeechToTextScreen />);
- fireEvent.press(screen.getByText('On-Device'));
- await waitFor(() => expect(mockSetActiveMode).toHaveBeenCalledWith('private', true));
- expect(mockUpdateConfig).toHaveBeenCalledWith(
- expect.objectContaining({
- defaultMode: 'private',
- inference: { dictation: { mode: 'local' } },
- }),
- );
-});
diff --git a/openwhispr-mobile/src/screens/__tests__/ProviderSettingsScreen.test.tsx b/openwhispr-mobile/src/screens/__tests__/WorkflowSettingsScreen.test.tsx
similarity index 59%
rename from openwhispr-mobile/src/screens/__tests__/ProviderSettingsScreen.test.tsx
rename to openwhispr-mobile/src/screens/__tests__/WorkflowSettingsScreen.test.tsx
index fc15f282d..491437106 100644
--- a/openwhispr-mobile/src/screens/__tests__/ProviderSettingsScreen.test.tsx
+++ b/openwhispr-mobile/src/screens/__tests__/WorkflowSettingsScreen.test.tsx
@@ -13,35 +13,41 @@ let mockActiveMode = 'cloud';
const mockCredentialStatus = jest.fn().mockResolvedValue({ isConfigured: false });
let mockConfig: Record<string, unknown> | null = null;
let mockScope: string | undefined;
-let mockModeParam: string | undefined;
-let mockUser: { id: string } | null = { id: 'user-1' };
-const mockPrivateReadiness = jest.fn();
const mockPreventRemove = jest.fn();
const mockDispatch = jest.fn();
-const mockLocalReasoningReadiness = jest.fn();
+let mockStoredPrompt = '';
+const mockPush = jest.fn();
+const mockSwitchMode = jest.fn();
+const mockPrivateReadiness = jest.fn();
+let mockFocusEffect: (() => void) | undefined;
const MockText = require('react-native').Text;
jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
jest.mock('@/components/ui/GradientGlassSurface', () => ({ GradientGlassSurface: () => null }));
jest.mock('expo-router', () => ({
- useLocalSearchParams: () => ({ scope: mockScope, mode: mockModeParam }),
- router: { push: jest.fn() },
-}));
-jest.mock('@/store/useAuthStore', () => ({
- useAuthStore: Object.assign(
- (selector: (state: unknown) => unknown) => selector({ user: mockUser }),
- { getState: () => ({ user: mockUser }) },
- ),
+ router: { push: (...args: unknown[]) => mockPush(...args) },
+ useLocalSearchParams: () => ({ scope: mockScope }),
+ // Tests call the latest effect to act out returning to the page.
+ useFocusEffect: (effect: () => void) => {
+ mockFocusEffect = effect;
+ },
}));
jest.mock('@/lib/privateMode', () => ({
getPrivateModeReadiness: () => mockPrivateReadiness(),
- getPrivateModeUnavailableMessage: () => 'Native modules are missing.',
}));
-jest.mock('@/lib/localReasoning', () => ({
- getLocalReasoningReadiness: () => mockLocalReasoningReadiness(),
- getLocalReasoningUnavailableMessage: () =>
- 'Local Apple Intelligence is unavailable on this device.',
+jest.mock('@/lib/workflowModeSwitch', () => ({
+ switchWorkflowMode: (...args: unknown[]) => mockSwitchMode(...args),
+}));
+jest.mock('@/components/settings/OnDeviceModelSection', () => ({
+ OnDeviceModelSection: ({ scope, picked }: { scope: string; picked?: string }) => (
+ <MockText>{`On-device models for ${scope}, picked ${picked ?? 'Automatic'}`}</MockText>
+ ),
+}));
+jest.mock('@/hooks/useConfigToggle', () => ({ useConfigToggle: () => jest.fn() }));
+jest.mock('@/store/useCustomPromptsStore', () => ({
+ useCustomPromptsStore: (selector: (state: unknown) => unknown) =>
+ selector({ customPrompts: { cleanup: mockStoredPrompt } }),
}));
jest.mock('@react-navigation/elements', () => ({ useHeaderHeight: () => 0 }));
jest.mock('@react-navigation/native', () => ({
@@ -96,7 +102,7 @@ jest.mock('@/services/providers/ProviderCredentials', () => ({
removeProviderCredential: (...args: unknown[]) => mockRemoveCredential(...args),
}));
-import { ProviderSettingsScreen } from '../ProviderSettingsScreen';
+import { WorkflowSettingsScreen } from '../WorkflowSettingsScreen';
function chooseProvider(provider: string): void {
fireEvent.press(screen.getByText('Provider'));
@@ -119,11 +125,17 @@ beforeEach(() => {
jest.clearAllMocks();
mockConfig = null;
mockScope = 'dictation';
- mockModeParam = undefined;
+ mockStoredPrompt = '';
+ // A successful switch saves the mode, as the real helper does through the config store.
+ mockSwitchMode.mockImplementation(async (scope: string, mode: string) => {
+ mockConfig = {
+ ...mockConfig,
+ inference: { ...(mockConfig?.inference as object), [scope]: { mode } },
+ };
+ return 'switched';
+ });
+ mockPrivateReadiness.mockResolvedValue({ status: 'missing', modelName: 'Parakeet v2' });
mockActiveMode = 'cloud';
- mockUser = { id: 'user-1' };
- mockPrivateReadiness.mockResolvedValue({ status: 'ready', modelName: 'Parakeet v3' });
- mockLocalReasoningReadiness.mockResolvedValue({ status: 'ready', tokenCounting: false });
mockPolicy.mockResolvedValue({ status: 'unmanaged' });
mockTestConnection.mockResolvedValue({ ok: true, verification: 'catalog-only' });
mockDiscoverModels.mockResolvedValue({
@@ -134,11 +146,14 @@ beforeEach(() => {
});
it('lets a signed-out user save a secure credential reference without persisting the key', async () => {
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
fireEvent.changeText(screen.getByLabelText('API key'), 'test-key-value');
- fireEvent.press(screen.getByText('Save selection'));
+ fireEvent.press(screen.getByText('Save'));
await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalled());
+ expect(await screen.findByTestId('toast-success')).toHaveTextContent(
+ 'Saved. Every workflow set to OpenAI uses this key.',
+ );
expect(mockSetCredential).toHaveBeenCalledWith('provider.openai', { apiKey: 'test-key-value' });
expect(mockUpdateConfig.mock.calls[0][0]).toMatchObject({
defaultMode: 'providers',
@@ -152,20 +167,22 @@ it('lets a signed-out user save a secure credential reference without persisting
});
it('rejects public HTTP endpoints before storing a credential', async () => {
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
chooseProvider('Custom');
- fireEvent.changeText(screen.getByLabelText('Endpoint URL'), 'http://example.com/v1');
+ fireEvent.changeText(screen.getByLabelText('Server URL'), 'http://example.com/v1');
fireEvent.changeText(screen.getByLabelText('Model ID'), 'custom-model');
fireEvent.changeText(screen.getByLabelText('API key'), 'test-key-value');
- fireEvent.press(screen.getByText('Save selection'));
- await screen.findByText('Use HTTPS, or HTTP for a private-network host.');
+ fireEvent.press(screen.getByText('Save'));
+ expect(await screen.findByTestId('toast-error')).toHaveTextContent(
+ 'Use HTTPS, or HTTP for a private-network host.',
+ );
expect(mockSetCredential).not.toHaveBeenCalled();
expect(mockUpdateConfig).not.toHaveBeenCalled();
});
it('keeps model choices separate when switching providers and clears credential input', async () => {
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
fireEvent.press(screen.getByText('Model'));
fireEvent.press(screen.getByText('Whisper'));
@@ -178,12 +195,12 @@ it('keeps model choices separate when switching providers and clears credential
it('saves custom endpoints without requiring an API key and preserves other scopes', async () => {
mockConfig = { defaultMode: 'cloud', inference: { cleanup: { mode: 'local' } } };
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
chooseProvider('Custom');
- fireEvent.changeText(screen.getByLabelText('Endpoint URL'), 'http://192.168.1.2:8080/v1/');
+ fireEvent.changeText(screen.getByLabelText('Server URL'), 'http://192.168.1.2:8080/v1/');
fireEvent.changeText(screen.getByLabelText('Model ID'), 'local-model');
- fireEvent.press(screen.getByText('Save selection'));
+ fireEvent.press(screen.getByText('Save'));
await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalled());
expect(mockSetCredential).not.toHaveBeenCalled();
expect(mockUpdateConfig.mock.calls[0][0].inference).toMatchObject({
@@ -197,20 +214,32 @@ it('saves custom endpoints without requiring an API key and preserves other scop
expect(mockUpdateConfig.mock.calls[0][0].inference.dictation.credentialRef).toBeUndefined();
});
-it('removes an existing credential and requires a replacement before saving', async () => {
+it('removes an existing key after confirmation and requires a replacement before saving', async () => {
+ const alert = jest
+ .spyOn(Alert, 'alert')
+ .mockImplementation((_title, _message, buttons) =>
+ buttons?.find((button) => button.style === 'destructive')?.onPress?.(),
+ );
mockCredentialStatus.mockResolvedValue({ isConfigured: true });
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
- fireEvent.press(await screen.findByText('Remove credential'));
+ fireEvent.press(await screen.findByText('Remove Key'));
+ expect(alert.mock.calls[0][0]).toBe('Remove your OpenAI key?');
await waitFor(() => expect(mockRemoveCredential).toHaveBeenCalledWith('provider.openai'));
+ expect(await screen.findByTestId('toast-success')).toHaveTextContent('OpenAI key removed.');
mockCredentialStatus.mockResolvedValue({ isConfigured: false });
- fireEvent.press(screen.getByText('Save selection'));
- await screen.findByText('Enter a credential for this provider.');
+ fireEvent.press(screen.getByText('Save'));
+ await waitFor(() =>
+ expect(screen.getByTestId('toast-error')).toHaveTextContent(
+ 'Enter a credential for this provider.',
+ ),
+ );
expect(mockUpdateConfig).not.toHaveBeenCalled();
+ alert.mockRestore();
});
it('lists only the supported providers', async () => {
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
fireEvent.press(screen.getByText('Provider'));
// OpenAI is both the selected row's subtitle and a picker choice.
@@ -225,11 +254,11 @@ it('lists only the supported providers', async () => {
it('saves text workflow selection independently from the dictation mode', async () => {
mockConfig = { defaultMode: 'private', inference: { dictation: { mode: 'local' } } };
mockScope = 'cleanup';
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
chooseProvider('Groq');
fireEvent.changeText(screen.getByLabelText('API key'), 'test-text-key');
- fireEvent.press(screen.getByText('Save selection'));
+ fireEvent.press(screen.getByText('Save'));
await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalled());
expect(mockUpdateConfig.mock.calls[0][0]).toMatchObject({
inference: {
@@ -248,7 +277,7 @@ it('restores a provider model saved in an earlier settings session', async () =>
dictation: { openai: { mode: 'providers', providerId: 'openai', modelId: 'whisper-1' } },
},
};
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
chooseProvider('Groq');
chooseProvider('OpenAI');
@@ -256,24 +285,25 @@ it('restores a provider model saved in an earlier settings session', async () =>
expect(screen.getByText('Whisper')).toBeTruthy();
});
-it('does not expose provider setup on Android', () => {
+it('offers Cloud and On-Device on Android, without Bring Your Own Key', () => {
const platform = require('react-native').Platform;
const original = platform.OS;
platform.OS = 'android';
try {
- render(<ProviderSettingsScreen />);
- expect(screen.queryByText('Save selection')).toBeNull();
- expect(screen.getByText(/Provider setup is available on iOS/)).toBeTruthy();
+ render(<WorkflowSettingsScreen />);
+ expect(screen.getByText('OpenWhispr Cloud')).toBeTruthy();
+ expect(screen.getByText('On-Device')).toBeTruthy();
+ expect(screen.queryByText('Bring Your Own Key')).toBeNull();
} finally {
platform.OS = original;
}
});
it('reports catalog-only checks without claiming inference access or changing the workflow', async () => {
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
fireEvent.changeText(screen.getByLabelText('API key'), 'test-key');
- fireEvent.press(screen.getByText('Check connection'));
+ fireEvent.press(screen.getByText('Check Connection'));
expect(await screen.findByTestId('toast-info')).toHaveTextContent(
'Model catalog accessible. Transcription and inference access have not been verified.',
);
@@ -294,21 +324,21 @@ it('reports catalog-only checks without claiming inference access or changing th
it('offers to replace or remove a saved key that can no longer be read', async () => {
mockCredentialStatus.mockRejectedValue(new Error('unreadable'));
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
- await screen.findByText('Remove credential');
+ await screen.findByText('Remove Key');
fireEvent.changeText(screen.getByLabelText('API key'), 'replacement-key');
- fireEvent.press(screen.getByText('Save selection'));
+ fireEvent.press(screen.getByText('Save'));
await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalled());
expect(mockSetCredential).toHaveBeenCalledWith('provider.openai', { apiKey: 'replacement-key' });
});
it('blocks diagnostic network calls when organization policy is unresolved', async () => {
mockPolicy.mockResolvedValue({ status: 'pending' });
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
fireEvent.changeText(screen.getByLabelText('API key'), 'test-key');
- fireEvent.press(screen.getByText('Check connection'));
+ fireEvent.press(screen.getByText('Check Connection'));
expect(await screen.findByTestId('toast-error')).toHaveTextContent(
'Organization policy does not currently permit this provider check.',
);
@@ -318,10 +348,10 @@ it('blocks diagnostic network calls when organization policy is unresolved', asy
it('reports a passing inference check as a success toast', async () => {
mockTestConnection.mockResolvedValue({ ok: true, verification: 'inference' });
mockScope = 'cleanup';
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
fireEvent.changeText(screen.getByLabelText('API key'), 'test-key');
- fireEvent.press(screen.getByText('Check connection'));
+ fireEvent.press(screen.getByText('Check Connection'));
expect(await screen.findByTestId('toast-success')).toHaveTextContent(
'Connection works. Save to use it.',
);
@@ -329,9 +359,9 @@ it('reports a passing inference check as a success toast', async () => {
it('reports a check without a key as an error toast and closes the keyboard', async () => {
const dismiss = jest.spyOn(Keyboard, 'dismiss');
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
- fireEvent.press(screen.getByText('Check connection'));
+ fireEvent.press(screen.getByText('Check Connection'));
expect(dismiss).toHaveBeenCalled();
expect(await screen.findByTestId('toast-error')).toHaveTextContent(
'Enter a credential for this provider.',
@@ -341,7 +371,7 @@ it('reports a check without a key as an error toast and closes the keyboard', as
it('closes the keyboard when a key is pasted, but not while typing', () => {
const dismiss = jest.spyOn(Keyboard, 'dismiss');
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
const input = screen.getByLabelText('API key');
fireEvent.changeText(input, 's');
@@ -353,10 +383,10 @@ it('closes the keyboard when a key is pasted, but not while typing', () => {
it('checks a provider from On-Device mode, since a check sends no user content', async () => {
mockActiveMode = 'private';
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
fireEvent.changeText(screen.getByLabelText('API key'), 'test-key');
- fireEvent.press(screen.getByText('Check connection'));
+ fireEvent.press(screen.getByText('Check Connection'));
await screen.findByTestId('toast-info');
expect(mockTestConnection).toHaveBeenCalled();
});
@@ -368,7 +398,7 @@ it('shows cleanup as waiting for a provider when Bring Your Own Key dictation wi
};
mockActiveMode = 'providers';
mockScope = 'cleanup';
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
expect(selectedMode()).toBe('Bring Your Own Key');
expect(
screen.getByText('Not saved yet. Cleanup is skipped until you save a selection.'),
@@ -378,16 +408,16 @@ it('shows cleanup as waiting for a provider when Bring Your Own Key dictation wi
it('shows a guest held in On-Device mode as On-Device, not a stale Cloud preference', () => {
mockConfig = { defaultMode: 'cloud' };
mockActiveMode = 'private';
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
expect(selectedMode()).toBe('On-Device');
});
it('discovers custom models before choosing a model, without silently selecting one', async () => {
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
chooseProvider('Custom');
- fireEvent.changeText(screen.getByLabelText('Endpoint URL'), 'https://example.com/v1');
- fireEvent.press(screen.getByText('Discover models'));
+ fireEvent.changeText(screen.getByLabelText('Server URL'), 'https://example.com/v1');
+ fireEvent.press(screen.getByText('Discover Models'));
expect(await screen.findByTestId('toast-info')).toHaveTextContent(
'Model catalog loaded. Inference access has not been verified.',
);
@@ -402,7 +432,7 @@ it('defaults an unselected workflow to On-Device for a private-mode user', () =>
mockConfig = { defaultMode: 'private' };
mockActiveMode = 'private';
mockScope = 'upload';
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
expect(selectedMode()).toBe('On-Device');
});
@@ -410,9 +440,9 @@ it('keeps uploads on the previous mode when dictation switches to Bring Your Own
mockConfig = { defaultMode: 'private' };
mockActiveMode = 'private';
mockCredentialStatus.mockResolvedValue({ isConfigured: true });
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
- fireEvent.press(screen.getByText('Save selection'));
+ fireEvent.press(screen.getByText('Save'));
await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalled());
const saved = mockUpdateConfig.mock.calls[0][0] as {
inference: Record<string, { mode: string }>;
@@ -425,9 +455,9 @@ it('keeps notes and chat on this phone when dictation leaves On-Device for a pro
mockConfig = { defaultMode: 'private' };
mockActiveMode = 'private';
mockCredentialStatus.mockResolvedValue({ isConfigured: true });
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
- fireEvent.press(screen.getByText('Save selection'));
+ fireEvent.press(screen.getByText('Save'));
await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalled());
expect(mockUpdateConfig.mock.calls[0][0]).toMatchObject({
inference: { notes: { mode: 'local' }, agent: { mode: 'local' } },
@@ -435,34 +465,255 @@ it('keeps notes and chat on this phone when dictation leaves On-Device for a pro
});
});
-it('releases the upload pin when dictation moves from Bring Your Own Key to Cloud', async () => {
+it('switches dictation from Bring Your Own Key to Cloud on tap, without Save', async () => {
mockConfig = {
defaultMode: 'providers',
inference: {
dictation: { mode: 'providers', providerId: 'openai', modelId: 'whisper-1' },
- upload: { mode: 'local' },
},
pinnedInference: ['upload'],
};
mockActiveMode = 'providers';
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
fireEvent.press(screen.getByText('OpenWhispr Cloud'));
- fireEvent.press(screen.getByText('Save selection'));
- await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalled());
- const saved = mockUpdateConfig.mock.calls[0][0] as {
- inference: Record<string, { mode: string } | undefined>;
+ await waitFor(() => expect(selectedMode()).toBe('OpenWhispr Cloud'));
+ expect(mockSwitchMode).toHaveBeenCalledWith('dictation', 'openwhispr');
+ expect(screen.queryByText('Save')).toBeNull();
+ expect(mockUpdateConfig).not.toHaveBeenCalled();
+});
+
+it('keeps the current mode when a switch is refused', async () => {
+ // No saved upload mode, so a refused switch has nothing in the config to fall back on.
+ mockConfig = { defaultMode: 'cloud' };
+ mockScope = 'upload';
+ mockSwitchMode.mockResolvedValue('refused');
+ render(<WorkflowSettingsScreen />);
+ fireEvent.press(screen.getByText('On-Device'));
+ await waitFor(() => expect(mockSwitchMode).toHaveBeenCalledWith('upload', 'local'));
+ expect(selectedMode()).toBe('OpenWhispr Cloud');
+ expect(screen.queryByText(/On-device models for/)).toBeNull();
+});
+
+it('switches to On-Device on return once a model was downloaded for it', async () => {
+ mockConfig = { defaultMode: 'cloud', inference: { upload: { mode: 'openwhispr' } } };
+ mockScope = 'upload';
+ mockSwitchMode.mockResolvedValueOnce('needs-model');
+ render(<WorkflowSettingsScreen />);
+ fireEvent.press(screen.getByText('On-Device'));
+ await waitFor(() => expect(mockSwitchMode).toHaveBeenCalledTimes(1));
+ // Back from the model list without a model: nothing changes.
+ await act(async () => mockFocusEffect?.());
+ expect(mockSwitchMode).toHaveBeenCalledTimes(1);
+ // Back again after downloading one.
+ mockPrivateReadiness.mockResolvedValue({ status: 'ready', modelName: 'Whisper base' });
+ await act(async () => mockFocusEffect?.());
+ await waitFor(() => expect(mockSwitchMode).toHaveBeenCalledTimes(2));
+ expect(mockSwitchMode).toHaveBeenLastCalledWith('upload', 'local');
+ expect(await screen.findByTestId('toast-success')).toHaveTextContent('Switched to On-Device.');
+ expect(selectedMode()).toBe('On-Device');
+});
+
+it('forgets a pending On-Device switch once another mode is chosen', async () => {
+ mockConfig = { defaultMode: 'cloud', inference: { upload: { mode: 'openwhispr' } } };
+ mockScope = 'upload';
+ mockSwitchMode.mockResolvedValueOnce('needs-model');
+ render(<WorkflowSettingsScreen />);
+ fireEvent.press(screen.getByText('On-Device'));
+ await waitFor(() => expect(mockSwitchMode).toHaveBeenCalledTimes(1));
+ fireEvent.press(screen.getByText('OpenWhispr Cloud'));
+ mockPrivateReadiness.mockResolvedValue({ status: 'ready', modelName: 'Whisper base' });
+ await act(async () => mockFocusEffect?.());
+ expect(mockSwitchMode).toHaveBeenCalledTimes(1);
+ expect(selectedMode()).toBe('OpenWhispr Cloud');
+});
+
+it('shows the on-device model list once On-Device is applied', async () => {
+ mockConfig = { defaultMode: 'cloud', inference: { upload: { mode: 'openwhispr' } } };
+ mockScope = 'upload';
+ render(<WorkflowSettingsScreen />);
+ fireEvent.press(screen.getByText('On-Device'));
+ expect(await screen.findByText('On-device models for upload, picked Automatic')).toBeTruthy();
+});
+
+it('passes the saved on-device model to the model list', () => {
+ mockConfig = {
+ defaultMode: 'cloud',
+ inference: { upload: { mode: 'local', modelId: 'whisper-base' } },
};
- expect(saved.inference.dictation).toEqual({ mode: 'openwhispr' });
- expect(saved.inference.upload).toBeUndefined();
+ mockScope = 'upload';
+ render(<WorkflowSettingsScreen />);
+ expect(screen.getByText('On-device models for upload, picked whisper-base')).toBeTruthy();
+});
+
+it('says a text workflow runs on Apple Intelligence when it is On-Device', () => {
+ mockConfig = { defaultMode: 'cloud', inference: { cleanup: { mode: 'local' } } };
+ mockScope = 'cleanup';
+ render(<WorkflowSettingsScreen />);
+ expect(screen.getByText('Runs on Apple Intelligence on this iPhone.')).toBeTruthy();
+ expect(screen.queryByText(/On-device models for/)).toBeNull();
+});
+
+it('waits for Save before switching to Bring Your Own Key', () => {
+ mockConfig = { defaultMode: 'cloud', inference: { notes: { mode: 'openwhispr' } } };
+ mockScope = 'notes';
+ render(<WorkflowSettingsScreen />);
+ expect(screen.queryByText('Save')).toBeNull();
+ enableProviders();
+ expect(screen.getByText('Save to switch to Bring Your Own Key.')).toBeTruthy();
+ expect(screen.getByText('Save')).toBeTruthy();
+ expect(mockSwitchMode).not.toHaveBeenCalled();
+ // Tapping the saved mode again drops the draft.
+ fireEvent.press(screen.getByText('OpenWhispr Cloud'));
+ expect(screen.queryByText('Save')).toBeNull();
+ expect(mockSwitchMode).not.toHaveBeenCalled();
+});
+
+it('shows the cleanup switch and prompt on the Text Cleanup page', () => {
+ mockScope = 'cleanup';
+ mockStoredPrompt = 'Always use bullet points.';
+ render(<WorkflowSettingsScreen />);
+ expect(screen.getByText('Enable Text Cleanup')).toBeTruthy();
+ expect(screen.getByText('Custom')).toBeTruthy();
+ fireEvent.press(screen.getByText('Cleanup Prompt'));
+ expect(mockPush).toHaveBeenCalledWith('/(account)/cleanup-prompt');
+ expect(screen.queryByText('Auto-generate Note Titles')).toBeNull();
+});
+
+it('puts the cleanup switch above the mode and hides the rest while cleanup is off', () => {
+ mockScope = 'cleanup';
+ const view = render(<WorkflowSettingsScreen />);
+ const page = JSON.stringify(view.toJSON());
+ expect(page.indexOf('Enable Text Cleanup')).toBeLessThan(page.indexOf('OpenWhispr Cloud'));
+ mockConfig = { defaultMode: 'cloud', cleanupEnabled: false };
+ view.rerender(<WorkflowSettingsScreen />);
+ expect(screen.getByText('Enable Text Cleanup')).toBeTruthy();
+ expect(screen.queryByText('OpenWhispr Cloud')).toBeNull();
+ expect(screen.queryByText('Cleanup Prompt')).toBeNull();
+ expect(screen.getByText('Dictation is inserted as spoken, with no AI cleanup.')).toBeTruthy();
+});
+
+it('says which other workflows share the provider key', async () => {
+ mockCredentialStatus.mockResolvedValue({ isConfigured: true });
+ mockActiveMode = 'providers';
+ mockScope = 'cleanup';
+ mockConfig = {
+ defaultMode: 'providers',
+ inference: {
+ dictation: { mode: 'providers', providerId: 'openai', modelId: 'whisper-1' },
+ upload: { mode: 'providers', providerId: 'openai', modelId: 'whisper-1' },
+ agent: { mode: 'providers', providerId: 'groq', modelId: 'openai/gpt-oss-20b' },
+ cleanup: { mode: 'providers', providerId: 'openai', modelId: 'gpt-5-mini' },
+ },
+ };
+ render(<WorkflowSettingsScreen />);
+ expect(
+ screen.getByText('Stays on this iPhone. Also used by Dictation and Uploads.'),
+ ).toBeTruthy();
+ await waitFor(() => expect(mockCredentialStatus).toHaveBeenCalled());
+});
+
+it('leaves workflows that are switched off out of the shared-key note', async () => {
+ mockCredentialStatus.mockResolvedValue({ isConfigured: true });
+ mockActiveMode = 'providers';
+ mockConfig = {
+ defaultMode: 'providers',
+ cleanupEnabled: false,
+ dictationAgentEnabled: false,
+ inference: {
+ dictation: { mode: 'providers', providerId: 'openai', modelId: 'whisper-1' },
+ upload: { mode: 'providers', providerId: 'openai', modelId: 'whisper-1' },
+ cleanup: { mode: 'providers', providerId: 'openai', modelId: 'gpt-5-mini' },
+ agent: { mode: 'providers', providerId: 'openai', modelId: 'gpt-5-mini' },
+ },
+ };
+ render(<WorkflowSettingsScreen />);
+ expect(screen.getByText('Stays on this iPhone. Also used by Uploads.')).toBeTruthy();
+ await waitFor(() => expect(mockCredentialStatus).toHaveBeenCalled());
+});
+
+it('says the key is shared before another workflow uses the provider', async () => {
+ render(<WorkflowSettingsScreen />);
+ enableProviders();
+ expect(
+ screen.getByText('Stays on this iPhone. Every workflow set to OpenAI uses the same key.'),
+ ).toBeTruthy();
+ await waitFor(() => expect(mockCredentialStatus).toHaveBeenCalled());
+});
+
+it('keeps Save disabled until something changes', async () => {
+ mockCredentialStatus.mockResolvedValue({ isConfigured: true });
+ mockActiveMode = 'providers';
+ mockConfig = {
+ defaultMode: 'providers',
+ inference: {
+ dictation: {
+ mode: 'providers',
+ providerId: 'openai',
+ modelId: 'whisper-1',
+ credentialRef: 'provider.openai',
+ },
+ },
+ };
+ render(<WorkflowSettingsScreen />);
+ fireEvent.press(screen.getByText('Save'));
+ await act(async () => undefined);
+ expect(mockUpdateConfig).not.toHaveBeenCalled();
+});
+
+it('shows a saved key as saved, until a replacement is typed', async () => {
+ mockCredentialStatus.mockResolvedValue({ isConfigured: true });
+ render(<WorkflowSettingsScreen />);
+ enableProviders();
+ expect(await screen.findByText('Saved')).toBeTruthy();
+ expect(screen.getByLabelText('API key').props.placeholder).toBe('••••••••••••');
+ fireEvent.changeText(screen.getByLabelText('API key'), 'r');
+ expect(screen.queryByText('Saved')).toBeNull();
+});
+
+it('asks for a key when none is saved', async () => {
+ render(<WorkflowSettingsScreen />);
+ enableProviders();
+ expect(screen.getByLabelText('API key').props.placeholder).toBe('Paste your API key');
+ expect(screen.queryByText('Saved')).toBeNull();
+ await waitFor(() => expect(mockCredentialStatus).toHaveBeenCalled());
+});
+
+it('turns Chat & Voice Assistant on and off from the top of its page', () => {
+ mockScope = 'agent';
+ const view = render(<WorkflowSettingsScreen />);
+ const page = JSON.stringify(view.toJSON());
+ expect(page.indexOf('Enable Chat & Voice Assistant')).toBeLessThan(
+ page.indexOf('OpenWhispr Cloud'),
+ );
+ fireEvent.press(screen.getByText('Voice Assistant'));
+ expect(mockPush).toHaveBeenCalledWith('/(account)/dictation-agent');
+ mockConfig = { defaultMode: 'cloud', dictationAgentEnabled: false };
+ view.rerender(<WorkflowSettingsScreen />);
+ expect(screen.queryByText('OpenWhispr Cloud')).toBeNull();
+ expect(screen.queryByText('Voice Assistant')).toBeNull();
+ expect(screen.getByText('Note chat and the voice assistant are off.')).toBeTruthy();
+});
+
+it('shows a default cleanup prompt as Default', () => {
+ mockScope = 'cleanup';
+ render(<WorkflowSettingsScreen />);
+ expect(screen.getByText('Default')).toBeTruthy();
+});
+
+it('shows the auto-title switch on the Note Formatting page only', () => {
+ mockScope = 'notes';
+ render(<WorkflowSettingsScreen />);
+ expect(screen.getByText('Auto-generate Note Titles')).toBeTruthy();
+ expect(screen.queryByText('Enable Text Cleanup')).toBeNull();
});
it('pins uploads to the mode the app is in, not a stale saved Cloud preference', async () => {
mockConfig = { defaultMode: 'cloud' };
mockActiveMode = 'private';
mockCredentialStatus.mockResolvedValue({ isConfigured: true });
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
- fireEvent.press(screen.getByText('Save selection'));
+ fireEvent.press(screen.getByText('Save'));
await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalled());
const saved = mockUpdateConfig.mock.calls[0][0] as {
inference: Record<string, { mode: string }>;
@@ -484,10 +735,10 @@ it('adds no pins when an existing user re-saves dictation with their own key', a
};
mockActiveMode = 'providers';
mockCredentialStatus.mockResolvedValue({ isConfigured: true });
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
// Dictation already opens in Bring Your Own Key mode for this config.
chooseProvider('OpenAI');
- fireEvent.press(screen.getByText('Save selection'));
+ fireEvent.press(screen.getByText('Save'));
await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalled());
const saved = mockUpdateConfig.mock.calls[0][0] as {
inference: Record<string, { mode: string }>;
@@ -514,21 +765,11 @@ it.each([
mockConfig = { defaultMode: 'private' };
mockActiveMode = 'private';
mockScope = scope;
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
expect(screen.getByText(note)).toBeTruthy();
});
-it('does not save a workflow that was never set until something is chosen', async () => {
- mockConfig = { defaultMode: 'private' };
- mockActiveMode = 'private';
- mockScope = 'agent';
- render(<ProviderSettingsScreen />);
- fireEvent.press(screen.getByText('Save selection'));
- await act(async () => undefined);
- expect(mockUpdateConfig).not.toHaveBeenCalled();
-});
-
-it('explains that On-Device mode keeps a workflow on this phone, and still saves it', async () => {
+it('explains that On-Device mode keeps a workflow on this phone, and still saves a change', async () => {
mockConfig = {
defaultMode: 'private',
inference: { upload: { mode: 'providers', providerId: 'openai', modelId: 'whisper-1' } },
@@ -536,13 +777,14 @@ it('explains that On-Device mode keeps a workflow on this phone, and still saves
mockActiveMode = 'private';
mockScope = 'upload';
mockCredentialStatus.mockResolvedValue({ isConfigured: true });
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
expect(
screen.getByText(
'On-Device mode keeps this on your iPhone. Your choice applies when dictation leaves On-Device.',
),
).toBeTruthy();
- fireEvent.press(screen.getByText('Save selection'));
+ fireEvent.changeText(screen.getByLabelText('API key'), 'replacement-key');
+ fireEvent.press(screen.getByText('Save'));
await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalled());
expect(mockUpdateConfig.mock.calls[0][0].inference.upload).toMatchObject({
providerId: 'openai',
@@ -552,78 +794,15 @@ it('explains that On-Device mode keeps a workflow on this phone, and still saves
it('does not show the On-Device note on the Dictation page', () => {
mockConfig = { defaultMode: 'private' };
mockActiveMode = 'private';
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
expect(screen.queryByText(/On-Device mode keeps this/)).not.toBeOnTheScreen();
});
-describe('mode checks the other mode pickers run', () => {
- let alert: jest.SpyInstance;
- beforeEach(() => {
- alert = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined);
- });
- afterEach(() => alert.mockRestore());
-
- it('asks for the on-device model before switching dictation to On-Device', async () => {
- mockPrivateReadiness.mockResolvedValue({ status: 'missing', modelName: 'Parakeet v3' });
- render(<ProviderSettingsScreen />);
- fireEvent.press(screen.getByText('On-Device'));
- fireEvent.press(screen.getByText('Save selection'));
- await waitFor(() => expect(alert).toHaveBeenCalled());
- expect(alert.mock.calls[0][0]).toBe('Download required');
- expect(mockUpdateConfig).not.toHaveBeenCalled();
- expect(mockSetActiveMode).not.toHaveBeenCalled();
- });
-
- it('asks a signed-out guest to sign in before saving Cloud dictation', async () => {
- mockUser = null;
- mockConfig = { defaultMode: 'private' };
- mockActiveMode = 'private';
- render(<ProviderSettingsScreen />);
- fireEvent.press(screen.getByText('OpenWhispr Cloud'));
- fireEvent.press(screen.getByText('Save selection'));
- await waitFor(() => expect(alert).toHaveBeenCalled());
- expect(alert.mock.calls[0][0]).toBe('Sign in required');
- expect(mockUpdateConfig).not.toHaveBeenCalled();
- });
-
- it('refuses On-Device cleanup where Apple Intelligence cannot run it', async () => {
- mockLocalReasoningReadiness.mockResolvedValue({ status: 'unavailable', tokenCounting: false });
- mockScope = 'cleanup';
- render(<ProviderSettingsScreen />);
- fireEvent.press(screen.getByText('On-Device'));
- fireEvent.press(screen.getByText('Save selection'));
- await waitFor(() => expect(alert).toHaveBeenCalled());
- expect(alert.mock.calls[0]).toEqual([
- 'On-Device Unavailable',
- 'Local Apple Intelligence is unavailable on this device.',
- ]);
- expect(mockUpdateConfig).not.toHaveBeenCalled();
- });
-
- it('saves On-Device cleanup once Apple Intelligence is ready', async () => {
- mockScope = 'cleanup';
- render(<ProviderSettingsScreen />);
- fireEvent.press(screen.getByText('On-Device'));
- fireEvent.press(screen.getByText('Save selection'));
- await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalled());
- expect(mockUpdateConfig.mock.calls[0][0].inference.cleanup).toEqual({ mode: 'local' });
- expect(alert).not.toHaveBeenCalled();
- });
-});
-
it('does not edit dictation settings from an unknown workflow link', () => {
mockScope = 'meeting';
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
expect(screen.getByText('This workflow is not available.')).toBeTruthy();
- expect(screen.queryByText('Save selection')).not.toBeOnTheScreen();
-});
-
-it('opens with Bring Your Own Key chosen when Speech to Text sent the user here for it', async () => {
- mockConfig = { defaultMode: 'cloud' };
- mockModeParam = 'providers';
- render(<ProviderSettingsScreen />);
- expect(selectedMode()).toBe('Bring Your Own Key');
- await waitFor(() => expect(mockCredentialStatus).toHaveBeenCalled());
+ expect(screen.queryByText('Save')).not.toBeOnTheScreen();
});
it('restores the provider saved last when switching back to Bring Your Own Key', async () => {
@@ -637,14 +816,14 @@ it('restores the provider saved last when switching back to Bring Your Own Key',
},
},
};
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
expect(screen.getByText('Groq')).toBeTruthy();
await waitFor(() => expect(mockCredentialStatus).toHaveBeenCalled());
});
it('keeps the focused field and Save above the keyboard', async () => {
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
const scroll = screen.UNSAFE_getByType(ScrollView);
expect(scroll.props.automaticallyAdjustKeyboardInsets).toBe(true);
expect(scroll.props.keyboardShouldPersistTaps).toBe('handled');
@@ -652,7 +831,7 @@ it('keeps the focused field and Save above the keyboard', async () => {
it('asks before leaving with a checked but unsaved key', async () => {
const alert = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined);
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
expect(mockPreventRemove).toHaveBeenLastCalledWith(false, expect.any(Function));
enableProviders();
fireEvent.changeText(screen.getByLabelText('API key'), 'unsaved-key');
@@ -669,19 +848,24 @@ it('asks before leaving with a checked but unsaved key', async () => {
it('lets the user leave freely once the selection is saved', async () => {
mockCredentialStatus.mockResolvedValue({ isConfigured: true });
- render(<ProviderSettingsScreen />);
+ // The page reads the saved selection back from the config store, as in the app.
+ mockUpdateConfig.mockImplementationOnce(async (updates: Record<string, unknown>) => {
+ mockConfig = { ...mockConfig, ...updates };
+ });
+ const view = render(<WorkflowSettingsScreen />);
enableProviders();
- fireEvent.press(screen.getByText('Save selection'));
- await screen.findByText('Selection saved.');
+ fireEvent.press(screen.getByText('Save'));
+ expect(await screen.findByTestId('toast-success')).toHaveTextContent('Saved.');
+ view.rerender(<WorkflowSettingsScreen />);
expect(mockPreventRemove).toHaveBeenLastCalledWith(false, expect.any(Function));
});
it('replays the toast when a check returns the same result again', async () => {
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
- fireEvent.press(screen.getByText('Check connection'));
+ fireEvent.press(screen.getByText('Check Connection'));
const first = (await screen.findByTestId('toast-error')).props.accessibilityHint;
- fireEvent.press(screen.getByText('Check connection'));
+ fireEvent.press(screen.getByText('Check Connection'));
await waitFor(() =>
expect(screen.getByTestId('toast-error').props.accessibilityHint).not.toBe(first),
);
@@ -690,9 +874,9 @@ it('replays the toast when a check returns the same result again', async () => {
it('keeps an error toast up longer than a success toast', async () => {
jest.useFakeTimers();
try {
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
- fireEvent.press(screen.getByText('Check connection'));
+ fireEvent.press(screen.getByText('Check Connection'));
await screen.findByTestId('toast-error');
act(() => jest.advanceTimersByTime(4000));
expect(screen.getByTestId('toast-error')).toBeOnTheScreen();
@@ -713,14 +897,14 @@ describe('a custom server reached under /v1', () => {
verification: 'catalog-only',
endpoint: withV1,
});
- render(<ProviderSettingsScreen />);
+ render(<WorkflowSettingsScreen />);
enableProviders();
chooseProvider('Custom');
- fireEvent.changeText(screen.getByLabelText('Endpoint URL'), bare);
+ fireEvent.changeText(screen.getByLabelText('Server URL'), bare);
fireEvent.changeText(screen.getByLabelText('Model ID'), 'local-model');
- fireEvent.press(screen.getByText('Discover models'));
- await waitFor(() => expect(screen.getByLabelText('Endpoint URL').props.value).toBe(withV1));
- fireEvent.press(screen.getByText('Save selection'));
+ fireEvent.press(screen.getByText('Discover Models'));
+ await waitFor(() => expect(screen.getByLabelText('Server URL').props.value).toBe(withV1));
+ fireEvent.press(screen.getByText('Save'));
await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalled());
expect(mockUpdateConfig.mock.calls[0][0].inference.dictation.endpoint).toBe(withV1);
});
@@ -746,10 +930,10 @@ describe('a custom server reached under /v1', () => {
reference === `custom.${bare}` ? { apiKey: 'saved-key' } : null,
);
mockTestConnection.mockResolvedValue({ ok: true, verification: 'inference', endpoint: withV1 });
- render(<ProviderSettingsScreen />);
- fireEvent.press(screen.getByText('Check connection'));
- await waitFor(() => expect(screen.getByLabelText('Endpoint URL').props.value).toBe(withV1));
- fireEvent.press(screen.getByText('Save selection'));
+ render(<WorkflowSettingsScreen />);
+ fireEvent.press(screen.getByText('Check Connection'));
+ await waitFor(() => expect(screen.getByLabelText('Server URL').props.value).toBe(withV1));
+ fireEvent.press(screen.getByText('Save'));
await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalled());
expect(mockSetCredential).toHaveBeenCalledWith(`custom.${withV1}`, { apiKey: 'saved-key' });
expect(mockUpdateConfig.mock.calls[0][0].inference.dictation).toMatchObject({
@@ -779,10 +963,10 @@ describe('a custom server reached under /v1', () => {
reference === `custom.${bare}` ? { apiKey: 'saved-key' } : null,
);
mockTestConnection.mockResolvedValue({ ok: true, verification: 'inference', endpoint: withV1 });
- render(<ProviderSettingsScreen />);
- fireEvent.press(screen.getByText('Check connection'));
- await waitFor(() => expect(screen.getByLabelText('Endpoint URL').props.value).toBe(withV1));
- fireEvent.press(screen.getByText('Check connection'));
+ render(<WorkflowSettingsScreen />);
+ fireEvent.press(screen.getByText('Check Connection'));
+ await waitFor(() => expect(screen.getByLabelText('Server URL').props.value).toBe(withV1));
+ fireEvent.press(screen.getByText('Check Connection'));
await waitFor(() => expect(mockTestConnection).toHaveBeenCalledTimes(2));
expect(mockTestConnection.mock.calls[1][0]).toMatchObject({ apiKey: 'saved-key' });
expect(mockSetCredential).not.toHaveBeenCalled();
@@ -802,9 +986,9 @@ describe('a custom server reached under /v1', () => {
},
};
mockGetCredential.mockResolvedValue({ apiKey: 'saved-key' });
- render(<ProviderSettingsScreen />);
- fireEvent.changeText(screen.getByLabelText('Endpoint URL'), 'http://192.168.1.9:11434/v1');
- fireEvent.press(screen.getByText('Save selection'));
+ render(<WorkflowSettingsScreen />);
+ fireEvent.changeText(screen.getByLabelText('Server URL'), 'http://192.168.1.9:11434/v1');
+ fireEvent.press(screen.getByText('Save'));
await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalled());
expect(mockSetCredential).not.toHaveBeenCalled();
expect(mockUpdateConfig.mock.calls[0][0].inference.dictation.credentialRef).toBeUndefined();
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/ToneStep.tsx b/openwhispr-mobile/src/screens/onboarding/steps/ToneStep.tsx
index e0eefa5ab..2e2bad957 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/ToneStep.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/ToneStep.tsx
@@ -57,7 +57,7 @@ export function ToneStep(): ReactElement {
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.
+ Live tones need Cloud, Text Cleanup, and an account.
</Text>
</View>
{KEYBOARD_TONES.map((tone) => (
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/ToneStep.test.tsx b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/ToneStep.test.tsx
index 6aabd4c0a..a2d174ae4 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/ToneStep.test.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/ToneStep.test.tsx
@@ -112,9 +112,7 @@ 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.getByText('Live tones need Cloud, Text Cleanup, and an account.')).toBeTruthy();
expect(screen.queryByText(/illustrative/)).toBeNull();
expect(screen.queryByText(/choose Local/)).toBeNull();
});
diff --git a/openwhispr-mobile/src/services/transcription/LocalTranscriptionService.ts b/openwhispr-mobile/src/services/transcription/LocalTranscriptionService.ts
index 9f239b336..99860d2e6 100644
--- a/openwhispr-mobile/src/services/transcription/LocalTranscriptionService.ts
+++ b/openwhispr-mobile/src/services/transcription/LocalTranscriptionService.ts
@@ -1,5 +1,6 @@
import type { ParakeetVersion } from '../../../modules/parakeet-asr/src';
import type { TranscriptionResponse } from '../../types';
+import type { LocalModelKey } from '../../lib/localModelCatalog';
import { getPreferredTranscriptionLanguages } from '../../lib/transcriptionLanguage';
import { LocalParakeetService } from './LocalParakeetService';
import { LocalWhisperService } from './LocalWhisperService';
@@ -22,6 +23,8 @@ export interface LocalTranscribeOptions {
wordTimestamps?: boolean;
/** Whisper initial prompt (dictionary/snippet hints). Parakeet has no prompt input — dropped there. */
prompt?: string;
+ /** The model picked for this workflow; unset or unusable means the automatic choice. */
+ model?: LocalModelKey;
}
function descriptorFor(
@@ -82,20 +85,20 @@ export class LocalTranscriptionService {
};
}
- private static async resolveEngine(): Promise<{
+ private static async resolveEngine(model?: LocalModelKey): Promise<{
languages: string[];
choice: LocalEngineChoice;
}> {
const languages = getPreferredTranscriptionLanguages();
const availability = await this.getAvailability();
- return { languages, choice: selectLocalEngine(languages, availability) };
+ return { languages, choice: selectLocalEngine(languages, availability, model) };
}
static async transcribe(
audioUri: string,
options: LocalTranscribeOptions = {},
): Promise<TranscriptionResponse> {
- const { languages, choice } = await this.resolveEngine();
+ const { languages, choice } = await this.resolveEngine(options.model);
if (choice.engine === 'parakeet') {
// Don't keep both runtimes' weights resident (~600 MB + ~500 MB) — release the idle one.
@@ -128,8 +131,8 @@ export class LocalTranscriptionService {
* Warm the engine the current language selection routes to (keyboard/Home pre-warm path).
* Never downloads; a Parakeet choice that isn't installed resolves to Whisper or a no-op.
*/
- static async prepareForLanguage(language?: string): Promise<void> {
- const { choice } = await this.resolveEngine();
+ static async prepareForLanguage(language?: string, model?: LocalModelKey): Promise<void> {
+ const { choice } = await this.resolveEngine(model);
if (choice.engine === 'parakeet') {
await LocalParakeetService.prepare(choice.version);
return;
diff --git a/openwhispr-mobile/src/services/transcription/TranscriptionService.ts b/openwhispr-mobile/src/services/transcription/TranscriptionService.ts
index 8824c6837..340a191d9 100644
--- a/openwhispr-mobile/src/services/transcription/TranscriptionService.ts
+++ b/openwhispr-mobile/src/services/transcription/TranscriptionService.ts
@@ -852,9 +852,12 @@ export class TranscriptionService {
// prompt, so on-device/private transcription recognizes them too. (Parakeet has
// no prompt input; the facade drops it on that branch.)
const hintWords = buildDictationHints(isDictationContext(requestContext));
+ const { getPickedLocalModel } =
+ require('@/lib/inferenceRouting') as typeof import('@/lib/inferenceRouting');
const response = await LocalTranscriptionService.transcribe(audioUri, {
language,
prompt: hintWords.length > 0 ? hintWords.join(', ') : undefined,
+ model: getPickedLocalModel(requestContext === 'file' ? 'upload' : 'dictation'),
});
if (__DEV__) {
console.log(
@@ -1044,7 +1047,9 @@ export class TranscriptionService {
if (!LocalTranscriptionService.isAvailable()) {
return;
}
- await LocalTranscriptionService.prepareForLanguage(language);
+ const { getPickedLocalModel } =
+ require('@/lib/inferenceRouting') as typeof import('@/lib/inferenceRouting');
+ await LocalTranscriptionService.prepareForLanguage(language, getPickedLocalModel('dictation'));
}
}
diff --git a/openwhispr-mobile/src/services/transcription/__tests__/LocalTranscriptionService.test.ts b/openwhispr-mobile/src/services/transcription/__tests__/LocalTranscriptionService.test.ts
index ec00e4e36..2684122cc 100644
--- a/openwhispr-mobile/src/services/transcription/__tests__/LocalTranscriptionService.test.ts
+++ b/openwhispr-mobile/src/services/transcription/__tests__/LocalTranscriptionService.test.ts
@@ -60,6 +60,26 @@ describe('LocalTranscriptionService', () => {
});
});
+ it('transcribes with the model picked for the workflow', async () => {
+ setLanguages(['en']);
+ const response = await LocalTranscriptionService.transcribe('file://a.wav', {
+ language: 'en',
+ model: 'parakeet-v3',
+ });
+ expect(mockParakeet.transcribe).toHaveBeenCalledWith(
+ 'file://a.wav',
+ expect.objectContaining({ version: 'v3' }),
+ );
+ expect(response.endpoint).toBe('parakeet-v3');
+ });
+
+ it('warms the picked model instead of the automatic one', async () => {
+ setLanguages(['en']);
+ await LocalTranscriptionService.prepareForLanguage('en', 'whisper-base');
+ expect(mockWhisper.prepareForLanguage).toHaveBeenCalledWith('en');
+ expect(mockParakeet.prepare).not.toHaveBeenCalled();
+ });
+
it('routes English dictation to Parakeet v2 with the language hint', async () => {
setLanguages(['en']);
const response = await LocalTranscriptionService.transcribe('file://a.wav', {
diff --git a/openwhispr-mobile/src/services/transcription/__tests__/TranscriptionService.localModel.test.ts b/openwhispr-mobile/src/services/transcription/__tests__/TranscriptionService.localModel.test.ts
new file mode 100644
index 000000000..bb25cd41f
--- /dev/null
+++ b/openwhispr-mobile/src/services/transcription/__tests__/TranscriptionService.localModel.test.ts
@@ -0,0 +1,78 @@
+import { TranscriptionService } from '../TranscriptionService';
+
+jest.mock('expo-constants', () => ({
+ __esModule: true,
+ default: { expoConfig: { version: '1.2.1' } },
+}));
+jest.mock('expo/fetch', () => ({ fetch: jest.fn() }));
+jest.mock('@/store/useAuthStore', () => ({
+ useAuthStore: { getState: () => ({ sessionCookie: 'test-session-cookie' }) },
+}));
+jest.mock('expo-file-system/legacy', () => ({
+ getInfoAsync: jest.fn(),
+ uploadAsync: jest.fn(),
+ FileSystemUploadType: { MULTIPART: 1 },
+ FileSystemSessionType: { FOREGROUND: 0 },
+}));
+jest.mock('../LocalWhisperService', () => ({ LocalWhisperService: {} }));
+const mockLocalTranscribe = jest.fn(async () => ({ text: 'local text', duration: 1 }));
+const mockPrepare = jest.fn(async () => undefined);
+jest.mock('../LocalTranscriptionService', () => ({
+ LocalTranscriptionService: {
+ isAvailable: () => true,
+ transcribe: (...args: unknown[]) => mockLocalTranscribe(...(args as [])),
+ prepareForLanguage: (...args: unknown[]) => mockPrepare(...(args as [])),
+ },
+}));
+jest.mock('@/lib/dictationHints', () => ({
+ buildDictationHints: () => [],
+ isDictationContext: () => true,
+}));
+jest.mock('@/lib/cleanupTranscript', () => ({ CLEANUP_TIMEOUT_MS: 30000 }));
+jest.mock('../../../../modules/background-uploader/src', () => ({
+ BackgroundUploader: { isAvailable: () => true, upload: jest.fn() },
+}));
+jest.mock('../../../../modules/audio-tools/src', () => ({
+ AudioTools: { isAvailable: () => true, splitToChunks: jest.fn(), cleanup: jest.fn() },
+}));
+jest.mock('../../../../modules/app-group-storage/src', () => ({
+ AppGroupStorage: { setItem: jest.fn() },
+ APP_GROUP_KEYS: {},
+}));
+const mockPicks: Record<string, string | undefined> = {};
+jest.mock('@/lib/inferenceRouting', () => ({
+ getPickedLocalModel: (scope: string) => mockPicks[scope],
+}));
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockPicks.dictation = 'parakeet-v3';
+ mockPicks.upload = 'whisper-base';
+});
+
+test('on-device files use the Uploads model and recordings use the Dictation model', async () => {
+ await TranscriptionService.transcribe({
+ audioUri: 'file:///import.m4a',
+ provider: 'local',
+ requestContext: 'file',
+ });
+ expect(mockLocalTranscribe).toHaveBeenLastCalledWith(
+ 'file:///import.m4a',
+ expect.objectContaining({ model: 'whisper-base' }),
+ );
+
+ await TranscriptionService.transcribe({
+ audioUri: 'file:///dictation.wav',
+ provider: 'local',
+ requestContext: 'keyboard',
+ });
+ expect(mockLocalTranscribe).toHaveBeenLastCalledWith(
+ 'file:///dictation.wav',
+ expect.objectContaining({ model: 'parakeet-v3' }),
+ );
+});
+
+test('pre-warming loads the Dictation model', async () => {
+ await TranscriptionService.prepareLocal('en');
+ expect(mockPrepare).toHaveBeenCalledWith('en', 'parakeet-v3');
+});
diff --git a/openwhispr-mobile/src/services/transcription/__tests__/localEngine.test.ts b/openwhispr-mobile/src/services/transcription/__tests__/localEngine.test.ts
index 331d0b09d..286551b55 100644
--- a/openwhispr-mobile/src/services/transcription/__tests__/localEngine.test.ts
+++ b/openwhispr-mobile/src/services/transcription/__tests__/localEngine.test.ts
@@ -1,5 +1,6 @@
import {
PARAKEET_V3_LANGUAGES,
+ localModelCoversLanguages,
preferredEngineForLanguages,
selectLocalEngine,
type LocalEngineAvailability,
@@ -105,3 +106,52 @@ describe('selectLocalEngine', () => {
});
});
});
+
+describe('localModelCoversLanguages', () => {
+ it('limits Parakeet v2 to English', () => {
+ expect(localModelCoversLanguages('parakeet-v2', ['en-US', 'en'])).toBe(true);
+ expect(localModelCoversLanguages('parakeet-v2', ['en', 'fr'])).toBe(false);
+ });
+
+ it('limits Parakeet v3 to its languages', () => {
+ expect(localModelCoversLanguages('parakeet-v3', ['fr', 'de'])).toBe(true);
+ expect(localModelCoversLanguages('parakeet-v3', ['he'])).toBe(false);
+ });
+
+ it('leaves auto-detect to Whisper', () => {
+ expect(localModelCoversLanguages('parakeet-v2', [])).toBe(false);
+ expect(localModelCoversLanguages('parakeet-v3', ['auto'])).toBe(false);
+ expect(localModelCoversLanguages('whisper-base', [])).toBe(true);
+ expect(localModelCoversLanguages('whisper-base', ['he', 'fr'])).toBe(true);
+ });
+});
+
+describe('selectLocalEngine with a picked model', () => {
+ it('uses a downloaded model that covers the languages over the automatic choice', () => {
+ expect(selectLocalEngine(['fr'], all(), 'whisper-base')).toEqual({ engine: 'whisper' });
+ expect(selectLocalEngine(['en'], all(), 'parakeet-v3')).toEqual({
+ engine: 'parakeet',
+ version: 'v3',
+ });
+ });
+
+ it('falls back to the automatic choice when the picked model is not downloaded', () => {
+ expect(selectLocalEngine(['en'], all({ parakeetV3Downloaded: false }), 'parakeet-v3')).toEqual({
+ engine: 'parakeet',
+ version: 'v2',
+ });
+ });
+
+ it('falls back to the automatic choice when the picked model misses a language', () => {
+ expect(selectLocalEngine(['fr'], all(), 'parakeet-v2')).toEqual({
+ engine: 'parakeet',
+ version: 'v3',
+ });
+ });
+
+ it('falls back when Parakeet is unavailable on this device', () => {
+ expect(selectLocalEngine(['en'], all({ parakeetSupported: false }), 'parakeet-v2')).toEqual({
+ engine: 'whisper',
+ });
+ });
+});
diff --git a/openwhispr-mobile/src/services/transcription/localEngine.ts b/openwhispr-mobile/src/services/transcription/localEngine.ts
index a3ee4f5cb..36fa90d79 100644
--- a/openwhispr-mobile/src/services/transcription/localEngine.ts
+++ b/openwhispr-mobile/src/services/transcription/localEngine.ts
@@ -1,4 +1,5 @@
import type { ParakeetVersion } from '../../../modules/parakeet-asr/src';
+import type { LocalModelKey } from '@/lib/localModelCatalog';
/**
* Pure routing policy for on-device transcription: which local engine handles the user's
@@ -84,6 +85,26 @@ export function preferredEngineForLanguages(
return { engine: 'whisper' };
}
+/** Whether a model can transcribe every selected language. Auto-detect needs Whisper. */
+export function localModelCoversLanguages(
+ model: LocalModelKey,
+ languages: readonly string[],
+): boolean {
+ if (model === 'whisper-base') return true;
+ const normalized = normalizeLanguages(languages);
+ if (normalized.length === 0) return false;
+ if (model === 'parakeet-v2') return normalized.every((code) => code === 'en');
+ return normalized.every((code) => PARAKEET_V3_LANGUAGES.has(code));
+}
+
+function isInstalled(model: LocalModelKey, availability: LocalEngineAvailability): boolean {
+ if (model === 'whisper-base') return availability.whisperDownloaded;
+ if (!availability.parakeetSupported) return false;
+ return model === 'parakeet-v2'
+ ? availability.parakeetV2Downloaded
+ : availability.parakeetV3Downloaded;
+}
+
/**
* Resolve the preferred engine against what's actually installed. Fallback order: preferred
* Parakeet → Whisper if downloaded → 'none' (caller surfaces a download prompt). Whisper-bound
@@ -92,7 +113,15 @@ export function preferredEngineForLanguages(
export function selectLocalEngine(
languages: readonly string[],
availability: LocalEngineAvailability,
+ // The model the user picked for this workflow. A missing or unsuitable pick falls back to the
+ // automatic choice, so a deleted model or a language change never breaks transcription.
+ picked?: LocalModelKey,
): LocalEngineChoice {
+ if (picked && isInstalled(picked, availability) && localModelCoversLanguages(picked, languages)) {
+ return picked === 'whisper-base'
+ ? { engine: 'whisper' }
+ : { engine: 'parakeet', version: picked === 'parakeet-v2' ? 'v2' : 'v3' };
+ }
const preferred = preferredEngineForLanguages(languages);
if (preferred.engine === 'parakeet' && availability.parakeetSupported) {