Skip to content

armgit / mimik

Public Imported from GitHub
0

🎬 A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots πŸ“–

feat(settings): warn when a checked key has no credits to spend

Luis Ortizcbb93b061d37
diff --git a/src/core/capture/ai/__tests__/validate.test.ts b/src/core/capture/ai/__tests__/validate.test.ts
index a8b11e2..58903bd 100644
--- a/src/core/capture/ai/__tests__/validate.test.ts
+++ b/src/core/capture/ai/__tests__/validate.test.ts
@@ -7,7 +7,7 @@ const { fetchMock } = vi.hoisted(() => {
vi.stubGlobal('fetch', fetchMock);
-import { validateApiKey } from '../validate';
+import { spendWarning, validateApiKey } from '../validate';
function jsonResponse(body: unknown, init?: ResponseInit) {
return new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' }, ...init });
@@ -322,4 +322,50 @@ describe('validateApiKey', () => {
expect(fetchMock.mock.calls[0][0]).toBe('https://api.openai.com/v1/models');
});
});
+
+ describe('whether a key can spend', () => {
+ const freeTierKeyBody = {
+ data: {
+ is_free_tier: true,
+ limit: null,
+ limit_remaining: null,
+ usage: 0,
+ rate_limit: { interval: '10s', requests: -1, note: 'This field is deprecated and safe to ignore.' },
+ },
+ };
+
+ it('warns when the account has never bought credits', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse(freeTierKeyBody));
+ fetchMock.mockResolvedValueOnce(modelsBody('openai/gpt-4o-mini'));
+ expect(await validateApiKey('openrouter', 'sk-or-free')).toEqual({
+ valid: true,
+ models: ['openai/gpt-4o-mini'],
+ warning: 'cannot-spend',
+ });
+ });
+
+ it('stays quiet for a funded account', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ data: { is_free_tier: false, limit_remaining: null } }));
+ fetchMock.mockResolvedValueOnce(modelsBody('openai/gpt-4o-mini'));
+ expect(await validateApiKey('openrouter', 'sk-or-paid')).toEqual({
+ valid: true,
+ models: ['openai/gpt-4o-mini'],
+ });
+ });
+
+ it('warns when the key has spent its own cap', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ data: { is_free_tier: false, limit_remaining: 0 } }));
+ fetchMock.mockResolvedValueOnce(modelsBody('openai/gpt-4o-mini'));
+ expect(await validateApiKey('openrouter', 'sk-or-spent')).toMatchObject({ warning: 'cannot-spend' });
+ });
+
+ it('ignores the deprecated rate limit field rather than reading it as a cap', () => {
+ expect(spendWarning({ data: { rate_limit: { requests: -1 } } })).toBeUndefined();
+ });
+
+ it('says nothing about providers that expose no spend information', async () => {
+ fetchMock.mockResolvedValueOnce(modelsBody('gpt-4o-mini'));
+ expect(await validateApiKey('openai', 'sk-good')).toEqual({ valid: true, models: ['gpt-4o-mini'] });
+ });
+ });
});
diff --git a/src/core/capture/ai/validate.ts b/src/core/capture/ai/validate.ts
index 0483db2..c720424 100644
--- a/src/core/capture/ai/validate.ts
+++ b/src/core/capture/ai/validate.ts
@@ -8,8 +8,10 @@ import {
resolveBaseUrl,
} from './models';
+export type KeyWarning = 'cannot-spend';
+
export type KeyValidation =
- | { valid: true; models?: string[] }
+ | { valid: true; models?: string[]; warning?: KeyWarning }
| { valid: false; reason: 'rejected' | 'network' | 'model-required' | 'model-invalid'; models?: string[] };
const REQUEST_TIMEOUT_MS = 10_000;
@@ -54,16 +56,15 @@ async function fetchModelsFromUrl(url: string, headers: Record<string, string>):
}
}
-async function checkCatalog(url: string, headers: Record<string, string>): Promise<KeyValidation> {
+type AuthProbe = { valid: true; body: unknown } | { valid: false; reason: 'rejected' | 'network' };
+
+async function probeAuth(url: string, headers: Record<string, string>): Promise<AuthProbe> {
try {
const res = await fetch(url, {
headers,
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
- if (res.ok) {
- const models = parseModelIds(await res.json().catch(() => null));
- return models ? { valid: true, models } : { valid: true };
- }
+ if (res.ok) return { valid: true, body: await res.json().catch(() => null) };
if (res.status === 401 || res.status === 403) return { valid: false, reason: 'rejected' };
return { valid: false, reason: 'network' };
} catch (err) {
@@ -72,6 +73,23 @@ async function checkCatalog(url: string, headers: Record<string, string>): Promi
}
}
+async function checkCatalog(url: string, headers: Record<string, string>): Promise<KeyValidation> {
+ const probe = await probeAuth(url, headers);
+ if (!probe.valid) return probe;
+ const models = parseModelIds(probe.body);
+ return models ? { valid: true, models } : { valid: true };
+}
+
+export function spendWarning(body: unknown): KeyWarning | undefined {
+ if (typeof body !== 'object' || body === null) return undefined;
+ const data = (body as { data?: unknown }).data;
+ if (typeof data !== 'object' || data === null) return undefined;
+ const key = data as { is_free_tier?: unknown; limit_remaining?: unknown };
+ if (key.is_free_tier === true) return 'cannot-spend';
+ if (typeof key.limit_remaining === 'number' && key.limit_remaining <= 0) return 'cannot-spend';
+ return undefined;
+}
+
async function probeWithInference(
protocol: AIProtocol,
baseUrl: string,
@@ -147,8 +165,10 @@ export async function validateApiKey(
const catalogUrl = `${base}/models`;
if (!config.keyCheckPath) return checkCatalog(catalogUrl, headers);
- const authenticated = await checkCatalog(`${base}${config.keyCheckPath}`, headers);
+ const authenticated = await probeAuth(`${base}${config.keyCheckPath}`, headers);
if (!authenticated.valid) return authenticated;
+
+ const warning = spendWarning(authenticated.body);
const models = await fetchModelsFromUrl(catalogUrl, headers);
- return models ? { valid: true, models } : { valid: true };
+ return { valid: true, ...(models ? { models } : {}), ...(warning ? { warning } : {}) };
}
diff --git a/src/lib/messaging.ts b/src/lib/messaging.ts
index 0f1006f..eeda699 100644
--- a/src/lib/messaging.ts
+++ b/src/lib/messaging.ts
@@ -118,6 +118,7 @@ export interface ValidateApiKeyResponse {
valid: boolean;
reason?: 'rejected' | 'network' | 'model-required' | 'model-invalid';
models?: string[];
+ warning?: 'cannot-spend';
}
export interface EnterBlurModeResponse {
diff --git a/src/ui/shared/key-check.tsx b/src/ui/shared/key-check.tsx
index 28471df..7b17c3d 100644
--- a/src/ui/shared/key-check.tsx
+++ b/src/ui/shared/key-check.tsx
@@ -1,4 +1,4 @@
-import { Check, Eye, EyeOff } from 'lucide-react';
+import { Check, Eye, EyeOff, TriangleAlert } from 'lucide-react';
import { useCallback, useRef, useState } from 'react';
import { i18n } from '#imports';
import { sendMessage } from '@/lib/messaging';
@@ -6,9 +6,12 @@ import { Input } from '@/ui/components/ui/input';
export type KeyStatus = 'checking' | 'valid' | 'rejected' | 'unreachable' | 'model-required' | 'model-invalid' | null;
+export type KeyWarning = 'cannot-spend';
+
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);
@@ -21,10 +24,12 @@ export function useKeyCheck() {
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'
@@ -43,9 +48,10 @@ export function useKeyCheck() {
validated.current = '';
setStatus(null);
setModels(null);
+ setWarning(null);
}, []);
- return { status, models, check, reset };
+ return { status, models, warning, check, reset };
}
export function KeyStatusNote({ status }: { status: KeyStatus }) {
@@ -87,6 +93,16 @@ export function KeyStatusNote({ status }: { status: KeyStatus }) {
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">