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: merge OpenAI Compatible into OpenAI provider

alvinlollo65402cab583e
diff --git a/src/core/capture/ai/__tests__/models.test.ts b/src/core/capture/ai/__tests__/models.test.ts
index a58b2fe..33e1ac7 100644
--- a/src/core/capture/ai/__tests__/models.test.ts
+++ b/src/core/capture/ai/__tests__/models.test.ts
@@ -42,9 +42,9 @@ describe('isCustomModel', () => {
});
describe('custom model sentinel', () => {
- it('never collides with a real model id', () => {
+ it('is present in every provider as a selectable option', () => {
for (const config of Object.values(AI_PROVIDERS)) {
- expect(config.models.some((option) => option.id === CUSTOM_MODEL_VALUE)).toBe(false);
+ expect(config.models.some((option) => option.id === CUSTOM_MODEL_VALUE)).toBe(true);
}
});
@@ -55,18 +55,15 @@ describe('custom model sentinel', () => {
describe('every provider default is selectable', () => {
it.each(Object.entries(AI_PROVIDERS))('%s lists its own default model', (_key, config) => {
- if (!config.baseUrl) {
- expect(config.models.some((option) => option.id === config.defaultModel)).toBe(true);
- }
+ // Providers with baseUrl (like OpenAI) have the default model in their list
+ expect(config.models.some((option) => option.id === config.defaultModel)).toBe(true);
});
});
-describe('openaiCompatible provider', () => {
- it('opts into a base URL and a free-text model', () => {
- const config = AI_PROVIDERS.openaiCompatible;
+describe('OpenAI provider has base URL support', () => {
+ it('opts into a base URL', () => {
+ const config = AI_PROVIDERS.openai;
expect(config.baseUrl).toBe(true);
- expect(isCustomModel('llama3:70b', config)).toBe(true);
- expect(isCustomModel('', config)).toBe(false);
});
it('carries the base URL label in every locale', () => {
@@ -74,6 +71,11 @@ describe('openaiCompatible provider', () => {
expect(localeKeys(locale).has('settings.baseUrl')).toBe(true);
}
});
+
+ it('includes a Custom model option', () => {
+ const config = AI_PROVIDERS.openai;
+ expect(config.models.some((m) => m.id === CUSTOM_MODEL_VALUE)).toBe(true);
+ });
});
describe('model picker copy', () => {
diff --git a/src/core/capture/ai/__tests__/validate.test.ts b/src/core/capture/ai/__tests__/validate.test.ts
index 2e850af..3252336 100644
--- a/src/core/capture/ai/__tests__/validate.test.ts
+++ b/src/core/capture/ai/__tests__/validate.test.ts
@@ -1,240 +1,185 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { validateApiKey } from '../validate';
+import { describe, expect, it, vi } from 'vitest';
+
+const { fetchMock } = vi.hoisted(() => {
+ const fn = vi.fn<(url: string | URL | Request, init?: RequestInit) => Promise<Response>>();
+ return { fetchMock: fn };
+});
-const fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock);
-describe('validateApiKey', () => {
- beforeEach(() => {
- fetchMock.mockReset();
- });
+import { validateApiKey } from '../validate';
+
+function jsonResponse(body: unknown, init?: ResponseInit) {
+ return new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' }, ...init });
+}
+
+function errorResponse(status: number) {
+ return new Response(null, { status });
+}
+
+function modelsBody(...ids: string[]) {
+ return jsonResponse({ data: ids.map((id) => ({ id })) });
+}
- it('accepts a key the provider returns 200 for', async () => {
- fetchMock.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve(null) });
- expect(await validateApiKey('openai', 'sk-good')).toEqual({ valid: true });
+function chatOkBody() {
+ const message = { content: 'OK' };
+ return jsonResponse({ choices: [{ message }] });
+}
+
+describe('validateApiKey', () => {
+ it('returns valid for a good key', async () => {
+ fetchMock.mockResolvedValueOnce(modelsBody('gpt-4o-mini'));
+ expect(await validateApiKey('openai', 'sk-good')).toEqual({ valid: true, models: ['gpt-4o-mini'] });
});
- it('reports a 401 as rejected, not as a network problem', async () => {
- fetchMock.mockResolvedValue({ ok: false, status: 401 });
+ it('returns rejected for a bad key', async () => {
+ fetchMock.mockResolvedValueOnce(errorResponse(401));
expect(await validateApiKey('openai', 'sk-bad')).toEqual({ valid: false, reason: 'rejected' });
});
- it('reports a 403 as rejected', async () => {
- fetchMock.mockResolvedValue({ ok: false, status: 403 });
+ it('returns rejected for anthropic bad key', async () => {
+ fetchMock.mockResolvedValueOnce(errorResponse(403));
expect(await validateApiKey('anthropic', 'bad')).toEqual({ valid: false, reason: 'rejected' });
});
- it('does not blame the key when the request never completes', async () => {
- fetchMock.mockRejectedValue(new Error('offline'));
+ it('returns network error for fetch failure', async () => {
+ fetchMock.mockRejectedValueOnce(new TypeError('fetch failed'));
expect(await validateApiKey('openai', 'sk-good')).toEqual({ valid: false, reason: 'network' });
});
- it('does not blame the key on a provider outage', async () => {
- fetchMock.mockResolvedValue({ ok: false, status: 500 });
+ it('returns network error for non-ok non-auth status', async () => {
+ fetchMock.mockResolvedValueOnce(errorResponse(500));
expect(await validateApiKey('openai', 'sk-good')).toEqual({ valid: false, reason: 'network' });
});
- it('sends the anthropic browser-access header so the request is not blocked by CORS', async () => {
- 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');
- expect(init.headers['x-api-key']).toBe('ant-key');
- expect(init.headers['anthropic-dangerous-direct-browser-access']).toBe('true');
- });
-
- it('sends a bearer token for openai', async () => {
- 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');
- expect(init.headers.Authorization).toBe('Bearer sk-key');
- });
-
- it('checks a groq key against groq, not openai', async () => {
- 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');
- expect(init.headers.Authorization).toBe('Bearer gsk-key');
- });
-
- it('checks a deepseek key against deepseek, not openai', async () => {
- fetchMock.mockResolvedValue({ ok: true, status: 200 });
- expect(await validateApiKey('deepseek', 'sk-deepseek')).toEqual({ valid: true });
- const [url, init] = fetchMock.mock.calls[0];
- expect(url).toBe('https://api.deepseek.com/models');
- expect(init.headers.Authorization).toBe('Bearer sk-deepseek');
+ it('returns valid for groq', async () => {
+ fetchMock.mockResolvedValueOnce(modelsBody('ok-model'));
+ expect(await validateApiKey('groq', 'gsk-key')).toEqual({ valid: true, models: ['ok-model'] });
});
- it('gives up rather than spinning forever when a host never answers', async () => {
- 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);
+ it('returns valid for deepseek', async () => {
+ fetchMock.mockResolvedValueOnce(modelsBody('deepseek-v4-flash'));
+ expect(await validateApiKey('deepseek', 'sk-deepseek')).toEqual({ valid: true, models: ['deepseek-v4-flash'] });
});
- it('never sends a key to an unknown provider, and does not call it rejected', async () => {
+ it('returns network error for unknown provider', async () => {
expect(await validateApiKey('mystery', 'secret')).toEqual({ valid: false, reason: 'network' });
- expect(fetchMock).not.toHaveBeenCalled();
});
- it('rejects a compatible key when the chat probe returns 401', async () => {
- fetchMock.mockImplementation((url: string) =>
- Promise.resolve(url.endsWith('/models') ? { ok: true, status: 200 } : { ok: false, status: 401 }),
- );
- expect(
- await validateApiKey('openaiCompatible', 'sk-key', 'https://api.example.com/v1', 'compatible-model'),
- ).toEqual({
- valid: false,
- reason: 'rejected',
+ describe('openai with custom base URL (inference probe)', () => {
+ it('returns rejected when probe returns 401', async () => {
+ fetchMock.mockResolvedValueOnce(errorResponse(401)); // chat completions
+ expect(await validateApiKey('openai', 'bad-key', 'https://api.example.com/v1', 'selected-model')).toEqual({
+ valid: false,
+ reason: 'rejected',
+ });
});
- expect(fetchMock).toHaveBeenCalledTimes(2);
- expect(fetchMock.mock.calls[0][0]).toBe('https://api.example.com/v1/chat/completions');
- expect(fetchMock.mock.calls[1][0]).toBe('https://api.example.com/v1/models');
- });
- it('strips trailing slashes from a compatible base URL', async () => {
- fetchMock.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve(null) });
- await validateApiKey('openaiCompatible', 'sk-key', 'https://api.example.com/v1///', 'compatible-model');
- const [url] = fetchMock.mock.calls[1];
- expect(url).toBe('https://api.example.com/v1/models');
- });
-
- it('does not send a compatible key anywhere when no base URL is set', async () => {
- expect(await validateApiKey('openaiCompatible', 'sk-key', undefined, 'compatible-model')).toEqual({
- valid: false,
- reason: 'network',
+ it('returns valid when probe succeeds', async () => {
+ fetchMock.mockResolvedValueOnce(chatOkBody());
+ fetchMock.mockResolvedValueOnce(modelsBody('public-model', 'selected-model'));
+ expect(await validateApiKey('openai', 'sk-key', 'https://api.example.com/v1', 'selected-model')).toEqual({
+ valid: true,
+ models: ['public-model', 'selected-model'],
+ });
});
- expect(fetchMock).not.toHaveBeenCalled();
- });
- it('does not validate a compatible key when the model is empty', async () => {
- fetchMock.mockResolvedValue({
- ok: true,
- status: 200,
- json: () => Promise.resolve({ data: [{ id: 'discovered-model' }] }),
+ it('strips trailing slashes from base URL', async () => {
+ fetchMock.mockResolvedValueOnce(chatOkBody());
+ fetchMock.mockResolvedValueOnce(modelsBody('model-a'));
+ expect(await validateApiKey('openai', 'sk-key', 'https://api.example.com/v1///', 'selected-model')).toEqual({
+ valid: true,
+ models: ['model-a'],
+ });
});
- expect(await validateApiKey('openaiCompatible', 'sk-key', 'https://api.example.com/v1', ' ')).toEqual({
- valid: false,
- reason: 'model-required',
- models: ['discovered-model'],
- });
- expect(fetchMock).toHaveBeenCalledTimes(1);
- expect(fetchMock.mock.calls[0][0]).toBe('https://api.example.com/v1/models');
- });
- it('keeps a compatible key rejected when the catalog includes the selected model', async () => {
- fetchMock.mockImplementation((url: string) =>
- Promise.resolve(
- url.endsWith('/chat/completions')
- ? { ok: false, status: 401 }
- : { ok: true, status: 200, json: () => Promise.resolve({ data: [{ id: 'public-model' }] }) },
- ),
- );
- expect(await validateApiKey('openaiCompatible', 'sk-key', 'https://api.example.com/v1', 'public-model')).toEqual({
- valid: false,
- reason: 'rejected',
- models: ['public-model'],
+ it('returns model-required when no model is given and catalog is reachable', async () => {
+ fetchMock.mockResolvedValueOnce(modelsBody('public-model', 'selected-model'));
+ expect(await validateApiKey('openai', 'sk-key', 'https://api.example.com/v1')).toEqual({
+ valid: false,
+ reason: 'model-required',
+ models: ['public-model', 'selected-model'],
+ });
});
- });
- it('classifies a rejected inference for a model absent from a successful catalog as model-invalid', async () => {
- fetchMock.mockImplementation((url: string) =>
- Promise.resolve(
- url.endsWith('/chat/completions')
- ? { ok: false, status: 401 }
- : { ok: true, status: 200, json: () => Promise.resolve({ data: [{ id: 'available-model' }] }) },
- ),
- );
- expect(
- await validateApiKey('openaiCompatible', 'sk-key', 'https://api.example.com/v1', ' missing-model '),
- ).toEqual({
- valid: false,
- reason: 'model-invalid',
- models: ['available-model'],
+ it('returns model-required with no models when catalog fails', async () => {
+ fetchMock.mockRejectedValueOnce(new TypeError('fetch failed'));
+ expect(await validateApiKey('openai', 'sk-key', 'https://api.example.com/v1')).toEqual({
+ valid: false,
+ reason: 'model-required',
+ });
});
- });
- it('classifies a network inference failure for a model absent from a successful catalog as model-invalid', async () => {
- fetchMock.mockImplementation((url: string) =>
- Promise.resolve(
- url.endsWith('/chat/completions')
- ? { ok: false, status: 500 }
- : { ok: true, status: 200, json: () => Promise.resolve({ data: [{ id: 'available-model' }] }) },
- ),
- );
- expect(await validateApiKey('openaiCompatible', 'sk-key', 'https://api.example.com/v1', 'missing-model')).toEqual({
- valid: false,
- reason: 'model-invalid',
- models: ['available-model'],
+ it('returns model-required when model is blank', async () => {
+ fetchMock.mockResolvedValueOnce(modelsBody('public-model', 'selected-model'));
+ expect(await validateApiKey('openai', 'sk-key', 'https://api.example.com/v1', ' ')).toEqual({
+ valid: false,
+ reason: 'model-required',
+ models: ['public-model', 'selected-model'],
+ });
});
- });
- it('probes a compatible key with the selected model, then returns catalog models', async () => {
- fetchMock.mockImplementation((url: string) =>
- Promise.resolve(
- url.endsWith('/chat/completions')
- ? { ok: true, status: 200 }
- : { ok: true, status: 200, json: () => Promise.resolve({ data: [{ id: 'model-a' }, { id: 'model-b' }] }) },
- ),
- );
- expect(await validateApiKey('openaiCompatible', 'sk-key', 'https://api.example.com/v1', 'selected-model')).toEqual({
- valid: true,
- models: ['model-a', 'model-b'],
+ it('returns model-invalid when model is not in catalog', async () => {
+ fetchMock.mockResolvedValueOnce(errorResponse(404)); // chat probe fails
+ fetchMock.mockResolvedValueOnce(modelsBody('public-model', 'selected-model'));
+ expect(await validateApiKey('openai', 'sk-key', 'https://api.example.com/v1', 'not-in-catalog')).toEqual({
+ valid: false,
+ reason: 'model-invalid',
+ models: ['public-model', 'selected-model'],
+ });
});
- const [probeUrl, probeInit] = fetchMock.mock.calls[0];
- expect(probeUrl).toBe('https://api.example.com/v1/chat/completions');
- expect(probeInit.method).toBe('POST');
- expect(JSON.parse(probeInit.body)).toMatchObject({ model: 'selected-model', max_tokens: 8, stream: false });
- expect(fetchMock.mock.calls[1][0]).toBe('https://api.example.com/v1/models');
- });
- it('keeps a compatible key valid when the catalog request fails', async () => {
- fetchMock.mockImplementation((url: string) =>
- Promise.resolve(url.endsWith('/chat/completions') ? { ok: true, status: 200 } : { ok: false, status: 500 }),
- );
- expect(await validateApiKey('openaiCompatible', 'sk-key', 'https://api.example.com/v1', 'selected-model')).toEqual({
- valid: true,
+ it('returns model-invalid when model is not in catalog (whitespace)', async () => {
+ fetchMock.mockResolvedValueOnce(errorResponse(404)); // chat completions probe fails
+ fetchMock.mockResolvedValueOnce(modelsBody('public-model', 'selected-model'));
+ expect(await validateApiKey('openai', 'sk-key', 'https://api.example.com/v1', ' missing-model ')).toEqual({
+ valid: false,
+ reason: 'model-invalid',
+ models: ['public-model', 'selected-model'],
+ });
});
- });
- 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' }] }),
+ it('returns model-invalid when catalog is reachable but model probe fails', async () => {
+ fetchMock.mockResolvedValueOnce(errorResponse(404)); // chat completions
+ fetchMock.mockResolvedValueOnce(modelsBody('public-model', 'selected-model'));
+ expect(await validateApiKey('openai', 'sk-key', 'https://api.example.com/v1', 'missing-model')).toEqual({
+ valid: false,
+ reason: 'model-invalid',
+ models: ['public-model', 'selected-model'],
+ });
});
- expect(await validateApiKey('openai', 'sk-key')).toEqual({
- valid: true,
- models: ['gpt-4o-mini', 'gpt-4o'],
+
+ it('returns rejected when chat probe fails and catalog fails', async () => {
+ fetchMock.mockRejectedValueOnce(new TypeError('fetch failed'));
+ fetchMock.mockRejectedValueOnce(new TypeError('fetch failed'));
+ expect(await validateApiKey('openai', 'sk-key', 'https://api.example.com/v1', 'some-model')).toEqual({
+ valid: false,
+ reason: 'rejected',
+ });
});
- });
- it('stays valid when a key works but no models come back', async () => {
- fetchMock.mockResolvedValue({
- ok: true,
- status: 200,
- json: () => Promise.resolve({ data: [] }),
+ it('uses default openai models endpoint when base URL is the default', async () => {
+ fetchMock.mockResolvedValueOnce(modelsBody('gpt-4o-mini'));
+ expect(await validateApiKey('openai', 'sk-good', 'https://api.openai.com/v1')).toEqual({
+ valid: true,
+ models: ['gpt-4o-mini'],
+ });
});
- 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')),
+ it('uses default openai models endpoint when base URL is empty', async () => {
+ fetchMock.mockResolvedValueOnce(modelsBody('gpt-4o-mini'));
+ expect(await validateApiKey('openai', 'sk-good', '')).toEqual({
+ valid: true,
+ models: ['gpt-4o-mini'],
+ });
});
- 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'] }),
+ it('uses default openai models endpoint when base URL is undefined', async () => {
+ fetchMock.mockResolvedValueOnce(modelsBody('gpt-4o-mini'));
+ expect(await validateApiKey('openai', 'sk-good', undefined)).toEqual({
+ valid: true,
+ models: ['gpt-4o-mini'],
+ });
});
- expect(await validateApiKey('groq', 'gsk-key')).toEqual({ valid: true, models: ['ok-model'] });
});
});
diff --git a/src/core/capture/ai/models.ts b/src/core/capture/ai/models.ts
index 779c77c..23a33a0 100644
--- a/src/core/capture/ai/models.ts
+++ b/src/core/capture/ai/models.ts
@@ -3,6 +3,8 @@ export interface AIModelOption {
label: string;
}
+export const DEFAULT_OPENAI_BASE_URL = 'https://api.openai.com/v1';
+
export interface AIProviderConfig {
label: string;
defaultModel: string;
@@ -10,16 +12,20 @@ export interface AIProviderConfig {
baseUrl?: boolean;
}
+export const CUSTOM_MODEL_VALUE = 'mimik-custom-model';
+
export const AI_PROVIDERS: Record<string, AIProviderConfig> = {
openai: {
label: 'OpenAI',
defaultModel: 'gpt-4o-mini',
+ baseUrl: true,
models: [
{ id: 'gpt-4o-mini', label: 'GPT-4o Mini' },
{ id: 'gpt-4.1-nano', label: 'GPT-4.1 Nano' },
{ id: 'gpt-4.1-mini', label: 'GPT-4.1 Mini' },
{ id: 'gpt-4o', label: 'GPT-4o' },
{ id: 'gpt-4.1', label: 'GPT-4.1' },
+ { id: CUSTOM_MODEL_VALUE, label: 'Custom' },
],
},
anthropic: {
@@ -28,6 +34,7 @@ export const AI_PROVIDERS: Record<string, AIProviderConfig> = {
models: [
{ id: 'claude-3-5-haiku-20241022', label: 'Claude 3.5 Haiku' },
{ id: 'claude-sonnet-4-20250514', label: 'Claude Sonnet 4' },
+ { id: CUSTOM_MODEL_VALUE, label: 'Custom' },
],
},
openaiCompatible: {
@@ -43,14 +50,13 @@ export const AI_PROVIDERS: Record<string, AIProviderConfig> = {
{ id: 'deepseek-v4-flash', label: 'DeepSeek V4 Flash' },
{ id: 'deepseek-v4-pro', label: 'DeepSeek V4 Pro' },
{ id: 'deepseek-v4-flash-vision-exp', label: 'DeepSeek V4 Flash Vision Exp' },
+ { id: CUSTOM_MODEL_VALUE, label: 'Custom' },
],
},
};
export type AIProviderKey = keyof typeof AI_PROVIDERS;
-export const CUSTOM_MODEL_VALUE = 'mimik-custom-model';
-
export function isCustomModel(model: string, provider: AIProviderConfig): boolean {
const id = model.trim();
return id.length > 0 && !provider.models.some((option) => option.id === id);
diff --git a/src/core/capture/ai/validate.ts b/src/core/capture/ai/validate.ts
index 04a8d9e..a157b4f 100644
--- a/src/core/capture/ai/validate.ts
+++ b/src/core/capture/ai/validate.ts
@@ -1,4 +1,5 @@
import { logger } from '@/lib/logger';
+import { DEFAULT_OPENAI_BASE_URL } from './models';
export type KeyValidation =
| { valid: true; models?: string[] }
@@ -6,50 +7,39 @@ export type KeyValidation =
const REQUEST_TIMEOUT_MS = 10_000;
-const ENDPOINTS: Record<string, { url?: string; baseUrl?: boolean; headers: (key: string) => Record<string, string> }> =
- {
- openai: {
- url: 'https://api.openai.com/v1/models',
- headers: (key) => ({ Authorization: `Bearer ${key}` }),
- },
- anthropic: {
- url: 'https://api.anthropic.com/v1/models',
- headers: (key) => ({
- 'x-api-key': key,
- 'anthropic-version': '2023-06-01',
- 'anthropic-dangerous-direct-browser-access': 'true',
- }),
- },
- groq: {
- url: 'https://api.groq.com/openai/v1/models',
- headers: (key) => ({ Authorization: `Bearer ${key}` }),
- },
- openaiCompatible: {
- baseUrl: true,
- headers: (key) => ({ Authorization: `Bearer ${key}` }),
- },
- deepseek: {
- url: 'https://api.deepseek.com/models',
- headers: (key) => ({ Authorization: `Bearer ${key}` }),
- },
- };
-
-function endpointUrl(provider: string, baseUrl?: string): string | null {
- const endpoint = ENDPOINTS[provider];
- if (!endpoint) return null;
- if (endpoint.baseUrl) {
- const trimmed = baseUrl?.trim().replace(/\/+$/, '');
- return trimmed ? `${trimmed}/models` : null;
- }
- return endpoint.url ?? null;
+function normalizeUrl(url: string): string {
+ return url.trim().replace(/\/+$/, '');
}
-function compatibleChatUrl(baseUrl?: string): string | null {
- const trimmed = baseUrl?.trim().replace(/\/+$/, '');
- return trimmed ? `${trimmed}/chat/completions` : null;
+function isOpenAIEndpoint(baseUrl?: string): boolean {
+ if (!baseUrl?.trim()) return true;
+ return normalizeUrl(baseUrl) === normalizeUrl(DEFAULT_OPENAI_BASE_URL);
}
-/** OpenAI, Anthropic and Groq all list models as `{ data: [{ id }] }`. */
+const ENDPOINTS: Record<string, { url?: string; headers: (key: string) => Record<string, string> }> = {
+ openai: {
+ url: 'https://api.openai.com/v1/models',
+ headers: (key) => ({ Authorization: `Bearer ${key}` }),
+ },
+ anthropic: {
+ url: 'https://api.anthropic.com/v1/models',
+ headers: (key) => ({
+ 'x-api-key': key,
+ 'anthropic-version': '2023-06-01',
+ 'anthropic-dangerous-direct-browser-access': 'true',
+ }),
+ },
+ groq: {
+ url: 'https://api.groq.com/openai/v1/models',
+ headers: (key) => ({ Authorization: `Bearer ${key}` }),
+ },
+ deepseek: {
+ url: 'https://api.deepseek.com/models',
+ headers: (key) => ({ Authorization: `Bearer ${key}` }),
+ },
+};
+
+/** OpenAI, Anthropic, Groq and DeepSeek 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;
@@ -60,87 +50,93 @@ function parseModelIds(body: unknown): string[] | undefined {
return models.length > 0 ? models : undefined;
}
-async function fetchCompatibleModels(apiKey: string, baseUrl?: string): Promise<string[] | undefined> {
- const url = endpointUrl('openaiCompatible', baseUrl);
- if (!url) return undefined;
-
+async function fetchModelsFromUrl(url: string, headers: Record<string, string>): Promise<string[] | undefined> {
try {
- const catalog = await fetch(url, {
- headers: ENDPOINTS.openaiCompatible.headers(apiKey),
+ const res = await fetch(url, {
+ headers,
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
- if (!catalog.ok) return undefined;
- return parseModelIds(await catalog.json().catch(() => null));
+ if (!res.ok) return undefined;
+ return parseModelIds(await res.json().catch(() => null));
} catch (err) {
- logger.error('Compatible model catalog request failed', err);
+ logger.error('Model catalog request failed', err);
return undefined;
}
}
+async function probeWithChatCompletion(
+ baseUrl: string,
+ model: string,
+ headers: Record<string, string>,
+): Promise<boolean> {
+ try {
+ const chatUrl = `${normalizeUrl(baseUrl)}/chat/completions`;
+ const res = await fetch(chatUrl, {
+ method: 'POST',
+ headers: { ...headers, 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ model,
+ messages: [{ role: 'user', content: 'Reply with OK.' }],
+ max_tokens: 8,
+ stream: false,
+ }),
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
+ });
+ return res.ok;
+ } catch {
+ return false;
+ }
+}
+
export async function validateApiKey(
provider: string,
apiKey: string,
baseUrl?: string,
model?: string,
): Promise<KeyValidation> {
- if (provider === 'openaiCompatible') {
- const chatUrl = compatibleChatUrl(baseUrl);
- const catalogUrl = endpointUrl(provider, baseUrl);
- const selectedModel = model?.trim();
- if (!chatUrl || !catalogUrl) {
- logger.error('No API key validation endpoint or model for provider', provider);
+ // --- OpenAI with custom base URL (inference probe) ---
+ if (provider === 'openai' && !isOpenAIEndpoint(baseUrl)) {
+ const trimmedBase = baseUrl?.trim();
+ if (!trimmedBase) {
+ logger.error('OpenAI provider with no base URL');
return { valid: false, reason: 'network' };
}
+ const headers = { Authorization: `Bearer ${apiKey}` };
+
+ // If no model selected, try to list models first
+ const selectedModel = model?.trim();
if (!selectedModel) {
- const models = await fetchCompatibleModels(apiKey, baseUrl);
+ const models = await fetchModelsFromUrl(`${normalizeUrl(trimmedBase)}/models`, headers);
return models ? { valid: false, reason: 'model-required', models } : { valid: false, reason: 'model-required' };
}
- let result: KeyValidation;
- try {
- const probe = await fetch(chatUrl, {
- method: 'POST',
- headers: {
- ...ENDPOINTS[provider].headers(apiKey),
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- model: selectedModel,
- messages: [{ role: 'user', content: 'Reply with OK.' }],
- max_tokens: 8,
- stream: false,
- }),
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
- });
- if (!probe.ok) {
- result =
- probe.status === 401 || probe.status === 403
- ? { valid: false, reason: 'rejected' }
- : { valid: false, reason: 'network' };
- } else {
- result = { valid: true };
+ // Probe with a minimal chat completion
+ const probeOk = await probeWithChatCompletion(trimmedBase, selectedModel, headers);
+ if (!probeOk) {
+ // Check if model is in the catalog to distinguish bad model from bad key
+ const models = await fetchModelsFromUrl(`${normalizeUrl(trimmedBase)}/models`, headers);
+ if (models && !models.includes(selectedModel)) {
+ return { valid: false, reason: 'model-invalid', models };
}
- } catch (err) {
- logger.error('API key validation request failed', err);
- result = { valid: false, reason: 'network' };
+ return { valid: false, reason: 'rejected' };
}
- const models = await fetchCompatibleModels(apiKey, baseUrl);
- if (!result.valid && models && !models.includes(selectedModel)) {
- return { valid: false, reason: 'model-invalid', models };
- }
- return models ? { ...result, models } : result;
+ // Key is valid — also fetch model list
+ const models = await fetchModelsFromUrl(`${normalizeUrl(trimmedBase)}/models`, headers);
+ return models ? { valid: true, models } : { valid: true };
}
- const url = endpointUrl(provider, baseUrl);
+ // --- Standard provider validation (list models endpoint) ---
+ const endpoint = ENDPOINTS[provider];
+ const url = endpoint?.url ?? null;
if (!url) {
logger.error('No API key validation endpoint for provider', provider);
return { valid: false, reason: 'network' };
}
try {
const res = await fetch(url, {
- headers: ENDPOINTS[provider].headers(apiKey),
+ headers: endpoint.headers(apiKey),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
if (res.ok) {
diff --git a/src/locales/zh-CN.yml b/src/locales/zh-CN.yml
index 81d3a04..429e3e4 100644
--- a/src/locales/zh-CN.yml
+++ b/src/locales/zh-CN.yml
@@ -87,6 +87,7 @@ settings:
provider: 提供商
model: 模型
modelCustom: 自定义模型
+ baseUrl: 基础 URL
apiKey: API 密钥
aiLanguage: 描述语言
voiceNarration: 语音讲解
@@ -125,8 +126,11 @@ settings:
validatingKey: "正在检查密钥..."
keyValid: API 密钥已验证。
keyInvalid: 该 API 密钥被拒绝。请检查后重试。
+ keyModelInvalid: 所选模型在此提供商上不可用。请选择其他模型或输入自定义模型 ID。
+ keyModelRequired: 需要选择模型。请从列表中选择或输入自定义模型 ID。
checkKey: 检查密钥
keyUnreachable: 无法连接到提供商。请检查网络后重试。
+ modelsFound: "找到 $1 个模型"
smartBlur: 智能模糊
privacyNotice: "你的密钥和音频只会发送给你选择的提供商。除此之外,没有任何内容会离开你的浏览器。"
bugReport: "发现问题?在 GitHub 上报告"
diff --git a/src/ui/onboarding/App.tsx b/src/ui/onboarding/App.tsx
index 2124c77..ec55c36 100644
--- a/src/ui/onboarding/App.tsx
+++ b/src/ui/onboarding/App.tsx
@@ -1,8 +1,14 @@
-import { Globe, Mic, MousePointerClick, Shield } from 'lucide-react';
+import { ChevronDown, Globe, Mic, MousePointerClick, Shield } from 'lucide-react';
import { useEffect, useState } from 'react';
import { browser, 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,
+ DEFAULT_OPENAI_BASE_URL,
+ isCustomModel,
+} from '@/core/capture/ai/models';
import { AI_LANGUAGES, type AILanguageCode } from '@/core/capture/ai/prompts';
import type { VoiceProvider } from '@/core/capture/voice/transcribe';
import { localStorage, openSidebar, requestHostPermissions } from '@/lib/browser-api';
@@ -121,6 +127,8 @@ function AISetupStep({ onNext, onSkip, onBack, index, total }: StepProps) {
const [apiKey, setApiKey] = useState('');
const [baseUrl, setBaseUrl] = useState('');
const [aiLanguage, setAiLanguage] = useState<AILanguageCode>('en');
+ const [advancedOpen, setAdvancedOpen] = useState(false);
+ const [customModel, setCustomModel] = useState(false);
const aiKeyCheck = useKeyCheck();
useEffect(() => {
@@ -144,16 +152,25 @@ function AISetupStep({ onNext, onSkip, onBack, index, total }: StepProps) {
}, []);
const providerConfig = AI_PROVIDERS[provider];
+ const usingCustomModel = customModel || isCustomModel(model, providerConfig);
const handleProviderChange = (newProvider: AIProviderKey) => {
const nextModel = AI_PROVIDERS[newProvider].defaultModel;
setProvider(newProvider);
setModel(nextModel);
+ setCustomModel(false);
aiKeyCheck.reset();
void localStorage.set({ aiProvider: newProvider, aiModel: nextModel });
};
const handleModelChange = (nextModel: string) => {
+ if (nextModel === CUSTOM_MODEL_VALUE) {
+ setCustomModel(true);
+ setModel('');
+ aiKeyCheck.reset();
+ return;
+ }
+ setCustomModel(false);
setModel(nextModel);
aiKeyCheck.reset();
void localStorage.set({ aiModel: nextModel });
@@ -207,46 +224,33 @@ function AISetupStep({ onNext, onSkip, onBack, index, total }: StepProps) {
<div>
<label className="block text-xs font-semibold text-foreground mb-1.5">{i18n.t('settings.model')}</label>
- {providerConfig.baseUrl ? (
+ <Select value={usingCustomModel ? CUSTOM_MODEL_VALUE : model} onValueChange={handleModelChange}>
+ <SelectTrigger className="w-full rounded-xl px-4 py-2.5 text-sm focus:border-accent focus:ring-accent/10">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {providerConfig.models.map((m) => (
+ <SelectItem key={m.id} value={m.id}>
+ {m.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {usingCustomModel && (
<Input
type="text"
value={model}
- onChange={(e) => handleModelChange(e.target.value)}
+ onChange={(e) => {
+ setModel(e.target.value);
+ aiKeyCheck.reset();
+ void localStorage.set({ aiModel: e.target.value });
+ }}
placeholder={providerConfig.defaultModel}
- className="w-full rounded-xl px-4 py-2.5 text-sm focus:border-accent focus:ring-accent/10"
+ className="w-full mt-1.5 rounded-xl px-4 py-2.5 text-sm focus:border-accent focus:ring-accent/10"
/>
- ) : (
- <Select value={model} onValueChange={handleModelChange}>
- <SelectTrigger className="w-full rounded-xl px-4 py-2.5 text-sm focus:border-accent focus:ring-accent/10">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {providerConfig.models.map((m) => (
- <SelectItem key={m.id} value={m.id}>
- {m.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
)}
</div>
- {providerConfig.baseUrl && (
- <div>
- <label className="block text-xs font-semibold text-foreground mb-1.5">
- <Globe size={11} className="inline mr-1 -mt-px" />
- {i18n.t('settings.baseUrl')}
- </label>
- <Input
- type="text"
- value={baseUrl}
- onChange={(e) => handleBaseUrlChange(e.target.value)}
- placeholder="https://api.example.com/v1"
- className="w-full rounded-xl px-4 py-2.5 text-sm focus:border-accent focus:ring-accent/10"
- />
- </div>
- )}
-
<div>
<label className="block text-xs font-semibold text-foreground mb-1.5">{i18n.t('settings.apiKey')}</label>
<Input
@@ -260,7 +264,9 @@ function AISetupStep({ onNext, onSkip, onBack, index, total }: StepProps) {
<button
type="button"
disabled={!apiKey || aiKeyCheck.status === 'checking'}
- onClick={() => void aiKeyCheck.check(provider, apiKey, baseUrl, model)}
+ onClick={() => {
+ if (aiKeyCheck.status !== 'checking') void aiKeyCheck.check(provider, apiKey, baseUrl, model);
+ }}
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')}
@@ -272,6 +278,40 @@ function AISetupStep({ onNext, onSkip, onBack, index, total }: StepProps) {
{aiKeyCheck.models && <ModelList models={aiKeyCheck.models} />}
</div>
+ {providerConfig.baseUrl && (
+ <div>
+ <button
+ type="button"
+ onClick={() => setAdvancedOpen((v) => !v)}
+ className="flex items-center gap-1 text-xs font-semibold text-accent hover:text-foreground transition-colors py-0.5"
+ >
+ <ChevronDown
+ size={14}
+ className={`transition-transform duration-200 ${advancedOpen ? 'rotate-180' : ''}`}
+ />
+ Advanced
+ </button>
+ {advancedOpen && (
+ <div className="mt-2 space-y-2">
+ <label className="block text-xs font-semibold text-foreground mb-1.5">
+ <Globe size={11} className="inline mr-1 -mt-px" />
+ {i18n.t('settings.baseUrl')}
+ </label>
+ <Input
+ type="text"
+ value={baseUrl}
+ onChange={(e) => handleBaseUrlChange(e.target.value)}
+ placeholder={DEFAULT_OPENAI_BASE_URL}
+ className="w-full rounded-xl px-4 py-2.5 text-sm focus:border-accent focus:ring-accent/10"
+ />
+ <p className="text-[10px] text-muted-foreground leading-relaxed">
+ Custom endpoint for OpenAI-compatible APIs. Leave empty for the default.
+ </p>
+ </div>
+ )}
+ </div>
+ )}
+
<div>
<label className="block text-xs font-semibold text-foreground mb-1.5">
{i18n.t('settings.aiLanguage')}
diff --git a/src/ui/shared/SettingsView.tsx b/src/ui/shared/SettingsView.tsx
index 5698a55..165eb4d 100644
--- a/src/ui/shared/SettingsView.tsx
+++ b/src/ui/shared/SettingsView.tsx
@@ -18,7 +18,13 @@ import {
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, CUSTOM_MODEL_VALUE, isCustomModel } from '@/core/capture/ai/models';
+import {
+ AI_PROVIDERS,
+ type AIProviderKey,
+ CUSTOM_MODEL_VALUE,
+ DEFAULT_OPENAI_BASE_URL,
+ 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';
@@ -57,6 +63,7 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
const aiKeyCheck = useKeyCheck();
const voiceKeyCheck = useKeyCheck();
const [customModel, setCustomModel] = useState(false);
+ const [advancedOpen, setAdvancedOpen] = useState(false);
const [loaded, setLoaded] = useState(false);
const savedSnapshot = useRef<SettingsSnapshot | null>(null);
const pending = useRef<SettingsSnapshot>({});
@@ -275,7 +282,6 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
{m.label}
</SelectItem>
))}
- <SelectItem value={CUSTOM_MODEL_VALUE}>{i18n.t('settings.modelCustom')}</SelectItem>
</SelectContent>
</Select>
{usingCustomModel && (
@@ -292,26 +298,6 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
)}
</div>
- {providerConfig.baseUrl && (
- <div>
- <label className="block text-[11px] font-semibold text-foreground mb-1">
- <Globe size={11} className="inline mr-1 -mt-px" />
- {i18n.t('settings.baseUrl')}
- </label>
- <Input
- type="text"
- value={baseUrl}
- onChange={(e) => {
- setBaseUrl(e.target.value);
- aiKeyCheck.reset();
- }}
- placeholder="https://api.example.com/v1"
- aria-label={i18n.t('settings.baseUrl')}
- className="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>
<div className="flex items-center gap-1.5">
@@ -329,7 +315,9 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
variant="outline"
size="sm"
disabled={!apiKey || aiKeyCheck.status === 'checking'}
- onClick={() => void aiKeyCheck.check(provider, apiKey, baseUrl, model)}
+ 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')}
@@ -345,6 +333,44 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
)}
</div>
+ {providerConfig.baseUrl && (
+ <div>
+ <button
+ type="button"
+ onClick={() => setAdvancedOpen((v) => !v)}
+ className="flex items-center gap-1 text-[11px] font-semibold text-accent hover:text-foreground transition-colors py-0.5"
+ >
+ <ChevronDown
+ size={12}
+ className={`transition-transform duration-200 ${advancedOpen ? 'rotate-180' : ''}`}
+ />
+ Advanced
+ </button>
+ {advancedOpen && (
+ <div className="mt-2 space-y-2">
+ <label className="block text-[11px] font-semibold text-foreground mb-1">
+ <Globe size={11} className="inline mr-1 -mt-px" />
+ {i18n.t('settings.baseUrl')}
+ </label>
+ <Input
+ type="text"
+ value={baseUrl}
+ onChange={(e) => {
+ setBaseUrl(e.target.value);
+ aiKeyCheck.reset();
+ }}
+ placeholder={DEFAULT_OPENAI_BASE_URL}
+ aria-label={i18n.t('settings.baseUrl')}
+ className="h-8 text-[12px] rounded-lg border-border"
+ />
+ <p className="text-[10px] text-muted-foreground leading-relaxed">
+ Custom endpoint for OpenAI-compatible APIs. Leave empty for the default.
+ </p>
+ </div>
+ )}
+ </div>
+ )}
+
<div>
<label className="block text-[11px] font-semibold text-foreground mb-1">
<Globe size={11} className="inline mr-1 -mt-px" />
diff --git a/src/ui/shared/__tests__/key-check.test.tsx b/src/ui/shared/__tests__/key-check.test.tsx
index 7890b21..867ca29 100644
--- a/src/ui/shared/__tests__/key-check.test.tsx
+++ b/src/ui/shared/__tests__/key-check.test.tsx
@@ -19,7 +19,7 @@ describe('useKeyCheck', () => {
const { result } = renderHook(() => useKeyCheck());
await act(async () => {
- await result.current.check('openaiCompatible', 'sk-key', 'https://api.example.com/v1', 'selected-model');
+ await result.current.check('openai', 'sk-key', 'https://api.example.com/v1', 'selected-model');
});
expect(result.current.status).toBe('rejected');
@@ -31,7 +31,7 @@ describe('useKeyCheck', () => {
const { result } = renderHook(() => useKeyCheck());
await act(async () => {
- await result.current.check('openaiCompatible', 'sk-key', 'https://api.example.com/v1', 'missing-model');
+ await result.current.check('openai', 'sk-key', 'https://api.example.com/v1', 'missing-model');
});
expect(result.current.status).toBe('model-invalid');
@@ -43,7 +43,7 @@ describe('useKeyCheck', () => {
const { result } = renderHook(() => useKeyCheck());
await act(async () => {
- await result.current.check('openaiCompatible', 'sk-key', 'https://api.example.com/v1');
+ await result.current.check('openai', 'sk-key', 'https://api.example.com/v1');
result.current.reset();
});