π¬ A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots π
TypeScript browser-extensionchrome-extensiondocumentationfirefox-extensionguide-generatorlocal-firstmanifest-v3privacy-firstproductivityreactscreenshotstep-by-step-guidetutorialtypescriptworkflowwxt
refactor: share the extension's AI settings card with the desktop
Luis Ortiz919bf9cc4020
diff --git a/AGENTS.md b/AGENTS.mdindex e988d37..c654efc 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -779,11 +779,25 @@ identical on both surfaces, so `AiSettings` lives in `packages/ui` and each app`validate` function β the desktop passes core's `validateApiKey` directly, and the extension goesthrough its background messaging, which is the only part that differs.-`SettingsView`, the extension's own 699-line settings screen, was deliberately **not** moved. It-carries voice narration, smart blur, brand logos and a microphone picker, none of which mean-anything on desktop, and it reaches for `@/lib/browser-api`. Moving it would have dragged all of-that across for the sake of four fields; extracting the four was less code and leaves the extension-untouched.+`AiSettings` is the extension's own AI card, lifted out of `SettingsView` rather than rewritten. A+parallel implementation was tried first and the wording immediately drifted β the extension said+"API key verified", the copy said "134 models available", and the spend warning was missing+altogether, because the extension shows the verdict, the model list and the warning as three+separate things and the copy collapsed them into one line. Two implementations of the same screen+diverge by default; one does not.++What moved with it: `KeyStatusNote`, `KeyWarningNote`, `ModelList`, `SecretInput` and `useKeyCheck`,+all now in `key-status.tsx`. The hook takes its validator as an argument, which is the only part+that genuinely differs β the extension goes through background messaging because a service worker is+what has `host_permissions`, and the desktop calls `validateApiKey` directly on top of the main+process fetch.++The rest of `SettingsView` stayed put. Voice narration, smart blur, brand logos and the microphone+picker have no desktop meaning, and it reaches for `@/lib/browser-api`. Splitting it did mean the+autosave had to change shape: the AI fields left the parent's snapshot, so `AiSettings` reports its+own changes through `onChange` and both halves queue into the same debounced flush. `SettingsView`+still keeps the provider and key in state for one reason β `resolveVoiceApiKey` falls back to the AI+key when no voice key is set β and it updates them from the patches the card sends up.The shortcut recorder reads a keystroke and writes an Electron accelerator. It refuses a bare key,because a global accelerator with no modifier takes that key from every application on the machine,diff --git a/apps/desktop/src/renderer/SettingsPanel.tsx b/apps/desktop/src/renderer/SettingsPanel.tsxindex a88ea54..cd3f0ad 100644--- a/apps/desktop/src/renderer/SettingsPanel.tsx+++ b/apps/desktop/src/renderer/SettingsPanel.tsx@@ -1,6 +1,7 @@import { validateApiKey } from '@mimik/core/capture/ai/validate';-import { i18n } from '@mimik/core/env';+import { i18n, localStorage } from '@mimik/core/env';import AiSettings from '@mimik/ui/shared/AiSettings';+import { useKeyCheck } from '@mimik/ui/shared/key-status';import { useEffect, useState } from 'react';import type { CaptureSettings, CaptureShortcuts } from '../main/capture/settings';import ShortcutRecorder from './ShortcutRecorder';@@ -51,6 +52,7 @@ function Toggle({export default function SettingsPanel({ onClose }: { onClose(): void }) {const [section, setSection] = useState<Section>('capture');+ const keyCheck = useKeyCheck(validateApiKey);const [settings, setSettings] = useState<CaptureSettings | null>(null);useEffect(() => {@@ -92,7 +94,9 @@ export default function SettingsPanel({ onClose }: { onClose(): void }) {<div className="min-w-0 flex-1 overflow-y-auto px-10 py-8"><div className="mx-auto flex max-w-[640px] flex-col gap-5">- {section === 'ai' && <AiSettings validate={validateApiKey} />}+ {section === 'ai' && (+ <AiSettings keyCheck={keyCheck} onChange={(patch) => void localStorage.set(patch as never)} />+ )}{section === 'capture' && settings && (<>diff --git a/packages/ui/src/shared/AiSettings.tsx b/packages/ui/src/shared/AiSettings.tsxindex 2737864..9b24b8e 100644--- a/packages/ui/src/shared/AiSettings.tsx+++ b/packages/ui/src/shared/AiSettings.tsx@@ -1,187 +1,276 @@-import { keyFor, migrateApiKeys, withKeyFor } from '@mimik/core/capture/ai/keys';-import { AI_PROVIDERS, type AIProviderKey, CUSTOM_MODEL_VALUE, DEFAULT_AI_PROVIDER } from '@mimik/core/capture/ai/models';-import { AI_LANGUAGES } from '@mimik/core/capture/ai/prompts';-import type { KeyValidation } from '@mimik/core/capture/ai/validate';+import { AI_LANGUAGES, type AILanguageCode } from '@mimik/core/capture/ai/prompts';+import { type AIApiKeys, keyFor, migrateApiKeys, withKeyFor } from '@mimik/core/capture/ai/keys';+import {+ AI_PROVIDERS,+ type AIProviderKey,+ CUSTOM_MODEL_VALUE,+ DEFAULT_AI_PROVIDER,+ isCustomBaseUrl,+ isCustomModel,+ providerOrDefault,+} from '@mimik/core/capture/ai/models';import { i18n, localStorage } from '@mimik/core/env';-import type { AIApiKeys } from '@mimik/core/capture/ai/keys';+import { Button } from '@mimik/ui/components/ui/button';import { Input } from '@mimik/ui/components/ui/input';-import { Check, Eye, EyeOff, Loader2, TriangleAlert } from 'lucide-react';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@mimik/ui/components/ui/select';+import {+ type KeyStatus,+ KeyStatusNote,+ KeyWarningNote,+ type KeyWarning,+ ModelList,+ SecretInput,+} from '@mimik/ui/shared/key-status';+import { Globe, Sparkles, TriangleAlert } from 'lucide-react';import { useEffect, useState } from 'react';-export type ValidateKey = (provider: string, apiKey: string, baseUrl?: string, model?: string) => Promise<KeyValidation>;+export interface KeyCheck {+ status: KeyStatus;+ models: string[] | null;+ warning: KeyWarning | null;+ check(provider: string, apiKey: string, baseUrl?: string, model?: string): Promise<void>;+ reset(): void;+}interface AiSettingsProps {- validate: ValidateKey;+ keyCheck: KeyCheck;+ onChange(patch: Record<string, unknown>): void;}-const FIELD =- 'w-full h-10 rounded-[10px] border border-border bg-card px-3 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-accent/30';--export default function AiSettings({ validate }: AiSettingsProps) {+export default function AiSettings({ keyCheck: aiKeyCheck, onChange }: AiSettingsProps) {const [provider, setProvider] = useState<AIProviderKey>(DEFAULT_AI_PROVIDER);- const [keys, setKeys] = useState<AIApiKeys>({});- const [model, setModel] = useState('');+ const [model, setModel] = useState(AI_PROVIDERS[DEFAULT_AI_PROVIDER].defaultModel);+ const [apiKey, setApiKey] = useState('');+ const [apiKeys, setApiKeys] = useState<AIApiKeys>({});const [baseUrl, setBaseUrl] = useState('');- const [language, setLanguage] = useState('en');- const [reveal, setReveal] = useState(false);- const [result, setResult] = useState<KeyValidation | null>(null);- const [checking, setChecking] = useState(false);+ const [customModel, setCustomModel] = useState(false);+ const [ownServer, setOwnServer] = useState(false);+ const [aiLanguage, setAiLanguage] = useState<AILanguageCode>('en');useEffect(() => {- localStorage.get(['aiProvider', 'aiApiKeys', 'aiModel', 'aiBaseUrl', 'aiLanguage']).then((stored) => {- const next = (stored.aiProvider as AIProviderKey) || DEFAULT_AI_PROVIDER;- setProvider(next);- setKeys(migrateApiKeys(stored));- setModel((stored.aiModel as string) || AI_PROVIDERS[next].defaultModel);- setBaseUrl((stored.aiBaseUrl as string) || '');- setLanguage((stored.aiLanguage as string) || 'en');+ localStorage.get(['aiApiKey', 'aiApiKeys', 'aiProvider', 'aiModel', 'aiBaseUrl', 'aiLanguage']).then((result) => {+ const p = providerOrDefault(result.aiProvider);+ const keys = migrateApiKeys(result);+ setProvider(p);+ setApiKeys(keys);+ setApiKey(keyFor(keys, p));+ setModel((result.aiModel as string) || AI_PROVIDERS[p].defaultModel);+ if (isCustomBaseUrl(AI_PROVIDERS[p], result.aiBaseUrl as string)) {+ setBaseUrl(result.aiBaseUrl as string);+ setOwnServer(true);+ }+ if (result.aiLanguage) setAiLanguage(result.aiLanguage as AILanguageCode);});}, []);- const apiKey = keyFor(keys, provider);- const config = AI_PROVIDERS[provider];-- const save = (patch: Record<string, unknown>) => {- void localStorage.set(patch as never);+ const handleProviderChange = (newProvider: AIProviderKey) => {+ setProvider(newProvider);+ setApiKey(keyFor(apiKeys, newProvider));+ aiKeyCheck.reset();+ setCustomModel(false);+ setModel(AI_PROVIDERS[newProvider].defaultModel);+ setOwnServer(false);+ setBaseUrl('');+ onChange({ aiProvider: newProvider, aiModel: AI_PROVIDERS[newProvider].defaultModel, aiBaseUrl: '' });};- const onProvider = (next: AIProviderKey) => {- setProvider(next);- setModel(AI_PROVIDERS[next].defaultModel);- setResult(null);- save({ aiProvider: next, aiModel: AI_PROVIDERS[next].defaultModel });+ const handleOwnServerToggle = () => {+ setOwnServer((on) => {+ if (on) {+ setBaseUrl('');+ onChange({ aiBaseUrl: '' });+ }+ return !on;+ });+ aiKeyCheck.reset();};- const onKey = (value: string) => {- const next = withKeyFor(keys, provider, value);- setKeys(next);- setResult(null);- save({ aiApiKeys: next });+ const handleModelChange = (value: string) => {+ if (value === CUSTOM_MODEL_VALUE) {+ setCustomModel(true);+ setModel('');+ aiKeyCheck.reset();+ return;+ }+ setCustomModel(false);+ setModel(value);+ aiKeyCheck.reset();+ onChange({ aiModel: value });};- const check = async () => {- setChecking(true);- setResult(await validate(provider, apiKey, baseUrl || undefined, model).catch(() => null));- setChecking(false);- };+ const providerConfig = AI_PROVIDERS[provider] ?? AI_PROVIDERS[DEFAULT_AI_PROVIDER];+ const usingCustomModel = customModel || isCustomModel(model, providerConfig);return (- <div className="flex flex-col gap-5">- <div className="grid grid-cols-2 gap-3.5">- <label className="flex flex-col gap-1.5">- <span className="text-[13px] font-medium">{i18n.t('settings_provider')}</span>- <select className={FIELD} value={provider} onChange={(e) => onProvider(e.target.value as AIProviderKey)}>- {Object.entries(AI_PROVIDERS).map(([id, p]) => (- <option key={id} value={id}>- {p.label}- </option>- ))}- </select>- </label>-- <label className="flex flex-col gap-1.5">- <span className="text-[13px] font-medium">{i18n.t('settings_model')}</span>- <select- className={FIELD}- value={model}- onChange={(e) => {- setModel(e.target.value);- save({ aiModel: e.target.value });- }}- >- {config.models.map((m) => (- <option key={m.id} value={m.id}>- {m.id === CUSTOM_MODEL_VALUE ? i18n.t('settings_modelCustom') : m.label}- </option>- ))}- </select>- </label>+ <div className="border border-border rounded-[10px] p-3.5 space-y-3">+ <div className="flex items-center gap-2.5">+ <div className="w-7 h-7 rounded-lg bg-secondary flex items-center justify-center">+ <Sparkles size={14} className="text-accent" /></div>+ <span className="text-xs font-bold text-foreground">{i18n.t('settings.aiDescriptions')}</span>+ </div>- <div className="flex flex-col gap-1.5">- <span className="text-[13px] font-medium">{i18n.t('settings_apiKey')}</span>- <div className="flex gap-2">- <div className="relative flex-1">- <Input- type={reveal ? 'text' : 'password'}- value={apiKey}- onChange={(e) => onKey(e.target.value)}- className="h-10 pr-10"- />- <button- type="button"- aria-label={i18n.t(reveal ? 'settings_hideKey' : 'settings_showKey')}- onClick={() => setReveal(!reveal)}- className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-accent"- >- {reveal ? <EyeOff size={15} /> : <Eye size={15} />}- </button>- </div>- <button- type="button"- onClick={() => void check()}- disabled={!apiKey || checking}- className="h-10 rounded-[10px] bg-primary px-4 text-sm font-semibold text-primary-foreground disabled:opacity-40"- >- {checking ? <Loader2 size={15} className="animate-spin" /> : i18n.t('settings_checkKey')}- </button>- </div>- {result && <KeyResult result={result} />}- {!apiKey && <p className="text-xs text-muted-foreground">{i18n.t('settings_aiNoKey')}</p>}- </div>+ <div>+ <label className="block text-[11px] font-semibold text-foreground mb-1">+ {i18n.t('settings.provider')}+ </label>+ <Select value={provider} onValueChange={(v) => handleProviderChange(v as AIProviderKey)}>+ <SelectTrigger className="h-8">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {Object.entries(AI_PROVIDERS).map(([key, cfg]) => (+ <SelectItem key={key} value={key}>+ {cfg.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>- <div className="grid grid-cols-2 gap-3.5">- <label className="flex flex-col gap-1.5">- <span className="text-[13px] font-medium">{i18n.t('settings_aiLanguage')}</span>- <select- className={FIELD}- value={language}- onChange={(e) => {- setLanguage(e.target.value);- save({ aiLanguage: e.target.value });- }}- >- {AI_LANGUAGES.map((l) => (- <option key={l.code} value={l.code}>- {l.label}- </option>- ))}- </select>- </label>+ <div>+ <label className="block text-[11px] font-semibold text-foreground mb-1">{i18n.t('settings.model')}</label>+ <Select value={usingCustomModel ? CUSTOM_MODEL_VALUE : model} onValueChange={handleModelChange}>+ <SelectTrigger className="h-8">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {providerConfig.models.map((m) => (+ <SelectItem key={m.id} value={m.id}>+ {m.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {usingCustomModel && (+ <Input+ value={model}+ onChange={(e) => {+ setModel(e.target.value);+ onChange({ aiModel: e.target.value });+ aiKeyCheck.reset();+ }}+ placeholder={providerConfig.defaultModel}+ aria-label={i18n.t('settings.modelCustom')}+ className="mt-1.5 h-8 text-[13px] rounded-lg border-border"+ />+ )}+ </div>- <label className="flex flex-col gap-1.5">- <span className="text-[13px] font-medium">{i18n.t('settings_baseUrl')}</span>+ <div>+ <label className="block text-[11px] font-semibold text-foreground mb-1">{i18n.t('settings.apiKey')}</label>+ <div className="flex items-center gap-1.5">+ <SecretInput+ value={apiKey}+ onChange={(next) => {+ setApiKey(next);+ setApiKeys((prev) => {+ const keys = withKeyFor(prev, provider, next);+ onChange({ aiApiKeys: keys, aiApiKey: next });+ return keys;+ });+ aiKeyCheck.reset();+ }}+ placeholder="sk-..."+ className="h-8 text-[13px] rounded-lg border-border"+ />+ <Button+ variant="outline"+ size="sm"+ disabled={!apiKey || aiKeyCheck.status === 'checking'}+ onClick={() => {+ if (aiKeyCheck.status !== 'checking') void aiKeyCheck.check(provider, apiKey, baseUrl, model);+ }}+ className="h-8 shrink-0 rounded-lg bg-card text-[11px] font-semibold"+ >+ {i18n.t('settings.checkKey')}+ </Button>+ </div>+ <KeyStatusNote status={aiKeyCheck.status} />+ <KeyWarningNote warning={aiKeyCheck.warning} />+ {aiKeyCheck.models && <ModelList models={aiKeyCheck.models} />}+ {!apiKey.trim() && (+ <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.aiNoKey')}</span>+ </p>+ )}+ </div>++ <div>+ <div className="flex items-center justify-between gap-3 py-0.5">+ <span className="text-[11px] font-semibold text-foreground flex items-center gap-1">+ <Globe size={11} className="-mt-px" />+ {i18n.t('settings.useOwnServer')}+ </span>+ <button+ type="button"+ role="switch"+ aria-checked={ownServer}+ aria-label={i18n.t('settings.useOwnServer')}+ onClick={handleOwnServerToggle}+ className={`w-9 h-5 rounded-full transition-colors relative shrink-0 ${+ ownServer ? '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 ${+ ownServer ? 'translate-x-4' : 'translate-x-0'+ }`}+ />+ </button>+ </div>+ {ownServer && (+ <div className="mt-2 space-y-1.5"><Input+ type="text"value={baseUrl}- placeholder={config.defaultBaseUrl}onChange={(e) => {setBaseUrl(e.target.value);- save({ aiBaseUrl: e.target.value });+ aiKeyCheck.reset();}}- className="h-10"+ placeholder={providerConfig.defaultBaseUrl}+ aria-label={i18n.t('settings.baseUrl')}+ className="h-8 text-[13px] rounded-lg border-border"/>- </label>- </div>+ <p className="text-[10px] text-muted-foreground leading-relaxed">+ {i18n.t(+ providerConfig.protocol === 'anthropic'+ ? 'settings.ownServerHintAnthropic'+ : 'settings.ownServerHintOpenai',+ )}+ </p>+ </div>+ )}</div>- );-}-function KeyResult({ result }: { result: KeyValidation }) {- if (result.valid) {- return (- <p className="flex items-center gap-1.5 text-xs font-medium text-success">- <Check size={14} />- {result.models?.length- ? i18n.t('settings_modelsFound', [String(result.models.length)])- : i18n.t('settings_keyValid')}- </p>- );- }- const unreachable = result.reason === 'network';- return (- <p className="flex items-center gap-1.5 text-xs font-medium text-destructive">- <TriangleAlert size={14} />- {i18n.t(unreachable ? 'settings_keyUnreachable' : 'settings_keyInvalid')}- </p>+ <div>+ <label className="block text-[11px] font-semibold text-foreground mb-1">+ <Globe size={11} className="inline mr-1 -mt-px" />+ {i18n.t('settings.aiLanguage')}+ </label>+ <Select value={aiLanguage} onValueChange={(v) => {+ setAiLanguage(v as AILanguageCode);+ onChange({ aiLanguage: v });+ }}>+ <SelectTrigger className="h-8">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {AI_LANGUAGES.map((lang) => (+ <SelectItem key={lang.code} value={lang.code}>+ {lang.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ </div>);}diff --git a/packages/ui/src/shared/key-status.tsx b/packages/ui/src/shared/key-status.tsxnew file mode 100644index 0000000..7f3ada6--- /dev/null+++ b/packages/ui/src/shared/key-status.tsx@@ -0,0 +1,175 @@+import { i18n } from '@mimik/core/env';+import { Input } from '@mimik/ui/components/ui/input';+import { Check, Eye, EyeOff, TriangleAlert } from 'lucide-react';+import { useCallback, useRef, useState } from 'react';++export type KeyStatus = 'checking' | 'valid' | 'rejected' | 'unreachable' | 'model-required' | 'model-invalid' | null;++export type KeyWarning = 'cannot-spend';++export function KeyStatusNote({ status }: { status: KeyStatus }) {+ if (status === 'checking') {+ return <p className="mt-1 text-[11px] text-muted-foreground">{i18n.t('settings.validatingKey')}</p>;+ }+ if (status === 'valid') {+ return (+ <p className="mt-1 text-[11px] flex items-center gap-1" style={{ color: 'var(--color-success)' }}>+ <Check size={11} />+ {i18n.t('settings.keyValid')}+ </p>+ );+ }+ if (status === 'rejected') {+ return (+ <p className="mt-1 text-[11px] text-destructive" role="alert">+ {i18n.t('settings.keyInvalid')}+ </p>+ );+ }+ if (status === 'unreachable') {+ return <p className="mt-1 text-[11px] text-muted-foreground">{i18n.t('settings.keyUnreachable')}</p>;+ }+ if (status === 'model-required') {+ return (+ <p className="mt-1 text-[11px] text-destructive" role="alert">+ {i18n.t('settings.keyModelRequired')}+ </p>+ );+ }+ if (status === 'model-invalid') {+ return (+ <p className="mt-1 text-[11px] text-destructive" role="alert">+ {i18n.t('settings.keyModelInvalid')}+ </p>+ );+ }+ return null;+}++export function KeyWarningNote({ warning }: { warning: KeyWarning | null }) {+ if (!warning) return null;+ return (+ <p className="mt-1 flex items-start gap-1.5 text-[10px] text-foreground leading-relaxed" role="status">+ <TriangleAlert size={11} className="shrink-0 mt-0.5 text-destructive" />+ <span>{i18n.t('settings.keyCannotSpend')}</span>+ </p>+ );+}++export function ModelList({ models }: { models: string[] }) {+ return (+ <div className="mt-1.5 rounded-lg bg-secondary px-2.5 py-2">+ <p className="text-[10px] font-semibold text-muted-foreground mb-1">+ {i18n.t('settings.modelsFound', [String(models.length)])}+ </p>+ <ul+ className="max-h-24 overflow-y-auto space-y-0.5"+ aria-label={i18n.t('settings.modelsFound', [String(models.length)])}+ >+ {models.map((id) => (+ <li key={id} className="text-[10px] text-foreground truncate font-mono">+ {id}+ </li>+ ))}+ </ul>+ </div>+ );+}++export function SecretInput({+ value,+ onChange,+ placeholder,+ className,+ buttonClassName,+}: {+ value: string;+ onChange: (next: string) => void;+ placeholder?: string;+ className?: string;+ buttonClassName?: string;+}) {+ const [revealed, setRevealed] = useState(false);+ const Icon = revealed ? EyeOff : Eye;+ return (+ <div className="relative flex-1 min-w-0">+ <Input+ type={revealed ? 'text' : 'password'}+ value={value}+ onChange={(e) => onChange(e.target.value)}+ placeholder={placeholder}+ className={`pr-8 ${className ?? ''}`}+ />+ <button+ type="button"+ onClick={() => setRevealed((on) => !on)}+ aria-pressed={revealed}+ aria-label={i18n.t(revealed ? 'settings.hideKey' : 'settings.showKey')}+ title={i18n.t(revealed ? 'settings.hideKey' : 'settings.showKey')}+ className={`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors ${buttonClassName ?? ''}`}+ >+ <Icon size={13} />+ </button>+ </div>+ );+}++export interface KeyCheckResult {+ valid: boolean;+ reason?: 'rejected' | 'network' | 'model-required' | 'model-invalid';+ models?: string[];+ warning?: KeyWarning;+}++export type ValidateKey = (+ provider: string,+ apiKey: string,+ baseUrl?: string,+ model?: string,+) => Promise<KeyCheckResult | null>;++export function useKeyCheck(validate: ValidateKey) {+ const [status, setStatus] = useState<KeyStatus>(null);+ const [models, setModels] = useState<string[] | null>(null);+ const [warning, setWarning] = useState<KeyWarning | null>(null);+ const validated = useRef('');+ const requestId = useRef(0);++ const check = useCallback(async (provider: string, apiKey: string, baseUrl?: string, model?: string) => {+ const fingerprint = `${provider}:${apiKey}:${baseUrl ?? ''}:${model ?? ''}`;+ if (validated.current === fingerprint) {+ setStatus('valid');+ return;+ }+ const currentRequestId = ++requestId.current;+ setStatus('checking');+ setModels(null);+ setWarning(null);+ const result = await validate(provider, apiKey, baseUrl, model).catch(() => null);+ if (requestId.current !== currentRequestId) return;+ if (result?.valid) validated.current = fingerprint;+ setModels(result?.models?.length ? result.models : null);+ setWarning(result?.valid && result.warning ? result.warning : null);+ setStatus(+ result?.valid+ ? 'valid'+ : result?.reason === 'rejected'+ ? 'rejected'+ : result?.reason === 'model-required'+ ? 'model-required'+ : result?.reason === 'model-invalid'+ ? 'model-invalid'+ : 'unreachable',+ );+ }, [validate]);++ const reset = useCallback(() => {+ requestId.current += 1;+ validated.current = '';+ setStatus(null);+ setModels(null);+ setWarning(null);+ }, []);++ return { status, models, warning, check, reset };+}diff --git a/src/ui/shared/SettingsView.tsx b/src/ui/shared/SettingsView.tsxindex 4b54269..659a9c8 100644--- a/src/ui/shared/SettingsView.tsx+++ b/src/ui/shared/SettingsView.tsx@@ -1,15 +1,6 @@import { PRESET_LABELS, type PresetKey } from '@mimik/core/blur/regexes';-import { type AIApiKeys, keyFor, migrateApiKeys, withKeyFor } from '@mimik/core/capture/ai/keys';-import {- AI_PROVIDERS,- type AIProviderKey,- CUSTOM_MODEL_VALUE,- DEFAULT_AI_PROVIDER,- isCustomBaseUrl,- isCustomModel,- providerOrDefault,-} from '@mimik/core/capture/ai/models';-import { AI_LANGUAGES, type AILanguageCode } from '@mimik/core/capture/ai/prompts';+import { keyFor, migrateApiKeys } from '@mimik/core/capture/ai/keys';+import { type AIProviderKey, providerOrDefault } from '@mimik/core/capture/ai/models';import { resolveVoiceApiKey } from '@mimik/core/capture/voice/api-key';import type { VoiceProvider } from '@mimik/core/capture/voice/transcribe';import { i18n } from '@mimik/core/env';@@ -21,6 +12,7 @@ import { Popover, PopoverContent, PopoverTrigger } from '@mimik/ui/components/uiimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@mimik/ui/components/ui/select';import { logger } from '@mimik/ui/lib/logger';import { changedSettings, type SettingsSnapshot } from '@mimik/ui/lib/settings-autosave';+import AiSettings from '@mimik/ui/shared/AiSettings';import ColorPicker from '@mimik/ui/shared/ColorPicker';import {ArrowLeft,@@ -29,7 +21,6 @@ import {ChevronDown,ChevronRight,EyeOff,- Globe,ImageIcon,Mic,Shield,@@ -41,7 +32,7 @@ import {} from 'lucide-react';import { useCallback, useEffect, useRef, useState } from 'react';import { localStorage } from '@/lib/browser-api';-import { KeyStatusNote, KeyWarningNote, ModelList, SecretInput, useKeyCheck } from '@/ui/shared/key-check';+import { KeyStatusNote, ModelList, SecretInput, useKeyCheck } from '@/ui/shared/key-check';import MicrophonePicker from '@/ui/shared/MicrophonePicker';interface SettingsViewProps {@@ -59,20 +50,15 @@ const FOOTER_PRESETS = () => [export default function SettingsView({ onBack }: SettingsViewProps) {const [provider, setProvider] = useState<AIProviderKey>('openai');- const [model, setModel] = useState(AI_PROVIDERS.openai.defaultModel);const [apiKey, setApiKey] = useState('');- const [apiKeys, setApiKeys] = useState<AIApiKeys>({});- const [baseUrl, setBaseUrl] = useState('');const [saved, setSaved] = useState(false);const aiKeyCheck = useKeyCheck();const voiceKeyCheck = useKeyCheck();- const [customModel, setCustomModel] = useState(false);- const [ownServer, setOwnServer] = useState(false);const [loaded, setLoaded] = useState(false);const savedSnapshot = useRef<SettingsSnapshot | null>(null);+ const flushRef = useRef<() => Promise<void>>(async () => {});const pending = useRef<SettingsSnapshot>({});const saveTimer = useRef<number | undefined>(undefined);- const [aiLanguage, setAiLanguage] = useState<AILanguageCode>('en');const [voiceProvider, setVoiceProvider] = useState<VoiceProvider>('openai');const [voiceApiKey, setVoiceApiKey] = useState('');const [voiceMicrophoneId, setVoiceMicrophoneId] = useState('');@@ -111,15 +97,7 @@ export default function SettingsView({ onBack }: SettingsViewProps) {.then((result) => {const p = providerOrDefault(result.aiProvider);setProvider(p);- setModel((result.aiModel as string) || AI_PROVIDERS[p].defaultModel);- const keys = migrateApiKeys(result);- setApiKeys(keys);- setApiKey(keyFor(keys, p));- if (isCustomBaseUrl(AI_PROVIDERS[p], result.aiBaseUrl as string)) {- setBaseUrl(result.aiBaseUrl as string);- setOwnServer(true);- }- if (result.aiLanguage) setAiLanguage(result.aiLanguage as AILanguageCode);+ setApiKey(keyFor(migrateApiKeys(result), p));if (result.blurPresets) setBlurPresets(result.blurPresets as Record<PresetKey, boolean>);setVoiceProvider((result.voiceProvider as VoiceProvider) || 'openai');if (result.voiceApiKey) setVoiceApiKey(result.voiceApiKey as string);@@ -133,12 +111,6 @@ export default function SettingsView({ onBack }: SettingsViewProps) {}, []);const stored = {- aiApiKey: apiKey,- aiApiKeys: apiKeys,- aiProvider: provider,- aiModel: model,- aiBaseUrl: baseUrl,- aiLanguage,blurPresets,voiceProvider,voiceApiKey,@@ -149,6 +121,12 @@ export default function SettingsView({ onBack }: SettingsViewProps) {brandAttribution,};+ const queue = useCallback((patch: SettingsSnapshot) => {+ Object.assign(pending.current, patch);+ window.clearTimeout(saveTimer.current);+ saveTimer.current = window.setTimeout(() => void flushRef.current(), SAVE_DEBOUNCE_MS);+ }, []);+const flush = useCallback(async () => {const patch = pending.current;pending.current = {};@@ -162,6 +140,8 @@ export default function SettingsView({ onBack }: SettingsViewProps) {}}, []);+ flushRef.current = flush;+useEffect(() => {if (!loaded) return;const snapshot = savedSnapshot.current;@@ -198,38 +178,6 @@ export default function SettingsView({ onBack }: SettingsViewProps) {setBrandLogo(await makeBrandLogo(file));};- const handleProviderChange = (newProvider: AIProviderKey) => {- setProvider(newProvider);- setApiKey(keyFor(apiKeys, newProvider));- aiKeyCheck.reset();- setCustomModel(false);- setModel(AI_PROVIDERS[newProvider].defaultModel);- setOwnServer(false);- setBaseUrl('');- };-- const handleOwnServerToggle = () => {- setOwnServer((on) => {- if (on) setBaseUrl('');- return !on;- });- aiKeyCheck.reset();- };-- const handleModelChange = (value: string) => {- if (value === CUSTOM_MODEL_VALUE) {- setCustomModel(true);- setModel('');- aiKeyCheck.reset();- return;- }- setCustomModel(false);- setModel(value);- aiKeyCheck.reset();- };-- const providerConfig = AI_PROVIDERS[provider] ?? AI_PROVIDERS[DEFAULT_AI_PROVIDER];- const usingCustomModel = customModel || isCustomModel(model, providerConfig);const voiceKey = resolveVoiceApiKey({ voiceProvider, voiceApiKey, aiProvider: provider, aiApiKey: apiKey });const BLUR_PRESET_I18N: Record<PresetKey, string> = {@@ -266,162 +214,14 @@ export default function SettingsView({ onBack }: SettingsViewProps) {</div><div className="flex-1 px-3 py-4 space-y-3">- <div className="border border-border rounded-[10px] p-3.5 space-y-3">- <div className="flex items-center gap-2.5">- <div className="w-7 h-7 rounded-lg bg-secondary flex items-center justify-center">- <Sparkles size={14} className="text-accent" />- </div>- <span className="text-xs font-bold text-foreground">{i18n.t('settings.aiDescriptions')}</span>- </div>-- <div>- <label className="block text-[11px] font-semibold text-foreground mb-1">- {i18n.t('settings.provider')}- </label>- <Select value={provider} onValueChange={(v) => handleProviderChange(v as AIProviderKey)}>- <SelectTrigger className="h-8">- <SelectValue />- </SelectTrigger>- <SelectContent>- {Object.entries(AI_PROVIDERS).map(([key, cfg]) => (- <SelectItem key={key} value={key}>- {cfg.label}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>-- <div>- <label className="block text-[11px] font-semibold text-foreground mb-1">{i18n.t('settings.model')}</label>- <Select value={usingCustomModel ? CUSTOM_MODEL_VALUE : model} onValueChange={handleModelChange}>- <SelectTrigger className="h-8">- <SelectValue />- </SelectTrigger>- <SelectContent>- {providerConfig.models.map((m) => (- <SelectItem key={m.id} value={m.id}>- {m.label}- </SelectItem>- ))}- </SelectContent>- </Select>- {usingCustomModel && (- <Input- value={model}- onChange={(e) => {- setModel(e.target.value);- aiKeyCheck.reset();- }}- placeholder={providerConfig.defaultModel}- aria-label={i18n.t('settings.modelCustom')}- className="mt-1.5 h-8 text-[13px] rounded-lg border-border"- />- )}- </div>-- <div>- <label className="block text-[11px] font-semibold text-foreground mb-1">{i18n.t('settings.apiKey')}</label>- <div className="flex items-center gap-1.5">- <SecretInput- value={apiKey}- onChange={(next) => {- setApiKey(next);- setApiKeys((prev) => withKeyFor(prev, provider, next));- aiKeyCheck.reset();- }}- placeholder="sk-..."- className="h-8 text-[13px] rounded-lg border-border"- />- <Button- variant="outline"- size="sm"- disabled={!apiKey || aiKeyCheck.status === 'checking'}- onClick={() => {- if (aiKeyCheck.status !== 'checking') void aiKeyCheck.check(provider, apiKey, baseUrl, model);- }}- className="h-8 shrink-0 rounded-lg bg-card text-[11px] font-semibold"- >- {i18n.t('settings.checkKey')}- </Button>- </div>- <KeyStatusNote status={aiKeyCheck.status} />- <KeyWarningNote warning={aiKeyCheck.warning} />- {aiKeyCheck.models && <ModelList models={aiKeyCheck.models} />}- {!apiKey.trim() && (- <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.aiNoKey')}</span>- </p>- )}- </div>-- <div>- <div className="flex items-center justify-between gap-3 py-0.5">- <span className="text-[11px] font-semibold text-foreground flex items-center gap-1">- <Globe size={11} className="-mt-px" />- {i18n.t('settings.useOwnServer')}- </span>- <button- type="button"- role="switch"- aria-checked={ownServer}- aria-label={i18n.t('settings.useOwnServer')}- onClick={handleOwnServerToggle}- className={`w-9 h-5 rounded-full transition-colors relative shrink-0 ${- ownServer ? '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 ${- ownServer ? 'translate-x-4' : 'translate-x-0'- }`}- />- </button>- </div>- {ownServer && (- <div className="mt-2 space-y-1.5">- <Input- type="text"- value={baseUrl}- onChange={(e) => {- setBaseUrl(e.target.value);- aiKeyCheck.reset();- }}- placeholder={providerConfig.defaultBaseUrl}- aria-label={i18n.t('settings.baseUrl')}- className="h-8 text-[13px] rounded-lg border-border"- />- <p className="text-[10px] text-muted-foreground leading-relaxed">- {i18n.t(- providerConfig.protocol === 'anthropic'- ? 'settings.ownServerHintAnthropic'- : 'settings.ownServerHintOpenai',- )}- </p>- </div>- )}- </div>-- <div>- <label className="block text-[11px] font-semibold text-foreground mb-1">- <Globe size={11} className="inline mr-1 -mt-px" />- {i18n.t('settings.aiLanguage')}- </label>- <Select value={aiLanguage} onValueChange={(v) => setAiLanguage(v as AILanguageCode)}>- <SelectTrigger className="h-8">- <SelectValue />- </SelectTrigger>- <SelectContent>- {AI_LANGUAGES.map((lang) => (- <SelectItem key={lang.code} value={lang.code}>- {lang.label}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- </div>+ <AiSettings+ keyCheck={aiKeyCheck}+ onChange={(patch) => {+ if (typeof patch.aiProvider === 'string') setProvider(patch.aiProvider as AIProviderKey);+ if (typeof patch.aiApiKey === 'string') setApiKey(patch.aiApiKey);+ queue(patch);+ }}+ /><div className="border border-border rounded-[10px] p-3.5 flex items-center justify-between gap-3"><div className="flex items-center gap-2.5">diff --git a/src/ui/shared/key-check.tsx b/src/ui/shared/key-check.tsxindex 6e5da20..5d00fd2 100644--- a/src/ui/shared/key-check.tsx+++ b/src/ui/shared/key-check.tsx@@ -1,162 +1,16 @@-import { i18n } from '@mimik/core/env';-import { Input } from '@mimik/ui/components/ui/input';-import { Check, Eye, EyeOff, TriangleAlert } from 'lucide-react';-import { useCallback, useRef, useState } from 'react';+import { useKeyCheck as useSharedKeyCheck } from '@mimik/ui/shared/key-status';+import { useCallback } from 'react';import { sendMessage } from '@/lib/messaging';-export type KeyStatus = 'checking' | 'valid' | 'rejected' | 'unreachable' | 'model-required' | 'model-invalid' | null;--export type KeyWarning = 'cannot-spend';+export type { KeyStatus, KeyWarning } from '@mimik/ui/shared/key-status';+export { KeyStatusNote, KeyWarningNote, ModelList, SecretInput } from '@mimik/ui/shared/key-status';export function useKeyCheck() {- const [status, setStatus] = useState<KeyStatus>(null);- const [models, setModels] = useState<string[] | null>(null);- const [warning, setWarning] = useState<KeyWarning | null>(null);- const validated = useRef('');- const requestId = useRef(0);-- const check = useCallback(async (provider: string, apiKey: string, baseUrl?: string, model?: string) => {- const fingerprint = `${provider}:${apiKey}:${baseUrl ?? ''}:${model ?? ''}`;- if (validated.current === fingerprint) {- setStatus('valid');- return;- }- const currentRequestId = ++requestId.current;- setStatus('checking');- setModels(null);- setWarning(null);- const result = await sendMessage('validateApiKey', { provider, apiKey, baseUrl, model }).catch(() => null);- if (requestId.current !== currentRequestId) return;- if (result?.valid) validated.current = fingerprint;- setModels(result?.models?.length ? result.models : null);- setWarning(result?.valid && result.warning ? result.warning : null);- setStatus(- result?.valid- ? 'valid'- : result?.reason === 'rejected'- ? 'rejected'- : result?.reason === 'model-required'- ? 'model-required'- : result?.reason === 'model-invalid'- ? 'model-invalid'- : 'unreachable',- );- }, []);-- const reset = useCallback(() => {- requestId.current += 1;- validated.current = '';- setStatus(null);- setModels(null);- setWarning(null);- }, []);-- return { status, models, warning, check, reset };-}--export function KeyStatusNote({ status }: { status: KeyStatus }) {- if (status === 'checking') {- return <p className="mt-1 text-[11px] text-muted-foreground">{i18n.t('settings.validatingKey')}</p>;- }- if (status === 'valid') {- return (- <p className="mt-1 text-[11px] flex items-center gap-1" style={{ color: 'var(--color-success)' }}>- <Check size={11} />- {i18n.t('settings.keyValid')}- </p>- );- }- if (status === 'rejected') {- return (- <p className="mt-1 text-[11px] text-destructive" role="alert">- {i18n.t('settings.keyInvalid')}- </p>- );- }- if (status === 'unreachable') {- return <p className="mt-1 text-[11px] text-muted-foreground">{i18n.t('settings.keyUnreachable')}</p>;- }- if (status === 'model-required') {- return (- <p className="mt-1 text-[11px] text-destructive" role="alert">- {i18n.t('settings.keyModelRequired')}- </p>- );- }- if (status === 'model-invalid') {- return (- <p className="mt-1 text-[11px] text-destructive" role="alert">- {i18n.t('settings.keyModelInvalid')}- </p>- );- }- return null;-}--export function KeyWarningNote({ warning }: { warning: KeyWarning | null }) {- if (!warning) return null;- return (- <p className="mt-1 flex items-start gap-1.5 text-[10px] text-foreground leading-relaxed" role="status">- <TriangleAlert size={11} className="shrink-0 mt-0.5 text-destructive" />- <span>{i18n.t('settings.keyCannotSpend')}</span>- </p>- );-}--export function ModelList({ models }: { models: string[] }) {- return (- <div className="mt-1.5 rounded-lg bg-secondary px-2.5 py-2">- <p className="text-[10px] font-semibold text-muted-foreground mb-1">- {i18n.t('settings.modelsFound', [String(models.length)])}- </p>- <ul- className="max-h-24 overflow-y-auto space-y-0.5"- aria-label={i18n.t('settings.modelsFound', [String(models.length)])}- >- {models.map((id) => (- <li key={id} className="text-[10px] text-foreground truncate font-mono">- {id}- </li>- ))}- </ul>- </div>- );-}--export function SecretInput({- value,- onChange,- placeholder,- className,- buttonClassName,-}: {- value: string;- onChange: (next: string) => void;- placeholder?: string;- className?: string;- buttonClassName?: string;-}) {- const [revealed, setRevealed] = useState(false);- const Icon = revealed ? EyeOff : Eye;- return (- <div className="relative flex-1 min-w-0">- <Input- type={revealed ? 'text' : 'password'}- value={value}- onChange={(e) => onChange(e.target.value)}- placeholder={placeholder}- className={`pr-8 ${className ?? ''}`}- />- <button- type="button"- onClick={() => setRevealed((on) => !on)}- aria-pressed={revealed}- aria-label={i18n.t(revealed ? 'settings.hideKey' : 'settings.showKey')}- title={i18n.t(revealed ? 'settings.hideKey' : 'settings.showKey')}- className={`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors ${buttonClassName ?? ''}`}- >- <Icon size={13} />- </button>- </div>+ return useSharedKeyCheck(+ useCallback(+ (provider: string, apiKey: string, baseUrl?: string, model?: string) =>+ sendMessage('validateApiKey', { provider, apiKey, baseUrl, model }),+ [],+ ),);}