π¬ 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
feat(ai): name why a description failed instead of logging a retry count
Luis Ortizb2fe07e0d619
diff --git a/src/core/capture/ai/__tests__/errors.test.ts b/src/core/capture/ai/__tests__/errors.test.tsnew file mode 100644index 0000000..5d35272--- /dev/null+++ b/src/core/capture/ai/__tests__/errors.test.ts@@ -0,0 +1,93 @@+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { APICallError, RetryError } from 'ai';+import { describe, expect, it } from 'vitest';+import { aiActionKey, aiFailureKey } from '@/ui/sidepanel/ai-status';+import { type AiFailureReason, describeAiFailure } from '../errors';++const LOCALES = ['en', 'de', 'es', 'fr', 'pt-BR', 'zh-CN'];+const REASONS: AiFailureReason[] = [+ 'rejected',+ 'no-credits',+ 'rate-limited',+ 'model-invalid',+ 'quota',+ 'network',+ 'unknown',+];++function apiError(statusCode: number) {+ return new APICallError({+ message: 'Provider returned error',+ url: 'https://openrouter.ai/api/v1/chat/completions',+ requestBodyValues: {},+ statusCode,+ });+}++describe('describeAiFailure', () => {+ it.each([+ [401, 'rejected'],+ [403, 'rejected'],+ [402, 'no-credits'],+ [429, 'rate-limited'],+ [404, 'model-invalid'],+ [413, 'quota'],+ [500, 'network'],+ ])('reads %i as %s', (status, reason) => {+ expect(describeAiFailure(apiError(status))).toMatchObject({ reason, status });+ });++ it('finds the status inside a retry error, so a rate limit is not read as unknown', () => {+ const retry = new RetryError({+ message: 'Failed after 3 attempts. Last error: Provider returned error',+ reason: 'maxRetriesExceeded',+ errors: [apiError(429), apiError(429), apiError(429)],+ });+ expect(describeAiFailure(retry)).toMatchObject({ reason: 'rate-limited', status: 429 });+ });++ it('reads a bare failure with no status as unknown rather than guessing', () => {+ expect(describeAiFailure(new TypeError('fetch failed'))).toEqual({+ reason: 'unknown',+ message: 'fetch failed',+ });+ });++ it('survives a thrown non-error', () => {+ expect(describeAiFailure('boom')).toEqual({ reason: 'unknown', message: 'boom' });+ expect(describeAiFailure(null)).toEqual({ reason: 'unknown', message: 'null' });+ });+});++describe('failure copy', () => {+ it('gives every reason its own message, in every locale', () => {+ for (const locale of LOCALES) {+ const text = readFileSync(join(process.cwd(), 'src/locales', `${locale}.yml`), 'utf8');+ for (const reason of REASONS) {+ for (const key of [aiFailureKey(reason), aiActionKey(reason)]) {+ const name = key.replace('aiStatus.', '');+ expect(text, `${locale} is missing ${name}`).toContain(` ${name}:`);+ }+ }+ }+ });++ it('maps an unrecognised reason to the catch-all rather than crashing', () => {+ expect(aiFailureKey(undefined)).toBe('aiStatus.unknown');+ expect(aiActionKey(undefined)).toBe('aiStatus.actionCheckKey');+ });++ it('names the provider in every headline that can', () => {+ const en = readFileSync(join(process.cwd(), 'src/locales/en.yml'), 'utf8');+ for (const reason of ['rejected', 'no-credits', 'rate-limited', 'model-invalid', 'network', 'unknown'] as const) {+ const name = aiFailureKey(reason).replace('aiStatus.', '');+ const line = en.split('\n').find((l) => l.startsWith(` ${name}:`));+ expect(line, `${name} should interpolate the provider`).toContain('$1');+ }+ });++ it('gives every reason an action to take', () => {+ for (const reason of REASONS) expect(aiActionKey(reason)).toMatch(/^aiStatus\.action/);+ });+});diff --git a/src/core/capture/ai/description.ts b/src/core/capture/ai/description.tsindex b66ace6..e2b4c93 100644--- a/src/core/capture/ai/description.ts+++ b/src/core/capture/ai/description.ts@@ -1,6 +1,5 @@import { generateText } from 'ai';import { localStorage } from '@/lib/browser-api';-import { logger } from '@/lib/logger';import type { DOMContext } from '../dom/context';import { serializeDOMContext } from '../dom/context';import { getLanguageSuffix, STEP_DESCRIPTION_PROMPT } from './prompts';@@ -13,18 +12,12 @@ export async function getAIDescription(apiKey: string,baseUrl?: string,): Promise<string | null> {- try {- const settings = await localStorage.get(['aiLanguage']);- const locale = (settings.aiLanguage as string) || 'en';- const { text } = await generateText({- model: createModel(provider, model, apiKey, baseUrl),- prompt:- STEP_DESCRIPTION_PROMPT.replace('{{context}}', serializeDOMContext(domContext)) + getLanguageSuffix(locale),- maxOutputTokens: 50,- });- return text.trim().replace(/^"|"$/g, '') || null;- } catch (err) {- logger.error('AI description failed, using fallback', err);- return null;- }+ const settings = await localStorage.get(['aiLanguage']);+ const locale = (settings.aiLanguage as string) || 'en';+ const { text } = await generateText({+ model: createModel(provider, model, apiKey, baseUrl),+ prompt: STEP_DESCRIPTION_PROMPT.replace('{{context}}', serializeDOMContext(domContext)) + getLanguageSuffix(locale),+ maxOutputTokens: 50,+ });+ return text.trim().replace(/^"|"$/g, '') || null;}diff --git a/src/core/capture/ai/errors.ts b/src/core/capture/ai/errors.tsnew file mode 100644index 0000000..191e035--- /dev/null+++ b/src/core/capture/ai/errors.ts@@ -0,0 +1,45 @@+export type AiFailureReason =+ | 'rejected'+ | 'no-credits'+ | 'rate-limited'+ | 'model-invalid'+ | 'quota'+ | 'network'+ | 'unknown';++export interface AiFailure {+ reason: AiFailureReason;+ status?: number;+ message: string;+}++function statusOf(err: unknown): number | undefined {+ let current = err;+ for (let depth = 0; depth < 5 && typeof current === 'object' && current !== null; depth += 1) {+ const status = (current as { statusCode?: unknown }).statusCode;+ if (typeof status === 'number') return status;+ current = (current as { lastError?: unknown; cause?: unknown }).lastError ?? (current as { cause?: unknown }).cause;+ }+ return undefined;+}++function messageOf(err: unknown): string {+ if (typeof err === 'object' && err !== null) {+ const message = (err as { message?: unknown }).message;+ if (typeof message === 'string' && message) return message;+ }+ return String(err);+}++export function describeAiFailure(err: unknown): AiFailure {+ const status = statusOf(err);+ const message = messageOf(err);++ if (status === 401 || status === 403) return { reason: 'rejected', status, message };+ if (status === 402) return { reason: 'no-credits', status, message };+ if (status === 429) return { reason: 'rate-limited', status, message };+ if (status === 404) return { reason: 'model-invalid', status, message };+ if (status === 413) return { reason: 'quota', status, message };+ if (status !== undefined) return { reason: 'network', status, message };+ return { reason: 'unknown', message };+}diff --git a/src/entrypoints/background/ai-description.ts b/src/entrypoints/background/ai-description.tsindex 2df13ed..e6f6aa0 100644--- a/src/entrypoints/background/ai-description.ts+++ b/src/entrypoints/background/ai-description.ts@@ -1,19 +1,31 @@import { getAIDescription } from '@/core/capture/ai/description';+import { describeAiFailure } from '@/core/capture/ai/errors';+import { resolveAiKey } from '@/core/capture/ai/keys';+import { AI_PROVIDERS } from '@/core/capture/ai/models';import type { DOMContext } from '@/core/capture/dom/context';import { localStorage } from '@/lib/browser-api';+import { logger } from '@/lib/logger';+import { broadcastAiToPanel } from '@/lib/port';export async function generateAiDescription(domContext: DOMContext): Promise<string | undefined> {- const settings = await localStorage.get(['aiApiKey', 'aiProvider', 'aiModel', 'aiBaseUrl']);- if (!settings.aiApiKey) return undefined;+ const settings = await localStorage.get(['aiApiKeys', 'aiApiKey', 'aiProvider', 'aiModel', 'aiBaseUrl']);+ const { provider, apiKey } = resolveAiKey(settings);+ if (!apiKey) return undefined;- const provider = (settings.aiProvider as string) || 'openai';- const model = (settings.aiModel as string) || 'gpt-4o-mini';- const description = await getAIDescription(- domContext,- provider,- model,- settings.aiApiKey as string,- settings.aiBaseUrl as string | undefined,- );- return description || undefined;+ const model = (settings.aiModel as string) || AI_PROVIDERS[provider].defaultModel;+ try {+ const description = await getAIDescription(+ domContext,+ provider,+ model,+ apiKey,+ settings.aiBaseUrl as string | undefined,+ );+ return description || undefined;+ } catch (err) {+ const failure = describeAiFailure(err);+ logger.error(`AI description failed (${failure.reason}${failure.status ? ` ${failure.status}` : ''})`, err);+ broadcastAiToPanel({ type: 'AI_UPDATE', reason: failure.reason, status: failure.status, provider });+ return undefined;+ }}diff --git a/src/lib/port.ts b/src/lib/port.tsindex 2c2c57a..e6886ae 100644--- a/src/lib/port.ts+++ b/src/lib/port.ts@@ -1,4 +1,5 @@import { browser } from '#imports';+import type { AiFailureReason } from '@/core/capture/ai/errors';import type { CaptureStateValue } from '@/core/capture/machine';import { logger } from '@/lib/logger';import type { VoiceErrorReason } from '@/lib/voice-messages';@@ -23,7 +24,14 @@ export interface PanelVoiceUpdate {narrated?: number;}-type PortMessage = PanelStateUpdate | PanelVoiceUpdate;+export interface PanelAiUpdate {+ type: 'AI_UPDATE';+ reason: AiFailureReason;+ status?: number;+ provider: string;+}++type PortMessage = PanelStateUpdate | PanelVoiceUpdate | PanelAiUpdate;type Port = ReturnType<typeof browser.runtime.connect>;function openPort(@@ -75,6 +83,7 @@ export function connectToBackground(callbacks: {onConnect: () => void;onDisconnect: () => void;onVoiceUpdate?: (update: PanelVoiceUpdate) => void;+ onAiUpdate?: (update: PanelAiUpdate) => void;}): () => void {return openPort(PORT_NAME,@@ -83,6 +92,8 @@ export function connectToBackground(callbacks: {callbacks.onStateUpdate(msg);} else if (msg.type === 'VOICE_UPDATE') {callbacks.onVoiceUpdate?.(msg);+ } else if (msg.type === 'AI_UPDATE') {+ callbacks.onAiUpdate?.(msg);}},callbacks.onConnect,@@ -148,6 +159,10 @@ export function broadcastStateToPanel(update: PanelStateUpdate): void {broadcastTo(panelPorts, update);}+export function broadcastAiToPanel(update: PanelAiUpdate): void {+ broadcastTo(panelPorts, update);+}+export function broadcastVoiceToPanel(update: PanelVoiceUpdate): void {lastVoiceUpdate = update;broadcastTo(panelPorts, update);diff --git a/src/ui/sidepanel/AiStatus.tsx b/src/ui/sidepanel/AiStatus.tsxnew file mode 100644index 0000000..c710114--- /dev/null+++ b/src/ui/sidepanel/AiStatus.tsx@@ -0,0 +1,25 @@+import { TriangleAlert } from 'lucide-react';+import { i18n } from '#imports';+import { findProvider } from '@/core/capture/ai/models';+import type { PanelAiUpdate } from '@/lib/port';+import { aiActionKey, aiFailureKey } from './ai-status';++interface AiStatusProps {+ update: PanelAiUpdate | null;+}++export default function AiStatus({ update }: AiStatusProps) {+ if (!update) return null;++ const label = findProvider(update.provider)?.label ?? update.provider;++ return (+ <div className="px-4 pt-2.5 flex items-start gap-2" role="status">+ <TriangleAlert size={13} className="shrink-0 mt-0.5 text-destructive" />+ <p className="text-[10px] leading-relaxed text-muted-foreground">+ <span className="font-semibold text-foreground">{i18n.t(aiFailureKey(update.reason), [label])}</span>{' '}+ {i18n.t(aiActionKey(update.reason))}+ </p>+ </div>+ );+}diff --git a/src/ui/sidepanel/App.tsx b/src/ui/sidepanel/App.tsxindex 0330fd1..67e3593 100644--- a/src/ui/sidepanel/App.tsx+++ b/src/ui/sidepanel/App.tsx@@ -17,7 +17,7 @@ import {import { logger } from '@/lib/logger';import { sendMessage } from '@/lib/messaging';import { getVoiceStatus } from '@/lib/offscreen';-import { connectToBackground, type PanelVoiceUpdate } from '@/lib/port';+import { connectToBackground, type PanelAiUpdate, type PanelVoiceUpdate } from '@/lib/port';import { Button } from '@/ui/components/ui/button';import { Input } from '@/ui/components/ui/input';import { TooltipProvider } from '@/ui/components/ui/tooltip';@@ -94,6 +94,7 @@ export default function App() {const [search, setSearch] = useState('');const [activeUrl, setActiveUrl] = useState<string>();const [voice, setVoice] = useState<PanelVoiceUpdate>({ type: 'VOICE_UPDATE', phase: 'idle' });+ const [aiFailure, setAiFailure] = useState<PanelAiUpdate | null>(null);const [voiceStarted, setVoiceStarted] = useState(false);useEffect(() => {@@ -113,6 +114,7 @@ export default function App() {onStateUpdate: (update) => {if (update.state === CaptureState.RECORDING) {setIsRecording(true);+ setAiFailure(null);const guideId = update.currentGuideId;if (guideId) {setView((prev) => (prev.name === 'recording' ? prev : { name: 'recording', guideId }));@@ -125,6 +127,7 @@ export default function App() {if (update.phase !== 'idle') setVoiceStarted(true);setVoice(update);},+ onAiUpdate: setAiFailure,});return disconnect;@@ -210,7 +213,7 @@ export default function App() {function renderView() {if (view.name === 'recording') {- return <RecordingView guideId={view.guideId} onStop={handleStopRecording} voice={voice} />;+ return <RecordingView guideId={view.guideId} onStop={handleStopRecording} voice={voice} aiFailure={aiFailure} />;}if (view.name === 'guideme') {diff --git a/src/ui/sidepanel/ai-status.ts b/src/ui/sidepanel/ai-status.tsnew file mode 100644index 0000000..6cedc5f--- /dev/null+++ b/src/ui/sidepanel/ai-status.ts@@ -0,0 +1,31 @@+import type { AiFailureReason } from '@/core/capture/ai/errors';++const AI_FAILURE_KEYS: Record<AiFailureReason, string> = {+ rejected: 'aiStatus.rejected',+ 'no-credits': 'aiStatus.noCredits',+ 'rate-limited': 'aiStatus.rateLimited',+ 'model-invalid': 'aiStatus.modelInvalid',+ quota: 'aiStatus.quota',+ network: 'aiStatus.network',+ unknown: 'aiStatus.unknown',+};++const AI_ACTION_KEYS: Record<AiFailureReason, string> = {+ rejected: 'aiStatus.actionCheckKey',+ 'no-credits': 'aiStatus.actionAddCredits',+ 'rate-limited': 'aiStatus.actionWait',+ 'model-invalid': 'aiStatus.actionPickModel',+ quota: 'aiStatus.actionPickModel',+ network: 'aiStatus.actionConnection',+ unknown: 'aiStatus.actionCheckKey',+};++export function aiFailureKey(reason: AiFailureReason | undefined): string {+ const key = reason === undefined ? undefined : AI_FAILURE_KEYS[reason];+ return key ?? AI_FAILURE_KEYS.unknown;+}++export function aiActionKey(reason: AiFailureReason | undefined): string {+ const key = reason === undefined ? undefined : AI_ACTION_KEYS[reason];+ return key ?? AI_ACTION_KEYS.unknown;+}