Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(mobile): Run On-Device cleanup when dictation is On-Device (#2432)
Chad Pihaee7765433a5d
diff --git a/openwhispr-mobile/src/components/settings/InferenceModePicker.tsx b/openwhispr-mobile/src/components/settings/InferenceModePicker.tsxindex e239cdd41..2b37bd862 100644--- a/openwhispr-mobile/src/components/settings/InferenceModePicker.tsx+++ b/openwhispr-mobile/src/components/settings/InferenceModePicker.tsx@@ -6,7 +6,8 @@ import type { InferenceMode } from '@/types';type Props = {scope: InferenceScope;- selectedMode: InferenceMode;+ // null when no mode is saved and none applies, so nothing is shown as picked.+ selectedMode: InferenceMode | null;onSelect: (mode: InferenceMode) => void;};diff --git a/openwhispr-mobile/src/lib/__tests__/aiWorkflows.test.ts b/openwhispr-mobile/src/lib/__tests__/aiWorkflows.test.tsnew file mode 100644index 000000000..66c0a6546--- /dev/null+++ b/openwhispr-mobile/src/lib/__tests__/aiWorkflows.test.ts@@ -0,0 +1,63 @@+import { workflowSummary } from '@/lib/aiWorkflows';+import type { UserConfig } from '@/types';++function config(overrides: Partial<UserConfig> = {}): UserConfig {+ return { defaultMode: 'private', ...overrides } as UserConfig;+}++describe('workflowSummary for Text Cleanup', () => {+ it.each([+ ['nothing saved', undefined],+ ['OpenWhispr Cloud', { mode: 'openwhispr' as const }],+ ['a provider', { mode: 'providers' as const, providerId: 'openai', modelId: 'gpt-5-mini' }],+ ])('is skipped in On-Device mode with %s saved', (_label, cleanup) => {+ const saved = config({ inference: cleanup ? { cleanup } : {} });+ expect(workflowSummary(saved, 'cleanup', 'private')).toBe('Skipped');+ });++ it('runs On-Device in On-Device mode when saved as On-Device', () => {+ const saved = config({ inference: { cleanup: { mode: 'local' } } });+ expect(workflowSummary(saved, 'cleanup', 'private')).toBe('On-Device');+ });++ it.each(['private', 'cloud'] as const)(+ 'says why saved On-Device cleanup cannot run in %s mode',+ (mode) => {+ const saved = config({ defaultMode: mode, inference: { cleanup: { mode: 'local' } } });+ expect(+ workflowSummary(saved, 'cleanup', mode, { onDeviceUnavailable: 'Apple Intelligence off' }),+ ).toBe('On-Device · Apple Intelligence off');+ },+ );++ it('ignores On-Device availability for a cleanup that does not run on the phone', () => {+ const saved = config({ defaultMode: 'cloud', inference: { cleanup: { mode: 'openwhispr' } } });+ expect(+ workflowSummary(saved, 'cleanup', 'cloud', { onDeviceUnavailable: 'Apple Intelligence off' }),+ ).toBe('OpenWhispr Cloud');+ });++ it.each(['private', 'cloud', 'providers'] as const)(+ 'is off in %s mode when Text Cleanup is turned off',+ (mode) => {+ const saved = config({+ defaultMode: mode,+ cleanupEnabled: false,+ inference: { cleanup: { mode: 'local' } },+ });+ expect(+ workflowSummary(saved, 'cleanup', mode, { onDeviceUnavailable: 'Apple Intelligence off' }),+ ).toBe('Off');+ },+ );++ it('still flags a provider cleanup whose key is missing', () => {+ const saved = config({+ defaultMode: 'providers',+ inference: { cleanup: { mode: 'providers', providerId: 'groq', modelId: 'llama' } },+ });+ expect(workflowSummary(saved, 'cleanup', 'providers', { keyMissing: true })).toBe(+ 'Groq · Key missing',+ );+ });+});diff --git a/openwhispr-mobile/src/lib/__tests__/transcribeAndCleanup.customPrompt.test.ts b/openwhispr-mobile/src/lib/__tests__/transcribeAndCleanup.customPrompt.test.tsindex 56103158e..57feff9ed 100644--- a/openwhispr-mobile/src/lib/__tests__/transcribeAndCleanup.customPrompt.test.ts+++ b/openwhispr-mobile/src/lib/__tests__/transcribeAndCleanup.customPrompt.test.ts@@ -99,7 +99,7 @@ describe('transcribeAndCleanup with a custom cleanup prompt', () => {expect(mockCleanup).not.toHaveBeenCalled();});- it('never cleans a local transcript, override or not', async () => {+ it('never cleans a local transcript when cleanup is not On-Device, override or not', async () => {mockTranscribe.mockResolvedValue({ text: 'local words', provider: 'local', duration: 1 });const result = await transcribeAndCleanup({audioUri: 'file://a.wav',diff --git a/openwhispr-mobile/src/lib/__tests__/transcribeAndCleanup.onDeviceCleanup.test.ts b/openwhispr-mobile/src/lib/__tests__/transcribeAndCleanup.onDeviceCleanup.test.tsnew file mode 100644index 000000000..711b471bb--- /dev/null+++ b/openwhispr-mobile/src/lib/__tests__/transcribeAndCleanup.onDeviceCleanup.test.ts@@ -0,0 +1,223 @@+/**+ * A transcript made on this phone is cleaned only when the user chose On-Device+ * cleanup, and then only by Apple Intelligence on this phone. Any other cleanup+ * choice would send it off the device, so the raw transcript is kept.+ */+import { TranscriptionService } from '@/services/transcription/TranscriptionService';+import { transcribeAndCleanup } from '@/lib/transcribeAndCleanup';+import { ReasoningService } from '@/services/reasoning/ReasoningService';+import { countLocalReasoningTokens, getLocalReasoningReadiness } from '@/lib/localReasoning';++let mockConfig: Record<string, unknown> = {};+let mockActiveMode = 'private';+let mockCustomPrompt: string | undefined;++jest.mock('expo-router', () => ({ router: { push: jest.fn() } }));+jest.mock('@/services/transcription/TranscriptionService', () => ({+ TranscriptionService: {+ transcribe: jest.fn(),+ transcribeWithCloudCleanup: jest.fn(),+ canAttemptFusedCloudCleanup: jest.fn(() => false),+ requestNeedsChunking: jest.fn(async () => false),+ isFusedCleanupUnavailableError: jest.fn(() => false),+ },+ isLocalModelMissingError: jest.fn(() => false),+}));+jest.mock('@/services/reasoning/ReasoningService', () => ({+ ReasoningService: {+ processText: jest.fn(async (req: { text: string }) => ({+ text: `cleaned:${req.text}`,+ model: 'm',+ })),+ },+}));+jest.mock('@/lib/localReasoning', () => ({+ ...jest.requireActual('@/lib/localReasoning'),+ getLocalReasoningReadiness: jest.fn(),+ countLocalReasoningTokens: jest.fn(),+}));+jest.mock('@/lib/permissions', () => ({+ isNoSpeechError: jest.fn(() => false),+}));+jest.mock('@/store/useAuthStore', () => ({+ useAuthStore: { getState: () => ({ user: { id: 'u', isAnonymous: false } }) },+}));+jest.mock('@/store/useConfigStore', () => ({+ useConfigStore: { getState: () => ({ config: mockConfig }) },+}));+jest.mock('@/store/useProcessingModeStore', () => ({+ useProcessingModeStore: { getState: () => ({ activeMode: mockActiveMode }) },+}));+jest.mock('@/store/useSnippetsStore', () => ({+ useSnippetsStore: { getState: () => ({ isLoaded: true, entries: [] }) },+}));+jest.mock('@/store/useDictionaryStore', () => ({+ useDictionaryStore: { getState: () => ({ isLoaded: true, entries: [] }) },+}));+jest.mock('@/store/useCustomPromptsStore', () => ({+ getActiveCustomCleanupPrompt: () => mockCustomPrompt,+}));++const mockTranscribe = TranscriptionService.transcribe as jest.Mock;+const mockReason = ReasoningService.processText as jest.Mock;+const mockReadiness = getLocalReasoningReadiness as jest.Mock;+const mockCountTokens = countLocalReasoningTokens as jest.Mock;++function transcribeOnDevice(+ lifecycle?: Parameters<typeof transcribeAndCleanup>[1],+): ReturnType<typeof transcribeAndCleanup> {+ return transcribeAndCleanup(+ {+ audioUri: 'file://a.wav',+ provider: 'local',+ requestContext: 'recording',+ },+ lifecycle,+ );+}++beforeEach(() => {+ jest.clearAllMocks();+ mockActiveMode = 'private';+ mockConfig = {+ cleanupEnabled: true,+ defaultMode: 'private',+ inference: { dictation: { mode: 'local' }, cleanup: { mode: 'local' } },+ };+ mockTranscribe.mockResolvedValue({ text: 'um hello there', provider: 'local', duration: 1 });+ mockReadiness.mockResolvedValue({ status: 'ready', tokenCounting: true });+ mockCountTokens.mockResolvedValue(null);+ mockCustomPrompt = undefined;+});++it('cleans an On-Device transcript on this phone when cleanup is set to On-Device', async () => {+ const result = await transcribeOnDevice();++ expect(mockReason).toHaveBeenCalledTimes(1);+ const req = mockReason.mock.calls[0][0] as Record<string, unknown>;+ expect(req.inferenceRoute).toEqual({ mode: 'local', scope: 'cleanup' });+ expect(req.routing).toEqual({ isPrivateNote: true });+ expect(result.text).toBe('cleaned:um hello there');+ expect(result.originalText).toBe('um hello there');+ expect(result.cleanupApplied).toBe(true);+});++it('cleans an On-Device upload on this phone outside On-Device mode too', async () => {+ mockActiveMode = 'cloud';+ mockConfig = {+ cleanupEnabled: true,+ defaultMode: 'cloud',+ inference: { upload: { mode: 'local' }, cleanup: { mode: 'local' } },+ };++ const result = await transcribeAndCleanup({+ audioUri: 'file://a.wav',+ provider: 'local',+ requestContext: 'file',+ });++ expect(mockReason).toHaveBeenCalledTimes(1);+ expect((mockReason.mock.calls[0][0] as Record<string, unknown>).inferenceRoute).toEqual({+ mode: 'local',+ scope: 'cleanup',+ });+ expect(result.text).toBe('cleaned:um hello there');+});++it.each([+ ['OpenWhispr Cloud', { mode: 'openwhispr' }],+ ['a provider', { mode: 'providers', providerId: 'openai', modelId: 'gpt-5-mini' }],+ ['nothing saved', undefined],+])('keeps an On-Device transcript raw when cleanup is set to %s', async (_label, cleanup) => {+ mockConfig = {+ cleanupEnabled: true,+ defaultMode: 'private',+ inference: { dictation: { mode: 'local' }, ...(cleanup ? { cleanup } : {}) },+ };++ const result = await transcribeOnDevice();++ expect(mockReason).not.toHaveBeenCalled();+ expect(result.text).toBe('um hello there');+ expect(result.cleanupApplied).toBe(false);+ expect(result.transcription.cleanupWarning).toBeUndefined();+});++it('keeps an On-Device transcript raw when cleanup is turned off', async () => {+ mockConfig = { ...mockConfig, cleanupEnabled: false };++ const result = await transcribeOnDevice();++ expect(mockReason).not.toHaveBeenCalled();+ expect(result.text).toBe('um hello there');+});++it.each([+ [+ 'appleIntelligenceOff',+ "Apple Intelligence is turned off in iOS Settings, so this can't run on-device.",+ ],+ ['disabled', 'Local Apple Intelligence is turned off in AI Models.'],+ ['modelNotReady', 'Apple Intelligence is still preparing its local model. Try again later.'],+ ['unavailable', 'Local Apple Intelligence is unavailable on this device.'],+])('says why On-Device cleanup could not run when readiness is %s', async (status, reason) => {+ mockReadiness.mockResolvedValue({ status, tokenCounting: false });++ const result = await transcribeOnDevice();++ expect(mockReason).not.toHaveBeenCalled();+ expect(result.text).toBe('um hello there');+ expect(result.transcription.cleanupWarning).toBe(`${reason} Your raw transcript is saved.`);+});++it('checks readiness again before refusing, so a fix in iOS Settings takes effect', async () => {+ mockReadiness+ .mockResolvedValueOnce({ status: 'appleIntelligenceOff', tokenCounting: false })+ .mockResolvedValue({ status: 'ready', tokenCounting: true });++ const result = await transcribeOnDevice();++ expect(mockReadiness).toHaveBeenCalledWith({ refresh: true });+ expect(result.text).toBe('cleaned:um hello there');+});++it('keeps a transcript too long for the on-device reply raw rather than cut short', async () => {+ const longText = 'word '.repeat(700).trim();+ mockTranscribe.mockResolvedValue({ text: longText, provider: 'local', duration: 1 });++ const result = await transcribeOnDevice();++ expect(mockReason).not.toHaveBeenCalled();+ expect(result.text).toBe(longText);+ expect(result.transcription.cleanupWarning).toBe(+ 'This transcript is too long for On-Device cleanup. Your raw transcript is saved.',+ );+});++it("uses Apple Intelligence's own token count for the length check when it has one", async () => {+ mockCountTokens.mockResolvedValue(5_000);++ const result = await transcribeOnDevice();++ expect(mockCountTokens).toHaveBeenCalledWith({ prompt: 'um hello there' });+ expect(mockReason).not.toHaveBeenCalled();+ expect(result.transcription.cleanupWarning).toMatch(/too long for On-Device cleanup/);+});++it('skips On-Device cleanup when the dictation was cancelled while transcribing', async () => {+ const result = await transcribeOnDevice({ shouldCancel: () => true });++ expect(mockReason).not.toHaveBeenCalled();+ expect(result.text).toBe('um hello there');+});++it('sends a custom cleanup prompt to On-Device cleanup', async () => {+ mockCustomPrompt = 'Always use bullet points.';++ await transcribeOnDevice();++ expect(mockReason).toHaveBeenCalledTimes(1);+ const req = mockReason.mock.calls[0][0] as Record<string, unknown>;+ expect(req.customPrompt).toBe('Always use bullet points.');+ expect(req.inferenceRoute).toEqual({ mode: 'local', scope: 'cleanup' });+});diff --git a/openwhispr-mobile/src/lib/aiWorkflows.ts b/openwhispr-mobile/src/lib/aiWorkflows.tsindex 03938eef0..4203fca54 100644--- a/openwhispr-mobile/src/lib/aiWorkflows.ts+++ b/openwhispr-mobile/src/lib/aiWorkflows.ts@@ -21,6 +21,10 @@ export const UNSET_PROVIDER_NOTES: Partial<Record<MobileInferenceScope, string>>'Not saved yet. The voice assistant is skipped until you save a selection; note chat uses OpenWhispr Cloud.',};+// On-Device mode skips cleanup until On-Device is saved for it, so the unset page picks nothing.+export const UNSET_ON_DEVICE_CLEANUP_NOTE =+ 'Not saved yet. On-Device mode skips cleanup until you choose On-Device.';+// What On-Device mode means for each workflow other than dictation.export const ON_DEVICE_MODE_NOTES: Partial<Record<MobileInferenceScope, string>> = {upload:@@ -28,11 +32,17 @@ export const ON_DEVICE_MODE_NOTES: Partial<Record<MobileInferenceScope, string>>notes:'On-Device mode formats notes on this iPhone and asks before sending one to your choice here.',cleanup:- 'On-Device mode keeps the raw transcript, so cleanup is skipped. Your choice applies when dictation leaves On-Device.',+ 'On-Device cleanup runs on this iPhone. Any other choice is skipped until dictation leaves On-Device, so the transcript never leaves this phone.',agent:'In On-Device mode the voice assistant is off, and note chat asks before sending a note off this iPhone.',};+// A local transcript is cleaned only when cleanup is saved as On-Device; unset or any+// other choice would take it off the phone, so it stays raw.+export function cleanupSavedOnDevice(config: UserConfig | null): boolean {+ return config?.inference?.cleanup?.mode === 'local';+}+export function parseWorkflow(value: unknown): MobileInferenceScope | null {return WORKFLOWS.find((scope) => scope === value) ?? null;}@@ -55,12 +65,25 @@ export function workflowSummary(config: UserConfig | null,scope: MobileInferenceScope,activeMode: ProcessingMode,- keyMissing = false,+ {+ keyMissing = false,+ onDeviceUnavailable,+ }: {+ keyMissing?: boolean;+ // Why Apple Intelligence can't run right now, when it can't.+ onDeviceUnavailable?: string;+ } = {},): string {- // On-Device mode skips cleanup and runs everything else on this phone first, whatever- // is saved. Only note chat set to OpenWhispr, or not set, goes straight to Cloud.+ if (scope === 'cleanup') {+ if (!(config?.cleanupEnabled ?? true)) return 'Off';+ if (cleanupSavedOnDevice(config) && onDeviceUnavailable)+ return `${MODE_LABELS.local} · ${onDeviceUnavailable}`;+ }+ // On-Device mode runs everything on this phone first, whatever is saved. Cleanup runs+ // only when set to On-Device, and only note chat set to OpenWhispr, or not set, goes+ // straight to Cloud.if (activeMode === 'private') {- if (scope === 'cleanup') return 'Skipped';+ if (scope === 'cleanup' && !cleanupSavedOnDevice(config)) return 'Skipped';const chatOnCloud = (config?.inference?.agent?.mode ?? 'openwhispr') === 'openwhispr';if (scope === 'agent' && chatOnCloud) return MODE_LABELS.openwhispr;}diff --git a/openwhispr-mobile/src/lib/cleanupTranscript.ts b/openwhispr-mobile/src/lib/cleanupTranscript.tsindex 4da26922e..cabbe7002 100644--- a/openwhispr-mobile/src/lib/cleanupTranscript.ts+++ b/openwhispr-mobile/src/lib/cleanupTranscript.ts@@ -12,6 +12,13 @@ import {detectAgentMention,} from './dictationAgent';import { buildDictationHints } from './dictationHints';+import {+ LOCAL_OUTPUT_TOKEN_RESERVE,+ countLocalReasoningTokens,+ estimateLocalTokens,+ getLocalReasoningReadiness,+ getLocalReasoningUnavailableMessage,+} from './localReasoning';import { withRetry, createApiRetryStrategy } from './retry';// Only 'keyboard' and 'recording' may receive agentName — notes/meeting are not dictation flows.@@ -41,6 +48,26 @@ function createTimeoutSignal(timeoutMs: number): { signal: AbortSignal; cancel:};}+// Apple Intelligence stops at LOCAL_OUTPUT_TOKEN_RESERVE without an error, so a transcript+// whose cleaned copy might not fit would come back cut short. The margin covers the+// punctuation and capitals cleanup adds.+const LOCAL_CLEANUP_MAX_TRANSCRIPT_TOKENS = Math.floor(LOCAL_OUTPUT_TOKEN_RESERVE * 0.8);++async function localSkipReason(+ text: string,+ scope: 'cleanup' | 'agent',+): Promise<string | undefined> {+ let readiness = await getLocalReasoningReadiness();+ // The cached answer outlives a fix in iOS Settings, so check again before refusing.+ if (readiness.status !== 'ready') readiness = await getLocalReasoningReadiness({ refresh: true });+ if (readiness.status !== 'ready') return getLocalReasoningUnavailableMessage(readiness);+ if (scope !== 'cleanup') return undefined;+ const tokens = (await countLocalReasoningTokens({ prompt: text })) ?? estimateLocalTokens(text);+ return tokens > LOCAL_CLEANUP_MAX_TRANSCRIPT_TOKENS+ ? 'This transcript is too long for On-Device cleanup.'+ : undefined;+}+function isDictationCleanupContext(context: CleanupContext | undefined): boolean {return context === 'keyboard' || context === 'recording';}@@ -116,6 +143,14 @@ export async function cleanupTranscript(return rawText;}const inferenceRoute = resolved.route;+ // Say why an on-device pass can't run, rather than retrying into a generic failure.+ if (inferenceRoute.mode === 'local') {+ const skipReason = await localSkipReason(rawText, scope);+ if (skipReason) {+ options.onSkipped?.(`${skipReason} Your raw transcript is saved.`);+ return rawText;+ }+ }// Only provider and on-device routes take the privacy hint. A Cloud route is// either the user's choice or a Cloud fallback they just consented to while// still in private mode; hinting it would make ReasoningService demand localdiff --git a/openwhispr-mobile/src/lib/transcribeAndCleanup.ts b/openwhispr-mobile/src/lib/transcribeAndCleanup.tsindex 09b55347f..d9c93b1c9 100644--- a/openwhispr-mobile/src/lib/transcribeAndCleanup.ts+++ b/openwhispr-mobile/src/lib/transcribeAndCleanup.ts@@ -11,6 +11,7 @@ import { getActiveCustomCleanupPrompt } from '@/store/useCustomPromptsStore';import { useProcessingModeStore } from '@/store/useProcessingModeStore';import { useSnippetsStore } from '@/store/useSnippetsStore';import { requiresRealAccount } from './accountAccess';+import { cleanupSavedOnDevice } from './aiWorkflows';import { cleanupTranscript, AGENT_ACTION_TIMEOUT_MS } from './cleanupTranscript';import {getDictationAgentName,@@ -32,7 +33,7 @@ export interface DictationProcessingLifecycle {onCleanupDone?: (result: TranscriptionResponse) => void;onRawTranscript?: (text: string, result: TranscriptionResponse) => void;onFusedCleanupFallback?: (error: unknown) => void;- // Polled after transcription completes, before the (cloud-only) cleanup pass.+ // Polled after transcription completes, before the cleanup pass.// When it returns true the cleanup call is skipped and the raw transcript is// returned — the caller discards it. Lets a keyboard cancel avoid paying for// cleanup of a result the user already abandoned.@@ -48,7 +49,7 @@ export interface DictationProcessingResult {}// The transcript before any cleanup pass: returned for local/private transcripts-// (cleanup is cloud-only) and when a cancel short-circuits cleanup.+// that On-Device cleanup won't clean, and when a cancel short-circuits cleanup.function rawTranscriptResult(transcription: TranscriptionResponse): DictationProcessingResult {const originalText = transcription.originalText || transcription.text;return {@@ -60,6 +61,14 @@ function rawTranscriptResult(transcription: TranscriptionResponse): DictationPro};}+// The pinned route decides where cleanup runs, and a local job always pins a local one;+// the saved choice decides whether it runs, read live like cleanupEnabled.+function cleansOnDevice(request: TranscriptionRequest): boolean {+ return (+ request.cleanupRoute?.mode === 'local' && cleanupSavedOnDevice(useConfigStore.getState().config)+ );+}+function cleanupToneForRequest(request: TranscriptionRequest): KeyboardTone | undefined {if (request.requestContext !== 'keyboard') return undefined;if (!request.keyboardTone || request.keyboardTone === 'default') return undefined;@@ -176,16 +185,14 @@ async function runSerialTranscribeAndCleanup(const originalText = transcription.text;lifecycle.onRawTranscript?.(originalText, transcription);- // Cleanup runs only when the transcription itself went to the cloud.// Local/private transcripts must never leave the device — not even for the- // cleanup pass. (transcription.provider, not request.provider, so the- // local-model-missing → cloud fallback still gets cleaned.)- if (transcription.provider === 'local') {+ // cleanup pass — so they are cleaned only by On-Device cleanup.+ if (transcription.provider === 'local' && !cleansOnDevice(request)) {return rawTranscriptResult(transcription);}- // Cancelled while transcribing: skip the cloud cleanup call entirely. The- // caller discards this result, so cleaning it would only waste cloud spend.+ // Cancelled while transcribing: skip the cleanup call entirely. The+ // caller discards this result, so cleaning it would only waste the work.if (lifecycle.shouldCancel?.()) {return rawTranscriptResult(transcription);}diff --git a/openwhispr-mobile/src/screens/AIModelsScreen.tsx b/openwhispr-mobile/src/screens/AIModelsScreen.tsxindex 5a0498570..fc96a451e 100644--- a/openwhispr-mobile/src/screens/AIModelsScreen.tsx+++ b/openwhispr-mobile/src/screens/AIModelsScreen.tsx@@ -134,6 +134,11 @@ export default function AIModelsScreen(): React.JSX.Element {);}+ const onDeviceUnavailable =+ localReadiness && localReadiness.status !== 'ready'+ ? localReasoningStatusLabel(localReadiness)+ : undefined;+return (<View className="flex-1 bg-systemBackground"><SettingsScreen>@@ -147,7 +152,10 @@ export default function AIModelsScreen(): React.JSX.Element {iconStyle="line"{...WORKFLOW_ICONS[scope]}title={WORKFLOW_LABELS[scope]}- subtitle={workflowSummary(config, scope, activeMode, missingKeys.includes(scope))}+ subtitle={workflowSummary(config, scope, activeMode, {+ keyMissing: missingKeys.includes(scope),+ onDeviceUnavailable,+ })}onPress={() => router.push({ pathname: '/(account)/ai-workflow', params: { scope } })}/>))}diff --git a/openwhispr-mobile/src/screens/CleanupPromptScreen.tsx b/openwhispr-mobile/src/screens/CleanupPromptScreen.tsxindex bb0d0ad90..baad2f9d6 100644--- a/openwhispr-mobile/src/screens/CleanupPromptScreen.tsx+++ b/openwhispr-mobile/src/screens/CleanupPromptScreen.tsx@@ -28,7 +28,7 @@ export default function CleanupPromptScreen() {const setCustomPrompt = useCustomPromptsStore((state) => state.setCustomPrompt);const resetCustomPrompt = useCustomPromptsStore((state) => state.resetCustomPrompt);const cleanupEnabled = useConfigStore((state) => state.config?.cleanupEnabled ?? true);- const cleanupSelected = useConfigStore((state) => !!state.config?.inference?.cleanup);+ const cleanupMode = useConfigStore((state) => state.config?.inference?.cleanup?.mode);const activeMode = useProcessingModeStore((state) => state.activeMode);const keyboardHeight = useKeyboardHeight();@@ -36,12 +36,13 @@ export default function CleanupPromptScreen() {const baseline = override ?? DEFAULT_CLEANUP_PROMPT;const [draft, setDraft] = useState(baseline);- // On-Device transcripts stay raw, and Bring Your Own Key skips cleanup until it has a selection.+ // On-Device transcripts are cleaned only by On-Device cleanup, and Bring Your Own Key+ // skips cleanup until it has a selection.const inactiveNotice = !cleanupEnabled? '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+ : activeMode === 'private' && cleanupMode !== 'local'+ ? 'On-Device mode skips cleanup unless it is set to On-Device. Your prompt is saved and applies when it runs.'+ : activeMode === 'providers' && !cleanupMode? 'Bring Your Own Key skips cleanup until Text Cleanup has a selection. Your prompt is saved and applies once it does.': null;const isDirty = draft !== baseline;diff --git a/openwhispr-mobile/src/screens/WorkflowSettingsScreen.tsx b/openwhispr-mobile/src/screens/WorkflowSettingsScreen.tsxindex fbb66b565..50baefc57 100644--- a/openwhispr-mobile/src/screens/WorkflowSettingsScreen.tsx+++ b/openwhispr-mobile/src/screens/WorkflowSettingsScreen.tsx@@ -33,6 +33,7 @@ import { workflowSaveConfig } from '@/lib/inferenceModes';import { InferenceModePicker } from '@/components/settings/InferenceModePicker';import {ON_DEVICE_MODE_NOTES,+ UNSET_ON_DEVICE_CLEANUP_NOTE,UNSET_PROVIDER_NOTES,WORKFLOW_LABELS,WORKFLOWS,@@ -234,6 +235,9 @@ function WorkflowSettings({ scope }: { scope: MobileInferenceScope }): React.JSXconst setActiveMode = useProcessingModeStore((state) => state.setActiveMode);const activeMode = useProcessingModeStore((state) => state.activeMode);const savedSelection = config?.inference?.[scope] ?? unsetSelection(scope, activeMode);+ // On-Device mode skips an unsaved cleanup, so the On-Device default must not look picked.+ const cleanupUnsaved =+ scope === 'cleanup' && activeMode === 'private' && !config?.inference?.cleanup;// 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>>({});@@ -261,7 +265,10 @@ function WorkflowSettings({ scope }: { scope: MobileInferenceScope }): React.JSXconst modelId = selection.modelId ?? defaultModelId(provider);const providerId = provider?.id;const models = provider?.models.length ? provider.models : discoveredModels;+ const shownMode =+ cleanupUnsaved && selection.mode === savedSelection.mode ? null : selection.mode;const modeNote =+ (shownMode === null ? UNSET_ON_DEVICE_CLEANUP_NOTE : undefined) ??(activeMode === 'private' ? ON_DEVICE_MODE_NOTES[scope] : undefined) ??(activeMode === 'providers' && !config?.inference?.[scope]? UNSET_PROVIDER_NOTES[scope]@@ -376,7 +383,7 @@ function WorkflowSettings({ scope }: { scope: MobileInferenceScope }): React.JSX);return;}- if (mode === savedSelection.mode) {+ if (mode === savedSelection.mode && !cleanupUnsaved) {setSelection(savedSelection);return;}@@ -649,7 +656,7 @@ function WorkflowSettings({ scope }: { scope: MobileInferenceScope }): React.JSX<><InferenceModePickerscope={speechScope ? 'speech' : 'text'}- selectedMode={selection.mode}+ selectedMode={shownMode}onSelect={chooseMode}/>{modeNote ? <SectionFooter>{modeNote}</SectionFooter> : null}@@ -661,7 +668,7 @@ function WorkflowSettings({ scope }: { scope: MobileInferenceScope }): React.JSX}/>) : null}- {selection.mode === 'local' && !speechScope ? (+ {shownMode === 'local' && !speechScope ? (<SectionFooter>Runs on Apple Intelligence on this iPhone.</SectionFooter>) : null}{selection.mode === 'providers' && provider ? (diff --git a/openwhispr-mobile/src/screens/__tests__/AIModelsScreen.test.tsx b/openwhispr-mobile/src/screens/__tests__/AIModelsScreen.test.tsxindex 8e162badf..cf77f2cc5 100644--- a/openwhispr-mobile/src/screens/__tests__/AIModelsScreen.test.tsx+++ b/openwhispr-mobile/src/screens/__tests__/AIModelsScreen.test.tsx@@ -26,8 +26,9 @@ jest.mock('@/store/useProcessingModeStore', () => ({selector({ activeMode: mockActiveMode }),}));jest.mock('@/hooks/useConfigToggle', () => ({ useConfigToggle: () => jest.fn() }));+const mockReadiness = jest.fn();jest.mock('@/lib/localReasoning', () => ({- getLocalReasoningReadiness: jest.fn(async () => ({ status: 'ready', tokenCounting: false })),+ getLocalReasoningReadiness: (...args: unknown[]) => mockReadiness(...args),}));jest.mock('@/services/providers/ProviderCredentials', () => ({clearProviderCredentials: (...args: unknown[]) => mockClearCredentials(...args),@@ -51,6 +52,7 @@ beforeEach(() => {mockConfig = null;Platform.OS = 'ios';mockCredentialStatus.mockResolvedValue({ isConfigured: true });+ mockReadiness.mockResolvedValue({ status: 'ready', tokenCounting: false });});afterAll(() => {@@ -131,13 +133,50 @@ it('shows what each workflow really does while On-Device mode is on', async () =// 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.+ // Cleanup set to anything but On-Device would leave the phone, so it is skipped.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.each([+ ['nothing saved', undefined],+ ['a provider', { mode: 'providers', providerId: 'openai', modelId: 'gpt-5-mini' }],+])('shows cleanup as skipped in On-Device mode with %s', async (_label, cleanup) => {+ mockActiveMode = 'private';+ mockConfig = {+ defaultMode: 'private',+ inference: { dictation: { mode: 'local' }, ...(cleanup ? { cleanup } : {}) },+ };+ render(<AIModelsScreen />);+ expect(screen.getByText('Skipped')).toBeTruthy();+ expect(screen.queryByText('OpenAI')).toBeNull();+ await screen.findByText(/Status: Ready/);+});++it('shows On-Device cleanup as running in On-Device mode', async () => {+ mockActiveMode = 'private';+ mockConfig = {+ defaultMode: 'private',+ inference: { dictation: { mode: 'local' }, cleanup: { mode: 'local' } },+ };+ render(<AIModelsScreen />);+ expect(screen.queryByText('Skipped')).toBeNull();+ await screen.findByText(/Status: Ready/);+});++it('says why On-Device cleanup cannot run while Apple Intelligence is off', async () => {+ mockReadiness.mockResolvedValue({ status: 'appleIntelligenceOff', tokenCounting: false });+ mockActiveMode = 'private';+ mockConfig = {+ defaultMode: 'private',+ inference: { dictation: { mode: 'local' }, cleanup: { mode: 'local' } },+ };+ render(<AIModelsScreen />);+ expect(await screen.findByText('On-Device · Apple Intelligence off')).toBeTruthy();+});+it('shows provider note chat as On-Device, which answers it on this iPhone first', async () => {mockActiveMode = 'private';mockCredentialStatus.mockResolvedValue({ isConfigured: true });diff --git a/openwhispr-mobile/src/screens/__tests__/CleanupPromptScreen.test.tsx b/openwhispr-mobile/src/screens/__tests__/CleanupPromptScreen.test.tsxindex 0e57fcb61..82c1848aa 100644--- a/openwhispr-mobile/src/screens/__tests__/CleanupPromptScreen.test.tsx+++ b/openwhispr-mobile/src/screens/__tests__/CleanupPromptScreen.test.tsx@@ -92,10 +92,23 @@ describe('CleanupPromptScreen — guidance', () => {expect(screen.queryByText(/requires Cloud mode/)).not.toBeOnTheScreen();});- it('says the prompt has no effect while On-Device mode keeps the raw transcript', () => {+ it('says the prompt has no effect while On-Device mode skips cleanup', () => {mockActiveMode = 'private';render(<CleanupPromptScreen />);- expect(screen.getByText(/On-Device mode keeps the raw transcript/)).toBeTruthy();+ expect(+ screen.getByText(/On-Device mode skips cleanup unless it is set to On-Device/),+ ).toBeTruthy();+ });++ it('treats On-Device cleanup in On-Device mode as using the prompt', () => {+ mockActiveMode = 'private';+ mockConfig = {+ defaultMode: 'private',+ cleanupEnabled: true,+ inference: { cleanup: { mode: 'local' } },+ };+ render(<CleanupPromptScreen />);+ expect(screen.queryByText(NOTICE)).not.toBeOnTheScreen();});it('treats provider cleanup as using the prompt', () => {diff --git a/openwhispr-mobile/src/screens/__tests__/WorkflowSettingsScreen.test.tsx b/openwhispr-mobile/src/screens/__tests__/WorkflowSettingsScreen.test.tsxindex 491437106..1140ccaf9 100644--- a/openwhispr-mobile/src/screens/__tests__/WorkflowSettingsScreen.test.tsx+++ b/openwhispr-mobile/src/screens/__tests__/WorkflowSettingsScreen.test.tsx@@ -436,6 +436,39 @@ it('defaults an unselected workflow to On-Device for a private-mode user', () =>expect(selectedMode()).toBe('On-Device');});+it('shows no cleanup mode for a private-mode user who has not saved one, since cleanup is skipped', () => {+ mockConfig = { defaultMode: 'private' };+ mockActiveMode = 'private';+ mockScope = 'cleanup';+ render(<WorkflowSettingsScreen />);+ expect(selectedMode()).toBeUndefined();+ expect(+ screen.getByText('Not saved yet. On-Device mode skips cleanup until you choose On-Device.'),+ ).toBeTruthy();+ expect(screen.queryByText('Runs on Apple Intelligence on this iPhone.')).toBeNull();+});++it('saves On-Device cleanup when a private-mode user taps it with nothing saved', async () => {+ mockConfig = { defaultMode: 'private' };+ mockActiveMode = 'private';+ mockScope = 'cleanup';+ render(<WorkflowSettingsScreen />);+ fireEvent.press(screen.getByText('On-Device'));+ await waitFor(() => expect(mockSwitchMode).toHaveBeenCalledWith('cleanup', 'local'));+ await waitFor(() => expect(selectedMode()).toBe('On-Device'));+ expect(screen.getByText('Runs on Apple Intelligence on this iPhone.')).toBeTruthy();+});++it('keeps On-Device cleanup selected once a private-mode user has saved it', () => {+ mockConfig = { defaultMode: 'private', inference: { cleanup: { mode: 'local' } } };+ mockActiveMode = 'private';+ mockScope = 'cleanup';+ render(<WorkflowSettingsScreen />);+ expect(selectedMode()).toBe('On-Device');+ fireEvent.press(screen.getByText('On-Device'));+ expect(mockSwitchMode).not.toHaveBeenCalled();+});+it('keeps uploads on the previous mode when dictation switches to Bring Your Own Key', async () => {mockConfig = { defaultMode: 'private' };mockActiveMode = 'private';@@ -748,11 +781,20 @@ it('adds no pins when an existing user re-saves dictation with their own key', aexpect(saved.inference.notes).toBeUndefined();});+it('explains that On-Device mode skips a saved Cloud cleanup choice', () => {+ mockConfig = { defaultMode: 'private', inference: { cleanup: { mode: 'openwhispr' } } };+ mockActiveMode = 'private';+ mockScope = 'cleanup';+ render(<WorkflowSettingsScreen />);+ expect(selectedMode()).toBe('OpenWhispr Cloud');+ expect(+ screen.getByText(+ 'On-Device cleanup runs on this iPhone. Any other choice is skipped until dictation leaves On-Device, so the transcript never leaves this phone.',+ ),+ ).toBeTruthy();+});+it.each([- [- 'cleanup',- 'On-Device mode keeps the raw transcript, so cleanup is skipped. Your choice applies when dictation leaves On-Device.',- ],['agent','In On-Device mode the voice assistant is off, and note chat asks before sending a note off this iPhone.',