Skip to content

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

62.8 KB
Raw Blame
import React from 'react';
import { Alert, AppState, Keyboard, ScrollView } from 'react-native';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react-native';

const mockUpdateConfig = jest.fn().mockResolvedValue(undefined);
const mockSetActiveMode = jest.fn();
const mockSetCredential = jest.fn().mockResolvedValue(undefined);
const mockRemoveCredential = jest.fn().mockResolvedValue(undefined);
const mockTestConnection = jest.fn();
const mockDiscoverModels = jest.fn();
const mockPolicy = jest.fn();
let mockActiveMode = 'cloud';
const mockCredentialStatus = jest.fn().mockResolvedValue({ isConfigured: false });
let mockConfig: Record<string, unknown> | null = null;
let mockScope: string | undefined;
let mockUser: { id: string; isAnonymous: boolean } | null = null;
jest.mock('@/store/useAuthStore', () => ({
  useAuthStore: (selector: (state: unknown) => unknown) => selector({ user: mockUser }),
}));
const mockPreventRemove = jest.fn();
const mockDispatch = jest.fn();
let mockStoredPrompt = '';
const mockPush = jest.fn();
const mockSwitchMode = jest.fn();
let mockLocalReasoningReady = false;
const mockPrivateReadiness = jest.fn();
let mockFocusEffect: (() => (() => void) | undefined) | 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', () => ({
  router: { push: (...args: unknown[]) => mockPush(...args) },
  useLocalSearchParams: () => ({ scope: mockScope }),
  // Tests call the latest effect to act out returning to the page.
  useFocusEffect: (effect: () => (() => void) | undefined) => {
    mockFocusEffect = effect;
  },
}));
const mockLocalReadiness = jest.fn();
jest.mock('@/lib/localReasoning', () => ({
  ...jest.requireActual('@/lib/localReasoning'),
  getLocalReasoningReadiness: (...args: unknown[]) => mockLocalReadiness(...args),
}));
jest.mock('@/lib/privateMode', () => ({
  getPrivateModeReadiness: () => mockPrivateReadiness(),
}));
jest.mock('@/lib/workflowModeSwitch', () => ({
  switchWorkflowMode: (...args: unknown[]) => mockSwitchMode(...args),
  leavingLocalModeWithLocalReasoning: async () => mockLocalReasoningReady,
}));
jest.mock('@/components/settings/OnDeviceModelSection', () => ({
  OnDeviceModelSection: ({
    scope,
    picked,
    lockedChoice,
  }: {
    scope: string;
    picked?: string;
    lockedChoice?: boolean;
  }) => (
    <MockText>
      {`On-device models for ${scope}, picked ${picked ?? 'Automatic'}${lockedChoice ? ', choice locked' : ''}`}
    </MockText>
  ),
}));
const mockToggle = jest.fn();
jest.mock('@/hooks/useConfigToggle', () => ({
  useConfigToggle: (key: string) => (value: unknown) => mockToggle(key, value),
}));
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', () => ({
  useNavigation: () => ({ dispatch: mockDispatch }),
  usePreventRemove: (...args: unknown[]) => mockPreventRemove(...args),
}));
jest.mock('@/components/ui/Toast', () => ({
  Toast: ({
    message,
    visible,
    type,
    showId,
  }: {
    message: string;
    visible: boolean;
    type: string;
    showId?: number;
  }) =>
    visible ? (
      <MockText testID={`toast-${type}`} accessibilityHint={`show ${showId}`}>
        {message}
      </MockText>
    ) : null,
}));
jest.mock('@/store/useConfigStore', () => ({
  useConfigStore: Object.assign(
    (selector: (state: unknown) => unknown) =>
      selector({ config: mockConfig, updateConfig: mockUpdateConfig }),
    { getState: () => ({ config: mockConfig, error: null }) },
  ),
}));
jest.mock('@/store/useProcessingModeStore', () => ({
  useProcessingModeStore: (selector: (state: unknown) => unknown) =>
    selector({ setActiveMode: mockSetActiveMode, activeMode: mockActiveMode }),
}));
jest.mock('@/services/providers/ProviderExecution', () => ({
  discoverProviderModels: (...args: unknown[]) => mockDiscoverModels(...args),
  testProviderConnection: (...args: unknown[]) => mockTestConnection(...args),
  ProviderExecutionError: class ProviderExecutionError extends Error {},
}));
jest.mock('@/services/providers/ProviderPolicy', () => ({
  getProviderPolicy: () => mockPolicy(),
}));
const mockGetCredential = jest.fn().mockResolvedValue(null);
jest.mock('@/services/providers/ProviderCredentials', () => ({
  getProviderCredentialReference: jest.fn(async (providerId: string, endpoint?: string) =>
    providerId === 'custom' ? `custom.${endpoint}` : `provider.${providerId}`,
  ),
  getProviderCredential: (...args: unknown[]) => mockGetCredential(...args),
  getProviderCredentialStatus: (...args: unknown[]) => mockCredentialStatus(...args),
  setProviderCredential: (...args: unknown[]) => mockSetCredential(...args),
  removeProviderCredential: (...args: unknown[]) => mockRemoveCredential(...args),
}));

import { WorkflowSettingsScreen } from '../WorkflowSettingsScreen';
import { CLOUD_CLEANUP_NEEDS_ACCOUNT_NOTE } from '@/lib/aiWorkflows';

function chooseProvider(provider: string): void {
  fireEvent.press(screen.getByText('Provider'));
  fireEvent.press(screen.getByText(provider));
}

function enableProviders(): void {
  fireEvent.press(screen.getByText('Bring Your Own Key'));
}

function selectedMode(): string | undefined {
  return ['OpenWhispr Cloud', 'On-Device', 'Bring Your Own Key'].find((title) => {
    let row = screen.getByText(title).parent;
    while (row && !row.props.accessibilityState) row = row.parent;
    return row?.props.accessibilityState.selected;
  });
}

beforeEach(() => {
  mockLocalReasoningReady = false;
  jest.clearAllMocks();
  mockConfig = null;
  mockScope = 'dictation';
  mockUser = null;
  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' });
  mockLocalReadiness.mockResolvedValue({ status: 'ready', tokenCounting: true });
  mockActiveMode = 'cloud';
  mockPolicy.mockResolvedValue({ status: 'unmanaged' });
  mockTestConnection.mockResolvedValue({ ok: true, verification: 'catalog-only' });
  mockDiscoverModels.mockResolvedValue({
    models: [{ id: 'server-model', name: 'Server Model' }],
    verification: 'catalog-only',
  });
  mockCredentialStatus.mockResolvedValue({ isConfigured: false });
});

it('lets a signed-out user save a secure credential reference without persisting the key', async () => {
  render(<WorkflowSettingsScreen />);
  enableProviders();
  fireEvent.changeText(screen.getByLabelText('API key'), 'test-key-value');
  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',
    inference: {
      dictation: { mode: 'providers', providerId: 'openai', credentialRef: 'provider.openai' },
    },
  });
  expect(JSON.stringify(mockUpdateConfig.mock.calls)).not.toContain('test-key-value');
  expect(mockSetActiveMode).toHaveBeenCalledWith('providers', true);
  expect(screen.getByLabelText('API key').props.value).toBe('');
});

it('rejects public HTTP endpoints before storing a credential', async () => {
  render(<WorkflowSettingsScreen />);
  enableProviders();
  chooseProvider('Custom');
  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'));
  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(<WorkflowSettingsScreen />);
  enableProviders();
  fireEvent.press(screen.getByText('Model'));
  fireEvent.press(screen.getByText('Whisper'));
  fireEvent.changeText(screen.getByLabelText('API key'), 'first-provider-key');
  chooseProvider('Groq');
  expect(screen.getByLabelText('API key').props.value).toBe('');
  chooseProvider('OpenAI');
  expect(screen.getByText('Whisper')).toBeTruthy();
});

it('saves custom endpoints without requiring an API key and preserves other scopes', async () => {
  mockConfig = { defaultMode: 'cloud', inference: { cleanup: { mode: 'local' } } };
  render(<WorkflowSettingsScreen />);
  enableProviders();
  chooseProvider('Custom');
  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'));
  await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalled());
  expect(mockSetCredential).not.toHaveBeenCalled();
  expect(mockUpdateConfig.mock.calls[0][0].inference).toMatchObject({
    cleanup: { mode: 'local' },
    dictation: {
      providerId: 'custom',
      modelId: 'local-model',
      endpoint: 'http://192.168.1.2:8080/v1',
    },
  });
  expect(mockUpdateConfig.mock.calls[0][0].inference.dictation.credentialRef).toBeUndefined();
});

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(<WorkflowSettingsScreen />);
  enableProviders();
  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'));
  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(<WorkflowSettingsScreen />);
  enableProviders();
  fireEvent.press(screen.getByText('Provider'));
  // OpenAI is both the selected row's subtitle and a picker choice.
  expect(screen.getAllByText('OpenAI')).toHaveLength(2);
  expect(screen.getByText('Groq')).toBeTruthy();
  expect(screen.getByText('Custom')).toBeTruthy();
  expect(screen.queryByText('Corti')).toBeNull();
  expect(screen.queryByText('Tinfoil')).toBeNull();
  await waitFor(() => expect(mockCredentialStatus).toHaveBeenCalled());
});

it('saves text workflow selection independently from the dictation mode', async () => {
  mockConfig = { defaultMode: 'private', inference: { dictation: { mode: 'local' } } };
  mockScope = 'cleanup';
  render(<WorkflowSettingsScreen />);
  enableProviders();
  chooseProvider('Groq');
  fireEvent.changeText(screen.getByLabelText('API key'), 'test-text-key');
  fireEvent.press(screen.getByText('Save'));
  await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalled());
  expect(mockUpdateConfig.mock.calls[0][0]).toMatchObject({
    inference: {
      dictation: { mode: 'local' },
      cleanup: { mode: 'providers', providerId: 'groq' },
    },
  });
  expect(mockUpdateConfig.mock.calls[0][0].defaultMode).toBeUndefined();
  expect(mockSetActiveMode).not.toHaveBeenCalled();
});

it('restores a provider model saved in an earlier settings session', async () => {
  mockConfig = {
    defaultMode: 'cloud',
    rememberedInference: {
      dictation: { openai: { mode: 'providers', providerId: 'openai', modelId: 'whisper-1' } },
    },
  };
  render(<WorkflowSettingsScreen />);
  enableProviders();
  chooseProvider('Groq');
  chooseProvider('OpenAI');
  // The current session's untouched default must not overwrite a saved provider choice.
  expect(screen.getByText('Whisper')).toBeTruthy();
});

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(<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(<WorkflowSettingsScreen />);
  enableProviders();
  fireEvent.changeText(screen.getByLabelText('API key'), 'test-key');
  fireEvent.press(screen.getByText('Check Connection'));
  expect(await screen.findByTestId('toast-info')).toHaveTextContent(
    'Model catalog accessible. Transcription and inference access have not been verified.',
  );
  expect(mockTestConnection).toHaveBeenCalledWith(
    expect.objectContaining({
      route: expect.objectContaining({
        scope: 'dictation',
        providerId: 'openai',
        credentialRef: 'provider.openai',
      }),
    }),
  );
  expect(mockTestConnection).toHaveBeenCalledWith(expect.objectContaining({ apiKey: 'test-key' }));
  expect(mockSetCredential).not.toHaveBeenCalled();
  expect(mockUpdateConfig).not.toHaveBeenCalled();
  expect(mockSetActiveMode).not.toHaveBeenCalled();
});

it('offers to replace or remove a saved key that can no longer be read', async () => {
  mockCredentialStatus.mockRejectedValue(new Error('unreadable'));
  render(<WorkflowSettingsScreen />);
  enableProviders();
  await screen.findByText('Remove Key');
  fireEvent.changeText(screen.getByLabelText('API key'), 'replacement-key');
  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(<WorkflowSettingsScreen />);
  enableProviders();
  fireEvent.changeText(screen.getByLabelText('API key'), 'test-key');
  fireEvent.press(screen.getByText('Check Connection'));
  expect(await screen.findByTestId('toast-error')).toHaveTextContent(
    'Organization policy does not currently permit this provider check.',
  );
  expect(mockTestConnection).not.toHaveBeenCalled();
});

it('reports a passing inference check as a success toast', async () => {
  mockTestConnection.mockResolvedValue({ ok: true, verification: 'inference' });
  mockScope = 'cleanup';
  render(<WorkflowSettingsScreen />);
  enableProviders();
  fireEvent.changeText(screen.getByLabelText('API key'), 'test-key');
  fireEvent.press(screen.getByText('Check Connection'));
  expect(await screen.findByTestId('toast-success')).toHaveTextContent(
    'Connection works. Save to use it.',
  );
});

it('reports a check without a key as an error toast and closes the keyboard', async () => {
  const dismiss = jest.spyOn(Keyboard, 'dismiss');
  render(<WorkflowSettingsScreen />);
  enableProviders();
  fireEvent.press(screen.getByText('Check Connection'));
  expect(dismiss).toHaveBeenCalled();
  expect(await screen.findByTestId('toast-error')).toHaveTextContent(
    'Enter a credential for this provider.',
  );
  expect(mockTestConnection).not.toHaveBeenCalled();
});

it('closes the keyboard when a key is pasted, but not while typing', () => {
  const dismiss = jest.spyOn(Keyboard, 'dismiss');
  render(<WorkflowSettingsScreen />);
  enableProviders();
  const input = screen.getByLabelText('API key');
  fireEvent.changeText(input, 's');
  fireEvent.changeText(input, 'sk');
  expect(dismiss).not.toHaveBeenCalled();
  fireEvent.changeText(input, 'sk-pasted-provider-key');
  expect(dismiss).toHaveBeenCalledTimes(1);
});

it('checks a provider from Local Mode, since a check sends no user content', async () => {
  mockActiveMode = 'private';
  render(<WorkflowSettingsScreen />);
  enableProviders();
  fireEvent.changeText(screen.getByLabelText('API key'), 'test-key');
  fireEvent.press(screen.getByText('Check Connection'));
  await screen.findByTestId('toast-info');
  expect(mockTestConnection).toHaveBeenCalled();
});

it('shows cleanup as waiting for a provider when Bring Your Own Key dictation will skip it', async () => {
  mockConfig = {
    defaultMode: 'providers',
    inference: { dictation: { mode: 'providers', providerId: 'openai', modelId: 'whisper-1' } },
  };
  mockActiveMode = 'providers';
  mockScope = 'cleanup';
  render(<WorkflowSettingsScreen />);
  expect(selectedMode()).toBe('Bring Your Own Key');
  expect(
    screen.getByText('Not saved yet. Cleanup is skipped until you save a selection.'),
  ).toBeTruthy();
});

it('shows a guest held in On-Device mode as On-Device, not a stale Cloud preference', () => {
  mockConfig = { defaultMode: 'cloud' };
  mockActiveMode = 'private';
  render(<WorkflowSettingsScreen />);
  expect(selectedMode()).toBe('On-Device');
});

it('discovers custom models before choosing a model, without silently selecting one', async () => {
  render(<WorkflowSettingsScreen />);
  enableProviders();
  chooseProvider('Custom');
  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.',
  );
  expect(screen.getByLabelText('Model ID').props.value).toBe('');
  fireEvent.press(screen.getByText('Model'));
  fireEvent.press(screen.getByText('Server Model'));
  expect(screen.getByLabelText('Model ID').props.value).toBe('server-model');
  expect(mockUpdateConfig).not.toHaveBeenCalled();
});

it('defaults an unselected workflow to On-Device for a private-mode user', () => {
  mockConfig = { defaultMode: 'private' };
  mockActiveMode = 'private';
  mockScope = 'upload';
  render(<WorkflowSettingsScreen />);
  expect(selectedMode()).toBe('On-Device');
});

// Local Mode cleans on this phone with nothing saved, so On-Device is what runs. Tapping it saves
// it, since an unsaved default would move to Cloud once the user signs in.
it('saves the On-Device cleanup a Local Mode user sees but has not saved', () => {
  mockConfig = { defaultMode: 'private' };
  mockActiveMode = 'private';
  mockScope = 'cleanup';
  render(<WorkflowSettingsScreen />);
  expect(selectedMode()).toBe('On-Device');
  expect(screen.getByText('Runs on Apple Intelligence on this iPhone.')).toBeTruthy();
  fireEvent.press(screen.getByText('On-Device'));
  expect(mockSwitchMode).toHaveBeenCalledWith('cleanup', 'local');
});

it('saves an upload Local Mode holds on this phone automatically when it is tapped', () => {
  mockConfig = {
    defaultMode: 'private',
    inference: { dictation: { mode: 'local' }, upload: { mode: 'local' } },
    pinnedInference: ['upload'],
  };
  mockActiveMode = 'private';
  mockScope = 'upload';
  render(<WorkflowSettingsScreen />);
  expect(selectedMode()).toBe('On-Device');
  fireEvent.press(screen.getByText('On-Device'));
  expect(mockSwitchMode).toHaveBeenCalledWith('upload', 'local');
});

it('says why a saved Cloud cleanup is skipped in Local Mode without an account', () => {
  mockUser = { id: 'a', isAnonymous: true };
  mockConfig = { defaultMode: 'private', inference: { cleanup: { mode: 'openwhispr' } } };
  mockActiveMode = 'private';
  mockScope = 'cleanup';
  render(<WorkflowSettingsScreen />);
  expect(selectedMode()).toBe('OpenWhispr Cloud');
  expect(screen.getByText(CLOUD_CLEANUP_NEEDS_ACCOUNT_NOTE)).toBeTruthy();
});

// Bring Your Own Key dictation also needs the separate Cloud pass, so a Cloud cleanup held when
// dictation left Cloud says why it is skipped rather than looking as if it runs.
it('says why a held Cloud cleanup is skipped under Bring Your Own Key without an account', () => {
  mockUser = { id: 'a', isAnonymous: true };
  mockConfig = {
    defaultMode: 'providers',
    inference: {
      dictation: { mode: 'providers', providerId: 'openai', modelId: 'whisper-1' },
      cleanup: { mode: 'openwhispr' },
    },
    pinnedInference: ['cleanup'],
  };
  mockActiveMode = 'providers';
  mockScope = 'cleanup';
  render(<WorkflowSettingsScreen />);
  expect(selectedMode()).toBe('OpenWhispr Cloud');
  expect(screen.getByText(CLOUD_CLEANUP_NEEDS_ACCOUNT_NOTE)).toBeTruthy();
});

// Note formatting runs its own selection in Local Mode, so a Cloud hold shows as Cloud.
it('shows note formatting held on Cloud as OpenWhispr Cloud in Local Mode', () => {
  mockConfig = {
    defaultMode: 'private',
    inference: { dictation: { mode: 'local' }, notes: { mode: 'openwhispr' } },
    pinnedInference: ['notes'],
  };
  mockActiveMode = 'private';
  mockScope = 'notes';
  render(<WorkflowSettingsScreen />);
  expect(selectedMode()).toBe('OpenWhispr Cloud');
});

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();
});

// Needs no account, so it is also how a guest, who is kept in Private mode, uses their own key.
it('keeps uploads on this phone when dictation leaves Local Mode for Bring Your Own Key', async () => {
  mockConfig = { defaultMode: 'private' };
  mockActiveMode = 'private';
  mockCredentialStatus.mockResolvedValue({ isConfigured: true });
  render(<WorkflowSettingsScreen />);
  enableProviders();
  expect(
    screen.getByText('Save to switch to Bring Your Own Key. This turns Local Mode off.'),
  ).toBeTruthy();
  fireEvent.press(screen.getByText('Save'));
  await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalled());
  const saved = mockUpdateConfig.mock.calls[0][0] as {
    inference: Record<string, { mode: string }>;
  };
  expect(saved.inference.dictation.mode).toBe('providers');
  expect(saved.inference.upload).toEqual({ mode: 'local' });
  expect(mockSetActiveMode).toHaveBeenCalledWith('providers', true);
});

// Local Mode uploaded to OpenWhispr Cloud with nothing saved and a session, so that is held.
it('keeps uploads on Cloud when a user with a session leaves Local Mode for a provider', async () => {
  mockUser = { id: 'a', isAnonymous: true };
  mockConfig = { defaultMode: 'private' };
  mockActiveMode = 'private';
  mockCredentialStatus.mockResolvedValue({ isConfigured: true });
  render(<WorkflowSettingsScreen />);
  enableProviders();
  fireEvent.press(screen.getByText('Save'));
  await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalled());
  expect(mockUpdateConfig.mock.calls[0][0]).toMatchObject({
    inference: {
      upload: { mode: 'openwhispr' },
      cleanup: { mode: 'local' },
      noteChat: { mode: 'local' },
    },
    pinnedInference: ['upload', 'cleanup', 'notes', 'noteChat', 'agent'],
  });
});

// Local Mode ran note formatting and the voice assistant on their own choices, Cloud when unset, and
// asked before sending note chat off the phone.
it('holds note formatting and the voice assistant on Cloud when dictation leaves Local Mode for a provider', async () => {
  mockLocalReasoningReady = true;
  mockConfig = { defaultMode: 'private' };
  mockActiveMode = 'private';
  mockCredentialStatus.mockResolvedValue({ isConfigured: true });
  render(<WorkflowSettingsScreen />);
  enableProviders();
  fireEvent.press(screen.getByText('Save'));
  await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalled());
  expect(mockUpdateConfig.mock.calls[0][0]).toMatchObject({
    inference: {
      notes: { mode: 'openwhispr' },
      noteChat: { mode: 'local' },
      agent: { mode: 'openwhispr' },
    },
    pinnedInference: ['upload', 'cleanup', 'notes', 'noteChat', 'agent'],
  });
});

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' },
    },
    pinnedInference: ['upload'],
  };
  mockActiveMode = 'providers';
  render(<WorkflowSettingsScreen />);
  fireEvent.press(screen.getByText('OpenWhispr Cloud'));
  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');
});

describe('a text workflow waiting on Apple Intelligence', () => {
  const WAITING_NOTE =
    'Switches to On-Device once Apple Intelligence is ready, while this page stays open.';
  let appStateListeners: ((state: string) => void)[];
  let leavePage: (() => void) | undefined;

  beforeEach(() => {
    appStateListeners = [];
    jest.spyOn(AppState, 'addEventListener').mockImplementation((_type, listener) => {
      appStateListeners.push(listener as (state: string) => void);
      return { remove: jest.fn() } as unknown as ReturnType<typeof AppState.addEventListener>;
    });
    mockConfig = { defaultMode: 'cloud', inference: { cleanup: { mode: 'openwhispr' } } };
    mockScope = 'cleanup';
    mockSwitchMode.mockResolvedValueOnce('not-ready');
    mockLocalReadiness.mockResolvedValue({ status: 'modelNotReady', tokenCounting: false });
  });

  afterEach(() => {
    leavePage?.();
    leavePage = undefined;
    jest.useRealTimers();
  });

  async function tapOnDevice(): Promise<void> {
    render(<WorkflowSettingsScreen />);
    fireEvent.press(screen.getByText('On-Device'));
    await waitFor(() => expect(mockSwitchMode).toHaveBeenCalledTimes(1));
    await act(async () => {
      leavePage = mockFocusEffect?.();
    });
  }

  it('says the switch finishes by itself', async () => {
    await tapOnDevice();
    expect(screen.getByText(WAITING_NOTE)).toBeTruthy();
    expect(mockSwitchMode).toHaveBeenCalledTimes(1);
    expect(selectedMode()).toBe('OpenWhispr Cloud');
  });

  // Apple Intelligence is turned on and downloads its model in iOS Settings.
  it('switches once it is ready on return from Settings', async () => {
    await tapOnDevice();
    mockLocalReadiness.mockResolvedValue({ status: 'ready', tokenCounting: true });
    await act(async () => appStateListeners.forEach((listener) => listener('active')));
    await waitFor(() => expect(mockSwitchMode).toHaveBeenCalledTimes(2));
    expect(mockSwitchMode).toHaveBeenLastCalledWith('cleanup', 'local');
    expect(mockLocalReadiness).toHaveBeenLastCalledWith({ refresh: true });
    expect(await screen.findByTestId('toast-success')).toHaveTextContent('Switched to On-Device.');
    expect(selectedMode()).toBe('On-Device');
  });

  it('switches once it is ready while the page stays open', async () => {
    jest.useFakeTimers();
    await tapOnDevice();
    mockLocalReadiness.mockResolvedValue({ status: 'ready', tokenCounting: true });
    await act(async () => {
      jest.advanceTimersByTime(10_000);
    });
    await waitFor(() => expect(mockSwitchMode).toHaveBeenCalledTimes(2));
    expect(selectedMode()).toBe('On-Device');
  });

  // The switch checks Apple Intelligence again, and its alert promises the page keeps waiting.
  it('keeps waiting when Apple Intelligence is not ready by the time it switches', async () => {
    await tapOnDevice();
    mockLocalReadiness.mockResolvedValue({ status: 'ready', tokenCounting: true });
    mockSwitchMode.mockResolvedValueOnce('not-ready');
    await act(async () => appStateListeners.forEach((listener) => listener('active')));
    await waitFor(() => expect(mockSwitchMode).toHaveBeenCalledTimes(2));
    expect(screen.getByText(WAITING_NOTE)).toBeTruthy();
    expect(screen.queryByTestId('toast-success')).toBeNull();
    expect(selectedMode()).toBe('OpenWhispr Cloud');

    await act(async () => appStateListeners.forEach((listener) => listener('active')));
    await waitFor(() => expect(mockSwitchMode).toHaveBeenCalledTimes(3));
    expect(await screen.findByTestId('toast-success')).toHaveTextContent('Switched to On-Device.');
    expect(selectedMode()).toBe('On-Device');
    expect(screen.queryByText(WAITING_NOTE)).toBeNull();
  });

  it('stops checking once the page is left', async () => {
    jest.useFakeTimers();
    await tapOnDevice();
    leavePage?.();
    leavePage = undefined;
    mockLocalReadiness.mockResolvedValue({ status: 'ready', tokenCounting: true });
    await act(async () => {
      appStateListeners.forEach((listener) => listener('active'));
      jest.advanceTimersByTime(10_000);
    });
    expect(mockSwitchMode).toHaveBeenCalledTimes(1);
  });

  it('stops waiting once another mode is chosen', async () => {
    await tapOnDevice();
    await act(async () => {
      fireEvent.press(screen.getByText('OpenWhispr Cloud'));
    });
    expect(screen.queryByText(WAITING_NOTE)).toBeNull();

    // React cleans up the waiting effect and runs the current one, which no longer waits.
    leavePage?.();
    leavePage = mockFocusEffect?.();
    expect(leavePage).toBeUndefined();
    mockLocalReadiness.mockResolvedValue({ status: 'ready', tokenCounting: true });
    await act(async () => appStateListeners.forEach((listener) => listener('active')));
    expect(mockSwitchMode).toHaveBeenCalledTimes(1);
  });
});

it('shows the on-device model list once On-Device is applied', async () => {
  mockConfig = { defaultMode: 'cloud', inference: { upload: { mode: 'openwhispr' } } };
  mockScope = 'upload';
  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' } },
  };
  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());
});

describe('the Chat page', () => {
  beforeEach(() => {
    mockScope = 'noteChat';
  });

  it('shows only the Chat switch on the Chat page', () => {
    const view = render(<WorkflowSettingsScreen />);
    const page = JSON.stringify(view.toJSON());
    expect(page.indexOf('Enable Chat')).toBeLessThan(page.indexOf('OpenWhispr Cloud'));
    expect(screen.queryByLabelText('Voice Assistant')).toBeNull();
    fireEvent(screen.getByLabelText('Chat'), 'valueChange', false);
    expect(mockToggle).toHaveBeenCalledWith('noteChatEnabled', false);
  });

  it('hides the model choice while chat is off', () => {
    mockConfig = { defaultMode: 'cloud', noteChatEnabled: false };
    render(<WorkflowSettingsScreen />);
    expect(screen.getByLabelText('Chat').props.value).toBe(false);
    expect(screen.queryByText('OpenWhispr Cloud')).toBeNull();
  });

  it('stays on when only the voice assistant is off', () => {
    mockConfig = { defaultMode: 'cloud', dictationAgentEnabled: false };
    render(<WorkflowSettingsScreen />);
    expect(screen.getByLabelText('Chat').props.value).toBe(true);
  });

  it('says what switching note chat off does', () => {
    mockConfig = { defaultMode: 'cloud', noteChatEnabled: false };
    render(<WorkflowSettingsScreen />);
    expect(
      screen.getByText('The Chat tab and Ask about this note are off while chat is off.'),
    ).toBeTruthy();
  });

  it('lists Note Chat and Voice Assistant as sharing a provider key', async () => {
    mockCredentialStatus.mockResolvedValue({ isConfigured: true });
    const groq = { mode: 'providers', providerId: 'groq', modelId: 'openai/gpt-oss-20b' };
    mockConfig = { defaultMode: 'cloud', inference: { noteChat: groq, agent: groq } };
    render(<WorkflowSettingsScreen />);
    expect(screen.getByText('Stays on this iPhone. Also used by Voice Assistant.')).toBeTruthy();
    await waitFor(() => expect(mockCredentialStatus).toHaveBeenCalled());
  });
});

describe('the Voice Assistant page', () => {
  beforeEach(() => {
    mockScope = 'agent';
  });

  it('shows the Voice Assistant switch and its settings on the Voice Assistant page', () => {
    const view = render(<WorkflowSettingsScreen />);
    const page = JSON.stringify(view.toJSON());
    expect(page.indexOf('Voice Assistant Settings')).toBeLessThan(page.indexOf('OpenWhispr Cloud'));
    expect(screen.queryByLabelText('Chat')).toBeNull();
    fireEvent(screen.getByLabelText('Voice Assistant'), 'valueChange', false);
    expect(mockUpdateConfig).toHaveBeenCalledWith({ dictationAgentEnabled: false });
    fireEvent.press(screen.getByText('Voice Assistant Settings'));
    expect(mockPush).toHaveBeenCalledWith('/(account)/dictation-agent');
  });

  it('hides the model choice and settings while the voice assistant is off', () => {
    mockConfig = { defaultMode: 'cloud', dictationAgentEnabled: false, noteChatEnabled: true };
    render(<WorkflowSettingsScreen />);
    expect(screen.getByLabelText('Voice Assistant').props.value).toBe(false);
    expect(screen.queryByText('OpenWhispr Cloud')).toBeNull();
    expect(screen.queryByText('Voice Assistant Settings')).toBeNull();
    expect(screen.getByText('The OpenWhispr keyboard shows no wand.')).toBeTruthy();
  });

  // The voice assistant runs its own selection, so Local Mode leaves it on.
  it('keeps the voice assistant on in Local Mode', () => {
    mockActiveMode = 'private';
    mockConfig = { defaultMode: 'private', dictationAgentEnabled: true };
    render(<WorkflowSettingsScreen />);
    expect(screen.getByLabelText('Voice Assistant').props.value).toBe(true);
    expect(screen.getByLabelText('Voice Assistant').props.disabled).toBeFalsy();
    expect(screen.getByText('Voice Assistant Settings')).toBeTruthy();
  });
});

it('treats Note Chat as unused for keys once its switch is off', async () => {
  mockCredentialStatus.mockResolvedValue({ isConfigured: true });
  mockActiveMode = 'providers';
  mockScope = 'cleanup';
  const openai = { mode: 'providers', providerId: 'openai', modelId: 'gpt-5-mini' };
  mockConfig = {
    defaultMode: 'providers',
    noteChatEnabled: false,
    inference: {
      dictation: { mode: 'providers', providerId: 'openai', modelId: 'whisper-1' },
      cleanup: openai,
      noteChat: openai,
    },
  };
  render(<WorkflowSettingsScreen />);
  expect(screen.getByText('Stays on this iPhone. Also used by Dictation.')).toBeTruthy();
  await waitFor(() => expect(mockCredentialStatus).toHaveBeenCalled());
});

// Local Mode runs the voice assistant on its saved provider too.
it('counts the Voice Assistant as using its key in Local Mode', async () => {
  mockCredentialStatus.mockResolvedValue({ isConfigured: true });
  mockActiveMode = 'private';
  mockScope = 'noteChat';
  const groq = { mode: 'providers', providerId: 'groq', modelId: 'openai/gpt-oss-20b' };
  mockConfig = { defaultMode: 'private', inference: { noteChat: groq, agent: groq } };
  render(<WorkflowSettingsScreen />);
  expect(screen.getByText('Stays on this iPhone. Also used by Voice Assistant.')).toBeTruthy();
  await waitFor(() => expect(mockCredentialStatus).toHaveBeenCalled());
});

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(<WorkflowSettingsScreen />);
  enableProviders();
  fireEvent.press(screen.getByText('Save'));
  await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalled());
  const saved = mockUpdateConfig.mock.calls[0][0] as {
    inference: Record<string, { mode: string }>;
  };
  expect(saved.inference.upload).toEqual({ mode: 'local' });
});

it('adds no pins when an existing user re-saves dictation with their own key', async () => {
  mockConfig = {
    defaultMode: 'providers',
    inference: {
      dictation: {
        mode: 'providers',
        providerId: 'groq',
        modelId: 'whisper-large-v3-turbo',
        credentialRef: 'provider.groq',
      },
    },
  };
  mockActiveMode = 'providers';
  mockCredentialStatus.mockResolvedValue({ isConfigured: true });
  render(<WorkflowSettingsScreen />);
  // Dictation already opens in Bring Your Own Key mode for this config.
  chooseProvider('OpenAI');
  fireEvent.press(screen.getByText('Save'));
  await waitFor(() => expect(mockUpdateConfig).toHaveBeenCalled());
  const saved = mockUpdateConfig.mock.calls[0][0] as {
    inference: Record<string, { mode: string }>;
  };
  // Unsaved workflows already run where they will keep running; nothing is newly held.
  expect(saved.inference.upload).toBeUndefined();
  expect(saved.inference.notes).toBeUndefined();
});

// Local Mode keeps dictation on this phone; uploads and cleanup run what is saved for them.
it.each([
  ['cleanup', { mode: 'openwhispr' }, 'OpenWhispr Cloud'],
  [
    'cleanup',
    { mode: 'providers', providerId: 'openai', modelId: 'gpt-5-mini' },
    'Bring Your Own Key',
  ],
  ['upload', { mode: 'openwhispr' }, 'OpenWhispr Cloud'],
  [
    'upload',
    { mode: 'providers', providerId: 'openai', modelId: 'whisper-1' },
    'Bring Your Own Key',
  ],
])('shows the %s choice saved in Local Mode', (scope, selection, label) => {
  mockConfig = { defaultMode: 'private', inference: { [scope]: selection } };
  mockActiveMode = 'private';
  mockScope = scope;
  render(<WorkflowSettingsScreen />);
  expect(selectedMode()).toBe(label);
});

// With nothing saved, Local Mode uploads to OpenWhispr Cloud with any session, and cleans there
// only for a signed-in account.
it.each([
  ['upload', null, 'On-Device'],
  ['upload', { id: 'a', isAnonymous: true }, 'OpenWhispr Cloud'],
  ['cleanup', { id: 'a', isAnonymous: true }, 'On-Device'],
  ['cleanup', { id: 'u', isAnonymous: false }, 'OpenWhispr Cloud'],
])('shows %s with nothing saved in Local Mode for %j as %s', (scope, user, label) => {
  mockUser = user;
  mockConfig = { defaultMode: 'private' };
  mockActiveMode = 'private';
  mockScope = scope;
  render(<WorkflowSettingsScreen />);
  expect(selectedMode()).toBe(label);
});

it('explains what Local Mode means for chat', () => {
  mockConfig = { defaultMode: 'private' };
  mockActiveMode = 'private';
  mockScope = 'noteChat';
  render(<WorkflowSettingsScreen />);
  expect(
    screen.getByText('In Local Mode chat asks before sending notes off this iPhone.'),
  ).toBeTruthy();
});

// Note formatting and the voice assistant run their own selections in Local Mode.
it.each(['notes', 'agent'])('says nothing about Local Mode on the %s page', (scope) => {
  mockConfig = { defaultMode: 'private' };
  mockActiveMode = 'private';
  mockScope = scope;
  render(<WorkflowSettingsScreen />);
  expect(screen.queryByText(/Local Mode/)).not.toBeOnTheScreen();
});

it('shows On-Device for a guest whose saved Cloud dictation Local Mode overrides', () => {
  mockConfig = { defaultMode: 'cloud', inference: { dictation: { mode: 'openwhispr' } } };
  mockActiveMode = 'private';
  render(<WorkflowSettingsScreen />);
  expect(selectedMode()).toBe('On-Device');
  fireEvent.press(screen.getByText('On-Device'));
  expect(mockSwitchMode).not.toHaveBeenCalled();
  expect(mockUpdateConfig).not.toHaveBeenCalled();
});

function modeDisabled(title: string): boolean {
  let row = screen.getByText(title).parent;
  while (row && !row.props.accessibilityState) row = row.parent;
  return !!row?.props.accessibilityState.disabled;
}

// Every page offers every mode in Local Mode; on Dictation's, picking OpenWhispr Cloud or Bring Your
// Own Key is how Local Mode is turned off.
it.each(['dictation', 'upload', 'cleanup', 'notes', 'noteChat', 'agent'])(
  'locks no mode for %s in Local Mode',
  (scope) => {
    mockConfig = { defaultMode: 'private' };
    mockActiveMode = 'private';
    mockScope = scope;
    render(<WorkflowSettingsScreen />);
    for (const title of ['OpenWhispr Cloud', 'On-Device', 'Bring Your Own Key'])
      expect(modeDisabled(title)).toBe(false);
  },
);

// Only Dictation's mode turns Local Mode off; saving a provider for uploads leaves it on.
it.each([
  ['dictation', 'Save to switch to Bring Your Own Key. This turns Local Mode off.'],
  ['upload', 'Save to switch to Bring Your Own Key.'],
])('says what saving Bring Your Own Key does for %s in Local Mode', (scope, note) => {
  mockConfig = { defaultMode: 'private' };
  mockActiveMode = 'private';
  mockScope = scope;
  render(<WorkflowSettingsScreen />);
  enableProviders();
  expect(screen.getByText(note)).toBeTruthy();
});

it('turns Local Mode off when OpenWhispr Cloud is picked on the Dictation page', async () => {
  mockConfig = { defaultMode: 'private', inference: { dictation: { mode: 'local' } } };
  mockActiveMode = 'private';
  render(<WorkflowSettingsScreen />);
  fireEvent.press(screen.getByText('OpenWhispr Cloud'));
  await waitFor(() => expect(mockSwitchMode).toHaveBeenCalledWith('dictation', 'openwhispr'));
});

it('locks no mode outside Local Mode', () => {
  render(<WorkflowSettingsScreen />);
  for (const title of ['OpenWhispr Cloud', 'On-Device', 'Bring Your Own Key'])
    expect(modeDisabled(title)).toBe(false);
});

// Dictation owns Local Mode, so its page says what On-Device does and how to leave it.
it.each([
  [
    'cloud',
    'On-Device turns on Local Mode: dictation stays on this iPhone, notes you make stay private, and chat asks before leaving it.',
  ],
  [
    'private',
    'Local Mode is on: dictation stays on this iPhone, notes you make stay private, and chat asks before leaving it. Choose OpenWhispr Cloud or Bring Your Own Key to turn it off.',
  ],
])('explains Local Mode on the Dictation page in %s mode', (mode, note) => {
  mockConfig = { defaultMode: mode };
  mockActiveMode = mode;
  render(<WorkflowSettingsScreen />);
  expect(screen.getByText(note)).toBeTruthy();
});

it('does not show the Local Mode note on the Dictation page', () => {
  mockConfig = { defaultMode: 'private' };
  mockActiveMode = 'private';
  render(<WorkflowSettingsScreen />);
  expect(screen.queryByText(/Local Mode keeps/)).not.toBeOnTheScreen();
});

it('does not edit dictation settings from an unknown workflow link', () => {
  mockScope = 'meeting';
  render(<WorkflowSettingsScreen />);
  expect(screen.getByText('This workflow is not available.')).toBeTruthy();
  expect(screen.queryByText('Save')).not.toBeOnTheScreen();
});

it('restores the provider saved last when switching back to Bring Your Own Key', async () => {
  mockConfig = {
    defaultMode: 'cloud',
    inference: { dictation: { mode: 'openwhispr' } },
    rememberedInference: {
      dictation: {
        groq: { mode: 'providers', providerId: 'groq', modelId: 'whisper-large-v3-turbo' },
        openai: { mode: 'providers', providerId: 'openai', modelId: 'whisper-1' },
      },
    },
  };
  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(<WorkflowSettingsScreen />);
  const scroll = screen.UNSAFE_getByType(ScrollView);
  expect(scroll.props.automaticallyAdjustKeyboardInsets).toBe(true);
  expect(scroll.props.keyboardShouldPersistTaps).toBe('handled');
});

it('asks before leaving with a checked but unsaved key', async () => {
  const alert = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined);
  render(<WorkflowSettingsScreen />);
  expect(mockPreventRemove).toHaveBeenLastCalledWith(false, expect.any(Function));
  enableProviders();
  fireEvent.changeText(screen.getByLabelText('API key'), 'unsaved-key');
  const [prevent, onPreventRemove] = mockPreventRemove.mock.calls.at(-1);
  expect(prevent).toBe(true);
  onPreventRemove({ data: { action: { type: 'GO_BACK' } } });
  expect(alert.mock.calls[0][0]).toBe('Discard unsaved changes?');
  const buttons = alert.mock.calls[0][2] ?? [];
  buttons.find((button) => button.text === 'Discard')?.onPress?.();
  expect(mockDispatch).toHaveBeenCalledWith({ type: 'GO_BACK' });
  alert.mockRestore();
  await waitFor(() => expect(mockCredentialStatus).toHaveBeenCalled());
});

it('lets the user leave freely once the selection is saved', async () => {
  mockCredentialStatus.mockResolvedValue({ isConfigured: true });
  // 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'));
  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(<WorkflowSettingsScreen />);
  enableProviders();
  fireEvent.press(screen.getByText('Check Connection'));
  const first = (await screen.findByTestId('toast-error')).props.accessibilityHint;
  fireEvent.press(screen.getByText('Check Connection'));
  await waitFor(() =>
    expect(screen.getByTestId('toast-error').props.accessibilityHint).not.toBe(first),
  );
});

it('keeps an error toast up longer than a success toast', async () => {
  jest.useFakeTimers();
  try {
    render(<WorkflowSettingsScreen />);
    enableProviders();
    fireEvent.press(screen.getByText('Check Connection'));
    await screen.findByTestId('toast-error');
    act(() => jest.advanceTimersByTime(4000));
    expect(screen.getByTestId('toast-error')).toBeOnTheScreen();
    act(() => jest.advanceTimersByTime(3000));
    expect(screen.queryByTestId('toast-error')).not.toBeOnTheScreen();
  } finally {
    jest.useRealTimers();
  }
});

describe('a custom server reached under /v1', () => {
  const bare = 'http://192.168.1.2:11434';
  const withV1 = `${bare}/v1`;

  it('adopts the address that answered a check, so later requests use it', async () => {
    mockDiscoverModels.mockResolvedValue({
      models: [],
      verification: 'catalog-only',
      endpoint: withV1,
    });
    render(<WorkflowSettingsScreen />);
    enableProviders();
    chooseProvider('Custom');
    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('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);
  });

  it('keeps the key saved for the address the check replaced', async () => {
    mockConfig = {
      defaultMode: 'providers',
      inference: {
        dictation: {
          mode: 'providers',
          providerId: 'custom',
          modelId: 'local-model',
          endpoint: bare,
          credentialRef: `custom.${bare}`,
        },
      },
    };
    mockCredentialStatus.mockImplementation(async (reference: string) => ({
      reference,
      isConfigured: reference === `custom.${bare}`,
    }));
    mockGetCredential.mockImplementation(async (reference: string) =>
      reference === `custom.${bare}` ? { apiKey: 'saved-key' } : null,
    );
    mockTestConnection.mockResolvedValue({ ok: true, verification: 'inference', endpoint: withV1 });
    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({
      endpoint: withV1,
      credentialRef: `custom.${withV1}`,
    });
  });

  it('checks again with the saved key after the check moved the address', async () => {
    mockConfig = {
      defaultMode: 'providers',
      inference: {
        dictation: {
          mode: 'providers',
          providerId: 'custom',
          modelId: 'local-model',
          endpoint: bare,
          credentialRef: `custom.${bare}`,
        },
      },
    };
    mockCredentialStatus.mockImplementation(async (reference: string) => ({
      reference,
      isConfigured: reference === `custom.${bare}`,
    }));
    mockGetCredential.mockImplementation(async (reference: string) =>
      reference === `custom.${bare}` ? { apiKey: 'saved-key' } : null,
    );
    mockTestConnection.mockResolvedValue({ ok: true, verification: 'inference', endpoint: withV1 });
    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();
  });

  it('never carries a saved key to a different server', async () => {
    mockConfig = {
      defaultMode: 'providers',
      inference: {
        dictation: {
          mode: 'providers',
          providerId: 'custom',
          modelId: 'local-model',
          endpoint: bare,
          credentialRef: `custom.${bare}`,
        },
      },
    };
    mockGetCredential.mockResolvedValue({ apiKey: 'saved-key' });
    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();
  });
});

function modeRow(title: string): { props: { accessibilityState?: Record<string, unknown> } } {
  let row = screen.getByText(title).parent;
  while (row && !row.props.accessibilityState) row = row.parent;
  if (!row) throw new Error(`No row for ${title}`);
  return row;
}

describe('an iPhone that cannot run Apple Intelligence', () => {
  const NEEDS = 'On-Device AI needs an iPhone with Apple Intelligence (iPhone 15 Pro or later).';

  beforeEach(() => {
    mockLocalReadiness.mockResolvedValue({ status: 'unsupportedDevice', tokenCounting: false });
  });

  it.each(['cleanup', 'notes', 'agent'])(
    'disables On-Device for %s and says what it needs',
    async (scope) => {
      mockScope = scope;
      render(<WorkflowSettingsScreen />);

      expect(await screen.findByText(NEEDS)).toBeTruthy();
      expect(modeRow('On-Device').props.accessibilityState?.disabled).toBe(true);
      fireEvent.press(screen.getByText('On-Device'));
      expect(mockSwitchMode).not.toHaveBeenCalled();
    },
  );

  it('keeps On-Device dictation, which runs its own speech model', async () => {
    mockScope = 'dictation';
    render(<WorkflowSettingsScreen />);

    await act(async () => {});
    expect(screen.queryByText(NEEDS)).not.toBeOnTheScreen();
    expect(modeRow('On-Device').props.accessibilityState?.disabled).toBeFalsy();
  });

  it.each([
    ['appleIntelligenceOff', 'Apple Intelligence is turned off in iOS Settings.'],
    ['modelNotReady', 'Apple Intelligence is downloading its model.'],
    [
      'unsupportedLanguage',
      "Apple Intelligence doesn't support Polish (Poland), your iPhone's language.",
    ],
  ])('keeps On-Device available and says why while it is %s', async (status, reason) => {
    mockLocalReadiness.mockResolvedValue({
      status,
      tokenCounting: false,
      deviceLanguage: 'Polish (Poland)',
    });
    mockScope = 'cleanup';
    render(<WorkflowSettingsScreen />);

    expect(await screen.findByText(reason)).toBeTruthy();
    expect(screen.queryByText('Text never leaves this phone.')).not.toBeOnTheScreen();
    expect(modeRow('On-Device').props.accessibilityState?.disabled).toBeFalsy();
  });

  it('checks again on return to the app, as Apple Intelligence is set up in iOS Settings', async () => {
    const appStateListeners: ((state: string) => void)[] = [];
    jest.spyOn(AppState, 'addEventListener').mockImplementation((_type, listener) => {
      appStateListeners.push(listener as (state: string) => void);
      return { remove: jest.fn() } as unknown as ReturnType<typeof AppState.addEventListener>;
    });
    mockLocalReadiness.mockResolvedValue({ status: 'modelNotReady', tokenCounting: false });
    mockScope = 'cleanup';
    render(<WorkflowSettingsScreen />);
    expect(await screen.findByText('Apple Intelligence is downloading its model.')).toBeTruthy();

    mockLocalReadiness.mockResolvedValue({ status: 'ready', tokenCounting: true });
    await act(async () => appStateListeners.forEach((listener) => listener('active')));
    expect(await screen.findByText('Text never leaves this phone.')).toBeTruthy();
    expect(mockLocalReadiness).toHaveBeenLastCalledWith({ refresh: true });
  });

  it('shows no Apple Intelligence status on Dictation, which runs its own speech model', async () => {
    mockLocalReadiness.mockResolvedValue({ status: 'modelNotReady', tokenCounting: false });
    mockScope = 'dictation';
    render(<WorkflowSettingsScreen />);

    await act(async () => {});
    expect(
      screen.queryByText('Apple Intelligence is downloading its model.'),
    ).not.toBeOnTheScreen();
  });

  it('says Local Mode cleanup is skipped, shows nothing picked and points at Cloud', async () => {
    mockActiveMode = 'private';
    mockConfig = { defaultMode: 'private', inference: {} };
    mockScope = 'cleanup';
    render(<WorkflowSettingsScreen />);

    expect(
      await screen.findByText(
        "This iPhone can't run On-Device cleanup, so it's skipped. OpenWhispr Cloud can clean up your transcripts.",
      ),
    ).toBeTruthy();
    expect(selectedMode()).toBeUndefined();
    expect(screen.queryByText('Runs on Apple Intelligence on this iPhone.')).not.toBeOnTheScreen();
  });
});