Skip to content

armgit / mimik

Public Imported from GitHub
0

🎬 A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots 📖

feat(settings): save changes as they are made and check the key on demand

Luis Ortizd16b91ecf54a
diff --git a/src/locales/de.yml b/src/locales/de.yml
index 4c3779e..9c86ab5 100644
--- a/src/locales/de.yml
+++ b/src/locales/de.yml
@@ -83,7 +83,6 @@ settings:
targetColorHint: "Klick-Hervorhebungen und Export-Akzente"
branding: "Export-Branding"
brandLogo: "Logo"
- brandLogoHint: "Erscheint auf dem Deckblatt jedes Exports. Transparentes PNG empfohlen."
uploadLogo: "Logo hochladen"
replaceLogo: "Ersetzen"
removeLogo: "Logo entfernen"
@@ -92,7 +91,6 @@ settings:
footerPresetConfidential: "Vertraulich — nur intern"
footerPresetNoDistribute: "Nicht weitergeben"
attribution: '"Made with Mimik" anzeigen'
- attributionHint: "In der Fußzeile jedes Exports"
targetColor: "Markenfarbe"
title: Einstellungen
aiDescriptions: KI-Beschreibungen
@@ -102,10 +100,8 @@ settings:
apiKey: API-Schlüssel
aiLanguage: Sprache der Beschreibungen
voiceNarration: Sprachkommentar
- voiceDescription: Sprich beim Aufnehmen laut mit — deine Worte werden zu den Schrittbeschreibungen.
voiceUsingAiKey: "Es ist kein Sprach-Schlüssel gesetzt, daher nutzt Mimik den OpenAI-Schlüssel aus den KI-Beschreibungen oben."
- voiceNoKey: "Der Sprachkommentar ist aktiv, aber es ist kein API-Schlüssel gesetzt — deine Aufnahmen werden nicht kommentiert."
- voiceDataNotice: Dein aufgenommenes Audio wird mit deinem eigenen API-Schlüssel an den oben gewählten Anbieter gesendet. Das ist der einzige Teil von Mimik, der überhaupt etwas aus deinem Browser sendet.
+ voiceNoKey: "Es ist kein API-Schlüssel gesetzt, daher werden deine Aufnahmen nicht vertont."
microphone: Mikrofon
microphoneDefault: Systemstandard
microphoneNeedsAccess: Erlaube den Mikrofonzugriff, um deine Gerätenamen zu sehen.
@@ -124,7 +120,7 @@ settings:
saveSettings: Einstellungen speichern
saved: Gespeichert
smartBlur: Smart Blur
- privacyNotice: Dein API-Schlüssel wird lokal gespeichert und nur an den ausgewählten KI-Anbieter gesendet. Ansonsten verlassen keine Daten deinen Browser.
+ privacyNotice: "Deine Schlüssel und Audiodaten gehen nur an den Anbieter, den du wählst. Sonst verlässt nichts deinen Browser."
bugReport: "Fehler gefunden? Melde ihn auf GitHub"
starCtaTitle: "Gefällt dir, was du siehst?"
starCtaMessage: Ein Stern auf GitHub hilft anderen, Mimik zu finden, und hält uns motiviert!
@@ -132,6 +128,8 @@ settings:
validatingKey: "Schlüssel wird geprüft…"
keyValid: API-Schlüssel bestätigt.
keyInvalid: Dieser API-Schlüssel wurde abgelehnt. Prüfe ihn und versuche es erneut.
+ checkKey: Schlüssel prüfen
+ keyUnreachable: Der Anbieter war nicht erreichbar. Prüfe deine Verbindung und versuche es erneut.
blurPresets:
email: E-Mail
diff --git a/src/locales/en.yml b/src/locales/en.yml
index 330dd76..30247cf 100644
--- a/src/locales/en.yml
+++ b/src/locales/en.yml
@@ -88,10 +88,8 @@ settings:
apiKey: API Key
aiLanguage: Description Language
voiceNarration: Voice Narration
- voiceDescription: Narrate out loud while you record and your words become the step descriptions.
voiceUsingAiKey: "No voice key is set, so Mimik uses the OpenAI key from AI Descriptions above."
- voiceNoKey: "Voice narration is on but no API key is set, so your recordings will not be narrated."
- voiceDataNotice: Your recorded audio is sent to the provider you choose above, using your own API key. This is the one part of Mimik that sends anything out of your browser.
+ voiceNoKey: "No API key is set, so your recordings will not be narrated."
microphone: Microphone
microphoneDefault: System default
microphoneNeedsAccess: Allow microphone access to see your device names.
@@ -111,7 +109,6 @@ settings:
targetColorHint: "Click highlights and export accents"
branding: "Export Branding"
brandLogo: "Logo"
- brandLogoHint: "Shown on the cover of every export. Transparent PNG recommended."
uploadLogo: "Upload logo"
replaceLogo: "Replace"
removeLogo: "Remove logo"
@@ -120,14 +117,15 @@ settings:
footerPresetConfidential: "Confidential — internal use only"
footerPresetNoDistribute: "Do not distribute"
attribution: 'Show "Made with Mimik"'
- attributionHint: "In the footer of every export"
saveSettings: Save Settings
saved: Saved
validatingKey: "Checking key\u2026"
keyValid: API key verified.
keyInvalid: That API key was rejected. Check it and try again.
+ checkKey: Check key
+ keyUnreachable: Could not reach the provider. Check your connection and try again.
smartBlur: Smart Blur
- privacyNotice: Your API key is stored locally and only sent to the selected AI provider. No data leaves your browser otherwise.
+ privacyNotice: "Your keys and audio go only to the provider you pick. Nothing else leaves your browser."
bugReport: "Found a bug? Report it on GitHub"
starCtaTitle: "Like what you see?"
starCtaMessage: A GitHub star helps others find Mimik and keeps us motivated!
diff --git a/src/locales/es.yml b/src/locales/es.yml
index fa00fad..4e23c0f 100644
--- a/src/locales/es.yml
+++ b/src/locales/es.yml
@@ -88,10 +88,8 @@ settings:
apiKey: Clave API
aiLanguage: Idioma de descripciones
voiceNarration: "Narración por voz"
- voiceDescription: "Narra en voz alta mientras grabas y tus palabras se convierten en las descripciones de los pasos."
voiceUsingAiKey: "No hay clave de voz, así que Mimik usa la clave de OpenAI de Descripciones con IA de arriba."
- voiceNoKey: "La narración por voz está activada pero no hay ninguna clave API, así que tus grabaciones no se narrarán."
- voiceDataNotice: "El audio que grabes se envía al proveedor que elijas arriba, usando tu propia clave API. Es la única parte de Mimik que saca algo de tu navegador."
+ voiceNoKey: "No hay ninguna clave de API configurada, así que tus grabaciones no se narrarán."
microphone: "Micrófono"
microphoneDefault: Predeterminado del sistema
microphoneNeedsAccess: "Permite el acceso al micrófono para ver los nombres de tus dispositivos."
@@ -111,7 +109,6 @@ settings:
targetColorHint: "Resaltados de clic y acentos de exportación"
branding: "Marca en exportaciones"
brandLogo: "Logotipo"
- brandLogoHint: "Aparece en la portada de cada exportación. Se recomienda PNG transparente."
uploadLogo: "Subir logotipo"
replaceLogo: "Reemplazar"
removeLogo: "Quitar logotipo"
@@ -120,14 +117,15 @@ settings:
footerPresetConfidential: "Confidencial — solo uso interno"
footerPresetNoDistribute: "No distribuir"
attribution: 'Mostrar "Made with Mimik"'
- attributionHint: "En el pie de cada exportación"
saveSettings: Guardar ajustes
saved: Guardado
validatingKey: "Comprobando clave\u2026"
keyValid: Clave de API verificada.
keyInvalid: "Esa clave de API fue rechazada. Compru\xE9bala e int\xE9ntalo de nuevo."
+ checkKey: Comprobar clave
+ keyUnreachable: No se pudo conectar con el proveedor. Revisa tu conexión e inténtalo de nuevo.
smartBlur: Desenfoque inteligente
- privacyNotice: Tu clave API se guarda en tu navegador y solo se envía al proveedor de IA que elijas. Nada más sale de aquí.
+ privacyNotice: "Tus claves y tu audio solo van al proveedor que elijas. Nada más sale de tu navegador."
bugReport: "¿Encontraste un bug? Repórtalo en GitHub"
starCtaTitle: "¿Te gusta Mimik?"
starCtaMessage: "Una estrella en GitHub nos ayuda un montón y hace que más gente descubra Mimik."
diff --git a/src/locales/fr.yml b/src/locales/fr.yml
index e3a2a9d..0c2c5ef 100644
--- a/src/locales/fr.yml
+++ b/src/locales/fr.yml
@@ -88,10 +88,8 @@ settings:
apiKey: "Clé API"
aiLanguage: Langue des descriptions
voiceNarration: "Narration vocale"
- voiceDescription: "Commentez à voix haute pendant l'enregistrement : vos mots deviennent les descriptions des étapes."
voiceUsingAiKey: "Aucune clé vocale n'est définie : Mimik utilise la clé OpenAI des descriptions IA ci-dessus."
- voiceNoKey: "La narration vocale est activée mais aucune clé API n'est définie : vos enregistrements ne seront pas narrés."
- voiceDataNotice: "L'audio enregistré est envoyé au fournisseur choisi ci-dessus, avec votre propre clé API. C'est la seule partie de Mimik qui fait sortir quelque chose de votre navigateur."
+ voiceNoKey: "Aucune clé API n'est définie, vos enregistrements ne seront donc pas narrés."
microphone: Microphone
microphoneDefault: "Micro par défaut du système"
microphoneNeedsAccess: "Autorisez l'accès au micro pour voir le nom de vos appareils."
@@ -111,7 +109,6 @@ settings:
targetColorHint: "Surbrillance des clics et accents des exports"
branding: "Image de marque des exports"
brandLogo: "Logo"
- brandLogoHint: "Affiché sur la couverture de chaque export. PNG transparent recommandé."
uploadLogo: "Téléverser un logo"
replaceLogo: "Remplacer"
removeLogo: "Supprimer le logo"
@@ -120,14 +117,15 @@ settings:
footerPresetConfidential: "Confidentiel — usage interne"
footerPresetNoDistribute: "Ne pas diffuser"
attribution: 'Afficher « Made with Mimik »'
- attributionHint: "Dans le pied de chaque export"
saveSettings: "Enregistrer"
saved: "Enregistré"
validatingKey: "V\xE9rification de la cl\xE9\u2026"
keyValid: "Cl\xE9 API v\xE9rifi\xE9e."
keyInvalid: "Cette cl\xE9 API a \xE9t\xE9 refus\xE9e. V\xE9rifiez-la et r\xE9essayez."
+ checkKey: Vérifier la clé
+ keyUnreachable: Le fournisseur est injoignable. Vérifiez votre connexion et réessayez.
smartBlur: Flou intelligent
- privacyNotice: "Votre clé API reste dans votre navigateur et n'est envoyée qu'au fournisseur IA choisi. Rien d'autre ne sort d'ici."
+ privacyNotice: "Vos clés et votre audio ne vont qu'au fournisseur que vous choisissez. Rien d'autre ne quitte votre navigateur."
bugReport: "Un bug ? Signalez-le sur GitHub"
starCtaTitle: "Vous aimez Mimik ?"
starCtaMessage: "Une étoile sur GitHub nous aide beaucoup et permet à d'autres de découvrir Mimik !"
diff --git a/src/locales/pt-BR.yml b/src/locales/pt-BR.yml
index 22b6a1c..da5a678 100644
--- a/src/locales/pt-BR.yml
+++ b/src/locales/pt-BR.yml
@@ -88,10 +88,8 @@ settings:
apiKey: Chave da API
aiLanguage: "Idioma das descrições"
voiceNarration: "Narração por voz"
- voiceDescription: "Narre em voz alta enquanto grava e suas palavras viram as descrições dos passos."
voiceUsingAiKey: "Não tem chave de voz, então o Mimik usa a chave da OpenAI das Descrições com IA lá de cima."
- voiceNoKey: "A narração por voz tá ligada, mas não tem nenhuma chave API, então suas gravações não vão ser narradas."
- voiceDataNotice: "O áudio gravado é enviado pro provedor que você escolher acima, usando sua própria chave API. É a única parte do Mimik que manda algo pra fora do seu navegador."
+ voiceNoKey: "Nenhuma chave de API foi definida, então suas gravações não serão narradas."
microphone: Microfone
microphoneDefault: "Padrão do sistema"
microphoneNeedsAccess: "Libere o acesso ao microfone pra ver o nome dos seus dispositivos."
@@ -111,7 +109,6 @@ settings:
targetColorHint: "Destaques de clique e acentos da exportação"
branding: "Marca nas exportações"
brandLogo: "Logotipo"
- brandLogoHint: "Aparece na capa de cada exportação. PNG transparente recomendado."
uploadLogo: "Enviar logotipo"
replaceLogo: "Substituir"
removeLogo: "Remover logotipo"
@@ -120,14 +117,15 @@ settings:
footerPresetConfidential: "Confidencial — uso interno"
footerPresetNoDistribute: "Não distribuir"
attribution: 'Mostrar "Made with Mimik"'
- attributionHint: "No rodapé de cada exportação"
saveSettings: Salvar ajustes
saved: Salvo
validatingKey: "Verificando chave\u2026"
keyValid: Chave de API verificada.
keyInvalid: Essa chave de API foi recusada. Verifique-a e tente novamente.
+ checkKey: Verificar chave
+ keyUnreachable: Não deu pra falar com o provedor. Confere sua conexão e tenta de novo.
smartBlur: Desfoque inteligente
- privacyNotice: Sua chave API fica salva no navegador e só é enviada pro provedor de IA que você escolher. Nada mais sai daqui.
+ privacyNotice: "Suas chaves e seu áudio vão só pro provedor que você escolher. Nada mais sai do seu navegador."
bugReport: "Achou um bug? Reporta no GitHub"
starCtaTitle: "Curtiu o Mimik?"
starCtaMessage: Uma estrela no GitHub ajuda outras pessoas a descobrir o Mimik e nos dá aquela motivação!
diff --git a/src/ui/shared/SettingsView.tsx b/src/ui/shared/SettingsView.tsx
index b0df40a..9dc303e 100644
--- a/src/ui/shared/SettingsView.tsx
+++ b/src/ui/shared/SettingsView.tsx
@@ -15,16 +15,17 @@ import {
Trash2,
TriangleAlert,
} from 'lucide-react';
-import { useEffect, useRef, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
import { i18n } from '#imports';
import { PRESET_LABELS, type PresetKey } from '@/core/blur/regexes';
-import { AI_PROVIDERS, type AIProviderKey } from '@/core/capture/ai/models';
+import { AI_PROVIDERS, type AIProviderKey, CUSTOM_MODEL_VALUE, isCustomModel } from '@/core/capture/ai/models';
import { AI_LANGUAGES, type AILanguageCode } from '@/core/capture/ai/prompts';
import { resolveVoiceApiKey } from '@/core/capture/voice/api-key';
import type { VoiceProvider } from '@/core/capture/voice/transcribe';
import { type BrandLogo, defaultFooterLine, makeBrandLogo } from '@/core/export/branding';
import { DEFAULT_TARGET_COLOR, TARGET_COLORS } from '@/core/screenshot/types';
import { localStorage } from '@/lib/browser-api';
+import { logger } from '@/lib/logger';
import { sendMessage } from '@/lib/messaging';
import { Button } from '@/ui/components/ui/button';
import { Input } from '@/ui/components/ui/input';
@@ -32,11 +33,15 @@ import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popo
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/ui/components/ui/select';
import ColorPicker from '@/ui/shared/ColorPicker';
import MicrophonePicker from '@/ui/shared/MicrophonePicker';
+import { changedSettings, type SettingsSnapshot } from '@/ui/shared/settings-autosave';
interface SettingsViewProps {
onBack?: () => void;
}
+const SAVE_DEBOUNCE_MS = 400;
+const SAVED_BADGE_MS = 1600;
+
const FOOTER_PRESETS = () => [
defaultFooterLine(),
i18n.t('settings.footerPresetConfidential'),
@@ -48,9 +53,14 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
const [model, setModel] = useState(AI_PROVIDERS.openai.defaultModel);
const [apiKey, setApiKey] = useState('');
const [saved, setSaved] = useState(false);
- const [keyStatus, setKeyStatus] = useState<'checking' | 'valid' | 'rejected' | null>(null);
+ const [keyStatus, setKeyStatus] = useState<'checking' | 'valid' | 'rejected' | 'unreachable' | null>(null);
+ const [customModel, setCustomModel] = useState(false);
+ const [loaded, setLoaded] = useState(false);
+ const validatedKey = useRef('');
+ const savedSnapshot = useRef<SettingsSnapshot | null>(null);
+ const pending = useRef<SettingsSnapshot>({});
+ const saveTimer = useRef<number | undefined>(undefined);
const [aiLanguage, setAiLanguage] = useState<AILanguageCode>('en');
- const [voiceEnabled, setVoiceEnabled] = useState(false);
const [voiceProvider, setVoiceProvider] = useState<VoiceProvider>('openai');
const [voiceApiKey, setVoiceApiKey] = useState('');
const [voiceMicrophoneId, setVoiceMicrophoneId] = useState('');
@@ -76,7 +86,6 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
'aiModel',
'aiLanguage',
'blurPresets',
- 'voiceEnabled',
'voiceProvider',
'voiceApiKey',
'voiceMicrophoneId',
@@ -92,7 +101,6 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
if (result.aiApiKey) setApiKey(result.aiApiKey as string);
if (result.aiLanguage) setAiLanguage(result.aiLanguage as AILanguageCode);
if (result.blurPresets) setBlurPresets(result.blurPresets as Record<PresetKey, boolean>);
- setVoiceEnabled(result.voiceEnabled === true);
setVoiceProvider((result.voiceProvider as VoiceProvider) || 'openai');
if (result.voiceApiKey) setVoiceApiKey(result.voiceApiKey as string);
if (result.voiceMicrophoneId) setVoiceMicrophoneId(result.voiceMicrophoneId as string);
@@ -100,9 +108,69 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
if (result.brandLogo) setBrandLogo(result.brandLogo as BrandLogo);
setBrandFooter(typeof result.brandFooter === 'string' ? result.brandFooter : defaultFooterLine());
if (result.brandAttribution === false) setBrandAttribution(false);
+ setLoaded(true);
});
}, []);
+ const stored = {
+ aiApiKey: apiKey,
+ aiProvider: provider,
+ aiModel: model,
+ aiLanguage,
+ blurPresets,
+ voiceProvider,
+ voiceApiKey,
+ voiceMicrophoneId,
+ targetColor,
+ brandLogo,
+ brandFooter,
+ brandAttribution,
+ };
+
+ const flush = useCallback(async () => {
+ const patch = pending.current;
+ pending.current = {};
+ if (Object.keys(patch).length === 0) return;
+ try {
+ await localStorage.set(patch);
+ setSaved(true);
+ } catch (err) {
+ logger.error('Settings autosave failed', err);
+ setSaved(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ if (!loaded) return;
+ const snapshot = savedSnapshot.current;
+ if (!snapshot) {
+ savedSnapshot.current = stored;
+ return;
+ }
+
+ const patch = changedSettings(stored, snapshot);
+ if (!patch) return;
+
+ savedSnapshot.current = stored;
+ Object.assign(pending.current, patch);
+ window.clearTimeout(saveTimer.current);
+ saveTimer.current = window.setTimeout(() => void flush(), SAVE_DEBOUNCE_MS);
+ });
+
+ useEffect(
+ () => () => {
+ window.clearTimeout(saveTimer.current);
+ void flush();
+ },
+ [flush],
+ );
+
+ useEffect(() => {
+ if (!saved) return;
+ const timer = window.setTimeout(() => setSaved(false), SAVED_BADGE_MS);
+ return () => window.clearTimeout(timer);
+ }, [saved]);
+
const handleLogoPick = async (file: File | undefined) => {
if (!file) return;
setBrandLogo(await makeBrandLogo(file));
@@ -110,42 +178,34 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
const handleProviderChange = (newProvider: AIProviderKey) => {
setProvider(newProvider);
+ setCustomModel(false);
setModel(AI_PROVIDERS[newProvider].defaultModel);
};
- const handleSave = async () => {
- if (apiKey) {
- setKeyStatus('checking');
- const result = await sendMessage('validateApiKey', { provider, apiKey }).catch(() => null);
- if (result && !result.valid && result.reason === 'rejected') {
- setKeyStatus('rejected');
- return;
- }
- setKeyStatus(result?.valid ? 'valid' : null);
- } else {
- setKeyStatus(null);
+ const handleModelChange = (value: string) => {
+ if (value === CUSTOM_MODEL_VALUE) {
+ setCustomModel(true);
+ setModel('');
+ return;
}
+ setCustomModel(false);
+ setModel(value);
+ };
- await localStorage.set({
- aiApiKey: apiKey,
- aiProvider: provider,
- aiModel: model,
- aiLanguage,
- blurPresets,
- voiceEnabled,
- voiceProvider,
- voiceApiKey,
- voiceMicrophoneId,
- targetColor,
- brandLogo,
- brandFooter,
- brandAttribution,
- });
- setSaved(true);
- setTimeout(() => setSaved(false), 2000);
+ const handleCheckKey = async () => {
+ const fingerprint = `${provider}:${apiKey}`;
+ if (validatedKey.current === fingerprint) {
+ setKeyStatus('valid');
+ return;
+ }
+ setKeyStatus('checking');
+ const result = await sendMessage('validateApiKey', { provider, apiKey }).catch(() => null);
+ if (result?.valid) validatedKey.current = fingerprint;
+ setKeyStatus(result?.valid ? 'valid' : result?.reason === 'rejected' ? 'rejected' : 'unreachable');
};
const providerConfig = AI_PROVIDERS[provider];
+ const usingCustomModel = customModel || isCustomModel(model, providerConfig);
const voiceKey = resolveVoiceApiKey({ voiceProvider, voiceApiKey, aiProvider: provider, aiApiKey: apiKey });
const BLUR_PRESET_I18N: Record<PresetKey, string> = {
@@ -169,6 +229,16 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
</button>
)}
<h1 className="text-[15px] font-bold text-foreground">{i18n.t('settings.title')}</h1>
+ <span
+ aria-live="polite"
+ className={`ml-auto flex items-center gap-1 text-[11px] font-semibold transition-opacity duration-300 ${
+ saved ? 'opacity-100' : 'opacity-0'
+ }`}
+ style={{ color: 'var(--color-success)' }}
+ >
+ <Check size={12} />
+ {i18n.t('settings.saved')}
+ </span>
</div>
<div className="flex-1 px-3 py-4 space-y-3">
@@ -200,7 +270,7 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
<div>
<label className="block text-[11px] font-semibold text-foreground mb-1">{i18n.t('settings.model')}</label>
- <Select value={model} onValueChange={(v) => setModel(v)}>
+ <Select value={usingCustomModel ? CUSTOM_MODEL_VALUE : model} onValueChange={handleModelChange}>
<SelectTrigger className="w-full rounded-lg px-3 py-2 text-[13px]">
<SelectValue />
</SelectTrigger>
@@ -210,19 +280,43 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
{m.label}
</SelectItem>
))}
+ <SelectItem value={CUSTOM_MODEL_VALUE}>{i18n.t('settings.modelCustom')}</SelectItem>
</SelectContent>
</Select>
+ {usingCustomModel && (
+ <Input
+ value={model}
+ onChange={(e) => setModel(e.target.value)}
+ placeholder={providerConfig.defaultModel}
+ aria-label={i18n.t('settings.modelCustom')}
+ className="mt-1.5 h-8 text-[12px] rounded-lg border-border"
+ />
+ )}
</div>
<div>
<label className="block text-[11px] font-semibold text-foreground mb-1">{i18n.t('settings.apiKey')}</label>
- <Input
- type="password"
- value={apiKey}
- onChange={(e) => setApiKey(e.target.value)}
- placeholder="sk-..."
- className="h-8 text-[12px] rounded-lg border-border"
- />
+ <div className="flex items-center gap-1.5">
+ <Input
+ type="password"
+ value={apiKey}
+ onChange={(e) => {
+ setApiKey(e.target.value);
+ setKeyStatus(null);
+ }}
+ placeholder="sk-..."
+ className="h-8 text-[12px] rounded-lg border-border"
+ />
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={!apiKey || keyStatus === 'checking'}
+ onClick={() => void handleCheckKey()}
+ className="h-8 shrink-0 rounded-lg bg-card text-[11px] font-semibold"
+ >
+ {i18n.t('settings.checkKey')}
+ </Button>
+ </div>
{keyStatus === 'checking' && (
<p className="mt-1 text-[11px] text-muted-foreground">{i18n.t('settings.validatingKey')}</p>
)}
@@ -235,6 +329,9 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
{keyStatus === 'rejected' && (
<p className="mt-1 text-[11px] text-destructive">{i18n.t('settings.keyInvalid')}</p>
)}
+ {keyStatus === 'unreachable' && (
+ <p className="mt-1 text-[11px] text-muted-foreground">{i18n.t('settings.keyUnreachable')}</p>
+ )}
</div>
<div>
@@ -299,7 +396,6 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
<label className="block text-[11px] font-semibold text-foreground mb-1">
{i18n.t('settings.brandLogo')}
</label>
- <p className="text-[10px] text-muted-foreground mb-2">{i18n.t('settings.brandLogoHint')}</p>
<input
ref={logoInputRef}
type="file"
@@ -363,10 +459,7 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
</div>
<div className="flex items-center justify-between gap-3 pt-1">
- <div>
- <div className="text-[11px] font-semibold text-foreground">{i18n.t('settings.attribution')}</div>
- <div className="text-[10px] text-muted-foreground">{i18n.t('settings.attributionHint')}</div>
- </div>
+ <div className="text-[11px] font-semibold text-foreground">{i18n.t('settings.attribution')}</div>
<button
onClick={() => setBrandAttribution((prev) => !prev)}
className={`w-9 h-5 rounded-full transition-colors relative shrink-0 ${
@@ -383,29 +476,13 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
</div>
<div className="border border-border rounded-[10px] p-3.5 space-y-3">
- <div className="flex items-center justify-between gap-2.5">
- <div className="flex items-center gap-2.5">
- <div className="w-7 h-7 rounded-lg bg-secondary flex items-center justify-center">
- <Mic size={14} className="text-accent" />
- </div>
- <span className="text-xs font-bold text-foreground">{i18n.t('settings.voiceNarration')}</span>
+ <div className="flex items-center gap-2.5">
+ <div className="w-7 h-7 rounded-lg bg-secondary flex items-center justify-center">
+ <Mic size={14} className="text-accent" />
</div>
- <button
- onClick={() => setVoiceEnabled((prev) => !prev)}
- className={`w-9 h-5 rounded-full transition-colors relative shrink-0 ${
- voiceEnabled ? 'bg-accent' : 'bg-border'
- }`}
- >
- <span
- className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white shadow-sm transition-transform ${
- voiceEnabled ? 'translate-x-4' : 'translate-x-0'
- }`}
- />
- </button>
+ <span className="text-xs font-bold text-foreground">{i18n.t('settings.voiceNarration')}</span>
</div>
- <p className="text-[10px] text-muted-foreground leading-relaxed">{i18n.t('settings.voiceDescription')}</p>
-
<div>
<label className="block text-[11px] font-semibold text-foreground mb-1">
{i18n.t('settings.provider')}
@@ -434,7 +511,7 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
<span>{i18n.t('settings.voiceUsingAiKey')}</span>
</p>
)}
- {voiceEnabled && voiceKey.source === 'none' && (
+ {voiceKey.source === 'none' && (
<p className="mt-1.5 flex items-start gap-1.5 text-[10px] text-destructive leading-relaxed" role="alert">
<TriangleAlert size={11} className="shrink-0 mt-0.5" />
<span>{i18n.t('settings.voiceNoKey')}</span>
@@ -445,11 +522,6 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
{import.meta.env.BROWSER !== 'firefox' && (
<MicrophonePicker value={voiceMicrophoneId} onChange={setVoiceMicrophoneId} />
)}
-
- <div className="flex items-start gap-2 px-3 py-2.5 rounded-lg bg-secondary text-[10px] text-muted-foreground leading-relaxed">
- <Shield size={12} className="shrink-0 mt-0.5 text-accent" />
- <span>{i18n.t('settings.voiceDataNotice')}</span>
- </div>
</div>
<div className="border border-border rounded-[10px] p-3.5 space-y-1">
@@ -488,20 +560,6 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
))}
</div>
- <Button
- onClick={handleSave}
- disabled={saved || keyStatus === 'checking'}
- className="w-full transition-all duration-300"
- style={saved ? { backgroundColor: 'var(--color-success)', color: '#fff', opacity: 0.9 } : undefined}
- >
- {saved && <Check size={16} />}
- {saved
- ? i18n.t('settings.saved')
- : keyStatus === 'checking'
- ? i18n.t('settings.validatingKey')
- : i18n.t('settings.saveSettings')}
- </Button>
-
<div className="flex items-start gap-2 px-3 py-2.5 rounded-lg bg-secondary text-[10px] text-muted-foreground leading-relaxed">
<Shield size={12} className="shrink-0 mt-0.5 text-accent" />
<span>{i18n.t('settings.privacyNotice')}</span>
diff --git a/src/ui/shared/__tests__/settings-autosave.test.ts b/src/ui/shared/__tests__/settings-autosave.test.ts
new file mode 100644
index 0000000..d91a8c5
--- /dev/null
+++ b/src/ui/shared/__tests__/settings-autosave.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest';
+import { changedSettings } from '../settings-autosave';
+
+describe('changedSettings', () => {
+ it('writes nothing when a render changed no value', () => {
+ const snapshot = { targetColor: '#4F46E5', voiceEnabled: true };
+ expect(changedSettings({ ...snapshot }, snapshot)).toBeNull();
+ });
+
+ it('writes only the field the user touched', () => {
+ const previous = { targetColor: '#4F46E5', voiceEnabled: true, aiModel: 'gpt-4o-mini' };
+ const next = { ...previous, targetColor: '#059669' };
+ expect(changedSettings(next, previous)).toEqual({ targetColor: '#059669' });
+ });
+
+ it('never rewrites a value another surface owns', () => {
+ const previous = { targetColor: '#4F46E5', voiceEnabled: false };
+ const next = { targetColor: '#059669', voiceEnabled: false };
+ expect(changedSettings(next, previous)).not.toHaveProperty('voiceEnabled');
+ });
+
+ it('compares objects by value, not by identity', () => {
+ const previous = { blurPresets: { email: true, ssn: false } };
+ const next = { blurPresets: { email: true, ssn: false } };
+ expect(changedSettings(next, previous)).toBeNull();
+ });
+
+ it('catches a nested toggle inside an object setting', () => {
+ const previous = { blurPresets: { email: true, ssn: false } };
+ const next = { blurPresets: { email: true, ssn: true } };
+ expect(changedSettings(next, previous)).toEqual({ blurPresets: { email: true, ssn: true } });
+ });
+
+ it('treats clearing a field as a change worth writing', () => {
+ expect(changedSettings({ aiApiKey: '' }, { aiApiKey: 'sk-old' })).toEqual({ aiApiKey: '' });
+ });
+
+ it('treats false as a value, not as absent', () => {
+ expect(changedSettings({ brandAttribution: false }, { brandAttribution: true })).toEqual({
+ brandAttribution: false,
+ });
+ });
+
+ it('collects several fields changed in one render', () => {
+ const previous = { a: 1, b: 2, c: 3 };
+ expect(changedSettings({ a: 9, b: 2, c: 8 }, previous)).toEqual({ a: 9, c: 8 });
+ });
+});
diff --git a/src/ui/shared/settings-autosave.ts b/src/ui/shared/settings-autosave.ts
new file mode 100644
index 0000000..40d8654
--- /dev/null
+++ b/src/ui/shared/settings-autosave.ts
@@ -0,0 +1,11 @@
+export type SettingsSnapshot = Record<string, unknown>;
+
+export function changedSettings(next: SettingsSnapshot, previous: SettingsSnapshot): SettingsSnapshot | null {
+ const patch: SettingsSnapshot = {};
+ for (const [key, value] of Object.entries(next)) {
+ if (Object.is(value, previous[key])) continue;
+ if (JSON.stringify(value) === JSON.stringify(previous[key])) continue;
+ patch[key] = value;
+ }
+ return Object.keys(patch).length > 0 ? patch : null;
+}