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: list the models a provider returns when checking an API key (Scrollable)

alvinlollocb41fa65d31e
diff --git a/src/core/capture/ai/__tests__/validate.test.ts b/src/core/capture/ai/__tests__/validate.test.ts
index 4deb824..02671b9 100644
--- a/src/core/capture/ai/__tests__/validate.test.ts
+++ b/src/core/capture/ai/__tests__/validate.test.ts
@@ -10,7 +10,7 @@ describe('validateApiKey', () => {
});
it('accepts a key the provider returns 200 for', async () => {
- fetchMock.mockResolvedValue({ ok: true, status: 200 });
+ fetchMock.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve(null) });
expect(await validateApiKey('openai', 'sk-good')).toEqual({ valid: true });
});
@@ -35,7 +35,7 @@ describe('validateApiKey', () => {
});
it('sends the anthropic browser-access header so the request is not blocked by CORS', async () => {
- fetchMock.mockResolvedValue({ ok: true, status: 200 });
+ fetchMock.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve(null) });
await validateApiKey('anthropic', 'ant-key');
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe('https://api.anthropic.com/v1/models');
@@ -44,7 +44,7 @@ describe('validateApiKey', () => {
});
it('sends a bearer token for openai', async () => {
- fetchMock.mockResolvedValue({ ok: true, status: 200 });
+ fetchMock.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve(null) });
await validateApiKey('openai', 'sk-key');
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe('https://api.openai.com/v1/models');
@@ -52,7 +52,7 @@ describe('validateApiKey', () => {
});
it('checks a groq key against groq, not openai', async () => {
- fetchMock.mockResolvedValue({ ok: true, status: 200 });
+ fetchMock.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve(null) });
expect(await validateApiKey('groq', 'gsk-key')).toEqual({ valid: true });
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe('https://api.groq.com/openai/v1/models');
@@ -60,7 +60,7 @@ describe('validateApiKey', () => {
});
it('gives up rather than spinning forever when a host never answers', async () => {
- fetchMock.mockResolvedValue({ ok: true, status: 200 });
+ fetchMock.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve(null) });
await validateApiKey('openai', 'sk-key');
const [, init] = fetchMock.mock.calls[0];
expect(init.signal).toBeInstanceOf(AbortSignal);
@@ -72,7 +72,7 @@ describe('validateApiKey', () => {
});
it('checks a compatible key against the stored base URL, not openai', async () => {
- fetchMock.mockResolvedValue({ ok: true, status: 200 });
+ fetchMock.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve(null) });
expect(await validateApiKey('openaiCompatible', 'sk-key', 'https://api.example.com/v1')).toEqual({ valid: true });
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe('https://api.example.com/v1/models');
@@ -80,7 +80,7 @@ describe('validateApiKey', () => {
});
it('strips trailing slashes from a compatible base URL', async () => {
- fetchMock.mockResolvedValue({ ok: true, status: 200 });
+ fetchMock.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve(null) });
await validateApiKey('openaiCompatible', 'sk-key', 'https://api.example.com/v1///');
const [url] = fetchMock.mock.calls[0];
expect(url).toBe('https://api.example.com/v1/models');
@@ -90,4 +90,43 @@ describe('validateApiKey', () => {
expect(await validateApiKey('openaiCompatible', 'sk-key')).toEqual({ valid: false, reason: 'network' });
expect(fetchMock).not.toHaveBeenCalled();
});
+
+ it('returns the model ids a provider lists for the key', async () => {
+ fetchMock.mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ data: [{ id: 'gpt-4o-mini' }, { id: 'gpt-4o' }] }),
+ });
+ expect(await validateApiKey('openai', 'sk-key')).toEqual({
+ valid: true,
+ models: ['gpt-4o-mini', 'gpt-4o'],
+ });
+ });
+
+ it('stays valid when a key works but no models come back', async () => {
+ fetchMock.mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ data: [] }),
+ });
+ expect(await validateApiKey('openai', 'sk-key')).toEqual({ valid: true });
+ });
+
+ it('stays valid when the body is not a model list at all', async () => {
+ fetchMock.mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: () => Promise.reject(new Error('not json')),
+ });
+ expect(await validateApiKey('openai', 'sk-key')).toEqual({ valid: true });
+ });
+
+ it('drops blank entries from a malformed model list', async () => {
+ fetchMock.mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ data: [{ id: '' }, { id: 'ok-model' }, {}, 'junk'] }),
+ });
+ expect(await validateApiKey('groq', 'gsk-key')).toEqual({ valid: true, models: ['ok-model'] });
+ });
});
diff --git a/src/core/capture/ai/validate.ts b/src/core/capture/ai/validate.ts
index ef4963a..464d400 100644
--- a/src/core/capture/ai/validate.ts
+++ b/src/core/capture/ai/validate.ts
@@ -1,6 +1,6 @@
import { logger } from '@/lib/logger';
-export type KeyValidation = { valid: true } | { valid: false; reason: 'rejected' | 'network' };
+export type KeyValidation = { valid: true; models?: string[] } | { valid: false; reason: 'rejected' | 'network' };
const REQUEST_TIMEOUT_MS = 10_000;
@@ -38,6 +38,17 @@ function endpointUrl(provider: string, baseUrl?: string): string | null {
return endpoint.url ?? null;
}
+/** OpenAI, Anthropic and Groq all list models as `{ data: [{ id }] }`. */
+function parseModelIds(body: unknown): string[] | undefined {
+ if (typeof body !== 'object' || body === null) return undefined;
+ const data = (body as { data?: unknown }).data;
+ if (!Array.isArray(data)) return undefined;
+ const models = data
+ .map((entry) => (typeof entry === 'object' && entry !== null ? (entry as { id?: unknown }).id : undefined))
+ .filter((id): id is string => typeof id === 'string' && id.length > 0);
+ return models.length > 0 ? models : undefined;
+}
+
export async function validateApiKey(provider: string, apiKey: string, baseUrl?: string): Promise<KeyValidation> {
const url = endpointUrl(provider, baseUrl);
if (!url) {
@@ -49,7 +60,11 @@ export async function validateApiKey(provider: string, apiKey: string, baseUrl?:
headers: ENDPOINTS[provider].headers(apiKey),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
- if (res.ok) return { valid: true };
+ if (res.ok) {
+ const body = await res.json().catch(() => null);
+ const models = parseModelIds(body);
+ return models ? { valid: true, models } : { valid: true };
+ }
if (res.status === 401 || res.status === 403) return { valid: false, reason: 'rejected' };
return { valid: false, reason: 'network' };
} catch (err) {
diff --git a/src/lib/messaging.ts b/src/lib/messaging.ts
index c930784..710a026 100644
--- a/src/lib/messaging.ts
+++ b/src/lib/messaging.ts
@@ -116,6 +116,7 @@ export interface ValidateApiKeyData {
export interface ValidateApiKeyResponse {
valid: boolean;
reason?: 'rejected' | 'network';
+ models?: string[];
}
export interface EnterBlurModeResponse {
diff --git a/src/locales/de.yml b/src/locales/de.yml
index a244f1e..1de840f 100644
--- a/src/locales/de.yml
+++ b/src/locales/de.yml
@@ -134,6 +134,7 @@ settings:
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.
+ modelsFound: "$1 Modelle verfügbar"
blurPresets:
email: E-Mail
diff --git a/src/locales/en.yml b/src/locales/en.yml
index d44d39a..4b6b9c9 100644
--- a/src/locales/en.yml
+++ b/src/locales/en.yml
@@ -128,6 +128,7 @@ settings:
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.
+ modelsFound: "$1 models available"
smartBlur: Smart Blur
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"
diff --git a/src/locales/es.yml b/src/locales/es.yml
index a373a2e..55d358d 100644
--- a/src/locales/es.yml
+++ b/src/locales/es.yml
@@ -128,6 +128,7 @@ settings:
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.
+ modelsFound: "$1 modelos disponibles"
smartBlur: Desenfoque inteligente
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"
diff --git a/src/locales/fr.yml b/src/locales/fr.yml
index c947397..4213edb 100644
--- a/src/locales/fr.yml
+++ b/src/locales/fr.yml
@@ -128,6 +128,7 @@ settings:
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.
+ modelsFound: "$1 modèles disponibles"
smartBlur: Flou intelligent
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"
diff --git a/src/locales/pt-BR.yml b/src/locales/pt-BR.yml
index c287609..4c2655d 100644
--- a/src/locales/pt-BR.yml
+++ b/src/locales/pt-BR.yml
@@ -128,6 +128,7 @@ settings:
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.
+ modelsFound: "$1 modelos disponíveis"
smartBlur: Desfoque inteligente
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"
diff --git a/src/ui/onboarding/App.tsx b/src/ui/onboarding/App.tsx
index ebd5263..df74f38 100644
--- a/src/ui/onboarding/App.tsx
+++ b/src/ui/onboarding/App.tsx
@@ -8,6 +8,7 @@ import type { VoiceProvider } from '@/core/capture/voice/transcribe';
import { localStorage, openSidebar, requestHostPermissions } from '@/lib/browser-api';
import { Input } from '@/ui/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/ui/components/ui/select';
+import { KeyStatusNote, ModelList, useKeyCheck } from '@/ui/shared/key-check';
import MicrophonePicker from '@/ui/shared/MicrophonePicker';
interface StepProps {
@@ -120,6 +121,7 @@ function AISetupStep({ onNext, onSkip, onBack, index, total }: StepProps) {
const [apiKey, setApiKey] = useState('');
const [baseUrl, setBaseUrl] = useState('');
const [aiLanguage, setAiLanguage] = useState<AILanguageCode>('en');
+ const aiKeyCheck = useKeyCheck();
useEffect(() => {
const load = () =>
@@ -147,6 +149,7 @@ function AISetupStep({ onNext, onSkip, onBack, index, total }: StepProps) {
const nextModel = AI_PROVIDERS[newProvider].defaultModel;
setProvider(newProvider);
setModel(nextModel);
+ aiKeyCheck.setStatus(null);
void localStorage.set({ aiProvider: newProvider, aiModel: nextModel });
};
@@ -157,11 +160,13 @@ function AISetupStep({ onNext, onSkip, onBack, index, total }: StepProps) {
const handleApiKeyChange = (nextKey: string) => {
setApiKey(nextKey);
+ aiKeyCheck.setStatus(null);
void localStorage.set({ aiApiKey: nextKey });
};
const handleBaseUrlChange = (nextUrl: string) => {
setBaseUrl(nextUrl);
+ aiKeyCheck.setStatus(null);
void localStorage.set({ aiBaseUrl: nextUrl });
};
@@ -250,6 +255,20 @@ function AISetupStep({ onNext, onSkip, onBack, index, total }: StepProps) {
placeholder="sk-..."
className="w-full rounded-xl px-4 py-2.5 text-sm focus:border-accent focus:ring-accent/10"
/>
+ <div className="flex items-center gap-3 mt-2">
+ <button
+ type="button"
+ disabled={!apiKey || aiKeyCheck.status === 'checking'}
+ onClick={() => void aiKeyCheck.check(provider, apiKey, baseUrl)}
+ className="px-4 py-2 bg-card text-foreground border border-border rounded-lg font-semibold text-xs hover:border-accent hover:text-accent transition-colors disabled:opacity-50 disabled:pointer-events-none"
+ >
+ {i18n.t('settings.checkKey')}
+ </button>
+ <div className="min-w-0">
+ <KeyStatusNote status={aiKeyCheck.status} />
+ </div>
+ </div>
+ {aiKeyCheck.models && <ModelList models={aiKeyCheck.models} />}
</div>
<div>
diff --git a/src/ui/shared/SettingsView.tsx b/src/ui/shared/SettingsView.tsx
index 0329038..6652509 100644
--- a/src/ui/shared/SettingsView.tsx
+++ b/src/ui/shared/SettingsView.tsx
@@ -26,12 +26,12 @@ import { type BrandLogo, defaultFooterLine, makeBrandLogo } from '@/core/export/
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';
import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/ui/components/ui/select';
import ColorPicker from '@/ui/shared/ColorPicker';
+import { KeyStatusNote, ModelList, useKeyCheck } from '@/ui/shared/key-check';
import MicrophonePicker from '@/ui/shared/MicrophonePicker';
import { changedSettings, type SettingsSnapshot } from '@/ui/shared/settings-autosave';
@@ -42,52 +42,6 @@ interface SettingsViewProps {
const SAVE_DEBOUNCE_MS = 400;
const SAVED_BADGE_MS = 1600;
-type KeyStatus = 'checking' | 'valid' | 'rejected' | 'unreachable' | null;
-
-function useKeyCheck() {
- const [status, setStatus] = useState<KeyStatus>(null);
- const validated = useRef('');
-
- const check = useCallback(async (provider: string, apiKey: string, baseUrl?: string) => {
- const fingerprint = `${provider}:${apiKey}:${baseUrl ?? ''}`;
- if (validated.current === fingerprint) {
- setStatus('valid');
- return;
- }
- setStatus('checking');
- const result = await sendMessage('validateApiKey', { provider, apiKey, baseUrl }).catch(() => null);
- if (result?.valid) validated.current = fingerprint;
- setStatus(result?.valid ? 'valid' : result?.reason === 'rejected' ? 'rejected' : 'unreachable');
- }, []);
-
- return { status, setStatus, check };
-}
-
-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>;
- }
- return null;
-}
-
const FOOTER_PRESETS = () => [
defaultFooterLine(),
i18n.t('settings.footerPresetConfidential'),
@@ -377,6 +331,7 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
</Button>
</div>
<KeyStatusNote status={aiKeyCheck.status} />
+ {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" />
@@ -574,6 +529,7 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
</Button>
</div>
<KeyStatusNote status={voiceKeyCheck.status} />
+ {voiceKeyCheck.models && <ModelList models={voiceKeyCheck.models} />}
{voiceKey.source === 'ai' && (
<p className="mt-1.5 flex items-start gap-1.5 text-[10px] text-muted-foreground leading-relaxed">
<Sparkles size={11} className="shrink-0 mt-0.5 text-accent" />
diff --git a/src/ui/shared/key-check.tsx b/src/ui/shared/key-check.tsx
new file mode 100644
index 0000000..061233c
--- /dev/null
+++ b/src/ui/shared/key-check.tsx
@@ -0,0 +1,73 @@
+import { Check } from 'lucide-react';
+import { useCallback, useRef, useState } from 'react';
+import { i18n } from '#imports';
+import { sendMessage } from '@/lib/messaging';
+
+export type KeyStatus = 'checking' | 'valid' | 'rejected' | 'unreachable' | null;
+
+export function useKeyCheck() {
+ const [status, setStatus] = useState<KeyStatus>(null);
+ const [models, setModels] = useState<string[] | null>(null);
+ const validated = useRef('');
+
+ const check = useCallback(async (provider: string, apiKey: string, baseUrl?: string) => {
+ const fingerprint = `${provider}:${apiKey}:${baseUrl ?? ''}`;
+ if (validated.current === fingerprint) {
+ setStatus('valid');
+ return;
+ }
+ setStatus('checking');
+ setModels(null);
+ const result = await sendMessage('validateApiKey', { provider, apiKey, baseUrl }).catch(() => null);
+ if (result?.valid) validated.current = fingerprint;
+ if (result?.valid && result.models?.length) setModels(result.models);
+ setStatus(result?.valid ? 'valid' : result?.reason === 'rejected' ? 'rejected' : 'unreachable');
+ }, []);
+
+ return { status, setStatus, models, check };
+}
+
+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>;
+ }
+ return null;
+}
+
+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>
+ );
+}