Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
feat(errors): friendly, translated provider error messages (#2510)
Chad Piha414319448518
diff --git a/CLAUDE.md b/CLAUDE.mdindex 9cd0f7e9f..83853d47f 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -66,6 +66,7 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.- Linux: before any paste or selection-copy chord, `linux-fast-paste --capabilities --await-modifier-release <ms>` waits for physically held modifiers to be released (XKB state on X11, `EVIOCGKEY` on Wayland; `unknown` without `/dev/input` access pastes as before). A chord injected into held keys arrives as a different shortcut, and a virtual device cannot release another device's key (#2113). Still held after 1.5 s → not pasted, `reason: "modifiers-held"`, and the renderer shows the dictation-error pill with the transcript on the clipboard; a selection edit blocked the same way reports `code: "modifiers_held"` and gets the same pill (the assistant caret paste reports the same code, for logs only). `ydotoold`'s virtual keyboard is ignored, since an interrupted chord can leave its modifier down, and an unreadable key state is logged once per session. The wait runs before `pasteLinux` detects the target window, and a selection copy that had to wait looks the target up again, since focus can move while a key is held: a fresh capture then runs the command on its own (`focus_moved`), and a revalidated session declines as `target_changed`. Retry on a modifiers-held pill pastes the kept transcript again rather than recording again (the macOS/Windows push force-stop pill keeps its record-again Retry, since neither platform waits for held keys), ignores clicks while its paste is pending, and never dismisses a newer pill. `useAudioRecording` keeps the pill in processing until the paste attempt settles (the audio manager settles before the paste starts), but never reports that to main, which drops dictation hotkeys while processing; a paste held back after the next dictation started leaves the transcript on the clipboard without a pill. The helper measures its wait on `CLOCK_MONOTONIC`, since the JS watchdog kills it at timeout + 1 s- **database.js**: SQLite operations for transcription history- **debugLogger.js**: Debug logging system with file output+- **providerHttpErrors.js**: Pure ESM classifier for BYOK provider failures (transcription and AI models), shared by main (require(esm)) and renderer. `providerHttpError({ provider, status, body, headers, model, surface, selfHosted })` builds an Error carrying `code` (`PROVIDER_AUTH_FAILED`, `PROVIDER_QUOTA_EXHAUSTED`, …), `messageKey` (`providerErrors.*`), `messageParams`, `settingsTarget` (`speechToText`/`llms`, fixable errors only) and redacted `technicalDetails`; `asProviderError` classifies AI SDK, timeout and network errors and leaves already-keyed errors alone. Raw provider bodies never reach UI text. Rendered by `src/utils/describeProviderError.ts`- **devServerManager.js**: Vite dev server integration- **dockManager.js**: Single owner of the macOS Dock icon- The icon follows the control panel: it appears when the panel opens and goes away when the panel closes to the tray, so no other caller (in particular the dictation panel's hide path) can resurrect itdiff --git a/preload.js b/preload.jsindex 5df23bff5..186b95edc 100644--- a/preload.js+++ b/preload.js@@ -99,6 +99,7 @@ contextBridge.exposeInMainWorld("electronAPI", {ipcRenderer.invoke("paste-at-captured-target", sessionId, text, options),hideWindow: () => ipcRenderer.invoke("hide-window"),showDictationPanel: () => ipcRenderer.invoke("show-dictation-panel"),+ openSettingsSection: (section) => ipcRenderer.invoke("open-settings-section", section),captureDictationTarget: () => ipcRenderer.invoke("capture-dictation-target"),onToggleDictation: registerListener("toggle-dictation", (callback) => () => callback()),onToggleVoiceAgent: registerListener("toggle-voice-agent", (callback) => () => callback()),@@ -1042,6 +1043,7 @@ contextBridge.exposeInMainWorld("electronAPI", {// Settings shortcut (Cmd+, / Ctrl+,)onShowSettings: registerListener("show-settings", (callback) => () => callback()),+ getPendingSettingsSection: () => ipcRenderer.invoke("get-pending-settings-section"),// Accessibility permission events (macOS)onAccessibilityMissing: (callback) => {diff --git a/src/components/CleanupFailureToastListener.tsx b/src/components/CleanupFailureToastListener.tsxindex ae6e8bfaf..6b0a751a0 100644--- a/src/components/CleanupFailureToastListener.tsx+++ b/src/components/CleanupFailureToastListener.tsx@@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next";import { useToast } from "./ui/useToast";import { consumeCleanupFailures, useCleanupFailureStore } from "../stores/cleanupFailureStore";import { isDictationPanelWindow } from "../utils/windowContext";+import { providerErrorToastProps } from "../utils/describeProviderError";/** Tells the user their dictation was pasted raw because AI cleanup failed. */export default function CleanupFailureToastListener() {@@ -21,6 +22,22 @@ export default function CleanupFailureToastListener() {if (isDictationPanelWindow()) {window.electronAPI?.showDictationPanel?.();}+ if (failure.surface === "llm") {+ // A classified provider failure: why cleanup failed, then that the raw text went in.+ const { description, actions } = providerErrorToastProps(failure, t);+ toast({+ title: t("app.toasts.cleanupFailed.title"),+ // A line break, not a space, so CJK sentences don't get one after "。".+ description: `${description}\n${t("app.toasts.cleanupFailed.description")}`,+ ...(actions ? { actions } : {}),+ variant: "destructive",+ // The dictation has already pasted, so the card can take the pill's place+ // like a transcription failure does.+ ...(isDictationPanelWindow() ? { presentation: "dictation-error" as const } : {}),+ duration: 10000,+ });+ return;+ }const title = failure.messageKey? t(failure.messageKey, failure.messageParams): failure.message || t("app.toasts.cleanupFailed.title");diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsxindex dc2fe01d6..197c72460 100644--- a/src/components/ControlPanel.tsx+++ b/src/components/ControlPanel.tsx@@ -83,6 +83,7 @@ import { applyChineseScript, resolveChineseScriptTarget } from "../utils/chineseimport { getAgentName } from "../utils/agentName";import HistoryView from "./HistoryView";import BackgroundActionToastListener from "./notes/BackgroundActionToastListener";+import { providerErrorToastProps } from "../utils/describeProviderError";import SpaceSyncToastListener from "./notes/SpaceSyncToastListener";import { syncService } from "../services/SyncService.js";import logger from "../utils/logger";@@ -125,6 +126,9 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelProconst [settingsSection, setSettingsSection] = useState<string | undefined>(initialSettingsSection);+ // Counts named show-settings requests, so asking again for the section the+ // modal was opened at still lands there after the user moved elsewhere in it.+ const [settingsRequest, setSettingsRequest] = useState(0);const [aiCTADismissed, setAiCTADismissed] = useState(() => localStorage.getItem("aiCTADismissed") === "true");@@ -428,9 +432,18 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro}, []);useEffect(() => {- const cleanup = window.electronAPI?.onShowSettings?.(() => {- setShowSettings(true);- });+ // A named section waits in main (it can outrace this listener on a cold+ // start); a bare request (app-menu Cmd+,) keeps an open modal where it is.+ const drain = async (showAnyway: boolean) => {+ const section = await window.electronAPI?.getPendingSettingsSection?.();+ if (section) {+ setSettingsSection(section);+ setSettingsRequest((count) => count + 1);+ }+ if (section || showAnyway) setShowSettings(true);+ };+ drain(false);+ const cleanup = window.electronAPI?.onShowSettings?.(() => drain(true));return () => cleanup?.();}, []);@@ -648,19 +661,17 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelProsettings.translationSourceLanguage,settings.translationTargetLanguage),- onCleanupError: (cleanupError: Error & { messageKey?: string }) => {+ onCleanupError: (cleanupError: unknown) => {logger.warn("Cleanup step failed in translation chain, translating raw transcript",- { error: cleanupError.message },+ { error: (cleanupError as Error).message },"transcription");// The chain still translates the raw transcript, so say why cleanup// was dropped rather than reporting a clean success (#2091).toast({title: t("app.toasts.cleanupFailed.title"),- description: cleanupError.messageKey- ? t(cleanupError.messageKey)- : cleanupError.message,+ ...providerErrorToastProps(cleanupError, t),variant: "destructive",});},@@ -729,10 +740,9 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro} catch (cleanupError) {// The row keeps its raw transcript, so the retry must not look like it// cleaned anything — report why, the way dictation does (#2091).- const failure = cleanupError as Error & { messageKey?: string };toast({title: t("app.toasts.cleanupFailed.title"),- description: failure.messageKey ? t(failure.messageKey) : failure.message,+ ...providerErrorToastProps(cleanupError, t),variant: "destructive",});}@@ -783,7 +793,7 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro} else {toast({title: t("controlPanel.history.retryError"),- description: result.messageKey ? t(result.messageKey) : result.error,+ ...providerErrorToastProps({ ...result, message: result.error }, t),variant: "destructive",});}@@ -912,6 +922,8 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro{showSettings && (<Suspense fallback={null}><SettingsModal+ // SettingsModal reads initialSection only on open, so a named request remounts it.+ key={`${settingsSection ?? "default"}-${settingsRequest}`}open={showSettings}onOpenChange={(open) => {setShowSettings(open);diff --git a/src/components/chat/ChatMessage.tsx b/src/components/chat/ChatMessage.tsxindex e3771770c..fa233b326 100644--- a/src/components/chat/ChatMessage.tsx+++ b/src/components/chat/ChatMessage.tsx@@ -3,7 +3,9 @@ import { useTranslation } from "react-i18next";import { Copy, Check, Search, FileText, ChevronDown, ChevronRight, CircleAlert } from "../icons";import { cn } from "../lib/utils";import { MarkdownRenderer } from "../ui/MarkdownRenderer";-import type { ToolCallInfo } from "./types";+import { TechnicalErrorDetails } from "../ui/TechnicalErrorDetails";+import { openProviderSettings } from "../../utils/describeProviderError";+import type { MessageError, ToolCallInfo } from "./types";import { extractNoteCards } from "./noteCards";import { toolIcons } from "./toolIcons";import { ApprovalCard } from "./ApprovalCard";@@ -15,6 +17,7 @@ interface ChatMessageProps {content: string;isStreaming: boolean;toolCalls?: ToolCallInfo[];+ error?: MessageError;onOpenNote?: (noteId: number) => void;}@@ -182,6 +185,7 @@ export const ChatMessage = memo(function ChatMessage({content,isStreaming,toolCalls,+ error,onOpenNote,}: ChatMessageProps) {const { t } = useTranslation();@@ -268,6 +272,17 @@ export const ChatMessage = memo(function ChatMessage({</span>)}+ {error?.settingsTarget && (+ <button+ type="button"+ onClick={() => openProviderSettings(error.settingsTarget!)}+ className="mt-1.5 text-xs font-medium text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 rounded-sm"+ >+ {t("providerErrors.openSettings")}+ </button>+ )}+ {error?.technicalDetails && <TechnicalErrorDetails details={error.technicalDetails} />}+{noteCards.length > 0 && !isStreaming && (<div>{noteCards.map((card) => (diff --git a/src/components/chat/ChatMessages.tsx b/src/components/chat/ChatMessages.tsxindex c5ba74bc4..191270d99 100644--- a/src/components/chat/ChatMessages.tsx+++ b/src/components/chat/ChatMessages.tsx@@ -65,6 +65,7 @@ export function ChatMessages({content={msg.content}isStreaming={msg.isStreaming}toolCalls={msg.toolCalls}+ error={msg.error}onOpenNote={onOpenNote}/>))}diff --git a/src/components/chat/types.ts b/src/components/chat/types.tsindex e3559bde9..c200b6dc2 100644--- a/src/components/chat/types.ts+++ b/src/components/chat/types.ts@@ -1,3 +1,6 @@+import type { TechnicalErrorDetailsData } from "../ui/useToast";+import type { ProviderSettingsTarget } from "../../utils/describeProviderError";+export interface ToolCallInfo {id: string;name: string;@@ -8,12 +11,19 @@ export interface ToolCallInfo {metadata?: Record<string, unknown> | Array<Record<string, unknown>>;}+export interface MessageError {+ technicalDetails?: TechnicalErrorDetailsData;+ settingsTarget?: ProviderSettingsTarget;+}+export interface Message {id: string;role: "user" | "assistant" | "tool";content: string;isStreaming: boolean;toolCalls?: ToolCallInfo[];+ /** Set on a failed reply; transient (not part of the saved conversation). */+ error?: MessageError;}export type AgentState =diff --git a/src/components/chat/useChatStreaming.ts b/src/components/chat/useChatStreaming.tsindex 7e798b5bb..487c9bb47 100644--- a/src/components/chat/useChatStreaming.ts+++ b/src/components/chat/useChatStreaming.ts@@ -5,6 +5,7 @@ import { isEnterpriseProvider } from "../../models/ModelRegistry";import { providerSupportsImages } from "../../services/ai/inferenceProviders";import { getSettings, useSettingsStore } from "../../stores/settingsStore";import { resolveChatStreamingInference } from "../../helpers/dictationAgentInference.js";+import { describeProviderError } from "../../utils/describeProviderError";import logger from "../../utils/logger";import {isAgentAllowed,@@ -783,13 +784,22 @@ export function useChatStreaming({"reasoning");announceResponse();+ const failure = describeProviderError(error, t);+ const messageError =+ failure.technicalDetails || failure.settingsTarget+ ? {+ technicalDetails: failure.technicalDetails,+ settingsTarget: failure.settingsTarget,+ }+ : undefined;setMessages((prev) =>prev.map((m) =>m.id === assistantId? {...m,- content: `${t("agentMode.chat.errorPrefix")}: ${(error as Error).message}`,+ content: `${t("agentMode.chat.errorPrefix")}: ${failure.description}`,isStreaming: false,+ ...(messageError ? { error: messageError } : {}),}: m)diff --git a/src/components/dictation/AssistantPanel.tsx b/src/components/dictation/AssistantPanel.tsxindex 3979cc8e8..1e71df592 100644--- a/src/components/dictation/AssistantPanel.tsx+++ b/src/components/dictation/AssistantPanel.tsx@@ -3,6 +3,8 @@ import { useTranslation } from "react-i18next";import { Check, Copy, Plus, X } from "../icons";import { BrandMarkIcon } from "./BrandMarkIcon";import { MarkdownRenderer } from "../ui/MarkdownRenderer";+import { TechnicalErrorDetails } from "../ui/TechnicalErrorDetails";+import { openProviderSettings } from "../../utils/describeProviderError";import { Button } from "../ui/button";import { useChatPersistence } from "../chat/useChatPersistence";import { useChatStreaming } from "../chat/useChatStreaming";@@ -508,21 +510,39 @@ export function AssistantPanel({}`}>{displayedResponse ? (- <div- ref={responseSelectionRootRef}- style={{ animation: "agent-message-in 160ms ease-out both" }}- >- <StableAssistantMarkdown- content={displayedResponse}- className="text-[15px] leading-relaxed text-foreground selection:bg-agent-brand/35 selection:text-foreground [&_p]:text-[15px] [&_li]:text-[15px]"- />- {latestAssistantMessage?.isStreaming && (- <span- className="ms-0.5 inline-block h-4 w-0.5 align-middle bg-foreground/70"- style={{ animation: "agent-cursor-blink 1s ease-in-out infinite" }}+ <>+ <div+ ref={responseSelectionRootRef}+ style={{ animation: "agent-message-in 160ms ease-out both" }}+ >+ <StableAssistantMarkdown+ content={displayedResponse}+ className="text-[15px] leading-relaxed text-foreground selection:bg-agent-brand/35 selection:text-foreground [&_p]:text-[15px] [&_li]:text-[15px]"/>+ {latestAssistantMessage?.isStreaming && (+ <span+ className="ms-0.5 inline-block h-4 w-0.5 align-middle bg-foreground/70"+ style={{ animation: "agent-cursor-blink 1s ease-in-out infinite" }}+ />+ )}+ </div>+ {/* Outside responseSelectionRootRef: a drag-select + copy over the+ response must never pick up these affordances. */}+ {latestAssistantMessage?.error?.settingsTarget && (+ <button+ type="button"+ onClick={() =>+ openProviderSettings(latestAssistantMessage.error!.settingsTarget!)+ }+ className="mt-2 text-[13px] font-medium text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 rounded-sm"+ >+ {t("providerErrors.openSettings")}+ </button>)}- </div>+ {latestAssistantMessage?.error?.technicalDetails && (+ <TechnicalErrorDetails details={latestAssistantMessage.error.technicalDetails} />+ )}+ </>) : null}{panelApprovals.map((entry) => (<ApprovalCard key={entry.key} entry={entry} />diff --git a/src/components/dictation/DictationErrorCard.tsx b/src/components/dictation/DictationErrorCard.tsxindex 72e58af20..2ce9757bf 100644--- a/src/components/dictation/DictationErrorCard.tsx+++ b/src/components/dictation/DictationErrorCard.tsx@@ -1,9 +1,10 @@import { useEffect, useLayoutEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";-import { RotateCcw, ScrollText, Settings, Copy, Check, X } from "../icons";+import { Check, X } from "../icons";import { ASSISTANT_PANEL_SIZE_LIMITS } from "../../helpers/voiceSurfaceGeometry.mjs";import { cn } from "../lib/utils";import type { ToastActionConfig } from "../ui/useToast";+import { TOAST_ACTION_ICONS } from "../ui/toastActionIcons";interface DictationErrorCardProps {title?: string;@@ -18,13 +19,6 @@ interface DictationErrorCardProps {ready?: boolean;}-const ACTION_ICONS = {- retry: RotateCcw,- transcript: ScrollText,- settings: Settings,- copy: Copy,-};-function ErrorAction({action,primary,@@ -70,7 +64,7 @@ function ErrorAction({resetTimer.current = setTimeout(() => setResult(undefined), 1800);};- const Icon = result === true ? Check : action.icon ? ACTION_ICONS[action.icon] : null;+ const Icon = result === true ? Check : action.icon ? TOAST_ACTION_ICONS[action.icon] : null;const label =result === true? action.feedback?.successLabel@@ -82,8 +76,10 @@ function ErrorAction({type="button"onClick={() => void handleClick()}disabled={pending}+ title={action.iconOnly ? label : undefined}className={cn(- "inline-flex h-8 min-w-0 shrink-0 items-center justify-center gap-1.5 rounded-full px-4",+ "inline-flex h-8 min-w-0 shrink-0 items-center justify-center gap-1.5 rounded-full",+ action.iconOnly ? "w-8" : "px-4","text-sm font-medium transition-[background-color,color,transform] duration-150","focus:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 active:scale-[0.98] disabled:cursor-wait",primary@@ -92,7 +88,10 @@ function ErrorAction({)}>{Icon && <Icon className="size-3.5 shrink-0" aria-hidden="true" />}- <span className="truncate" aria-live={action.feedback ? "polite" : undefined}>+ <span+ className={action.iconOnly ? "sr-only" : "truncate"}+ aria-live={action.feedback ? "polite" : undefined}+ >{label}</span></button>@@ -129,7 +128,7 @@ function ErrorDescription({ text, hotkey }: { text: string; hotkey?: string }) {);}-/** Shared one/two-action error surface for the floating dictation window. */+/** Shared error surface (title, description, actions) for the floating dictation window. */export function DictationErrorCard({title,description,@@ -215,11 +214,17 @@ export function DictationErrorCard({<ErrorActionkey={`${action.label}-${index}`}action={action}- primary={index === 0}+ primary={index === 0 && !action.iconOnly}onAction={onAction}/>);+ // Up to two labelled actions share one row with the icon-only ones after them.+ const labelledActions = actions.filter((action) => !action.iconOnly);+ const iconActions = actions.filter((action) => action.iconOnly);+ const singleRow = labelledActions.length <= 2;+ const rowActions = singleRow ? [...labelledActions, ...iconActions] : actions;+return (<sectionref={cardRef}@@ -268,7 +273,21 @@ export function DictationErrorCard({{hasSecondaryAction ? (<div className="px-2 py-3">{text}- <div className="mt-3 grid grid-cols-2 gap-2">{actions.map(renderAction)}</div>+ <div+ className={cn("mt-3 grid gap-2", !singleRow && "grid-cols-2")}+ style={+ singleRow+ ? {+ gridTemplateColumns: [+ ...labelledActions.map(() => "minmax(0, 1fr)"),+ ...iconActions.map(() => "2rem"),+ ].join(" "),+ }+ : undefined+ }+ >+ {rowActions.map(renderAction)}+ </div></div>) : (<div className="flex items-center gap-2 px-2 py-3">diff --git a/src/components/notes/BackgroundActionToastListener.tsx b/src/components/notes/BackgroundActionToastListener.tsxindex d6e0adece..a116d0504 100644--- a/src/components/notes/BackgroundActionToastListener.tsx+++ b/src/components/notes/BackgroundActionToastListener.tsx@@ -10,6 +10,7 @@ import {type ActionAppliedEvent,} from "../../stores/actionProcessingStore";import { getActionName } from "../../stores/actionStore";+import { providerErrorToastProps } from "../../utils/describeProviderError";const UNDO_WINDOW_MS = 6000;@@ -29,7 +30,7 @@ export default function BackgroundActionToastListener() {for (const event of consumeErrorEvents()) {toast({title: event.notice ? undefined : t("notes.enhance.title"),- description: event.messageKey ? t(event.messageKey, event.messageParams) : event.message,+ ...providerErrorToastProps(event, t),variant: event.notice ? undefined : "destructive",});}diff --git a/src/components/notes/UploadAudioView.tsx b/src/components/notes/UploadAudioView.tsxindex e801133d4..0b2d3114b 100644--- a/src/components/notes/UploadAudioView.tsx+++ b/src/components/notes/UploadAudioView.tsx@@ -42,6 +42,7 @@ import { useAuth } from "../../hooks/useAuth";import { useUsage } from "../../hooks/useUsage";import { useSettings } from "../../hooks/useSettings";import { requestSignIn } from "../../utils/requestSignIn";+import { describeProviderError } from "../../utils/describeProviderError";import {getAllReasoningModels,getBatchTranscriptionModel,@@ -758,7 +759,7 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: UploaerrorKey? t(`notes.upload.${errorKey}`): res.messageKey- ? t(res.messageKey)+ ? describeProviderError({ ...res, message: res.error }, t).description: res.error || t("notes.upload.transcriptionFailed"));setState("error");@@ -773,7 +774,11 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploaif (errorKey) {setError(t(`notes.upload.${errorKey}`));} else {- setError(err instanceof Error ? err.message : t("notes.upload.errorOccurred"));+ setError(+ err instanceof Error+ ? describeProviderError(err, t).description+ : t("notes.upload.errorOccurred")+ );}setState("error");}diff --git a/src/components/ui/TechnicalErrorDetails.tsx b/src/components/ui/TechnicalErrorDetails.tsxindex ed093963f..020da02d0 100644--- a/src/components/ui/TechnicalErrorDetails.tsx+++ b/src/components/ui/TechnicalErrorDetails.tsx@@ -1,30 +1,11 @@import { Check, Copy } from "../icons";-import type { TFunction } from "i18next";import type { JSX } from "react";import { useTranslation } from "react-i18next";import { useCopyFeedback } from "../../hooks/useCopyFeedback";+import { formatProviderErrorDetails } from "../../utils/describeProviderError";import { cn } from "../lib/utils";import type { TechnicalErrorDetailsData } from "./useToast";-function formatTechnicalErrorDetails(details: TechnicalErrorDetailsData, t: TFunction): string {- return [- details.status !== undefined- ? `${t("reasoning.enterprise.technicalDetails.httpStatus")}: ${details.status}`- : "",- details.exceptionType- ? `${t("reasoning.enterprise.technicalDetails.awsException")}: ${details.exceptionType}`- : "",- details.requestId- ? `${t("reasoning.enterprise.technicalDetails.awsRequestId")}: ${details.requestId}`- : "",- details.underlyingError- ? `${t("reasoning.enterprise.technicalDetails.underlyingError")}: ${details.underlyingError}`- : "",- ]- .filter(Boolean)- .join("\n");-}-export function TechnicalErrorDetails({details,onDark = false,@@ -33,7 +14,7 @@ export function TechnicalErrorDetails({onDark?: boolean;}): JSX.Element | null {const { t } = useTranslation();- const text = details ? formatTechnicalErrorDetails(details, t) : "";+ const text = details ? formatProviderErrorDetails(details, t) : "";const { copied, copy } = useCopyFeedback(text, { resetMs: 2000 });if (!text) return null;diff --git a/src/components/ui/Toast.tsx b/src/components/ui/Toast.tsxindex 5329a15ec..54cf73558 100644--- a/src/components/ui/Toast.tsx+++ b/src/components/ui/Toast.tsx@@ -16,6 +16,7 @@ import {} from "../../helpers/toastPresentation";import { useCopyFeedback } from "../../hooks/useCopyFeedback";import { DictationErrorCard } from "../dictation/DictationErrorCard";+import { TOAST_ACTION_ICONS } from "./toastActionIcons";import { TechnicalErrorDetails } from "./TechnicalErrorDetails";/** The inline action beside a toast's text; dismissing is left to the caller. */@@ -37,6 +38,56 @@ export function ToastActionButton({);}+/** A structured action under a standard toast's text: a compact button, or its icon alone. */+function StandardToastAction({+ action,+ onAction,+}: {+ action: ToastActionConfig;+ onAction: (action: ToastActionConfig) => ReturnType<ToastActionConfig["onClick"]>;+}) {+ const [result, setResult] = React.useState<boolean | undefined>();+ const resetTimer = React.useRef<ReturnType<typeof setTimeout> | undefined>(undefined);+ React.useEffect(() => () => clearTimeout(resetTimer.current), []);++ const handleClick = async () => {+ let outcome: void | boolean;+ try {+ outcome = await onAction(action);+ } catch {+ outcome = false;+ }+ if (!action.feedback || typeof outcome !== "boolean") return;+ setResult(outcome);+ clearTimeout(resetTimer.current);+ resetTimer.current = setTimeout(() => setResult(undefined), 1800);+ };++ const label =+ result === true+ ? action.feedback?.successLabel+ : result === false+ ? action.feedback?.failureLabel+ : action.label;+ if (!action.iconOnly) {+ return <ToastActionButton onClick={handleClick}>{label}</ToastActionButton>;+ }+ const Icon = result === true ? Check : action.icon ? TOAST_ACTION_ICONS[action.icon] : Copy;+ return (+ <button+ type="button"+ onClick={() => void handleClick()}+ title={label}+ className="rounded-sm border border-white/20 bg-white/10 p-1 text-white/70 transition-colors hover:border-white/35 hover:bg-white/20 hover:text-white"+ >+ <Icon className="size-3" aria-hidden="true" />+ <span className="sr-only" aria-live={action.feedback ? "polite" : undefined}>+ {label}+ </span>+ </button>+ );+}+interface ToastState extends ToastProps {id: string;isExiting?: boolean;@@ -351,6 +402,9 @@ const Toast: React.FC<const message = title || description;const detail = title && description ? description : undefined;+ // Structured actions come with a classified error: its description is a+ // sentence to read, and Copy details replaces the raw-error copy box.+ const rowActions = actions?.length ? actions : undefined;if (presentation === "dictation-error") {return (@@ -402,7 +456,7 @@ const Toast: React.FC<<div className="mt-1 text-xs leading-snug text-white/45">{secondaryDescription}</div>)}{detail &&- (isDestructive ? (+ (isDestructive && !rowActions ? (<divclassName={cn("text-xs leading-snug mt-1 px-1.5 py-1 rounded-[3px] font-mono",@@ -448,6 +502,17 @@ const Toast: React.FC<</div>)}<TechnicalErrorDetails details={technicalDetails} onDark />+ {rowActions && (+ <div className="mt-2 flex items-center gap-1.5">+ {rowActions.map((rowAction, index) => (+ <StandardToastAction+ key={`${rowAction.label}-${index}`}+ action={rowAction}+ onAction={handleStructuredAction}+ />+ ))}+ </div>+ )}</div>{action && <div className="shrink-0 self-center">{action}</div>}diff --git a/src/components/ui/TranscriptionItem.tsx b/src/components/ui/TranscriptionItem.tsxindex 3d02c237b..39e4a06bc 100644--- a/src/components/ui/TranscriptionItem.tsx+++ b/src/components/ui/TranscriptionItem.tsx@@ -100,6 +100,11 @@ export default function TranscriptionItem({const isConfigError =errorCode === "API_KEY_MISSING" ||errorCode === "INVALID_KEY" ||+ errorCode === "PROVIDER_AUTH_FAILED" ||+ errorCode === "PROVIDER_ACCESS_DENIED" ||+ errorCode === "PROVIDER_QUOTA_EXHAUSTED" ||+ errorCode === "PROVIDER_MODEL_NOT_FOUND" ||+ errorCode === "PROVIDER_NO_RESPONSE" ||errorCode === "MODEL_NOT_AVAILABLE" ||errorCode === "CUSTOM_ENDPOINT_INVALID";const isLimitError = errorCode === "LIMIT_REACHED";diff --git a/src/components/ui/toastActionIcons.ts b/src/components/ui/toastActionIcons.tsnew file mode 100644index 000000000..2a28ae260--- /dev/null+++ b/src/components/ui/toastActionIcons.ts@@ -0,0 +1,9 @@+import { Copy, RotateCcw, ScrollText, Settings } from "../icons";++/** The icon for each `ToastActionConfig["icon"]`. */+export const TOAST_ACTION_ICONS = {+ retry: RotateCcw,+ transcript: ScrollText,+ settings: Settings,+ copy: Copy,+};diff --git a/src/components/ui/useToast.ts b/src/components/ui/useToast.tsindex 966e066cc..623311045 100644--- a/src/components/ui/useToast.ts+++ b/src/components/ui/useToast.ts@@ -3,6 +3,7 @@ import * as React from "react";export type ToastPresentation = "standard" | "dictation-error";export interface TechnicalErrorDetailsData {+ provider?: string;status?: number;exceptionType?: string;requestId?: string;@@ -15,6 +16,8 @@ export interface ToastActionConfig {onClick: () => void | boolean | Promise<void | boolean>;feedback?: { successLabel: string; failureLabel: string };dismissOnClick?: boolean;+ /** Shown as its icon alone, after the labelled actions; the label becomes its accessible name. */+ iconOnly?: boolean;}export interface ToastProps {diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex b7a265497..25e8532d7 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -89,6 +89,8 @@ import {resolveStreamingStartFallback,} from "./transcriptionFallback";import { transcriptionFailureOutcome } from "./transcriptionFailureOutcome";+import { IPC_ERROR_FIELDS, errorFromIpcResult } from "./ipcErrorFields";+import { asProviderError, providerHttpError, redactProviderBody } from "./providerHttpErrors";import {executeTranslationChain,hasTextContent,@@ -158,6 +160,8 @@ const cleanupFailureFromError = (error) => ({message: error?.message || String(error),...(error?.messageKey ? { messageKey: error.messageKey } : {}),...(error?.messageParams ? { messageParams: error.messageParams } : {}),+ ...(error?.surface ? { surface: error.surface } : {}),+ ...(error?.settingsTarget ? { settingsTarget: error.settingsTarget } : {}),...(error?.action ? { action: error.action } : {}),...(error?.actionKey ? { actionKey: error.actionKey } : {}),...(error?.copyCommand ? { copyCommand: error.copyCommand } : {}),@@ -3638,12 +3642,21 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);.filter(Boolean).slice(0, 100),});- const result = await call(proxyPayload);+ // Managed Azure is enterprise: its failures keep their own shape.+ const classifyProxyFailure = (err) =>+ managedResolution+ ? err+ : asProviderError(err, { provider: proxySpec.displayName, surface: "transcription" });+ let result;+ try {+ result = await call(proxyPayload);+ } catch (err) {+ throw classifyProxyFailure(err);+ }if (result?.error) {- const err = new Error(result.error);- if (result.code) err.code = result.code;- if (result.messageKey) err.messageKey = result.messageKey;- throw err;+ // Main serialises an unclassified network failure as its bare+ // message (net::ERR_*), so classify the rebuilt error here.+ throw classifyProxyFailure(errorFromIpcResult(result));}const proxyText = result?.text;if (!proxyText?.trim()) {@@ -3805,14 +3818,29 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);"transcription");+ // Name the resolved route, not cloudTranscriptionProvider: self-hosted+ // dictation keeps that setting (usually "openai") while posting to the+ // user's own server.+ const providerErrorContext = {+ provider: route.provider === "groq" ? "Groq" : "OpenAI",+ selfHosted: route.provider === "self-hosted" || route.provider === "custom",+ model: route.model ?? model,+ surface: "transcription",+ };+requestController = new AbortController();this._activeTranscriptionAbortController = requestController;- const response = await fetch(endpoint, {- method: "POST",- headers,- body: formData,- signal: requestController.signal,- });+ let response;+ try {+ response = await fetch(endpoint, {+ method: "POST",+ headers,+ body: formData,+ signal: requestController.signal,+ });+ } catch (err) {+ throw asProviderError(err, providerErrorContext);+ }const responseContentType = response.headers.get("content-type") || "";@@ -3833,18 +3861,16 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);"Transcription API error response",{status: response.status,- errorText,+ errorText: redactProviderBody(errorText),},"transcription");- const err = new Error(`API Error: ${response.status} ${errorText}`);- if (response.status === 401) err.code = "INVALID_KEY";- else if (response.status === 429) {- // The user's own provider rate-limited the request — not an OpenWhispr plan limit- err.code = "PROVIDER_RATE_LIMITED";- err.messageKey = "hooks.audioRecording.errorDescriptions.providerRateLimited";- } else if (response.status >= 500) err.code = "SERVER_ERROR";- throw err;+ throw providerHttpError({+ ...providerErrorContext,+ status: response.status,+ body: errorText,+ headers: response.headers,+ });}let result;@@ -3997,8 +4023,11 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);const wrapped = new Error(`OpenAI API failed: ${error.message}. Local fallback also failed: ${fallbackError.message}`);- if (error.code) wrapped.code = error.code;- if (error.messageKey) wrapped.messageKey = error.messageKey;+ // The toast renders the cloud failure, so its message params and details+ // must survive the wrap, or the copy shows a bare "{{provider}}".+ for (const key of IPC_ERROR_FIELDS) {+ if (error[key] !== undefined) wrapped[key] = error[key];+ }throw wrapped;}}diff --git a/src/helpers/cortiAuth.js b/src/helpers/cortiAuth.jsindex 169b42604..71daeddd7 100644--- a/src/helpers/cortiAuth.js+++ b/src/helpers/cortiAuth.js@@ -57,7 +57,10 @@ async function getCortiToken({ environment, tenant, clientId, clientSecret }, feif (!response.ok) {const errorText = await response.text().catch(() => "");- throw new Error(`Corti authentication failed: ${response.status} ${errorText}`.trim());+ throw Object.assign(+ new Error(`Corti authentication failed: ${response.status} ${errorText}`.trim()),+ { status: response.status }+ );}const data = await response.json();diff --git a/src/helpers/cortiTranscription.js b/src/helpers/cortiTranscription.jsindex 8f9ba8792..3e697c4e6 100644--- a/src/helpers/cortiTranscription.js+++ b/src/helpers/cortiTranscription.js@@ -2,6 +2,7 @@ const { net } = require("electron");const crypto = require("crypto");const debugLogger = require("./debugLogger");const { getCortiToken } = require("./cortiAuth");+const { providerHttpError, redactProviderBody } = require("./providerHttpErrors");async function request(token, tenant, url, options = {}) {const response = await net.fetch(url, {@@ -14,7 +15,17 @@ async function request(token, tenant, url, options = {}) {});if (!response.ok) {const errorText = await response.text().catch(() => "");- throw new Error(`Corti API Error: ${response.status} ${errorText}`.trim());+ debugLogger.warn("Corti transcription failed", {+ status: response.status,+ body: redactProviderBody(errorText),+ });+ throw providerHttpError({+ provider: "Corti",+ status: response.status,+ body: errorText,+ headers: response.headers,+ surface: "transcription",+ });}return response;}@@ -34,7 +45,21 @@ async function transcribeAudio({audioBuffer,language,}) {- const token = await getCortiToken({ environment, tenant, clientId, clientSecret });+ const token = await getCortiToken({ environment, tenant, clientId, clientSecret }).catch(+ (error) => {+ if (typeof error.status !== "number") throw error;+ debugLogger.warn("Corti authentication failed", {+ status: error.status,+ body: redactProviderBody(error.message),+ });+ throw providerHttpError({+ provider: "Corti",+ status: error.status,+ body: error.message,+ surface: "transcription",+ });+ }+ );const base = `https://api.${environment}.corti.app/v2`;debugLogger.debug(diff --git a/src/helpers/geminiTranscription.js b/src/helpers/geminiTranscription.jsindex 81bb3a0b1..2226a0cb6 100644--- a/src/helpers/geminiTranscription.js+++ b/src/helpers/geminiTranscription.js@@ -1,5 +1,11 @@const { net } = require("electron");const debugLogger = require("./debugLogger");+const {+ PROVIDER_ERROR_CODES,+ providerHttpError,+ providerError,+ redactProviderBody,+} = require("./providerHttpErrors");// gemini-3.5-transcribe is only served by the Interactions API; there is no// generateContent or OpenAI-compatible endpoint for it.@@ -31,9 +37,10 @@ async function transcribeWithGemini(fetchImpl) {if (!apiKey?.trim()) {- const error = new Error("Gemini API key not configured. Add your key in Settings.");- error.code = "API_KEY_MISSING";- throw error;+ throw providerError(PROVIDER_ERROR_CODES.KEY_MISSING, {+ provider: "Gemini",+ surface: "transcription",+ });}const resolvedModel = model || "gemini-3.5-transcribe";@@ -75,25 +82,19 @@ async function transcribeWithGemini(if (!response.ok) {const errorText = await response.text().catch(() => "");- // Google rejects a bad key with 400 + reason API_KEY_INVALID rather than 401,- // so status alone would surface the raw JSON instead of a fixable message.- if (- response.status === 401 ||- response.status === 403 ||- errorText.includes("API_KEY_INVALID")- ) {- const error = new Error("Invalid Gemini API key. Check your key in Settings.");- error.code = "INVALID_KEY";- throw error;- }- const error = new Error(`Gemini API Error: ${response.status} ${errorText}`.trim());- if (response.status === 429) {- error.code = "PROVIDER_RATE_LIMITED";- error.messageKey = "hooks.audioRecording.errorDescriptions.providerRateLimited";- } else if (response.status >= 500) {- error.code = "SERVER_ERROR";- }- throw error;+ debugLogger.warn("Gemini transcription failed", {+ status: response.status,+ body: redactProviderBody(errorText),+ });+ // Google rejects a bad key with 400 + API_KEY_INVALID; the classifier reads that signal.+ throw providerHttpError({+ provider: "Gemini",+ model: resolvedModel,+ status: response.status,+ body: errorText,+ headers: response.headers,+ surface: "transcription",+ });}const data = await response.json();diff --git a/src/helpers/ipcErrorFields.js b/src/helpers/ipcErrorFields.jsnew file mode 100644index 000000000..22d59617b--- /dev/null+++ b/src/helpers/ipcErrorFields.js@@ -0,0 +1,29 @@+// ESM shared by main (require(esm)) and renderer. ipcMain.handle keeps only+// the message of a rejected promise, so handlers resolve with these fields and+// the renderer rebuilds the Error from them.++export const IPC_ERROR_FIELDS = Object.freeze([+ "code",+ "messageKey",+ "messageParams",+ "settingsTarget",+ "technicalDetails",+ "status",+ "surface",+]);++export function ipcErrorFields(error) {+ const fields = { error: error?.message || String(error) };+ for (const key of IPC_ERROR_FIELDS) {+ if (error?.[key] !== undefined) fields[key] = error[key];+ }+ return fields;+}++export function errorFromIpcResult(result) {+ const error = new Error(result?.error || "Request failed");+ for (const key of IPC_ERROR_FIELDS) {+ if (result?.[key] !== undefined) error[key] = result[key];+ }+ return error;+}diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 5e2d7bb67..ea54a7164 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -34,6 +34,15 @@ const {} = require("./policyResponseError");const { classifyAndLog } = require("./networkErrors");const { resolveSystemDefaultMicrophone } = require("./systemDefaultMicrophone");+const { ipcErrorFields } = require("./ipcErrorFields");+const {+ PROVIDER_ERROR_CODES,+ isProviderSettingsTarget,+ providerHttpError,+ providerError,+ asProviderError,+ redactProviderBody,+} = require("./providerHttpErrors");const {registerConnectorIpc,createConnectorPolicyResolver,@@ -44,8 +53,12 @@ const { createNoteAttendeesLookup, searchContacts } = require("./connectors/cont// packaged, and the route resolver only needs {id, baseUrl} per provider.const transcriptionProviderBaseUrls = () =>require("../models/modelRegistryData.json").transcriptionProviders;+// Classified errors show the provider's display name; routes only carry its id.+const transcriptionProviderName = (id) =>+ require("../models/modelRegistryData.json").transcriptionProviders.find((p) => p.id === id)+ ?.name || id;// ipcMain.handle keeps only the message when a promise rejects, dropping custom-// props — proxy handlers return {error, code, messageKey} so the renderer can+// props — proxy handlers return the classified fields so the renderer can// rebuild the error.const serializeIpcError =(fn) =>@@ -53,7 +66,7 @@ const serializeIpcError =try {return await fn(...args);} catch (error) {- return { error: error.message, code: error.code, messageKey: error.messageKey };+ return ipcErrorFields(error);}};@@ -1544,6 +1557,12 @@ class IPCHandlers {this.windowManager.showDictationPanel({ reposition: true });});+ ipcMain.handle("open-settings-section", async (_event, section) => {+ if (!isProviderSettingsTarget(section)) return { success: false };+ await this.windowManager.openSettings(section);+ return { success: true };+ });+ipcMain.handle("capture-dictation-target", async () => {// Recording start awaits this handler, so the Linux/Windows window probe// runs in the background: a stalled AT-SPI peer would otherwise hold the@@ -4614,7 +4633,10 @@ class IPCHandlers {serializeIpcError(async (event, { audioBuffer, language, keyterms }) => {const apiKey = this.environmentManager.getXaiKey();if (!apiKey) {- throw new Error("xAI API key not configured");+ throw providerError(PROVIDER_ERROR_CODES.KEY_MISSING, {+ provider: "xAI",+ surface: "transcription",+ });}const formData = new FormData();@@ -4639,7 +4661,17 @@ class IPCHandlers {if (!response.ok) {const errorText = await response.text();- throw new Error(`xAI API Error: ${response.status} ${errorText}`);+ debugLogger.warn("xAI transcription failed", {+ status: response.status,+ body: redactProviderBody(errorText),+ });+ throw providerHttpError({+ provider: "xAI",+ status: response.status,+ body: errorText,+ headers: response.headers,+ surface: "transcription",+ });}return await response.json();@@ -4651,13 +4683,17 @@ class IPCHandlers {serializeIpcError(async (event, { audioBuffer, model, language, contextBias }) => {const apiKey = this.environmentManager.getMistralKey();if (!apiKey) {- throw new Error("Mistral API key not configured");+ throw providerError(PROVIDER_ERROR_CODES.KEY_MISSING, {+ provider: "Mistral",+ surface: "transcription",+ });}+ const transcriptionModel = model || "voxtral-mini-latest";const formData = new FormData();const audioBlob = new Blob([Buffer.from(audioBuffer)], { type: "audio/webm" });formData.append("file", audioBlob, "audio.webm");- formData.append("model", model || "voxtral-mini-latest");+ formData.append("model", transcriptionModel);if (language && language !== "auto") {formData.append("language", language);}@@ -4677,7 +4713,18 @@ class IPCHandlers {if (!response.ok) {const errorText = await response.text();- throw new Error(`Mistral API Error: ${response.status} ${errorText}`);+ debugLogger.warn("Mistral transcription failed", {+ status: response.status,+ body: redactProviderBody(errorText),+ });+ throw providerHttpError({+ provider: "Mistral",+ model: transcriptionModel,+ status: response.status,+ body: errorText,+ headers: response.headers,+ surface: "transcription",+ });}return await response.json();@@ -4706,7 +4753,10 @@ class IPCHandlers {const clientId = this.environmentManager.getCortiClientId();const clientSecret = this.environmentManager.getCortiClientSecret();if (!clientId || !clientSecret) {- throw new Error("Corti credentials not configured");+ throw providerError(PROVIDER_ERROR_CODES.KEY_MISSING, {+ provider: "Corti",+ surface: "transcription",+ });}const { transcribeAudio } = require("./cortiTranscription");@@ -5378,7 +5428,10 @@ class IPCHandlers {const apiKey = this.environmentManager.getAnthropicKey();if (!apiKey) {- throw new Error("Anthropic API key not configured");+ throw providerError(PROVIDER_ERROR_CODES.KEY_MISSING, {+ provider: "Anthropic",+ surface: "llm",+ });}const systemPrompt = config?.systemPrompt || "";@@ -5426,17 +5479,23 @@ class IPCHandlers {if (!response.ok) {const errorText = await response.text();- let errorData = { error: response.statusText };- try {- errorData = JSON.parse(errorText);- } catch {- errorData = { error: errorText || response.statusText };- }- throw new Error(- errorData.error?.message ||- errorData.error ||- `Anthropic API error: ${response.status}`- );+ debugLogger.warn("Anthropic API error", {+ status: response.status,+ body: redactProviderBody(errorText),+ });+ return {+ success: false,+ ...ipcErrorFields(+ providerHttpError({+ provider: "Anthropic",+ model: modelId,+ status: response.status,+ body: errorText,+ headers: response.headers,+ surface: "llm",+ })+ ),+ };}const data = await response.json();@@ -5454,7 +5513,13 @@ class IPCHandlers {return { success: true, text: outputText };} catch (error) {debugLogger.error("Anthropic reasoning error:", error);- return { success: false, error: error.message, messageKey: error.messageKey };+ // A network failure rejects proxyFetch before any response.+ return {+ success: false,+ ...ipcErrorFields(+ asProviderError(error, { provider: "Anthropic", model: modelId, surface: "llm" })+ ),+ };}});@@ -6467,6 +6532,7 @@ class IPCHandlers {ipcMain.handle("retry-transcription", async (event, id, settings) => {const buffer = this.audioStorageManager.getAudioBuffer(id);if (!buffer) return { success: false, error: "Audio file not found" };+ let providerErrorContext = null;try {let result;const preferredLanguage = settings?.preferredLanguage;@@ -6498,6 +6564,22 @@ class IPCHandlers {throw err;}+ // Mirrors the branch order below: self-hosted wins over OpenWhispr+ // cloud, which wins over the BYOK providers. Managed, local and cloud+ // failures keep their own shape.+ if (+ (route.transport === "http-batch" && route.provider === "self-hosted") ||+ ((route.transport === "http-batch" || route.transport === "proxied") &&+ settings?.cloudTranscriptionMode !== "openwhispr")+ ) {+ providerErrorContext = {+ provider: transcriptionProviderName(route.provider),+ selfHosted: route.provider === "self-hosted" || route.provider === "custom",+ model: route.model,+ surface: "transcription",+ };+ }+if (route.transport === "managed") {const text = await this.executeManagedTranscription(event, route, {audioBuffer: buffer,@@ -6521,7 +6603,16 @@ class IPCHandlers {});if (!response.ok) {const errorText = await response.text();- throw new Error(`Self-hosted API Error: ${response.status} ${errorText}`);+ debugLogger.warn("Self-hosted retry failed", {+ status: response.status,+ body: redactProviderBody(errorText),+ });+ throw providerHttpError({+ ...providerErrorContext,+ status: response.status,+ body: errorText,+ headers: response.headers,+ });}const data = await response.json();if (data?.text) {@@ -6616,7 +6707,10 @@ class IPCHandlers {const clientId = this.environmentManager.getCortiClientId();const clientSecret = this.environmentManager.getCortiClientSecret();if (!clientId || !clientSecret) {- throw new Error("Corti credentials not configured. Add them in Settings.");+ throw providerError(PROVIDER_ERROR_CODES.KEY_MISSING, {+ provider: "Corti",+ surface: "transcription",+ });}const { transcribeAudio } = require("./cortiTranscription");const { text } = await transcribeAudio({@@ -6661,7 +6755,10 @@ class IPCHandlers {? this.environmentManager.getGroqKey(): this.environmentManager.getOpenAIKey();if (!apiKey && provider !== "custom") {- throw new Error(`${provider} API key not configured`);+ throw providerError(PROVIDER_ERROR_CODES.KEY_MISSING, {+ provider: transcriptionProviderName(provider),+ surface: "transcription",+ });}// The renderer re-encodes WebM before uploading to a Custom endpoint@@ -6717,7 +6814,17 @@ class IPCHandlers {const response = await proxyFetch(endpoint, { method: "POST", headers, body: formData });if (!response.ok) {const errorText = await response.text();- throw new Error(`${provider} API Error: ${response.status} ${errorText}`);+ debugLogger.warn("Retry transcription provider failed", {+ provider,+ status: response.status,+ body: redactProviderBody(errorText),+ });+ throw providerHttpError({+ ...providerErrorContext,+ status: response.status,+ body: errorText,+ headers: response.headers,+ });}const data = await response.json();if (data?.text) {@@ -6749,14 +6856,17 @@ class IPCHandlers {});}return { success: true, transcription: updated };- } catch (error) {+ } catch (rawError) {+ const error = providerErrorContext+ ? asProviderError(rawError, providerErrorContext)+ : rawError;debugLogger.error("Retry transcription failed",{ id, error: error.message, code: error.code },"audio-storage");if (error.code) {- return { success: false, error: error.message, code: error.code, ...error };+ return { success: false, ...ipcErrorFields(error) };}return { success: false, error: error.message };}@@ -10143,6 +10253,7 @@ class IPCHandlers {) => {const fs = require("fs");let cleanupUpload = null;+ let providerErrorContext = null;try {if (typeof filePath !== "string") {return { success: false, error: "Invalid file path" };@@ -10193,6 +10304,14 @@ class IPCHandlers {return { success: true, text };}+ // Every branch below calls a BYOK provider or the user's own server.+ providerErrorContext = {+ provider: transcriptionProviderName(route.provider),+ selfHosted: route.provider === "self-hosted" || route.provider === "custom",+ model: route.model,+ surface: "transcription",+ };+if (route.transport === "http-batch" && route.provider === "self-hosted") {// User's own server, so the 25 MB third-party cap does not apply.const { body, boundary } = buildMultipartBody(@@ -10203,11 +10322,15 @@ class IPCHandlers {);const data = await postMultipart(new URL(route.endpoint), body, boundary);if (data.statusCode !== 200) {- throw new Error(- data.data?.error?.message ||- data.data?.error ||- `Self-hosted API Error: ${data.statusCode}`- );+ debugLogger.warn("Self-hosted file transcription failed", {+ status: data.statusCode,+ body: redactProviderBody(data.data),+ });+ throw providerHttpError({+ ...providerErrorContext,+ status: data.statusCode,+ body: data.data,+ });}return { success: true, text: data.data.text };}@@ -10221,7 +10344,10 @@ class IPCHandlers {const clientId = this.environmentManager.getCortiClientId();const clientSecret = this.environmentManager.getCortiClientSecret();if (!clientId || !clientSecret) {- throw new Error("Corti credentials not configured. Add them in Settings.");+ throw providerError(PROVIDER_ERROR_CODES.KEY_MISSING, {+ provider: "Corti",+ surface: "transcription",+ });}const { transcribeAudio } = require("./cortiTranscription");const { text } = await transcribeAudio({@@ -10259,7 +10385,10 @@ class IPCHandlers {}if (!apiKey && route.provider !== "custom") {- throw new Error("No API key configured. Add your key in Settings.");+ throw providerError(PROVIDER_ERROR_CODES.KEY_MISSING, {+ provider: transcriptionProviderName(route.provider),+ surface: "transcription",+ });}const audioBuffer = fs.readFileSync(realByok);@@ -10331,16 +10460,17 @@ class IPCHandlers {: undefined;const data = await postMultipart(url, body, boundary, headers);- if (data.statusCode === 401) {- return { success: false, error: "Invalid API key. Check your key in Settings." };- }- if (data.statusCode === 429) {- return { success: false, error: "Rate limit exceeded. Please try again later." };- }if (data.statusCode !== 200) {- throw new Error(- data.data?.error?.message || data.data?.error || `API error: ${data.statusCode}`- );+ debugLogger.warn("BYOK file transcription failed", {+ provider: route.provider,+ status: data.statusCode,+ body: redactProviderBody(data.data),+ });+ throw providerHttpError({+ ...providerErrorContext,+ status: data.statusCode,+ body: data.data,+ });}if (diarize && data.data?.speakers) {@@ -10380,14 +10510,12 @@ class IPCHandlers {}const segments = timestamps ? mapVerboseSegments(data.data) : null;return { success: true, text: data.data.text, ...(segments ? { segments } : {}) };- } catch (error) {+ } catch (rawError) {+ const error = providerErrorContext+ ? asProviderError(rawError, providerErrorContext)+ : rawError;debugLogger.error("BYOK audio file transcription error", { error: error.message });- return {- success: false,- error: error.message,- code: error.code,- messageKey: error.messageKey,- };+ return { success: false, ...ipcErrorFields(error) };} finally {cleanupUpload?.();}@@ -11831,6 +11959,10 @@ class IPCHandlers {return this.windowManager?.consumePendingNoteNavigation() ?? null;});+ ipcMain.handle("get-pending-settings-section", async () => {+ return this.windowManager?.consumePendingSettingsSection() ?? null;+ });+ipcMain.handle("meeting-notification-ready", async (event) => {this.windowManager?.showNotificationWindow(event.sender);});diff --git a/src/helpers/providerHttpErrors.js b/src/helpers/providerHttpErrors.jsnew file mode 100644index 000000000..9cd1e6b02--- /dev/null+++ b/src/helpers/providerHttpErrors.js@@ -0,0 +1,308 @@+// ESM like emailCompose.js: imported by the renderer and loaded by the main+// process through require(esm). Pure on purpose (no electron, no logger) so+// both sides classify a provider failure the same way.++import { LLM_REQUEST_TIMEOUT_CODE } from "./llmRequestTimeout.js";++export const PROVIDER_ERROR_CODES = Object.freeze({+ AUTH_FAILED: "PROVIDER_AUTH_FAILED",+ ACCESS_DENIED: "PROVIDER_ACCESS_DENIED",+ QUOTA_EXHAUSTED: "PROVIDER_QUOTA_EXHAUSTED",+ RATE_LIMITED: "PROVIDER_RATE_LIMITED",+ MODEL_NOT_FOUND: "PROVIDER_MODEL_NOT_FOUND",+ PAYLOAD_TOO_LARGE: "PROVIDER_PAYLOAD_TOO_LARGE",+ BAD_REQUEST: "PROVIDER_BAD_REQUEST",+ UNAVAILABLE: "PROVIDER_UNAVAILABLE",+ TIMEOUT: "PROVIDER_TIMEOUT",+ UNREACHABLE: "PROVIDER_UNREACHABLE",+ NO_RESPONSE: "PROVIDER_NO_RESPONSE",+ ERROR: "PROVIDER_ERROR",+ KEY_MISSING: "API_KEY_MISSING",+});++const C = PROVIDER_ERROR_CODES;++const PROVIDER_SETTINGS_TARGETS = Object.freeze(["speechToText", "llms"]);++export const isProviderSettingsTarget = (value) => PROVIDER_SETTINGS_TARGETS.includes(value);++const SETTINGS_TARGET_BY_SURFACE = { transcription: "speechToText", llm: "llms" };++// Only failures the user fixes in Settings get the deep link.+const FIXABLE = new Set([+ C.AUTH_FAILED,+ C.ACCESS_DENIED,+ C.QUOTA_EXHAUSTED,+ C.MODEL_NOT_FOUND,+ C.NO_RESPONSE,+ C.KEY_MISSING,+]);++const MESSAGE_KEYS = {+ [C.AUTH_FAILED]: "providerErrors.authFailed",+ [C.ACCESS_DENIED]: "providerErrors.accessDenied",+ [C.QUOTA_EXHAUSTED]: "providerErrors.quotaExhausted",+ [C.RATE_LIMITED]: "hooks.audioRecording.errorDescriptions.providerRateLimited",+ [C.MODEL_NOT_FOUND]: "providerErrors.modelNotFound",+ [C.PAYLOAD_TOO_LARGE]: "providerErrors.payloadTooLarge",+ [C.BAD_REQUEST]: "providerErrors.badRequest",+ [C.UNAVAILABLE]: "providerErrors.unavailable",+ [C.TIMEOUT]: "providerErrors.timeout",+ [C.UNREACHABLE]: "providerErrors.unreachable",+ [C.NO_RESPONSE]: "providerErrors.noResponse",+ [C.ERROR]: "providerErrors.unknown",+};++// English twins of the en locale strings, by message key: Error.message is what+// History rows, logs and key-less surfaces show, so it reads as a sentence, not+// a status dump. The transcription-only hooks keys say "your transcription+// provider"; their twins name it, since History has no other place to.+const ENGLISH = {+ "providerErrors.authFailed": "{{provider}} rejected your API key.",+ "providerErrors.accessDenied": "{{provider}} denied access. Your key may not include this model.",+ "providerErrors.quotaExhausted": "Your {{provider}} account is out of credit.",+ "providerErrors.rateLimited":+ "{{provider}} rate-limited the request. Wait a moment and try again.",+ "providerErrors.modelNotFound": "{{provider}} doesn't recognize the model “{{model}}”.",+ "providerErrors.modelNotFoundNoModel": "{{provider}} doesn't recognize the selected model.",+ "providerErrors.payloadTooLarge": "This recording is too large for {{provider}}.",+ "providerErrors.requestTooLarge": "This request is too large for {{provider}}.",+ "providerErrors.badRequest": "{{provider}} couldn't process this request.",+ "providerErrors.unavailable": "{{provider}} is having problems right now. Try again shortly.",+ "providerErrors.timeout": "{{provider}} took too long to respond.",+ "providerErrors.unreachable": "Couldn't reach {{provider}}. Check your connection.",+ "providerErrors.noResponse":+ "Couldn't get a response from {{provider}}. Check your API key and connection.",+ "providerErrors.unknown": "{{provider}} returned an unexpected error.",+ "providerErrors.keyMissing":+ "No API key is set for {{provider}}. Add it in Settings → Language Models.",+ "providerErrors.selfHosted.authFailed": "Your server rejected the API key.",+ "providerErrors.selfHosted.accessDenied":+ "Your server denied access. The key may not include this model.",+ "providerErrors.selfHosted.quotaExhausted": "Your server says the account is out of credit.",+ "providerErrors.selfHosted.rateLimited":+ "Your server rate-limited the request. Wait a moment and try again.",+ "providerErrors.selfHosted.modelNotFound": "Your server doesn't recognize the model “{{model}}”.",+ "providerErrors.selfHosted.modelNotFoundNoModel":+ "Your server doesn't recognize the selected model.",+ "providerErrors.selfHosted.payloadTooLarge": "This recording is too large for your server.",+ "providerErrors.selfHosted.requestTooLarge": "This request is too large for your server.",+ "providerErrors.selfHosted.badRequest": "Your server couldn't process this request.",+ "providerErrors.selfHosted.unavailable":+ "Your server is having problems right now. Try again shortly.",+ "providerErrors.selfHosted.timeout": "Your server took too long to respond.",+ "providerErrors.selfHosted.unreachable": "Couldn't reach your server. Check that it's running.",+ "providerErrors.selfHosted.noResponse":+ "Couldn't get a response from your server. Check its API key and that it's running.",+ "providerErrors.selfHosted.unknown": "Your server returned an unexpected error.",+ "hooks.audioRecording.errorDescriptions.providerRateLimited":+ "{{provider}} rate-limited the request. Wait a moment and try again.",+ "hooks.audioRecording.errorDescriptions.providerKeyMissing":+ "No API key is set for {{provider}}.",+};++export const SELF_HOSTED_NAME = "Your server";++const INVALID_KEY_SIGNAL =+ /invalid[ _-]?(x-)?api[ _-]?key|incorrect api key|api_key_invalid|authentication_error|unauthorized/i;+// Only signals that mean the account is out of credit. Rate-limit 429s use the+// broader words: Gemini's starts "You exceeded your current quota, please check+// your plan and billing details" and Groq's links to its /settings/billing page.+const QUOTA_SIGNAL =+ /insufficient_quota|credit balance|insufficient (credits|balance|funds)|out of credits|payment required/i;+const MODEL_SIGNAL =+ /model_not_found|model[^.\n]{0,80}(not found|does not exist|not available|is not supported)|(unknown|invalid|unsupported) model/i;++const NETWORK_CODES = new Set([+ "ENOTFOUND",+ "EAI_AGAIN",+ "ECONNREFUSED",+ "ECONNRESET",+ "EPIPE",+ "ETIMEDOUT",+ "UND_ERR_SOCKET",+ "UND_ERR_CONNECT_TIMEOUT",+ "CERT_HAS_EXPIRED",+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",+ "DEPTH_ZERO_SELF_SIGNED_CERT",+]);++// Electron's net.fetch rejects with a plain Error whose message is the+// Chromium net error (no code). ERR_ABORTED is a cancellation, never a failure.+const ELECTRON_NET_ERROR = /net::ERR_[A-Z_]+/;+const ELECTRON_NET_TIMEOUTS = new Set(["net::ERR_TIMED_OUT", "net::ERR_CONNECTION_TIMED_OUT"]);++function electronNetError(err) {+ const match = typeof err.message === "string" ? err.message.match(ELECTRON_NET_ERROR) : null;+ return match && match[0] !== "net::ERR_ABORTED" ? match[0] : null;+}++const MAX_DETAIL_CHARS = 500;++const SECRET_PATTERNS = [+ [/\bBearer\s+[A-Za-z0-9._~+/=-]{4,}/gi, "Bearer [redacted]"],+ [/\bsk-(?:ant-|proj-)?[A-Za-z0-9_*.-]{4,}/g, "[redacted]"],+ [/\bgsk_[A-Za-z0-9*]{4,}/g, "[redacted]"],+ [/\bAIza[A-Za-z0-9_-]{4,}/g, "[redacted]"],+ [/\bxai-[A-Za-z0-9*]{4,}/g, "[redacted]"],+];++function bodyToText(body) {+ if (body == null) return "";+ return typeof body === "string" ? body : JSON.stringify(body);+}++export function redactProviderBody(body) {+ let text = bodyToText(body);+ if (/<\s*(!doctype|html|body|head)\b/i.test(text)) return "<HTML response>";+ for (const [pattern, replacement] of SECRET_PATTERNS) {+ text = text.replace(pattern, replacement);+ }+ text = text.replace(/\s+/g, " ").trim();+ return text.length > MAX_DETAIL_CHARS ? `${text.slice(0, MAX_DETAIL_CHARS)}…` : text;+}++function readHeader(headers, name) {+ if (!headers) return undefined;+ if (typeof headers.get === "function") return headers.get(name) || undefined;+ const match = Object.keys(headers).find((key) => key.toLowerCase() === name);+ return match ? headers[match] : undefined;+}++function requestIdFrom(headers) {+ return (+ readHeader(headers, "x-request-id") ||+ readHeader(headers, "request-id") ||+ readHeader(headers, "cf-ray")+ );+}++function codeForStatus(status, text, selfHosted) {+ if (status === 401) return C.AUTH_FAILED;+ if ((status === 400 || status === 403) && INVALID_KEY_SIGNAL.test(text)) return C.AUTH_FAILED;+ if (status === 402) return C.QUOTA_EXHAUSTED;+ if ([400, 403, 429].includes(status) && QUOTA_SIGNAL.test(text)) return C.QUOTA_EXHAUSTED;+ if (status === 403) return C.ACCESS_DENIED;+ if (status === 429) return C.RATE_LIMITED;+ if (status === 404) {+ // A self-hosted 404 is far more often a wrong URL than a wrong model.+ return selfHosted && !MODEL_SIGNAL.test(text) ? C.ERROR : C.MODEL_NOT_FOUND;+ }+ if (status === 400 && MODEL_SIGNAL.test(text)) return C.MODEL_NOT_FOUND;+ if (status === 413) return C.PAYLOAD_TOO_LARGE;+ if ([400, 415, 422].includes(status)) return C.BAD_REQUEST;+ if (status === 408 || status === 504) return C.TIMEOUT;+ if (status >= 500 && status < 600) return C.UNAVAILABLE;+ return C.ERROR;+}++function buildClassification(code, { provider, model, surface, selfHosted, technicalDetails }) {+ const providerName = selfHosted ? SELF_HOSTED_NAME : provider;+ const messageParams = { provider: providerName };+ let messageKey = MESSAGE_KEYS[code];+ if (code === C.MODEL_NOT_FOUND) {+ if (model) messageParams.model = model;+ else messageKey = "providerErrors.modelNotFoundNoModel";+ }+ if (code === C.KEY_MISSING) {+ messageKey =+ surface === "transcription"+ ? "hooks.audioRecording.errorDescriptions.providerKeyMissing"+ : "providerErrors.keyMissing";+ }+ if (surface === "llm") {+ // The transcription keys are the dictation pill's established copy; LLM+ // surfaces name the provider and send text, not a recording.+ if (code === C.RATE_LIMITED) messageKey = "providerErrors.rateLimited";+ if (code === C.PAYLOAD_TOO_LARGE) messageKey = "providerErrors.requestTooLarge";+ }+ // "Your server" takes a different case or article in each sentence in many+ // languages (Russian, German), so self-hosted errors have their own sentences.+ if (selfHosted && messageKey.startsWith("providerErrors.")) {+ messageKey = messageKey.replace("providerErrors.", "providerErrors.selfHosted.");+ }+ const settingsTarget = FIXABLE.has(code) ? SETTINGS_TARGET_BY_SURFACE[surface] : undefined;+ return {+ code,+ messageKey,+ messageParams,+ surface,+ ...(settingsTarget ? { settingsTarget } : {}),+ technicalDetails: { provider: providerName, ...(technicalDetails || {}) },+ };+}++function englishMessage({ messageKey, messageParams }) {+ return ENGLISH[messageKey].replace(/\{\{(\w+)\}\}/g, (_, name) => messageParams[name] ?? "");+}++function toError(classification, extra = {}) {+ return Object.assign(new Error(englishMessage(classification)), classification, extra);+}++export function providerHttpError(args) {+ const { provider, status, body, headers, model, surface, selfHosted = false } = args;+ const text = bodyToText(body);+ const underlyingError = redactProviderBody(text);+ const requestId = requestIdFrom(headers);+ return toError(+ buildClassification(codeForStatus(status, text, selfHosted), {+ provider,+ model,+ surface,+ selfHosted,+ technicalDetails: {+ status,+ ...(requestId ? { requestId } : {}),+ ...(underlyingError ? { underlyingError } : {}),+ },+ }),+ { status }+ );+}++export function providerError(code, ctx) {+ return toError(buildClassification(code, ctx), { provider: ctx.provider });+}++export function asProviderError(err, ctx) {+ if (!err || typeof err !== "object" || err.messageKey || err.name === "AbortError") return err;+ const inner = err.name === "AI_RetryError" && err.lastError ? err.lastError : err;+ const netError = electronNetError(inner);+ const nodeCode = [inner.code, inner.cause?.code].find((code) => NETWORK_CODES.has(code));+ let classified = null;+ if (typeof inner.statusCode === "number") {+ classified = providerHttpError({+ ...ctx,+ status: inner.statusCode,+ body: inner.responseBody ?? inner.message,+ headers: inner.responseHeaders,+ });+ } else if (inner.code === LLM_REQUEST_TIMEOUT_CODE || inner.name === "TimeoutError") {+ classified = providerError(C.TIMEOUT, ctx);+ } else if (netError) {+ classified = providerError(ELECTRON_NET_TIMEOUTS.has(netError) ? C.TIMEOUT : C.UNREACHABLE, {+ ...ctx,+ technicalDetails: { underlyingError: netError },+ });+ } else if (+ nodeCode ||+ (inner instanceof TypeError && /fetch failed|network/i.test(inner.message))+ ) {+ classified = providerError(C.UNREACHABLE, {+ ...ctx,+ ...(nodeCode ? { technicalDetails: { underlyingError: nodeCode } } : {}),+ });+ } else if (inner instanceof TypeError && /failed to fetch/i.test(inner.message)) {+ // Chromium's fetch also reports a CORS-blocked HTTP error this way (OpenAI+ // answers a bad sk- key with a 401 that has no CORS header), so online it+ // may be the key. Main never sees this message.+ classified = providerError(+ globalThis.navigator?.onLine === false ? C.UNREACHABLE : C.NO_RESPONSE,+ ctx+ );+ }+ if (!classified) return err;+ classified.cause = err;+ return classified;+}diff --git a/src/helpers/tinfoilTranscription.js b/src/helpers/tinfoilTranscription.jsindex 7f931b058..b47e08075 100644--- a/src/helpers/tinfoilTranscription.js+++ b/src/helpers/tinfoilTranscription.js@@ -1,6 +1,12 @@const debugLogger = require("./debugLogger");const modelRegistryData = require("../models/modelRegistryData.json");const { tinfoilSecureFetch } = require("./tinfoilSecureClient");+const {+ PROVIDER_ERROR_CODES,+ providerHttpError,+ providerError,+ redactProviderBody,+} = require("./providerHttpErrors");const TINFOIL_TRANSCRIPTION_PATH = "/v1/audio/transcriptions";@@ -26,9 +32,10 @@ async function transcribeWithTinfoil({apiKey,}) {if (!apiKey?.trim()) {- const error = new Error("Tinfoil API key not configured. Add your key in Settings.");- error.code = "API_KEY_MISSING";- throw error;+ throw providerError(PROVIDER_ERROR_CODES.KEY_MISSING, {+ provider: "Tinfoil",+ surface: "transcription",+ });}const model = getBatchModel();@@ -50,21 +57,20 @@ async function transcribeWithTinfoil({body: formData,});- if (response.status === 401) {- const error = new Error("Invalid Tinfoil API key. Check your key in Settings.");- error.code = "INVALID_KEY";- throw error;- }if (!response.ok) {const errorText = await response.text().catch(() => "");- const error = new Error(`Tinfoil API Error: ${response.status} ${errorText}`.trim());- if (response.status === 429) {- error.code = "PROVIDER_RATE_LIMITED";- error.messageKey = "hooks.audioRecording.errorDescriptions.providerRateLimited";- } else if (response.status >= 500) {- error.code = "SERVER_ERROR";- }- throw error;+ debugLogger.warn("Tinfoil transcription failed", {+ status: response.status,+ body: redactProviderBody(errorText),+ });+ throw providerHttpError({+ provider: "Tinfoil",+ model,+ status: response.status,+ body: errorText,+ headers: response.headers,+ surface: "transcription",+ });}const data = await response.json();diff --git a/src/helpers/transcriptionFailureOutcome.js b/src/helpers/transcriptionFailureOutcome.jsindex 652a6b83f..2c02294ab 100644--- a/src/helpers/transcriptionFailureOutcome.js+++ b/src/helpers/transcriptionFailureOutcome.js@@ -1,4 +1,5 @@import { DICTIONARY_ECHO_CODE } from "../utils/dictionaryEchoFilter.js";+import { IPC_ERROR_FIELDS } from "./ipcErrorFields.js";// How a transcription failure ends, for batch recordings and re-uploaded// streaming ones alike. Silence is not reported. A transcript discarded as an@@ -12,16 +13,14 @@ export const transcriptionFailureOutcome = (error) => {if (error.message === "No audio detected") {return { noAudio: true, keepAudio: false, report: null };}- return {- noAudio: false,- keepAudio: true,- report: {- title: error.selectionEditFatal ? "Selection Edit Failed" : "Transcription Error",- description: error.selectionEditFatal- ? error.message- : `Transcription failed: ${error.message}`,- code: error.code,- messageKey: error.messageKey,- },+ const report = {+ title: error.selectionEditFatal ? "Selection Edit Failed" : "Transcription Error",+ description: error.selectionEditFatal+ ? error.message+ : `Transcription failed: ${error.message}`,};+ for (const key of IPC_ERROR_FIELDS) {+ if (error[key] !== undefined) report[key] = error[key];+ }+ return { noAudio: false, keepAudio: true, report };};diff --git a/src/helpers/windowManager.js b/src/helpers/windowManager.jsindex af226a0b9..e4bc2cca1 100644--- a/src/helpers/windowManager.js+++ b/src/helpers/windowManager.js@@ -104,6 +104,7 @@ class WindowManager {this._assistantPanelBusy = false;this._pendingMeetingNoteNavigation = null;this._pendingNoteNavigation = null;+ this._pendingSettingsSection = null;app.on("before-quit", () => {this.isQuitting = true;@@ -2256,13 +2257,22 @@ class WindowManager {}}- async openSettings() {+ // A named section waits here like a note navigation: a control panel created+ // by this call registers its show-settings listener only after the event.+ async openSettings(section) {+ if (section) this._pendingSettingsSection = section;await this.createControlPanelWindow();if (this.controlPanelWindow && !this.controlPanelWindow.isDestroyed()) {this.controlPanelWindow.webContents.send("show-settings");}}+ consumePendingSettingsSection() {+ const section = this._pendingSettingsSection;+ this._pendingSettingsSection = null;+ return section;+ }+showLoadFailureDialog(windowName, errorCode, errorDescription, validatedURL) {if (this.loadErrorShown) {return;diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.jsindex 3d0b653b3..be1f3285d 100644--- a/src/hooks/useAudioRecording.js+++ b/src/hooks/useAudioRecording.js@@ -6,6 +6,7 @@ import { playStartCue, playStopCue } from "../utils/dictationCues";import { getSettings } from "../stores/settingsStore";import { expandSnippets } from "../utils/snippets";import { getRecordingErrorTitle, getRecordingErrorDescription } from "../utils/recordingErrors";+import { providerErrorActions } from "../utils/describeProviderError";import { isAccessibilitySkipped } from "../utils/permissions";import { needsSttConfigBeforeStart } from "../helpers/sttConfigPolicy";import {@@ -361,6 +362,8 @@ export const useAudioRecording = (toast, options = {}) => {code,settingsLaunchFailed = false,onRetry,+ settingsTarget,+ technicalDetails,}) => {const errorGeneration = ++dictationErrorGenerationRef.current;const isCurrent = () => errorGeneration === dictationErrorGenerationRef.current;@@ -468,6 +471,8 @@ export const useAudioRecording = (toast, options = {}) => {},];+ actions.push(...providerErrorActions({ settingsTarget, technicalDetails }, t, isCurrent));+if (recoverableTranscript) {actions.push({label: t("hooks.audioRecording.errorActions.viewTranscript"),@@ -563,6 +568,8 @@ export const useAudioRecording = (toast, options = {}) => {duration: error?.code === "AUTH_EXPIRED" ? 8000 : undefined,code: error?.code,transcript: error?.transcript,+ settingsTarget: error?.settingsTarget,+ technicalDetails: error?.technicalDetails,});}if (getSettings().pauseMediaOnDictation) {diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.jsonindex ebf886c9b..a0af9a69c 100644--- a/src/locales/ar/translation.json+++ b/src/locales/ar/translation.json@@ -4896,5 +4896,48 @@},"start": "تدوين الملاحظات","join": "انضمام وتفريغ صوتي"+ },+ "providerErrors": {+ "authFailed": "رفض {{provider}} مفتاح API الخاص بك.",+ "accessDenied": "رفض {{provider}} الوصول. قد لا يشمل مفتاحك هذا النموذج.",+ "quotaExhausted": "نفذ الرصيد في حساب {{provider}} الخاص بك.",+ "rateLimited": "قام {{provider}} بتقييد معدل الطلب. انتظر لحظة وحاول مرة أخرى.",+ "modelNotFound": "لا يتعرّف {{provider}} على النموذج “{{model}}”.",+ "modelNotFoundNoModel": "لا يتعرّف {{provider}} على النموذج المحدد.",+ "payloadTooLarge": "هذا التسجيل أكبر من أن يقبله {{provider}}.",+ "requestTooLarge": "هذا الطلب أكبر من أن يقبله {{provider}}.",+ "badRequest": "تعذّر على {{provider}} معالجة هذا الطلب.",+ "unavailable": "يواجه {{provider}} مشكلات الآن. حاول مرة أخرى بعد قليل.",+ "timeout": "استغرق {{provider}} وقتًا طويلاً للاستجابة.",+ "unreachable": "تعذّر الوصول إلى {{provider}}. تحقق من اتصالك.",+ "noResponse": "تعذّر الحصول على رد من {{provider}}. تحقق من مفتاح API واتصالك.",+ "unknown": "أعاد {{provider}} خطأ غير متوقع.",+ "keyMissing": "لا يوجد مفتاح API مضبوط لـ {{provider}}. أضفه في الإعدادات ← النماذج اللغوية.",+ "selfHosted": {+ "authFailed": "رفض خادمك مفتاح API.",+ "accessDenied": "رفض خادمك الوصول. قد لا يشمل المفتاح هذا النموذج.",+ "quotaExhausted": "يفيد خادمك بأن الحساب قد نفذ رصيده.",+ "rateLimited": "قام خادمك بتقييد معدل الطلب. انتظر لحظة وحاول مرة أخرى.",+ "modelNotFound": "لا يتعرّف خادمك على النموذج “{{model}}”.",+ "modelNotFoundNoModel": "لا يتعرّف خادمك على النموذج المحدد.",+ "payloadTooLarge": "هذا التسجيل أكبر من أن يقبله خادمك.",+ "requestTooLarge": "هذا الطلب أكبر من أن يقبله خادمك.",+ "badRequest": "تعذّر على خادمك معالجة هذا الطلب.",+ "unavailable": "يواجه خادمك مشكلات الآن. حاول مرة أخرى بعد قليل.",+ "timeout": "استغرق خادمك وقتًا طويلاً للاستجابة.",+ "unreachable": "تعذّر الوصول إلى خادمك. تحقق من أنه قيد التشغيل.",+ "noResponse": "تعذّر الحصول على رد من خادمك. تحقق من مفتاح API الخاص به ومن أنه قيد التشغيل.",+ "unknown": "أعاد خادمك خطأ غير متوقع."+ },+ "openSettings": "فتح الإعدادات",+ "copyDetails": "نسخ التفاصيل",+ "titles": {+ "transcription": "فشل التفريغ الصوتي",+ "llm": "فشل طلب الذكاء الاصطناعي"+ },+ "details": {+ "provider": "المزوّد",+ "requestId": "معرّف الطلب"+ }}}diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 2c24d4f60..672723297 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -4774,5 +4774,48 @@},"start": "Notizen aufnehmen","join": "Beitreten & transkribieren"+ },+ "providerErrors": {+ "authFailed": "{{provider}} hat Ihren API-Schlüssel abgelehnt.",+ "accessDenied": "{{provider}} hat den Zugriff verweigert. Ihr Schlüssel deckt dieses Modell möglicherweise nicht ab.",+ "quotaExhausted": "Ihr {{provider}}-Konto hat kein Guthaben mehr.",+ "rateLimited": "{{provider}} hat die Anfrage begrenzt. Warten Sie einen Moment und versuchen Sie es erneut.",+ "modelNotFound": "{{provider}} kennt das Modell „{{model}}“ nicht.",+ "modelNotFoundNoModel": "{{provider}} kennt das ausgewählte Modell nicht.",+ "payloadTooLarge": "Diese Aufnahme ist für {{provider}} zu groß.",+ "requestTooLarge": "Diese Anfrage ist für {{provider}} zu groß.",+ "badRequest": "{{provider}} konnte diese Anfrage nicht verarbeiten.",+ "unavailable": "{{provider}} hat derzeit Probleme. Versuchen Sie es in Kürze erneut.",+ "timeout": "{{provider}} hat zu lange zum Antworten gebraucht.",+ "unreachable": "{{provider}} konnte nicht erreicht werden. Überprüfen Sie Ihre Verbindung.",+ "noResponse": "Keine Antwort von {{provider}} erhalten. Überprüfen Sie Ihren API-Schlüssel und Ihre Verbindung.",+ "unknown": "{{provider}} hat einen unerwarteten Fehler zurückgegeben.",+ "keyMissing": "Für {{provider}} ist kein API-Schlüssel hinterlegt. Fügen Sie ihn unter Einstellungen → Sprachmodelle hinzu.",+ "selfHosted": {+ "authFailed": "Ihr Server hat den API-Schlüssel abgelehnt.",+ "accessDenied": "Ihr Server hat den Zugriff verweigert. Der Schlüssel deckt dieses Modell möglicherweise nicht ab.",+ "quotaExhausted": "Ihr Server meldet, dass das Konto kein Guthaben mehr hat.",+ "rateLimited": "Ihr Server hat die Anfrage begrenzt. Warten Sie einen Moment und versuchen Sie es erneut.",+ "modelNotFound": "Ihr Server kennt das Modell „{{model}}“ nicht.",+ "modelNotFoundNoModel": "Ihr Server kennt das ausgewählte Modell nicht.",+ "payloadTooLarge": "Diese Aufnahme ist für Ihren Server zu groß.",+ "requestTooLarge": "Diese Anfrage ist für Ihren Server zu groß.",+ "badRequest": "Ihr Server konnte diese Anfrage nicht verarbeiten.",+ "unavailable": "Ihr Server hat derzeit Probleme. Versuchen Sie es in Kürze erneut.",+ "timeout": "Ihr Server hat zu lange zum Antworten gebraucht.",+ "unreachable": "Ihr Server konnte nicht erreicht werden. Überprüfen Sie, ob er läuft.",+ "noResponse": "Keine Antwort von Ihrem Server erhalten. Überprüfen Sie seinen API-Schlüssel und ob er läuft.",+ "unknown": "Ihr Server hat einen unerwarteten Fehler zurückgegeben."+ },+ "openSettings": "Einstellungen öffnen",+ "copyDetails": "Details kopieren",+ "titles": {+ "transcription": "Transkription fehlgeschlagen",+ "llm": "KI-Anfrage fehlgeschlagen"+ },+ "details": {+ "provider": "Anbieter",+ "requestId": "Anfrage-ID"+ }}}diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 43dd3bd04..aab15ea85 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -4774,5 +4774,48 @@},"start": "Take notes","join": "Join & transcribe"+ },+ "providerErrors": {+ "authFailed": "{{provider}} rejected your API key.",+ "accessDenied": "{{provider}} denied access. Your key may not include this model.",+ "quotaExhausted": "Your {{provider}} account is out of credit.",+ "rateLimited": "{{provider}} rate-limited the request. Wait a moment and try again.",+ "modelNotFound": "{{provider}} doesn't recognize the model “{{model}}”.",+ "modelNotFoundNoModel": "{{provider}} doesn't recognize the selected model.",+ "payloadTooLarge": "This recording is too large for {{provider}}.",+ "requestTooLarge": "This request is too large for {{provider}}.",+ "badRequest": "{{provider}} couldn't process this request.",+ "unavailable": "{{provider}} is having problems right now. Try again shortly.",+ "timeout": "{{provider}} took too long to respond.",+ "unreachable": "Couldn't reach {{provider}}. Check your connection.",+ "noResponse": "Couldn't get a response from {{provider}}. Check your API key and connection.",+ "unknown": "{{provider}} returned an unexpected error.",+ "keyMissing": "No API key is set for {{provider}}. Add it in Settings → Language Models.",+ "selfHosted": {+ "authFailed": "Your server rejected the API key.",+ "accessDenied": "Your server denied access. The key may not include this model.",+ "quotaExhausted": "Your server says the account is out of credit.",+ "rateLimited": "Your server rate-limited the request. Wait a moment and try again.",+ "modelNotFound": "Your server doesn't recognize the model “{{model}}”.",+ "modelNotFoundNoModel": "Your server doesn't recognize the selected model.",+ "payloadTooLarge": "This recording is too large for your server.",+ "requestTooLarge": "This request is too large for your server.",+ "badRequest": "Your server couldn't process this request.",+ "unavailable": "Your server is having problems right now. Try again shortly.",+ "timeout": "Your server took too long to respond.",+ "unreachable": "Couldn't reach your server. Check that it's running.",+ "noResponse": "Couldn't get a response from your server. Check its API key and that it's running.",+ "unknown": "Your server returned an unexpected error."+ },+ "openSettings": "Open Settings",+ "copyDetails": "Copy details",+ "titles": {+ "transcription": "Transcription failed",+ "llm": "AI request failed"+ },+ "details": {+ "provider": "Provider",+ "requestId": "Request ID"+ }}}diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex e8dd81d8b..bf97741b6 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -4774,5 +4774,48 @@},"start": "Tomar notas","join": "Unirse y transcribir"+ },+ "providerErrors": {+ "authFailed": "{{provider}} rechazó tu clave de API.",+ "accessDenied": "{{provider}} denegó el acceso. Es posible que tu clave no incluya este modelo.",+ "quotaExhausted": "Tu cuenta de {{provider}} se ha quedado sin crédito.",+ "rateLimited": "{{provider}} limitó la solicitud. Espera un momento e inténtalo de nuevo.",+ "modelNotFound": "{{provider}} no reconoce el modelo «{{model}}».",+ "modelNotFoundNoModel": "{{provider}} no reconoce el modelo seleccionado.",+ "payloadTooLarge": "Esta grabación es demasiado grande para {{provider}}.",+ "requestTooLarge": "Esta solicitud es demasiado grande para {{provider}}.",+ "badRequest": "{{provider}} no pudo procesar esta solicitud.",+ "unavailable": "{{provider}} está teniendo problemas en este momento. Inténtalo de nuevo en breve.",+ "timeout": "{{provider}} tardó demasiado en responder.",+ "unreachable": "No se pudo conectar con {{provider}}. Comprueba tu conexión.",+ "noResponse": "No se recibió respuesta de {{provider}}. Comprueba tu clave de API y tu conexión.",+ "unknown": "{{provider}} devolvió un error inesperado.",+ "keyMissing": "No hay ninguna clave de API configurada para {{provider}}. Añádela en Ajustes → Modelos de lenguaje.",+ "selfHosted": {+ "authFailed": "Tu servidor rechazó la clave de API.",+ "accessDenied": "Tu servidor denegó el acceso. Es posible que la clave no incluya este modelo.",+ "quotaExhausted": "Tu servidor indica que la cuenta se ha quedado sin crédito.",+ "rateLimited": "Tu servidor limitó la solicitud. Espera un momento e inténtalo de nuevo.",+ "modelNotFound": "Tu servidor no reconoce el modelo «{{model}}».",+ "modelNotFoundNoModel": "Tu servidor no reconoce el modelo seleccionado.",+ "payloadTooLarge": "Esta grabación es demasiado grande para tu servidor.",+ "requestTooLarge": "Esta solicitud es demasiado grande para tu servidor.",+ "badRequest": "Tu servidor no pudo procesar esta solicitud.",+ "unavailable": "Tu servidor está teniendo problemas en este momento. Inténtalo de nuevo en breve.",+ "timeout": "Tu servidor tardó demasiado en responder.",+ "unreachable": "No se pudo conectar con tu servidor. Comprueba que esté en funcionamiento.",+ "noResponse": "No se recibió respuesta de tu servidor. Comprueba su clave de API y que esté en funcionamiento.",+ "unknown": "Tu servidor devolvió un error inesperado."+ },+ "openSettings": "Abrir Ajustes",+ "copyDetails": "Copiar detalles",+ "titles": {+ "transcription": "Error de transcripción",+ "llm": "Error en la solicitud de IA"+ },+ "details": {+ "provider": "Proveedor",+ "requestId": "ID de solicitud"+ }}}diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 6d2683a40..a3ea51d55 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -4774,5 +4774,48 @@},"start": "Prendre des notes","join": "Rejoindre et transcrire"+ },+ "providerErrors": {+ "authFailed": "{{provider}} a rejeté votre clé API.",+ "accessDenied": "{{provider}} a refusé l’accès. Votre clé ne couvre peut-être pas ce modèle.",+ "quotaExhausted": "Votre compte {{provider}} n’a plus de crédit.",+ "rateLimited": "{{provider}} a limité la requête. Patientez un instant et réessayez.",+ "modelNotFound": "{{provider}} ne reconnaît pas le modèle « {{model}} ».",+ "modelNotFoundNoModel": "{{provider}} ne reconnaît pas le modèle sélectionné.",+ "payloadTooLarge": "Cet enregistrement est trop volumineux pour {{provider}}.",+ "requestTooLarge": "Cette requête est trop volumineuse pour {{provider}}.",+ "badRequest": "{{provider}} n’a pas pu traiter cette requête.",+ "unavailable": "{{provider}} rencontre actuellement des problèmes. Réessayez dans un instant.",+ "timeout": "{{provider}} a pris trop de temps à répondre.",+ "unreachable": "Impossible de contacter {{provider}}. Vérifiez votre connexion.",+ "noResponse": "Aucune réponse de {{provider}}. Vérifiez votre clé API et votre connexion.",+ "unknown": "{{provider}} a renvoyé une erreur inattendue.",+ "keyMissing": "Aucune clé API n’est définie pour {{provider}}. Ajoutez-la dans Réglages → Modèles de langage.",+ "selfHosted": {+ "authFailed": "Votre serveur a rejeté la clé API.",+ "accessDenied": "Votre serveur a refusé l’accès. La clé ne couvre peut-être pas ce modèle.",+ "quotaExhausted": "Votre serveur indique que le compte n’a plus de crédit.",+ "rateLimited": "Votre serveur a limité la requête. Patientez un instant et réessayez.",+ "modelNotFound": "Votre serveur ne reconnaît pas le modèle « {{model}} ».",+ "modelNotFoundNoModel": "Votre serveur ne reconnaît pas le modèle sélectionné.",+ "payloadTooLarge": "Cet enregistrement est trop volumineux pour votre serveur.",+ "requestTooLarge": "Cette requête est trop volumineuse pour votre serveur.",+ "badRequest": "Votre serveur n’a pas pu traiter cette requête.",+ "unavailable": "Votre serveur rencontre actuellement des problèmes. Réessayez dans un instant.",+ "timeout": "Votre serveur a pris trop de temps à répondre.",+ "unreachable": "Impossible de contacter votre serveur. Vérifiez qu’il est en cours d’exécution.",+ "noResponse": "Aucune réponse de votre serveur. Vérifiez sa clé API et qu’il est en cours d’exécution.",+ "unknown": "Votre serveur a renvoyé une erreur inattendue."+ },+ "openSettings": "Ouvrir les réglages",+ "copyDetails": "Copier les détails",+ "titles": {+ "transcription": "Échec de la transcription",+ "llm": "Échec de la requête IA"+ },+ "details": {+ "provider": "Fournisseur",+ "requestId": "ID de requête"+ }}}diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 92bcaf535..40fdcff82 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -4774,5 +4774,48 @@},"start": "Prendi appunti","join": "Partecipa e trascrivi"+ },+ "providerErrors": {+ "authFailed": "{{provider}} ha rifiutato la tua chiave API.",+ "accessDenied": "{{provider}} ha negato l’accesso. La tua chiave potrebbe non includere questo modello.",+ "quotaExhausted": "Il tuo account {{provider}} ha esaurito il credito.",+ "rateLimited": "{{provider}} ha limitato la richiesta. Attendi un momento e riprova.",+ "modelNotFound": "{{provider}} non riconosce il modello “{{model}}”.",+ "modelNotFoundNoModel": "{{provider}} non riconosce il modello selezionato.",+ "payloadTooLarge": "Questa registrazione è troppo grande per {{provider}}.",+ "requestTooLarge": "Questa richiesta è troppo grande per {{provider}}.",+ "badRequest": "{{provider}} non è riuscito a elaborare questa richiesta.",+ "unavailable": "{{provider}} sta avendo problemi in questo momento. Riprova a breve.",+ "timeout": "{{provider}} ha impiegato troppo tempo a rispondere.",+ "unreachable": "Impossibile contattare {{provider}}. Controlla la tua connessione.",+ "noResponse": "Nessuna risposta da {{provider}}. Controlla la tua chiave API e la connessione.",+ "unknown": "{{provider}} ha restituito un errore imprevisto.",+ "keyMissing": "Nessuna chiave API impostata per {{provider}}. Aggiungila in Impostazioni → Modelli linguistici.",+ "selfHosted": {+ "authFailed": "Il tuo server ha rifiutato la chiave API.",+ "accessDenied": "Il tuo server ha negato l’accesso. La chiave potrebbe non includere questo modello.",+ "quotaExhausted": "Il tuo server segnala che l'account ha esaurito il credito.",+ "rateLimited": "Il tuo server ha limitato la richiesta. Attendi un momento e riprova.",+ "modelNotFound": "Il tuo server non riconosce il modello “{{model}}”.",+ "modelNotFoundNoModel": "Il tuo server non riconosce il modello selezionato.",+ "payloadTooLarge": "Questa registrazione è troppo grande per il tuo server.",+ "requestTooLarge": "Questa richiesta è troppo grande per il tuo server.",+ "badRequest": "Il tuo server non è riuscito a elaborare questa richiesta.",+ "unavailable": "Il tuo server sta avendo problemi in questo momento. Riprova a breve.",+ "timeout": "Il tuo server ha impiegato troppo tempo a rispondere.",+ "unreachable": "Impossibile contattare il tuo server. Verifica che sia in esecuzione.",+ "noResponse": "Nessuna risposta dal tuo server. Verifica la sua chiave API e che sia in esecuzione.",+ "unknown": "Il tuo server ha restituito un errore imprevisto."+ },+ "openSettings": "Apri Impostazioni",+ "copyDetails": "Copia dettagli",+ "titles": {+ "transcription": "Trascrizione non riuscita",+ "llm": "Richiesta IA non riuscita"+ },+ "details": {+ "provider": "Provider",+ "requestId": "ID richiesta"+ }}}diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex 9ac16a73b..77a456fe7 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -4774,5 +4774,48 @@},"start": "メモを取る","join": "参加して文字起こし"+ },+ "providerErrors": {+ "authFailed": "{{provider}} がAPIキーを拒否しました。",+ "accessDenied": "{{provider}} がアクセスを拒否しました。お使いのキーがこのモデルに対応していない可能性があります。",+ "quotaExhausted": "{{provider}} アカウントのクレジットが不足しています。",+ "rateLimited": "{{provider}} がリクエストを制限しました。しばらく待ってからもう一度お試しください。",+ "modelNotFound": "{{provider}} はモデル「{{model}}」を認識できません。",+ "modelNotFoundNoModel": "{{provider}} は選択されたモデルを認識できません。",+ "payloadTooLarge": "この録音は {{provider}} には大きすぎます。",+ "requestTooLarge": "このリクエストは {{provider}} には大きすぎます。",+ "badRequest": "{{provider}} はこのリクエストを処理できませんでした。",+ "unavailable": "{{provider}} で現在問題が発生しています。しばらくしてから再度お試しください。",+ "timeout": "{{provider}} からの応答に時間がかかりすぎました。",+ "unreachable": "{{provider}} に接続できませんでした。接続を確認してください。",+ "noResponse": "{{provider}} から応答がありませんでした。APIキーと接続を確認してください。",+ "unknown": "{{provider}} から予期しないエラーが返されました。",+ "keyMissing": "{{provider}} のAPIキーが設定されていません。設定 → 言語モデル から追加してください。",+ "selfHosted": {+ "authFailed": "サーバーがAPIキーを拒否しました。",+ "accessDenied": "サーバーがアクセスを拒否しました。キーがこのモデルに対応していない可能性があります。",+ "quotaExhausted": "サーバーがアカウントのクレジット不足を報告しています。",+ "rateLimited": "サーバーがリクエストを制限しました。しばらく待ってからもう一度お試しください。",+ "modelNotFound": "サーバーはモデル「{{model}}」を認識できません。",+ "modelNotFoundNoModel": "サーバーは選択されたモデルを認識できません。",+ "payloadTooLarge": "この録音はサーバーには大きすぎます。",+ "requestTooLarge": "このリクエストはサーバーには大きすぎます。",+ "badRequest": "サーバーはこのリクエストを処理できませんでした。",+ "unavailable": "サーバーで現在問題が発生しています。しばらくしてから再度お試しください。",+ "timeout": "サーバーからの応答に時間がかかりすぎました。",+ "unreachable": "サーバーに接続できませんでした。サーバーが起動しているか確認してください。",+ "noResponse": "サーバーから応答がありませんでした。APIキーとサーバーが起動しているかを確認してください。",+ "unknown": "サーバーから予期しないエラーが返されました。"+ },+ "openSettings": "設定を開く",+ "copyDetails": "詳細をコピー",+ "titles": {+ "transcription": "文字起こしに失敗しました",+ "llm": "AIリクエストに失敗しました"+ },+ "details": {+ "provider": "プロバイダー",+ "requestId": "リクエストID"+ }}}diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex c49bec60d..90110a10d 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -4774,5 +4774,48 @@},"start": "Fazer anotações","join": "Entrar e transcrever"+ },+ "providerErrors": {+ "authFailed": "{{provider}} rejeitou sua chave de API.",+ "accessDenied": "{{provider}} negou o acesso. Sua chave pode não incluir este modelo.",+ "quotaExhausted": "Sua conta {{provider}} está sem crédito.",+ "rateLimited": "{{provider}} limitou a solicitação. Aguarde um momento e tente novamente.",+ "modelNotFound": "{{provider}} não reconhece o modelo “{{model}}”.",+ "modelNotFoundNoModel": "{{provider}} não reconhece o modelo selecionado.",+ "payloadTooLarge": "Esta gravação é grande demais para {{provider}}.",+ "requestTooLarge": "Esta solicitação é grande demais para {{provider}}.",+ "badRequest": "{{provider}} não conseguiu processar esta solicitação.",+ "unavailable": "{{provider}} está com problemas no momento. Tente novamente em breve.",+ "timeout": "{{provider}} demorou demais para responder.",+ "unreachable": "Não foi possível conectar-se a {{provider}}. Verifique sua conexão.",+ "noResponse": "Não foi possível obter uma resposta de {{provider}}. Verifique sua chave de API e sua conexão.",+ "unknown": "{{provider}} retornou um erro inesperado.",+ "keyMissing": "Nenhuma chave de API definida para {{provider}}. Adicione-a em Configurações → Modelos de linguagem.",+ "selfHosted": {+ "authFailed": "Seu servidor rejeitou a chave de API.",+ "accessDenied": "Seu servidor negou o acesso. A chave pode não incluir este modelo.",+ "quotaExhausted": "Seu servidor informa que a conta está sem crédito.",+ "rateLimited": "Seu servidor limitou a solicitação. Aguarde um momento e tente novamente.",+ "modelNotFound": "Seu servidor não reconhece o modelo “{{model}}”.",+ "modelNotFoundNoModel": "Seu servidor não reconhece o modelo selecionado.",+ "payloadTooLarge": "Esta gravação é grande demais para o seu servidor.",+ "requestTooLarge": "Esta solicitação é grande demais para o seu servidor.",+ "badRequest": "Seu servidor não conseguiu processar esta solicitação.",+ "unavailable": "Seu servidor está com problemas no momento. Tente novamente em breve.",+ "timeout": "Seu servidor demorou demais para responder.",+ "unreachable": "Não foi possível conectar-se ao seu servidor. Verifique se ele está em execução.",+ "noResponse": "Não foi possível obter uma resposta do seu servidor. Verifique a chave de API dele e se ele está em execução.",+ "unknown": "Seu servidor retornou um erro inesperado."+ },+ "openSettings": "Abrir Configurações",+ "copyDetails": "Copiar detalhes",+ "titles": {+ "transcription": "Falha na transcrição",+ "llm": "Falha na solicitação de IA"+ },+ "details": {+ "provider": "Provedor",+ "requestId": "ID da solicitação"+ }}}diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 320cd02f4..20ebe0c76 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -4820,5 +4820,48 @@},"start": "Вести заметки","join": "Присоединиться и вести заметки"+ },+ "providerErrors": {+ "authFailed": "{{provider}} отклонил ваш API-ключ.",+ "accessDenied": "{{provider}} отказал в доступе. Возможно, ваш ключ не включает эту модель.",+ "quotaExhausted": "На вашем аккаунте {{provider}} закончились средства.",+ "rateLimited": "{{provider}} ограничил частоту запросов. Подождите немного и попробуйте снова.",+ "modelNotFound": "{{provider}} не распознаёт модель «{{model}}».",+ "modelNotFoundNoModel": "{{provider}} не распознаёт выбранную модель.",+ "payloadTooLarge": "Эта запись слишком велика для {{provider}}.",+ "requestTooLarge": "Этот запрос слишком велик для {{provider}}.",+ "badRequest": "{{provider}} не смог обработать этот запрос.",+ "unavailable": "У {{provider}} сейчас проблемы. Повторите попытку позже.",+ "timeout": "{{provider}} слишком долго не отвечал.",+ "unreachable": "Не удалось связаться с {{provider}}. Проверьте подключение.",+ "noResponse": "Не удалось получить ответ от {{provider}}. Проверьте API-ключ и подключение.",+ "unknown": "{{provider}} вернул неожиданную ошибку.",+ "keyMissing": "Для {{provider}} не задан API-ключ. Добавьте его в Настройках → Языковые модели.",+ "selfHosted": {+ "authFailed": "Ваш сервер отклонил API-ключ.",+ "accessDenied": "Ваш сервер отказал в доступе. Возможно, ключ не включает эту модель.",+ "quotaExhausted": "Ваш сервер сообщает, что на аккаунте закончились средства.",+ "rateLimited": "Ваш сервер ограничил частоту запросов. Подождите немного и попробуйте снова.",+ "modelNotFound": "Ваш сервер не распознаёт модель «{{model}}».",+ "modelNotFoundNoModel": "Ваш сервер не распознаёт выбранную модель.",+ "payloadTooLarge": "Эта запись слишком велика для вашего сервера.",+ "requestTooLarge": "Этот запрос слишком велик для вашего сервера.",+ "badRequest": "Ваш сервер не смог обработать этот запрос.",+ "unavailable": "У вашего сервера сейчас проблемы. Повторите попытку позже.",+ "timeout": "Ваш сервер слишком долго не отвечал.",+ "unreachable": "Не удалось связаться с вашим сервером. Проверьте, что он запущен.",+ "noResponse": "Не удалось получить ответ от вашего сервера. Проверьте его API-ключ и что он запущен.",+ "unknown": "Ваш сервер вернул неожиданную ошибку."+ },+ "openSettings": "Открыть настройки",+ "copyDetails": "Скопировать детали",+ "titles": {+ "transcription": "Не удалось выполнить транскрипцию",+ "llm": "Не удалось выполнить запрос к ИИ"+ },+ "details": {+ "provider": "Провайдер",+ "requestId": "ID запроса"+ }}}diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex ce0165593..e6657a3c3 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -4774,5 +4774,48 @@},"start": "开始记录","join": "加入并转录"+ },+ "providerErrors": {+ "authFailed": "{{provider}} 拒绝了你的 API 密钥。",+ "accessDenied": "{{provider}} 拒绝了访问。你的密钥可能不包含此模型。",+ "quotaExhausted": "你的 {{provider}} 账户额度已用尽。",+ "rateLimited": "{{provider}} 限制了请求频率。请稍候再试。",+ "modelNotFound": "{{provider}} 不识别模型“{{model}}”。",+ "modelNotFoundNoModel": "{{provider}} 不识别所选的模型。",+ "payloadTooLarge": "此录音对 {{provider}} 来说太大了。",+ "requestTooLarge": "此请求对 {{provider}} 来说太大了。",+ "badRequest": "{{provider}} 无法处理此请求。",+ "unavailable": "{{provider}} 目前遇到了问题。请稍后重试。",+ "timeout": "{{provider}} 响应超时。",+ "unreachable": "无法连接到 {{provider}}。请检查你的网络连接。",+ "noResponse": "未能收到 {{provider}} 的响应。请检查你的 API 密钥和网络连接。",+ "unknown": "{{provider}} 返回了一个意外错误。",+ "keyMissing": "尚未为 {{provider}} 设置 API 密钥。请在“设置 → 语言模型”中添加。",+ "selfHosted": {+ "authFailed": "你的服务器拒绝了 API 密钥。",+ "accessDenied": "你的服务器拒绝了访问。该密钥可能不包含此模型。",+ "quotaExhausted": "你的服务器报告该账户额度已用尽。",+ "rateLimited": "你的服务器限制了请求频率。请稍候再试。",+ "modelNotFound": "你的服务器不识别模型“{{model}}”。",+ "modelNotFoundNoModel": "你的服务器不识别所选的模型。",+ "payloadTooLarge": "此录音对你的服务器来说太大了。",+ "requestTooLarge": "此请求对你的服务器来说太大了。",+ "badRequest": "你的服务器无法处理此请求。",+ "unavailable": "你的服务器目前遇到了问题。请稍后重试。",+ "timeout": "你的服务器响应超时。",+ "unreachable": "无法连接到你的服务器。请检查它是否正在运行。",+ "noResponse": "未能收到你的服务器的响应。请检查它的 API 密钥以及它是否正在运行。",+ "unknown": "你的服务器返回了一个意外错误。"+ },+ "openSettings": "打开设置",+ "copyDetails": "复制详情",+ "titles": {+ "transcription": "转录失败",+ "llm": "AI 请求失败"+ },+ "details": {+ "provider": "服务商",+ "requestId": "请求 ID"+ }}}diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 5399c21fd..82dda0e2b 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -4774,5 +4774,48 @@},"start": "開始記錄","join": "加入並轉錄"+ },+ "providerErrors": {+ "authFailed": "{{provider}} 拒絕了你的 API 金鑰。",+ "accessDenied": "{{provider}} 拒絕存取。你的金鑰可能不包含此模型。",+ "quotaExhausted": "你的 {{provider}} 帳戶額度已用盡。",+ "rateLimited": "{{provider}} 限制了請求頻率。請稍候再試。",+ "modelNotFound": "{{provider}} 無法識別模型「{{model}}」。",+ "modelNotFoundNoModel": "{{provider}} 無法識別所選的模型。",+ "payloadTooLarge": "這段錄音對 {{provider}} 來說太大了。",+ "requestTooLarge": "這個請求對 {{provider}} 來說太大了。",+ "badRequest": "{{provider}} 無法處理此請求。",+ "unavailable": "{{provider}} 目前發生問題。請稍後再試。",+ "timeout": "{{provider}} 回應逾時。",+ "unreachable": "無法連線到 {{provider}}。請檢查你的網路連線。",+ "noResponse": "未能收到 {{provider}} 的回應。請檢查你的 API 金鑰和網路連線。",+ "unknown": "{{provider}} 回傳了意外的錯誤。",+ "keyMissing": "尚未為 {{provider}} 設定 API 金鑰。請在「設定 → 語言模型」中新增。",+ "selfHosted": {+ "authFailed": "你的伺服器拒絕了 API 金鑰。",+ "accessDenied": "你的伺服器拒絕存取。該金鑰可能不包含此模型。",+ "quotaExhausted": "你的伺服器回報該帳戶額度已用盡。",+ "rateLimited": "你的伺服器限制了請求頻率。請稍候再試。",+ "modelNotFound": "你的伺服器無法識別模型「{{model}}」。",+ "modelNotFoundNoModel": "你的伺服器無法識別所選的模型。",+ "payloadTooLarge": "這段錄音對你的伺服器來說太大了。",+ "requestTooLarge": "這個請求對你的伺服器來說太大了。",+ "badRequest": "你的伺服器無法處理此請求。",+ "unavailable": "你的伺服器目前發生問題。請稍後再試。",+ "timeout": "你的伺服器回應逾時。",+ "unreachable": "無法連線到你的伺服器。請確認它正在執行。",+ "noResponse": "未能收到你的伺服器的回應。請檢查它的 API 金鑰,並確認它正在執行。",+ "unknown": "你的伺服器回傳了意外的錯誤。"+ },+ "openSettings": "開啟設定",+ "copyDetails": "複製詳細資訊",+ "titles": {+ "transcription": "轉錄失敗",+ "llm": "AI 請求失敗"+ },+ "details": {+ "provider": "服務商",+ "requestId": "請求 ID"+ }}}diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.tsindex 38016eb79..8879516f9 100644--- a/src/services/ReasoningService.ts+++ b/src/services/ReasoningService.ts@@ -42,6 +42,13 @@ import { detectEndpointDialect } from "./ai/thinkingSuppressionDialects";import { openCodeSessionHeaders } from "./ai/openCodeSession";import { createStreamingThinkFilter } from "./ai/streamingThinkFilter";import { extractApiErrorMessage } from "./ai/apiErrorMessage";+import {+ PROVIDER_ERROR_CODES,+ asProviderError,+ providerError,+ providerHttpError,+ redactProviderBody,+} from "../helpers/providerHttpErrors.js";import { clearTinfoilClientCache } from "./ai/tinfoilClient";import { resolveChatRoute } from "../helpers/chatRouting";import { assertAgentAllowedByPolicy, assertReasoningAllowedByPolicy } from "./reasoningPolicy";@@ -250,10 +257,10 @@ class ReasoningService extends BaseReasoningService {provider,error: errorMsg,});- const error = new Error(errorMsg) as Error & { code: string; provider: string };- error.code = "API_KEY_MISSING";- error.provider = displayName;- throw error;+ throw providerError(PROVIDER_ERROR_CODES.KEY_MISSING, {+ provider: displayName,+ surface: "llm",+ });}return apiKey;@@ -329,6 +336,13 @@ class ReasoningService extends BaseReasoningService {// Minted before the retry loop so every attempt of this call is one conversation.const openCodeHeaders = openCodeSessionHeaders(endpoint);+ const errorContext = {+ provider: providerName,+ selfHosted: providerName === "LAN",+ model,+ surface: "llm",+ };+const requestGeneration = this.requestCancellationGeneration;const response = await withRetry(async () => {if (requestGeneration !== this.requestCancellationGeneration) {@@ -369,19 +383,22 @@ class ReasoningService extends BaseReasoningService {errorData = { error: errorText || res.statusText };}- const errorMessage = extractApiErrorMessage(- errorData,- `${providerName} API error: ${res.status}`- );-+ // Providers echo the rejected key back, so every logged field is redacted.logger.logReasoning(`${providerName.toUpperCase()}_API_ERROR_DETAIL`, {status: res.status,statusText: res.statusText,- error: errorData,- errorMessage,- fullResponse: errorText.substring(0, 500),+ error: redactProviderBody(errorData),+ errorMessage: redactProviderBody(+ extractApiErrorMessage(errorData, `${providerName} API error: ${res.status}`)+ ),+ fullResponse: redactProviderBody(errorText),+ });+ throw providerHttpError({+ ...errorContext,+ status: res.status,+ body: errorText,+ headers: res.headers,});- throw httpError(errorMessage, res.status);}const jsonResponse = await res.json();@@ -407,7 +424,11 @@ class ReasoningService extends BaseReasoningService {clearTimeout(timeoutId);this.activeRequestControllers.delete(controller);}- }, createApiRetryStrategy());+ }, createApiRetryStrategy()).catch((error) => {+ // Classified only once it has left withRetry, so the deadline is still+ // attempted exactly once.+ throw asProviderError(error, errorContext);+ });if (!response.choices || !response.choices[0]) {logger.logReasoning(`${providerName.toUpperCase()}_RESPONSE_ERROR`, {@@ -656,6 +677,11 @@ class ReasoningService extends BaseReasoningService {abortController.abort();}, timeoutSeconds * 1000);+ const selfHostedErrorContext = {+ selfHosted: true,+ model,+ surface: "llm",+ };let response: Response;try {response = await fetchWithParamFallback(@@ -673,22 +699,38 @@ class ReasoningService extends BaseReasoningService {clearTimeout(timeoutId);if ((error as Error).name === "AbortError" && abortController.signal.aborted) {if (!timeoutTriggered) return;- throw new Error("Streaming request timed out");+ throw route.kind === "self-hosted"+ ? providerError(PROVIDER_ERROR_CODES.TIMEOUT, selfHostedErrorContext)+ : new Error("Streaming request timed out");}- throw error;+ // A stopped LAN server rejects the fetch before any response.+ throw route.kind === "self-hosted" ? asProviderError(error, selfHostedErrorContext) : error;}if (!response.ok) {clearTimeout(timeoutId);const errorText = await response.text();+ logger.logReasoning("AGENT_STREAM_ERROR", {+ status: response.status,+ body: redactProviderBody(errorText),+ });+ if (route.kind === "self-hosted") {+ throw providerHttpError({+ ...selfHostedErrorContext,+ status: response.status,+ body: errorText,+ headers: response.headers,+ });+ }let errorMessage: string;try {- const errorData = JSON.parse(errorText);- errorMessage = extractApiErrorMessage(errorData, `API error: ${response.status}`);+ errorMessage = extractApiErrorMessage(+ JSON.parse(errorText),+ `API error: ${response.status}`+ );} catch {errorMessage = errorText || `API error: ${response.status}`;}- logger.logReasoning("AGENT_STREAM_ERROR", { status: response.status, errorMessage });throw new Error(errorMessage);}@@ -745,7 +787,9 @@ class ReasoningService extends BaseReasoningService {} catch (error) {if ((error as Error).name === "AbortError" && abortController.signal.aborted) {if (!timeoutTriggered) return;- throw new Error("Streaming request timed out");+ throw route.kind === "self-hosted"+ ? providerError(PROVIDER_ERROR_CODES.TIMEOUT, selfHostedErrorContext)+ : new Error("Streaming request timed out");}throw error;} finally {@@ -979,6 +1023,28 @@ class ReasoningService extends BaseReasoningService {yield { type: "done", finishReason: "stop" };return;}+ // BYOK and LAN-with-tools failures arrive as AI SDK errors; enterprise+ // providers have their own mappers and local errors their own keys.+ if (mode === "providers" || mode === "self-hosted") {+ // A "custom" BYOK provider (config.baseUrl) counts as self-hosted+ // alongside LAN (config.lanUrl) — both are the user's own server.+ // OpenRouter is a cloud provider and keeps its own display name.+ const isSelfHosted = mode === "self-hosted" || provider === "custom";+ const classified = asProviderError(error, {+ provider: getProviderDisplayName(provider),+ selfHosted: isSelfHosted,+ model,+ surface: "llm",+ });+ // The classified details already hold the status and the redacted body.+ const details = classified.technicalDetails;+ logger.warn(+ "BYOK chat stream failed",+ { provider, status: details?.status, body: details?.underlyingError },+ "reasoning"+ );+ throw classified;+ }throw error;} finally {if (this.streamAbortController === abortController) {diff --git a/src/services/ai/inferenceProviders/anthropic.ts b/src/services/ai/inferenceProviders/anthropic.tsindex 0cd540ed8..8d5342b0a 100644--- a/src/services/ai/inferenceProviders/anthropic.ts+++ b/src/services/ai/inferenceProviders/anthropic.ts@@ -2,6 +2,7 @@ import type { InferenceProvider } from "./types";import { getCloudModel } from "../../../models/ModelRegistry";import { wrapCleanupTranscript } from "../../../config/prompts";import logger from "../../../utils/logger";+import { errorFromIpcResult } from "../../../helpers/ipcErrorFields";export const anthropicProvider: InferenceProvider = {id: "anthropic",@@ -36,8 +37,9 @@ export const anthropicProvider: InferenceProvider = {if (!result.success) {logger.logReasoning("ANTHROPIC_ERROR", { model, processingTimeMs, error: result.error });- // Carry the main process's i18n key (a truncated cleanup) so the toast can translate it.- throw Object.assign(new Error(result.error), { messageKey: result.messageKey });+ // Main resolves with the serialized error (code, i18n key, status…) so the+ // toast can translate it.+ throw errorFromIpcResult(result);}logger.logReasoning("ANTHROPIC_SUCCESS", {diff --git a/src/services/ai/inferenceProviders/gemini.ts b/src/services/ai/inferenceProviders/gemini.tsindex 3648741ed..c22c65d09 100644--- a/src/services/ai/inferenceProviders/gemini.ts+++ b/src/services/ai/inferenceProviders/gemini.ts@@ -1,5 +1,5 @@import type { InferenceProvider } from "./types";-import { withRetry, createApiRetryStrategy, httpError } from "../../../utils/retry";+import { withRetry, createApiRetryStrategy } from "../../../utils/retry";import { API_ENDPOINTS } from "../../../config/constants";import {getLlmRequestTimeoutSeconds,@@ -7,9 +7,13 @@ import {} from "../../../helpers/llmRequestTimeout.js";import { extractGeminiText } from "../../../helpers/geminiResponse.js";import { wrapCleanupTranscript } from "../../../config/prompts";-import { extractApiErrorMessage } from "../apiErrorMessage";import { emptyOutputError, truncatedOutputError } from "../chatRequestBody";import logger from "../../../utils/logger";+import {+ asProviderError,+ providerHttpError,+ redactProviderBody,+} from "../../../helpers/providerHttpErrors.js";interface GeminiResponse {candidates?: Array<{@@ -115,24 +119,20 @@ export const geminiProvider: InferenceProvider = {if (!res.ok) {const errorText = await res.text();- let errorData: { error?: { message?: string } | string; message?: string } = {- error: res.statusText,- };- try {- errorData = JSON.parse(errorText);- } catch {- errorData = { error: errorText || res.statusText };- }-logger.logReasoning("GEMINI_API_ERROR_DETAIL", {status: res.status,statusText: res.statusText,- error: errorData,- fullResponse: errorText.substring(0, 500),+ fullResponse: redactProviderBody(errorText),});- const errMsg = extractApiErrorMessage(errorData, `Gemini API error: ${res.status}`);- throw httpError(errMsg, res.status);+ throw providerHttpError({+ provider: "Gemini",+ model,+ status: res.status,+ body: errorText,+ headers: res.headers,+ surface: "llm",+ });}const jsonResponse = (await res.json()) as GeminiResponse;@@ -152,7 +152,11 @@ export const geminiProvider: InferenceProvider = {} finally {clearTimeout(timeoutId);}- }, createApiRetryStrategy());+ }, createApiRetryStrategy()).catch((error) => {+ // Classified only once it has left withRetry, so the deadline is still+ // attempted exactly once.+ throw asProviderError(error, { provider: "Gemini", model, surface: "llm" });+ });const candidate = response.candidates?.[0];// Outside withRetry: don't repeat cutoffs/blocks; cleanup falls back to the original.diff --git a/src/services/ai/inferenceProviders/openai.ts b/src/services/ai/inferenceProviders/openai.tsindex d00b407b0..a9b8f89f1 100644--- a/src/services/ai/inferenceProviders/openai.ts+++ b/src/services/ai/inferenceProviders/openai.ts@@ -2,7 +2,7 @@ import type { InferenceProvider } from "./types";import { API_ENDPOINTS, TOKEN_LIMITS, buildApiUrl } from "../../../config/constants";import { getCloudModel, getOpenAiApiConfig } from "../../../models/ModelRegistry";import { getSettings } from "../../../stores/settingsStore";-import { withRetry, createApiRetryStrategy, httpError } from "../../../utils/retry";+import { withRetry, createApiRetryStrategy } from "../../../utils/retry";import logger from "../../../utils/logger";import { canBorrowCleanupCustomKey, resolveConfiguredOpenAIBase } from "../openaiBase";import {@@ -20,6 +20,11 @@ import {import { extractApiErrorMessage } from "../apiErrorMessage";import { wrapCleanupTranscript } from "../../../config/prompts";import { openCodeSessionHeaders } from "../openCodeSession";+import {+ asProviderError,+ providerHttpError,+ redactProviderBody,+} from "../../../helpers/providerHttpErrors.js";const OPENAI_ENDPOINT_PREF_STORAGE_KEY = "openAiEndpointPreference";const PROBE_TIMEOUT_MS = 2_000;@@ -202,6 +207,13 @@ export const openaiProvider: InferenceProvider = {endpointCandidates = getEndpointCandidates(openAiBase);}const isCustomEndpoint = openAiBase !== API_ENDPOINTS.OPENAI_BASE;+ // Only the user's own endpoint is self-hosted; isCustomEndpoint also covers OpenRouter.+ const errorContext = {+ provider: isOpenRouter ? "OpenRouter" : "OpenAI",+ selfHosted: isCustomProvider,+ model,+ surface: "llm",+ };// One cleanup call is one conversation: every attempt below (endpoint// fallback, parameter fallback, retry) reuses the same session id.const openCodeHeaders = openCodeSessionHeaders(openAiBase);@@ -300,16 +312,26 @@ export const openaiProvider: InferenceProvider = {(res.status === 404 || res.status === 405) && type === "responses";if (isUnsupportedEndpoint) {- lastError = httpError(errorMessage, res.status);+ lastError = providerHttpError({+ ...errorContext,+ status: res.status,+ body: errorData,+ headers: res.headers,+ });rememberPreference(openAiBase, "chat");logger.logReasoning("OPENAI_ENDPOINT_FALLBACK", {attemptedEndpoint: endpoint,- error: errorMessage,+ error: redactProviderBody(errorMessage),});continue;}- throw httpError(errorMessage, res.status);+ throw providerHttpError({+ ...errorContext,+ status: res.status,+ body: errorData,+ headers: res.headers,+ });}rememberPreference(openAiBase, type);@@ -336,7 +358,11 @@ export const openaiProvider: InferenceProvider = {}throw lastRetryableError || lastError || new Error("No OpenAI endpoint responded");- }, retryStrategy);+ }, retryStrategy).catch((error) => {+ // Classified only once it has left withRetry, so the deadline is still+ // attempted exactly once.+ throw asProviderError(error, errorContext);+ });const isResponsesApi = Array.isArray(response?.output);const isChatCompletions = Array.isArray(response?.choices);diff --git a/src/stores/actionProcessingStore.ts b/src/stores/actionProcessingStore.tsindex 15025cbac..8c63fe074 100644--- a/src/stores/actionProcessingStore.ts+++ b/src/stores/actionProcessingStore.ts@@ -11,6 +11,7 @@ import { tagActionItemOwners, type MentionPerson } from "../utils/mentionMarkdowimport type { ActionItem, NoteItem } from "../types/electron";import { estimateNoteTokens, planNoteChunks, splitChunkInHalf } from "../helpers/noteChunking";import type { LocalInferenceError } from "../utils/localInferenceError";+import type { TechnicalErrorDetailsData } from "../components/ui/useToast";import type { ReasoningConfig } from "../services/BaseReasoningService";import {EMPTY_OUTPUT_MESSAGE_KEY,@@ -91,6 +92,8 @@ export interface ActionErrorEvent {messageParams?: Record<string, string | number>;/** Not a failure: the run found nothing to write, so the toast only informs. */notice?: boolean;+ settingsTarget?: string;+ technicalDetails?: TechnicalErrorDetailsData;}interface ActionProcessingStoreState {@@ -586,10 +589,13 @@ export function runBackgroundAction(processingFlags.set(noteId, false);clearNoteState(noteId);const message = err instanceof Error ? err.message : labels.actionFailed;- const { messageKey, messageParams, notice } = (err ?? {}) as {+ const { messageKey, messageParams, notice, settingsTarget, technicalDetails } = (err ??+ {}) as {messageKey?: string;messageParams?: Record<string, string | number>;notice?: boolean;+ settingsTarget?: string;+ technicalDetails?: TechnicalErrorDetailsData;};pushErrorEvent({noteId,@@ -597,6 +603,8 @@ export function runBackgroundAction(messageKey: (messageKey && NOTE_ERROR_KEYS[messageKey]) || messageKey,messageParams,notice,+ settingsTarget,+ technicalDetails,});} finally {if (activeRuns.get(noteId) === runId) activeRuns.delete(noteId);diff --git a/src/stores/batchQueueStore.ts b/src/stores/batchQueueStore.tsindex c7e07c0f4..171a42a8b 100644--- a/src/stores/batchQueueStore.ts+++ b/src/stores/batchQueueStore.ts@@ -8,6 +8,7 @@ import { getSettings } from "./settingsStore";import { isTranscriptionContextAllowed } from "./policyRules";import { usePolicyStore } from "./policyStore";import { isManagedTranscriptionActive } from "../services/managedTranscription";+import { describeProviderError } from "../utils/describeProviderError";export type QueueItemStatus = "queued" | "downloading" | "transcribing" | "done" | "error";@@ -219,7 +220,12 @@ export function processBatchQueue(status: "error",error:transcriptionErrorKey(transcriptionResult) ||- (transcriptionResult.messageKey ? i18n.t(transcriptionResult.messageKey) : undefined) ||+ (transcriptionResult.messageKey+ ? describeProviderError(+ { ...transcriptionResult, message: transcriptionResult.error },+ i18n.t+ ).description+ : undefined) ||transcriptionResult.error ||"batchTranscriptionFailed",});diff --git a/src/stores/cleanupFailureStore.ts b/src/stores/cleanupFailureStore.tsindex 97b5d4d10..e7330f9dd 100644--- a/src/stores/cleanupFailureStore.ts+++ b/src/stores/cleanupFailureStore.ts@@ -1,18 +1,16 @@import { create } from "zustand";+import type { TechnicalErrorDetailsData } from "../components/ui/useToast";export interface CleanupFailure {message: string;messageKey?: string;messageParams?: Record<string, string | number>;+ surface?: "transcription" | "llm";+ settingsTarget?: string;action?: string;actionKey?: string;copyCommand?: string;- technicalDetails?: {- status?: number;- exceptionType?: string;- requestId?: string;- underlyingError?: string;- };+ technicalDetails?: TechnicalErrorDetailsData;}interface CleanupFailureState {diff --git a/src/types/electron.ts b/src/types/electron.tsindex 68451873c..6dcb856ad 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -3,6 +3,8 @@ import type { PermissionGuideState, PermissionGuideAction } from "./permissionGuimport type { TinfoilCatalogModel } from "../models/tinfoilModels";import type { UsageResponse } from "../lib/usageStore";import type { OrgPolicy } from "./policy";+import type { TechnicalErrorDetailsData } from "../components/ui/useToast";+import type { ProviderSettingsTarget } from "../utils/describeProviderError";import type {ManagedEnterpriseConfig,ManagedEnterpriseRequestContext,@@ -129,6 +131,17 @@ export type TranscriptionErrorCode =| "INVALID_KEY"| "MODEL_NOT_AVAILABLE"| "CUSTOM_ENDPOINT_INVALID"+ | "PROVIDER_AUTH_FAILED"+ | "PROVIDER_ACCESS_DENIED"+ | "PROVIDER_QUOTA_EXHAUSTED"+ | "PROVIDER_MODEL_NOT_FOUND"+ | "PROVIDER_PAYLOAD_TOO_LARGE"+ | "PROVIDER_BAD_REQUEST"+ | "PROVIDER_UNAVAILABLE"+ | "PROVIDER_TIMEOUT"+ | "PROVIDER_UNREACHABLE"+ | "PROVIDER_NO_RESPONSE"+ | "PROVIDER_ERROR"| null;export type MeetingPromptVariant = "detected" | "starting" | "underway";@@ -150,13 +163,24 @@ export interface MeetingAutoEndRequest {reason?: MeetingAutoEndReason;}+/** Fields a main-process handler resolves with in place of a rejected Error. */+export interface IpcErrorFields {+ error: string;+ code?: string;+ messageKey?: string;+ messageParams?: Record<string, string | number>;+ settingsTarget?: string;+ technicalDetails?: TechnicalErrorDetailsData;+ status?: number;+ surface?: "transcription" | "llm";+}+/*** Proxied-transcription IPC results. `ipcMain.handle` drops custom error props on* rejection, so these handlers resolve with a serialized error instead of throwing.*/export type ProxyTranscriptionResult =- | { text: string; model?: string; error?: undefined }- | { error: string; code?: string; messageKey?: string; text?: undefined };+ { text: string; model?: string; error?: undefined } | (IpcErrorFields & { text?: undefined });export interface AuthTokenState {token: string | null;@@ -1263,6 +1287,7 @@ declare global {}>;hideWindow: () => Promise<void>;showDictationPanel: () => Promise<void>;+ openSettingsSection?: (section: ProviderSettingsTarget) => Promise<{ success: boolean }>;captureDictationTarget?: () => Promise<{ success: boolean; pid: number | null }>;onToggleDictation: (callback: () => void) => () => void;onToggleVoiceAgent?: (callback: () => void) => () => void;@@ -1966,7 +1991,7 @@ declare global {modelId: string,agentName: string | null,config: any- ) => Promise<{ success: boolean; text?: string; error?: string; messageKey?: string }>;+ ) => Promise<{ success: boolean; text?: string } & Partial<IpcErrorFields>>;// Enterprise reasoning (Bedrock, Azure, Vertex)processEnterpriseReasoning: (@@ -2163,6 +2188,7 @@ declare global {// Settings shortcut (Cmd+, / Ctrl+,)onShowSettings?: (callback: () => void) => () => void;+ getPendingSettingsSection?: () => Promise<string | null>;// Accessibility permission events (macOS)markMacAccessibilityFeaturesReady?: (expectedAccountScope?: ActiveAccountScope) => void;diff --git a/src/utils/describeProviderError.ts b/src/utils/describeProviderError.tsnew file mode 100644index 000000000..c89466f9c--- /dev/null+++ b/src/utils/describeProviderError.ts@@ -0,0 +1,128 @@+import type { TFunction } from "i18next";+import type { TechnicalErrorDetailsData, ToastActionConfig } from "../components/ui/useToast";+import { SELF_HOSTED_NAME, isProviderSettingsTarget } from "../helpers/providerHttpErrors.js";++export type ProviderSettingsTarget = "speechToText" | "llms";++interface DescribableError {+ message?: string;+ messageKey?: string;+ messageParams?: Record<string, string | number>;+ settingsTarget?: string;+ technicalDetails?: TechnicalErrorDetailsData;+}++export interface ProviderErrorDescription {+ description: string;+ technicalDetails?: TechnicalErrorDetailsData;+ settingsTarget?: ProviderSettingsTarget;+}++/** One rendering of a (possibly classified) error for every surface. */+export function describeProviderError(error: unknown, t: TFunction): ProviderErrorDescription {+ if (typeof error === "string") return { description: error };+ const source = (error ?? {}) as DescribableError;+ const description = source.messageKey+ ? String(t(source.messageKey, source.messageParams))+ : source.message || "";+ const settingsTarget = isProviderSettingsTarget(source.settingsTarget)+ ? (source.settingsTarget as ProviderSettingsTarget)+ : undefined;+ return {+ description,+ ...(source.technicalDetails ? { technicalDetails: source.technicalDetails } : {}),+ ...(settingsTarget ? { settingsTarget } : {}),+ };+}++export function formatProviderErrorDetails(+ details: TechnicalErrorDetailsData,+ t: TFunction+): string {+ const isProvider = Boolean(details.provider);+ const provider =+ details.provider === SELF_HOSTED_NAME+ ? t("settingsPage.aiModels.modes.selfHosted")+ : details.provider;+ return [+ provider ? `${t("providerErrors.details.provider")}: ${provider}` : "",+ details.status !== undefined+ ? `${t("reasoning.enterprise.technicalDetails.httpStatus")}: ${details.status}`+ : "",+ details.exceptionType+ ? `${t("reasoning.enterprise.technicalDetails.awsException")}: ${details.exceptionType}`+ : "",+ details.requestId+ ? `${t(+ isProvider+ ? "providerErrors.details.requestId"+ : "reasoning.enterprise.technicalDetails.awsRequestId"+ )}: ${details.requestId}`+ : "",+ details.underlyingError+ ? `${t("reasoning.enterprise.technicalDetails.underlyingError")}: ${details.underlyingError}`+ : "",+ ]+ .filter(Boolean)+ .join("\n");+}++export function openProviderSettings(target: ProviderSettingsTarget): void {+ void window.electronAPI?.openSettingsSection?.(target);+}++/**+ * Open Settings (fixable errors) and an icon-only Copy details for a toast or+ * dictation card. `isCurrent` lets a superseded card ignore a late click.+ */+export function providerErrorActions(+ error: { settingsTarget?: string; technicalDetails?: TechnicalErrorDetailsData },+ t: TFunction,+ isCurrent: () => boolean = () => true+): ToastActionConfig[] {+ const actions: ToastActionConfig[] = [];+ const { settingsTarget, technicalDetails } = error;+ if (isProviderSettingsTarget(settingsTarget)) {+ actions.push({+ label: t("providerErrors.openSettings"),+ icon: "settings",+ onClick: () => openProviderSettings(settingsTarget as ProviderSettingsTarget),+ });+ }+ if (technicalDetails) {+ actions.push({+ label: t("providerErrors.copyDetails"),+ icon: "copy",+ iconOnly: true,+ dismissOnClick: false,+ feedback: {+ successLabel: t("common.copied"),+ failureLabel: t("hooks.audioRecording.pastePermission.copyFailed"),+ },+ onClick: async () => {+ if (!isCurrent()) return;+ let copied = false;+ try {+ const result = await window.electronAPI?.writeClipboard?.(+ formatProviderErrorDetails(technicalDetails, t)+ );+ copied = result?.success === true;+ } catch {+ copied = false;+ }+ if (isCurrent()) return copied;+ },+ });+ }+ return actions;+}++/** Description and actions for a standard toast reporting a (possibly classified) error. */+export function providerErrorToastProps(+ error: unknown,+ t: TFunction+): { description: string; actions?: ToastActionConfig[] } {+ const { description, technicalDetails, settingsTarget } = describeProviderError(error, t);+ const actions = providerErrorActions({ settingsTarget, technicalDetails }, t);+ return { description, ...(actions.length ? { actions } : {}) };+}diff --git a/src/utils/recordingErrors.ts b/src/utils/recordingErrors.tsindex b71ca9118..c8ef89dfe 100644--- a/src/utils/recordingErrors.ts+++ b/src/utils/recordingErrors.ts@@ -1,10 +1,13 @@import { TFunction } from "i18next";+import { describeProviderError } from "./describeProviderError";type RecordingError = {code?: string;title: string;description?: string;messageKey?: string;+ messageParams?: Record<string, string | number | boolean>;+ surface?: string;/** Toast variant; defaults to destructive for genuine failures. */variant?: "default" | "destructive";};@@ -32,6 +35,11 @@ export function getRecordingErrorTitle(error: RecordingError, t: TFunction): strreturn t("hooks.audioRecording.errorTitles.dailyLimitReached");if (error.code === "PROVIDER_RATE_LIMITED")return t("hooks.audioRecording.errorTitles.providerRateLimited");+ if (error.code?.startsWith("PROVIDER_")) {+ return t(+ error.surface === "llm" ? "providerErrors.titles.llm" : "providerErrors.titles.transcription"+ );+ }return error.title;}@@ -39,6 +47,6 @@ export function getRecordingErrorDescription(error: RecordingError, t: TFunctionif (error.code === "ACCESSIBILITY_PERMISSION_REQUIRED") {return t("hooks.audioRecording.pastePermission.description");}- if (error.messageKey) return t(error.messageKey);+ if (error.messageKey) return describeProviderError(error, t).description;return error.description ?? "";}diff --git a/src/utils/retry.ts b/src/utils/retry.tsindex 4bded5d37..4531b43c6 100644--- a/src/utils/retry.ts+++ b/src/utils/retry.ts@@ -1,5 +1,6 @@import { RETRY_CONFIG } from "../config/constants.ts";import { LLM_REQUEST_TIMEOUT_CODE } from "../helpers/llmRequestTimeout.js";+import { PROVIDER_ERROR_CODES } from "../helpers/providerHttpErrors.js";export interface RetryOptions {maxRetries?: number;@@ -53,6 +54,9 @@ export function createApiRetryStrategy() {// the same deadline expires again, and the provider bills every attempt.if (error?.code === LLM_REQUEST_TIMEOUT_CODE) return false;+ // An empty account stays empty: retrying only delays the message.+ if (error?.code === PROVIDER_ERROR_CODES.QUOTA_EXHAUSTED) return false;+// No HTTP status means the request never got an answer (network drop).const status = error?.status ?? error?.response?.status;if (typeof status !== "number") return true;diff --git a/test/components/chatMessageRendering.test.js b/test/components/chatMessageRendering.test.jsindex 9d7a6af0c..65776262a 100644--- a/test/components/chatMessageRendering.test.js+++ b/test/components/chatMessageRendering.test.js@@ -73,3 +73,42 @@ test("a question typed on several lines keeps its line breaks", async (t) => {assert.ok(text);assert.match(text.getAttribute("class") ?? "", /(^|\s)whitespace-pre-wrap(\s|$)/);});++// A classified provider failure (Task 3's describeProviderError) rides along on the+// message as `error`; the reply shows an Open Settings link and a details disclosure.+test("a reply with a classified error shows an Open Settings link and technical details", async (t) => {+ const { container, render } = await mountChatMessages(t);++ await render({+ messages: [+ {+ id: "a",+ role: "assistant",+ content: "Error: OpenAI rejected your API key.",+ isStreaming: false,+ error: { settingsTarget: "llms", technicalDetails: { provider: "OpenAI", status: 401 } },+ },+ ],+ });++ assert.match(container.textContent, /OpenAI rejected your API key\./);+ const settingsButton = findElement(+ container,+ (element) => element.tagName === "BUTTON" && /providerErrors\.openSettings/.test(element.textContent)+ );+ assert.ok(settingsButton, "shows the Open Settings affordance");+ assert.match(container.textContent, /reasoning\.enterprise\.technicalDetails\.title/);+ assert.match(container.textContent, /OpenAI/);+ assert.match(container.textContent, /401/);+});++test("a reply with no error shows neither the settings link nor technical details", async (t) => {+ const { container, render } = await mountChatMessages(t);++ await render({+ messages: [{ id: "a", role: "assistant", content: "All good.", isStreaming: false }],+ });++ assert.doesNotMatch(container.textContent, /providerErrors\.openSettings/);+ assert.doesNotMatch(container.textContent, /reasoning\.enterprise\.technicalDetails\.title/);+});diff --git a/test/helpers/anthropicReasoningNetworkError.test.js b/test/helpers/anthropicReasoningNetworkError.test.jsnew file mode 100644index 000000000..5cfe20ab7--- /dev/null+++ b/test/helpers/anthropicReasoningNetworkError.test.js@@ -0,0 +1,158 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const Module = require("node:module");++// process-anthropic-reasoning's catch block used to return the raw error+// message/messageKey only, so a network failure (proxyFetch rejecting before+// any HTTP response, e.g. DNS/TLS) reached the renderer as a bare, unclassified+// Error instead of a translatable PROVIDER_UNREACHABLE. This exercises the+// real handler closure against a stubbed Electron `net.fetch`, following the+// pattern in test/helpers/retryTranscriptionHandler.test.js.+const handlersModulePath = require.resolve("../../src/helpers/ipcHandlers");+const originalLoad = Module._load;++const handlers = new Map();+let fetchBehavior = async () => {+ throw new Error("net::ERR_INTERNET_DISCONNECTED");+};++const electronStub = {+ app: {+ getPath: () => "/tmp",+ getName: () => "test",+ getVersion: () => "0.0.0",+ isPackaged: false,+ on: () => {},+ requestSingleInstanceLock: () => true,+ },+ ipcMain: {+ handle: (channel, fn) => handlers.set(channel, fn),+ on: () => {},+ removeHandler: () => {},+ },+ net: {+ fetch: async (...args) => fetchBehavior(...args),+ },+ BrowserWindow: class BrowserWindow {+ static getAllWindows() {+ return [];+ }+ static fromWebContents() {+ return null;+ }+ },+ shell: {},+ dialog: {},+ screen: { getPrimaryDisplay: () => ({ workAreaSize: { width: 0, height: 0 } }) },+ systemPreferences: { getMediaAccessStatus: () => "granted" },+ session: { fromPartition: () => ({}) },+ clipboard: {},+ nativeImage: {},+ globalShortcut: {},+ utilityProcess: {},+ MessageChannelMain: class {},+};++Module._load = function loadWithMocks(request, parent, isMain) {+ if (request === "electron") return electronStub;+ return originalLoad.call(this, request, parent, isMain);+};++// A permissive `this` for setupHandlers: registration only stores closures, so+// any manager not exercised by this handler can be an inert stub.+function anything() {+ return new Proxy(function () {}, {+ get: (t, prop) => {+ if (prop === Symbol.toPrimitive || prop === "toString") return () => "";+ if (prop === "then") return undefined;+ return anything();+ },+ apply: () => anything(),+ });+}++function buildFakeThis() {+ const target = {+ sessionId: "test-session",+ environmentManager: {+ getAnthropicKey: () => "sk-ant-test-key",+ },+ };+ return new Proxy(target, {+ get: (t, prop) => (prop in t ? t[prop] : anything()),+ });+}++let anthropicHandler;+test.before(() => {+ delete require.cache[handlersModulePath];+ const IPCHandlers = require(handlersModulePath);+ const Ctor = IPCHandlers.default || IPCHandlers;+ Ctor.prototype.setupHandlers.call(buildFakeThis());+ anthropicHandler = handlers.get("process-anthropic-reasoning");+ assert.ok(anthropicHandler, "process-anthropic-reasoning must be registered");+});++test.after(() => {+ Module._load = originalLoad;+});++// Electron's net.fetch rejects with a plain Error carrying the Chromium net+// error as its message and no code.+test("a network failure (net::ERR_INTERNET_DISCONNECTED) resolves classified instead of a bare error", async () => {+ fetchBehavior = async () => {+ throw new Error("net::ERR_INTERNET_DISCONNECTED");+ };++ const result = await anthropicHandler({ sender: {} }, "hello", "claude-sonnet-5", null, {});++ assert.equal(result.success, false);+ assert.equal(result.code, "PROVIDER_UNREACHABLE");+ assert.equal(result.messageKey, "providerErrors.unreachable");+ assert.equal(result.surface, "llm");+ assert.match(result.error, /Couldn't reach Anthropic/);+});++test("an Anthropic HTTP failure resolves with classified IPC fields", async () => {+ fetchBehavior = async () =>+ new Response(+ '{"type":"error","error":{"type":"invalid_request_error","message":"Your credit balance is too low to access the Anthropic API."}}',+ { status: 400, headers: { "request-id": "req_9" } }+ );++ const result = await anthropicHandler({ sender: {} }, "hello", "claude-sonnet-5", null, {});++ assert.equal(result.success, false);+ assert.equal(result.code, "PROVIDER_QUOTA_EXHAUSTED");+ assert.equal(result.messageKey, "providerErrors.quotaExhausted");+ assert.deepEqual(result.messageParams, { provider: "Anthropic" });+ assert.equal(result.settingsTarget, "llms");+ assert.equal(result.status, 400);+ assert.equal(result.technicalDetails.requestId, "req_9");+ assert.equal(result.error, "Your Anthropic account is out of credit.");+});++test("an already-classified failure (missing key) passes through unchanged", async () => {+ const noKeyThis = {+ sessionId: "test-session",+ environmentManager: { getAnthropicKey: () => "" },+ };+ const proxiedThis = new Proxy(noKeyThis, {+ get: (t, prop) => (prop in t ? t[prop] : anything()),+ });+ const handlersForNoKey = new Map();+ const originalHandle = electronStub.ipcMain.handle;+ electronStub.ipcMain.handle = (channel, fn) => handlersForNoKey.set(channel, fn);+ delete require.cache[handlersModulePath];+ const IPCHandlers = require(handlersModulePath);+ const Ctor = IPCHandlers.default || IPCHandlers;+ Ctor.prototype.setupHandlers.call(proxiedThis);+ electronStub.ipcMain.handle = originalHandle;++ const handler = handlersForNoKey.get("process-anthropic-reasoning");+ const result = await handler({ sender: {} }, "hello", "claude-sonnet-5", null, {});++ assert.equal(result.success, false);+ assert.equal(result.code, "API_KEY_MISSING");+ assert.equal(result.messageKey, "providerErrors.keyMissing");+});diff --git a/test/helpers/apiRetryStrategy.test.js b/test/helpers/apiRetryStrategy.test.jsindex e79302a44..55f0b6963 100644--- a/test/helpers/apiRetryStrategy.test.js+++ b/test/helpers/apiRetryStrategy.test.js@@ -121,3 +121,27 @@ test("withRetry makes exactly one attempt for a client-side deadline", async ());assert.equal(attempts, 1, "each retry of an expired deadline is another billed request");});++test("an exhausted quota does not retry, but a plain rate limit still does", async () => {+ const { createApiRetryStrategy } = await load();+ const { shouldRetry } = createApiRetryStrategy();++ assert.equal(+ shouldRetry(Object.assign(new Error("out of credit"), { status: 429, code: "PROVIDER_QUOTA_EXHAUSTED" })),+ false+ );+ assert.equal(shouldRetry(Object.assign(new Error("slow down"), { status: 429 })), true);+});++test("a classified 408 or 504 timeout still retries", async () => {+ const { createApiRetryStrategy } = await load();+ const { providerHttpError } = await import("../../src/helpers/providerHttpErrors.js");+ const { shouldRetry } = createApiRetryStrategy();+ const ctx = { provider: "Groq", surface: "llm" };++ for (const status of [408, 504]) {+ const gatewayTimeout = providerHttpError({ ...ctx, status, body: "" });+ assert.equal(gatewayTimeout.code, "PROVIDER_TIMEOUT");+ assert.equal(shouldRetry(gatewayTimeout), true, String(status));+ }+});diff --git a/test/helpers/assistantPanel.test.js b/test/helpers/assistantPanel.test.jsindex 572aa1d06..727e7c1db 100644--- a/test/helpers/assistantPanel.test.js+++ b/test/helpers/assistantPanel.test.js@@ -10,7 +10,9 @@ const noop = () => {};const { installInteractiveDom, findElement } = require("../lib/interactiveDom");-async function renderAssistantPanel(+// Loads the real AssistantPanel with its heavier dependencies mocked, and real+// i18n so translated text (not keys) renders.+async function setupAssistantPanel(t,messages,{@@ -75,7 +77,7 @@ async function renderAssistantPanel(`,"/hooks/useCopyFeedback": `export function useCopyFeedback() {- return { copied: false, async copy() {}, confirmCopied() {} };+ return { copied: false, async copy() {}, async copyText() { return true; }, confirmCopied() {} };}`,"/stores/settingsStore": `@@ -123,26 +125,30 @@ async function renderAssistantPanel(interpolation: { escapeValue: false },});const { AssistantPanel } = await vite.ssrLoadModule("/components/dictation/AssistantPanel.tsx");- return renderToStaticMarkup(- React.createElement(AssistantPanel, {- pendingCommand: null,- onCommandConsumed: noop,- onCommandDiscarded: noop,- initialConversationId,- onConversationIdChange: noop,- voiceState: "idle",- thinking: false,- open: true,- footerPhase: "pill",- horizontalDirection: "right",- onClose: noop,- onBusyChange: noop,- onResponseReadyChange: noop,- onResponseContent: noop,- onConversationReset: noop,- onSelectionContextChange: noop,- })- );+ const props = {+ pendingCommand: null,+ onCommandConsumed: noop,+ onCommandDiscarded: noop,+ initialConversationId,+ onConversationIdChange: noop,+ voiceState: "idle",+ thinking: false,+ open: true,+ footerPhase: "pill",+ horizontalDirection: "right",+ onClose: noop,+ onBusyChange: noop,+ onResponseReadyChange: noop,+ onResponseContent: noop,+ onConversationReset: noop,+ onSelectionContextChange: noop,+ };+ return { AssistantPanel, props };+}++async function renderAssistantPanel(t, messages, options) {+ const { AssistantPanel, props } = await setupAssistantPanel(t, messages, options);+ return renderToStaticMarkup(React.createElement(AssistantPanel, props));}test("an empty idle Assistant shows typed input and generic suggestions", async (t) => {@@ -548,6 +554,64 @@ test("Assistant selection must stay entirely inside the response root", async (tassert.equal(getSelectionInside(responseRoot), null);});+// The Open Settings link and technical details must never ride along in a+// drag-select + copy over the response, or the clipboard would pick up UI+// chrome instead of just the answer.+test("Cmd+C copies a selection in a classified error's answer, but not one running into its Open Settings or details", async (t) => {+ let root = null;+ t.after(async () => {+ if (root) await React.act(async () => root.unmount());+ });+ installBrowserGlobals(t);+ const container = installInteractiveDom(t);+ t.mock.method(globalThis.document, "addEventListener");++ const { AssistantPanel, props } = await setupAssistantPanel(t, [+ {+ id: "assistant-1",+ role: "assistant",+ content: "Error: OpenAI rejected your API key.",+ isStreaming: false,+ error: { settingsTarget: "llms", technicalDetails: { provider: "OpenAI", status: 401 } },+ },+ ]);+ const { createRoot } = require("react-dom/client");+ root = createRoot(container);+ await React.act(async () => root.render(React.createElement(AssistantPanel, props)));++ const answer = findElement(+ container,+ (element) => element.textContent === "Error: OpenAI rejected your API key."+ );+ const settingsButton = findElement(+ container,+ (element) => element.tagName === "BUTTON" && element.textContent.includes("Open Settings")+ );+ const details = findElement(container, (element) => element.tagName === "DETAILS");+ assert.ok(answer && settingsButton && details, "shows the answer, Open Settings and details");++ let selectionEnd = null;+ globalThis.window.getSelection = () => ({+ isCollapsed: false,+ rangeCount: 1,+ getRangeAt: () => ({ startContainer: answer, endContainer: selectionEnd }),+ toString: () => "selected text",+ });+ const onKeyDown = globalThis.document.addEventListener.mock.calls.findLast(+ (call) => call.arguments[0] === "keydown"+ ).arguments[1];+ const copiesSelectionEndingIn = (node) => {+ selectionEnd = node;+ const preventDefault = t.mock.fn();+ onKeyDown({ key: "c", metaKey: true, ctrlKey: false, altKey: false, preventDefault });+ return preventDefault.mock.callCount() === 1;+ };++ assert.equal(copiesSelectionEndingIn(answer), true, "a selection inside the answer is copied");+ assert.equal(copiesSelectionEndingIn(settingsButton), false, "Open Settings is never copied");+ assert.equal(copiesSelectionEndingIn(details), false, "technical details are never copied");+});+test("a failed Assistant resize releases its open claim so opening can retry", async (t) => {installBrowserGlobals(t);const vite = await createRendererServer(t, {diff --git a/test/helpers/audioManagerCleanupFallback.test.js b/test/helpers/audioManagerCleanupFallback.test.jsindex 5cfda12ff..57b51e5b6 100644--- a/test/helpers/audioManagerCleanupFallback.test.js+++ b/test/helpers/audioManagerCleanupFallback.test.js@@ -280,3 +280,43 @@ test("translation cleanup failures survive successful and skipped translation foassert.deepEqual(manager._takePendingResultExtras(), {});}});++test("a classified provider cleanup failure keeps the fields its toast needs", async (t) => {+ const { createManager } = await loadAudioManager(t, {+ cachePrefix: "openwhispr-classified-cleanup-failure-",+ settingsKey: "__classifiedCleanupFailureSettings",+ });+ const failure = Object.assign(new Error("OpenAI rejected your API key."), {+ code: "PROVIDER_AUTH_FAILED",+ messageKey: "providerErrors.authFailed",+ messageParams: { provider: "OpenAI" },+ settingsTarget: "llms",+ surface: "llm",+ technicalDetails: { provider: "OpenAI", status: 401 },+ });+ const manager = createManager({+ pendingCleanupFailure: null,+ processWithReasoningModel: async () => {+ throw failure;+ },+ });++ await manager.runTranslationChain({+ text: "raw dictation",+ settings: { translationSourceLanguage: "en", translationTargetLanguage: "en" },+ agentName: null,+ route: { model: "translation-model", cleanupReachable: true, cleanupConfig: {}, config: {} },+ cleanup: { mode: "model", model: "cleanup-model" },+ });++ assert.deepEqual(manager._takePendingResultExtras(), {+ cleanupFailure: {+ message: failure.message,+ messageKey: failure.messageKey,+ messageParams: failure.messageParams,+ surface: failure.surface,+ settingsTarget: failure.settingsTarget,+ technicalDetails: failure.technicalDetails,+ },+ });+});diff --git a/test/helpers/audioManagerCloudFallbackPolicy.test.js b/test/helpers/audioManagerCloudFallbackPolicy.test.jsindex 4c845e1c3..f299caeec 100644--- a/test/helpers/audioManagerCloudFallbackPolicy.test.js+++ b/test/helpers/audioManagerCloudFallbackPolicy.test.js@@ -142,6 +142,30 @@ test("cloud->local fallback under org policy", async (t) => {assert.equal(result.source, "local-fallback");assert.equal(localWhisperCalls, 1);});++ await t.test("a failed fallback keeps the cloud failure's classified fields", async () => {+ setManagedPolicy(["providers", "local"]);+ captureFetch(t, () => {+ throw new TypeError("Failed to fetch");+ });+ window.electronAPI.transcribeLocalWhisper = async () => ({+ success: false,+ error: "model missing",+ });++ // A real Blob: the direct fetch builds FormData, which rejects the stub above.+ const recording = new Blob(["recording"], { type: "audio/webm" });+ await assert.rejects(createManager().processWithOpenAIAPI(recording, {}), (error) => {+ assert.equal(error.code, "PROVIDER_NO_RESPONSE");+ assert.equal(error.messageKey, "providerErrors.noResponse");+ // Without params the toast would render the literal "{{provider}}".+ assert.deepEqual(error.messageParams, { provider: "OpenAI" });+ assert.equal(error.surface, "transcription");+ assert.equal(error.technicalDetails?.provider, "OpenAI");+ assert.match(error.message, /Local fallback also failed/);+ return true;+ });+ });});test("managed custom transcription never falls through to OpenAI", async (t) => {@@ -459,16 +483,25 @@ test("proxied providers dispatch through the registry", async (t) => {assert.equal(fetched.length, 0);});- await t.test("structured proxy errors are rebuilt with code and messageKey", async () => {+ await t.test("structured proxy errors are rebuilt with every classified field", async () => {setSettings(settingsFor("mistral"));window.electronAPI.proxyMistralTranscription = async () => ({- error: "Mistral API Error: 401 unauthorized",- code: "INVALID_KEY",- messageKey: "some.key",+ error: "Mistral rejected your API key.",+ code: "PROVIDER_AUTH_FAILED",+ messageKey: "providerErrors.authFailed",+ messageParams: { provider: "Mistral" },+ settingsTarget: "speechToText",+ technicalDetails: { provider: "Mistral", status: 401 },+ status: 401,+ surface: "transcription",});await assert.rejects(manager.processWithOpenAIAPI(audioBlob), (error) => {- assert.equal(error.code, "INVALID_KEY");- assert.equal(error.messageKey, "some.key");+ assert.equal(error.code, "PROVIDER_AUTH_FAILED");+ assert.equal(error.messageKey, "providerErrors.authFailed");+ assert.deepEqual(error.messageParams, { provider: "Mistral" });+ assert.equal(error.settingsTarget, "speechToText");+ assert.equal(error.status, 401);+ assert.deepEqual(error.technicalDetails, { provider: "Mistral", status: 401 });return true;});});diff --git a/test/helpers/audioManagerProviderErrors.test.js b/test/helpers/audioManagerProviderErrors.test.jsnew file mode 100644index 000000000..f8de7f409--- /dev/null+++ b/test/helpers/audioManagerProviderErrors.test.js@@ -0,0 +1,125 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { loadAudioManager } = require("./harness/audioManager");++// processWithOpenAIAPI classifies BYOK transcription failures from the throw+// shapes production sees: a renderer fetch Response or TypeError for direct+// providers, and the { error } fields main serialises for proxied ones.+async function loadManager(t, settings, window = {}) {+ const loaded = await loadAudioManager(t, {+ cachePrefix: "openwhispr-provider-errors-test-",+ settingsKey: "__providerErrorsSettings",+ settings: { useLocalWhisper: false, allowLocalFallback: false, ...settings },+ });+ Object.assign(loaded.window.electronAPI, window);+ return loaded.createManager({+ isProcessing: true,+ _activeTranscriptionAbortController: null,+ getEffectiveSttLanguage: () => "auto",+ getAPIKey: async () => "test-key",+ getWhisperPrompt: () => null,+ getKeyterms: () => [],+ isDictionaryEcho: () => false,+ processTranscription: async (text) => text,+ isReasoningAvailable: async () => false,+ });+}++const selfHostedSettings = {+ cloudTranscriptionMode: "byok",+ // Self-hosted dictation leaves the provider setting at its default.+ cloudTranscriptionProvider: "openai",+ transcriptionMode: "self-hosted",+ remoteTranscriptionUrl: "https://stt.example.com/v1",+ remoteTranscriptionModel: "whisper-large-v3",+};++const recording = () => new Blob(["recording"], { type: "audio/webm" });++async function rejection(promise) {+ try {+ await promise;+ } catch (error) {+ return error;+ }+ assert.fail("expected processWithOpenAIAPI to reject");+}++test("a self-hosted 404 blames the user's server, not OpenAI", async (t) => {+ const manager = await loadManager(t, selfHostedSettings);+ t.mock.method(globalThis, "fetch", async () => new Response("Not Found", { status: 404 }));++ const error = await rejection(manager.processWithOpenAIAPI(recording()));++ assert.equal(error.code, "PROVIDER_ERROR");+ assert.equal(error.messageKey, "providerErrors.selfHosted.unknown");+ assert.equal(error.message, "Your server returned an unexpected error.");+ assert.doesNotMatch(error.message, /OpenAI/);+});++test("a direct-fetch \"Failed to fetch\" asks to check the key and connection", async (t) => {+ const manager = await loadManager(t, { cloudTranscriptionProvider: "groq" });+ t.mock.method(globalThis, "fetch", async () => {+ throw new TypeError("Failed to fetch");+ });++ const error = await rejection(manager.processWithOpenAIAPI(recording()));++ assert.equal(error.code, "PROVIDER_NO_RESPONSE");+ assert.equal(error.messageKey, "providerErrors.noResponse");+ assert.equal(error.settingsTarget, "speechToText");+ assert.equal(error.messageParams.provider, "Groq");+ assert.equal(error.surface, "transcription");+});++test("a cancelled direct fetch stays an AbortError", async (t) => {+ const manager = await loadManager(t, { cloudTranscriptionProvider: "openai" });+ t.mock.method(globalThis, "fetch", async () => {+ throw new DOMException("The operation was aborted.", "AbortError");+ });++ const error = await rejection(manager.processWithOpenAIAPI(recording()));++ assert.equal(error.name, "AbortError");+ assert.equal(error.code, 20);+ assert.equal(error.messageKey, undefined);+});++test("a proxied provider's net::ERR_* failure is classified with its display name", async (t) => {+ const manager = await loadManager(+ t,+ { cloudTranscriptionProvider: "mistral", cloudTranscriptionModel: "voxtral-mini-latest" },+ // What serializeIpcError returns for an unclassified net.fetch rejection.+ { proxyMistralTranscription: async () => ({ error: "net::ERR_INTERNET_DISCONNECTED" }) }+ );++ const error = await rejection(manager.processWithOpenAIAPI(recording()));++ assert.equal(error.code, "PROVIDER_UNREACHABLE");+ assert.equal(error.messageParams.provider, "Mistral");+ assert.equal(error.message, "Couldn't reach Mistral. Check your connection.");+});++test("a proxied provider's already-classified failure passes through unchanged", async (t) => {+ const manager = await loadManager(+ t,+ { cloudTranscriptionProvider: "mistral", cloudTranscriptionModel: "voxtral-mini-latest" },+ {+ proxyMistralTranscription: async () => ({+ error: "Mistral rejected your API key.",+ code: "PROVIDER_AUTH_FAILED",+ messageKey: "providerErrors.authFailed",+ messageParams: { provider: "Mistral" },+ settingsTarget: "speechToText",+ status: 401,+ surface: "transcription",+ }),+ }+ );++ const error = await rejection(manager.processWithOpenAIAPI(recording()));++ assert.equal(error.code, "PROVIDER_AUTH_FAILED");+ assert.equal(error.status, 401);+ assert.equal(error.settingsTarget, "speechToText");+});diff --git a/test/helpers/cleanupFailureToast.test.js b/test/helpers/cleanupFailureToast.test.jsindex 687394f76..dff5dcb68 100644--- a/test/helpers/cleanupFailureToast.test.js+++ b/test/helpers/cleanupFailureToast.test.js@@ -102,3 +102,77 @@ test("technical AWS details use the selected UI language", async (t) => {assert.match(markup, /Error subyacente: Bedrock overloaded/);assert.match(markup, /aria-label="Copiar detalles técnicos"/);});++async function recordClassifiedCleanupFailure(t, { dictationWindow }) {+ let root = null;+ t.after(async () => {+ if (root) await React.act(async () => root.unmount());+ delete globalThis.__cleanupFailureToasts;+ });+ globalThis.__cleanupFailureToasts = [];+ installBrowserGlobals(t);+ const container = installHookDom(t);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-cleanup-failure-toast-llm-",+ mockModules: {+ "/ui/useToast": `+ export const useToast = () => ({+ toast: (props) => globalThis.__cleanupFailureToasts.push(props)+ });+ `,+ "/utils/windowContext": `+ export const isDictationPanelWindow = () => ${dictationWindow};+ `,+ },+ });+ const { default: CleanupFailureToastListener } = await vite.ssrLoadModule(+ "/components/CleanupFailureToastListener.tsx"+ );+ const { default: i18n } = await vite.ssrLoadModule("/i18n.ts");+ await i18n.changeLanguage("en");+ const { recordCleanupFailure, useCleanupFailureStore } = await vite.ssrLoadModule(+ "/stores/cleanupFailureStore.ts"+ );+ useCleanupFailureStore.setState({ pending: 0, lastMessage: "", lastFailure: null });++ root = createRoot(container);+ await React.act(async () => root.render(React.createElement(CleanupFailureToastListener)));++ await React.act(async () =>+ recordCleanupFailure({+ message: "OpenAI rejected your API key.",+ surface: "llm",+ messageKey: "providerErrors.authFailed",+ messageParams: { provider: "OpenAI" },+ settingsTarget: "llms",+ technicalDetails: { provider: "OpenAI", status: 401 },+ })+ );+ return globalThis.__cleanupFailureToasts.at(-1);+}++test("a classified cleanup failure says why, then that the dictation went in raw, with Open Settings and Copy details", async (t) => {+ const toastProps = await recordClassifiedCleanupFailure(t, { dictationWindow: false });+ assert.equal(toastProps.title, "Cleanup failed");+ assert.equal(+ toastProps.description,+ "OpenAI rejected your API key.\nOriginal dictation pasted without AI cleanup."+ );+ assert.deepEqual(+ toastProps.actions.map(({ label, iconOnly }) => ({ label, iconOnly })),+ [+ { label: "Open Settings", iconOnly: undefined },+ { label: "Copy details", iconOnly: true },+ ]+ );+ assert.equal(toastProps.technicalDetails, undefined, "details are behind Copy details");+ assert.equal(toastProps.secondaryDescription, undefined);+ assert.equal(toastProps.presentation, undefined);+});++test("in the dictation window a classified cleanup failure uses the pill's error card", async (t) => {+ const toastProps = await recordClassifiedCleanupFailure(t, { dictationWindow: true });+ assert.equal(toastProps.presentation, "dictation-error");+ assert.equal(toastProps.duration, 10_000);+ assert.equal(toastProps.actions.length, 2);+});diff --git a/test/helpers/cortiTranscription.test.js b/test/helpers/cortiTranscription.test.jsnew file mode 100644index 000000000..b74227837--- /dev/null+++ b/test/helpers/cortiTranscription.test.js@@ -0,0 +1,44 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const Module = require("node:module");++// cortiAuth and cortiTranscription call Electron's net.fetch, so stub it.+const originalLoad = Module._load;+let fetchBehavior = async () => {+ throw new Error("fetch not stubbed");+};+const electronStub = {+ app: { isReady: () => false, getPath: () => "/tmp", getVersion: () => "0.0.0" },+ net: { fetch: (...args) => fetchBehavior(...args) },+};+Module._load = function loadWithElectronStub(request, parent, isMain) {+ if (request === "electron") return electronStub;+ return originalLoad.call(this, request, parent, isMain);+};+test.after(() => {+ Module._load = originalLoad;+});++const { transcribeAudio } = require("../../src/helpers/cortiTranscription");++test("a rejected Corti client secret is classified instead of showing the token endpoint's body", async () => {+ const body = '{"error":"unauthorized_client","error_description":"Invalid client credentials"}';+ fetchBehavior = async () => new Response(body, { status: 401 });++ const error = await transcribeAudio({+ environment: "eu",+ tenant: "acme",+ clientId: "corti-id",+ clientSecret: "wrong-secret",+ audioBuffer: Buffer.from("audio"),+ }).then(+ () => assert.fail("expected the token mint to fail"),+ (err) => err+ );++ assert.equal(error.code, "PROVIDER_AUTH_FAILED");+ assert.equal(error.message, "Corti rejected your API key.");+ assert.equal(error.settingsTarget, "speechToText");+ assert.equal(error.technicalDetails.status, 401);+ assert.match(error.technicalDetails.underlyingError, /Invalid client credentials/);+});diff --git a/test/helpers/geminiTranscription.test.js b/test/helpers/geminiTranscription.test.jsindex fe492db80..8644135de 100644--- a/test/helpers/geminiTranscription.test.js+++ b/test/helpers/geminiTranscription.test.js@@ -116,20 +116,48 @@ test("HTTP statuses map to coded errors without leaking the key", async () => {);};- for (const status of [401, 403]) {- const error = await statusError(status);- assert.equal(error.code, "INVALID_KEY");- assert.equal(error.message.includes("sk-secret"), false);- }+ const unauthorized = await statusError(401);+ assert.equal(unauthorized.code, "PROVIDER_AUTH_FAILED");+ assert.equal(unauthorized.message.includes("sk-secret"), false);++ // A bare 403 with no key-signal body is access-denied, not an auth failure —+ // the shared classifier only promotes 403 to PROVIDER_AUTH_FAILED when the+ // body itself names an invalid/incorrect key.+ const forbidden = await statusError(403);+ assert.equal(forbidden.code, "PROVIDER_ACCESS_DENIED");+ assert.equal(forbidden.message.includes("sk-secret"), false);+assert.equal((await statusError(429)).code, "PROVIDER_RATE_LIMITED");- assert.equal((await statusError(500)).code, "SERVER_ERROR");+ assert.equal((await statusError(500)).code, "PROVIDER_UNAVAILABLE");// Google's real answer to a bad key, captured from the live API.const badKey = await statusError(400, '{"error":{"reason":"API_KEY_INVALID"}}');- assert.equal(badKey.code, "INVALID_KEY");+ assert.equal(badKey.code, "PROVIDER_AUTH_FAILED");assert.equal(badKey.message.includes("sk-secret"), false);- assert.equal((await statusError(400, "unsupported mime")).code, undefined);+ assert.equal((await statusError(400, "unsupported mime")).code, "PROVIDER_BAD_REQUEST");+});++test("failures carry the classified key and Gemini as provider", async () => {+ const fetchImpl = async () => ({+ ok: false,+ status: 400,+ text: async () => '{"error":{"details":[{"reason":"API_KEY_INVALID"}]}}',+ });+ await assert.rejects(+ () =>+ transcribeWithGemini(+ { audioBuffer: AUDIO, model: "m", contentType: "audio/mp3", apiKey: "k" },+ fetchImpl+ ),+ (error) => {+ assert.equal(error.messageKey, "providerErrors.authFailed");+ assert.deepEqual(error.messageParams, { provider: "Gemini" });+ assert.equal(error.settingsTarget, "speechToText");+ assert.equal(error.technicalDetails.status, 400);+ return true;+ }+ );});test("a failed interaction status rejects even on HTTP 200", async () => {@@ -151,6 +179,25 @@ test("any non-completed status rejects instead of returning empty text", async ();});+test("an HTTP failure logs its status and a redacted body", async (t) => {+ const debugLogger = require("../../src/helpers/debugLogger");+ const warnings = [];+ t.mock.method(debugLogger, "warn", (message, meta) => warnings.push({ message, meta }));+ const fetchImpl = async () => ({+ ok: false,+ status: 400,+ text: async () => '{"error":{"message":"API key not valid: AIzaSyLeakedKey123"}}',+ });++ await assert.rejects(transcribeWithGemini({ audioBuffer: AUDIO, apiKey: "k" }, fetchImpl));++ const failure = warnings.find(({ message }) => message === "Gemini transcription failed");+ assert.ok(failure, "the failure must be logged");+ assert.equal(failure.meta.status, 400);+ assert.match(failure.meta.body, /API key not valid/);+ assert.equal(failure.meta.body.includes("AIzaSyLeakedKey123"), false);+});+test("canonical mime types map onto Gemini's documented ones", async () => {const { fetchImpl, calls } = makeFetch({ status: "completed", output_text: "ok" });diff --git a/test/helpers/ipcErrorFields.test.js b/test/helpers/ipcErrorFields.test.jsnew file mode 100644index 000000000..4f92f7110--- /dev/null+++ b/test/helpers/ipcErrorFields.test.js@@ -0,0 +1,48 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/helpers/ipcErrorFields.js");++test("ipcErrorFields keeps every classified field and drops undefined ones", async () => {+ const { ipcErrorFields } = await load();+ const error = Object.assign(new Error("Mistral rejected your API key."), {+ code: "PROVIDER_AUTH_FAILED",+ messageKey: "providerErrors.authFailed",+ messageParams: { provider: "Mistral" },+ settingsTarget: "speechToText",+ technicalDetails: { provider: "Mistral", status: 401 },+ status: 401,+ surface: "transcription",+ });+ assert.deepEqual(ipcErrorFields(error), {+ error: "Mistral rejected your API key.",+ code: "PROVIDER_AUTH_FAILED",+ messageKey: "providerErrors.authFailed",+ messageParams: { provider: "Mistral" },+ settingsTarget: "speechToText",+ technicalDetails: { provider: "Mistral", status: 401 },+ status: 401,+ surface: "transcription",+ });+ assert.deepEqual(ipcErrorFields(new Error("plain")), { error: "plain" });+});++test("errorFromIpcResult rebuilds an Error with the same fields", async () => {+ const { ipcErrorFields, errorFromIpcResult } = await load();+ const original = Object.assign(new Error("x"), {+ code: "PROVIDER_UNAVAILABLE",+ messageKey: "providerErrors.unavailable",+ messageParams: { provider: "xAI" },+ technicalDetails: { status: 503 },+ status: 503,+ surface: "transcription",+ });+ const rebuilt = errorFromIpcResult(ipcErrorFields(original));+ assert.ok(rebuilt instanceof Error);+ assert.equal(rebuilt.message, "x");+ for (const key of ["code", "messageKey", "status", "surface"]) {+ assert.equal(rebuilt[key], original[key]);+ }+ assert.deepEqual(rebuilt.messageParams, original.messageParams);+ assert.deepEqual(rebuilt.technicalDetails, original.technicalDetails);+});diff --git a/test/helpers/pastePermissionToast.test.js b/test/helpers/pastePermissionToast.test.jsindex 841f66f5b..d3f1d5d96 100644--- a/test/helpers/pastePermissionToast.test.js+++ b/test/helpers/pastePermissionToast.test.js@@ -191,3 +191,96 @@ test("real card keeps copy local, guards pending clicks, resets feedback and renawait React.act(async () => t.mock.timers.tick(1801));assert.equal(h.container.textContent, "");});++test("an icon-only action follows the labelled ones in the same row", async (t) => {+ const h = await setup(t);+ const { DictationErrorCard } = await h.vite.ssrLoadModule(+ "/components/dictation/DictationErrorCard.tsx"+ );+ const action = (label, extra = {}) => ({ label, onClick: () => {}, ...extra });+ const button = (label) =>+ findElement(h.container, (e) => e.tagName === "BUTTON" && e.textContent.trim() === label);++ await h.render(+ React.createElement(DictationErrorCard, {+ title: "Transcription failed",+ description: "Mistral rejected your API key.",+ actions: [+ action("Retry"),+ action("Copy details", { icon: "copy", iconOnly: true }),+ action("Open Settings"),+ ],+ onAction: (value) => value.onClick(),+ })+ );+ assert.deepEqual(+ button("Retry").parentNode.childNodes.map((node) => node.textContent.trim()),+ ["Retry", "Open Settings", "Copy details"]+ );+ assert.equal(button("Copy details").getAttribute("title"), "Copy details");+});++test("a standard toast with structured actions shows its description as text and the actions under it", async (t) => {+ const h = await setup(t);+ const { ToastProvider } = await h.vite.ssrLoadModule("/components/ui/Toast.tsx");+ const { useToast } = await h.vite.ssrLoadModule("/components/ui/useToast.ts");+ let context;+ function Probe() {+ context = useToast();+ return null;+ }+ await h.render(React.createElement(ToastProvider, null, React.createElement(Probe)));+ const clicks = [];+ await React.act(async () =>+ context.toast({+ title: "Failed to re-transcribe",+ description: "Groq rejected your API key.",+ variant: "destructive",+ duration: 0,+ actions: [+ { label: "Open Settings", onClick: () => clicks.push("settings") },+ {+ label: "Copy details",+ icon: "copy",+ iconOnly: true,+ dismissOnClick: false,+ feedback: { successLabel: "Copied", failureLabel: "Copy failed" },+ onClick: async () => {+ clicks.push("copy");+ return true;+ },+ },+ ],+ })+ );+ assert.ok(+ findElement(h.container, (e) => e.textContent === "Groq rejected your API key."),+ "description rendered"+ );+ assert.ok(+ !findElement(h.container, (e) => e.getAttribute("aria-label") === "Copy error"),+ "no raw-error copy box"+ );+ const buttons = (root) => {+ const found = [];+ (function walk(node) {+ if (node.tagName === "BUTTON") found.push(node);+ node.childNodes?.forEach(walk);+ })(root);+ return found;+ };+ const settings = buttons(h.container).find((b) => b.textContent.trim() === "Open Settings");+ const row = settings.parentNode;+ assert.deepEqual(+ buttons(row).map((b) => b.getAttribute("title") || b.textContent.trim()),+ ["Open Settings", "Copy details"]+ );+ const copyButton = buttons(row)[1];+ await React.act(async () => click(copyButton));+ assert.equal(copyButton.getAttribute("title"), "Copied");+ assert.equal(context.toastCount, 1, "Copy details keeps the toast open");+ await React.act(async () => click(settings));+ assert.deepEqual(clicks, ["copy", "settings"]);+ await React.act(() => new Promise((resolve) => setTimeout(resolve, 250)));+ assert.equal(context.toastCount, 0, "Open Settings dismisses the toast");+});diff --git a/test/helpers/providerHttpErrors.test.js b/test/helpers/providerHttpErrors.test.jsnew file mode 100644index 000000000..5fb8aef64--- /dev/null+++ b/test/helpers/providerHttpErrors.test.js@@ -0,0 +1,434 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/helpers/providerHttpErrors.js");++const classify = async (args) =>+ (await load()).providerHttpError({ provider: "Mistral", surface: "transcription", ...args });++test("401 is an auth failure that points at Speech-to-Text settings", async () => {+ const c = await classify({ status: 401, body: '{"detail":"Invalid API Key"}' });+ assert.equal(c.code, "PROVIDER_AUTH_FAILED");+ assert.equal(c.messageKey, "providerErrors.authFailed");+ assert.deepEqual(c.messageParams, { provider: "Mistral" });+ assert.equal(c.settingsTarget, "speechToText");+ assert.equal(c.surface, "transcription");+});++test("LLM surface points fixable errors at Language Models settings", async () => {+ const c = await classify({ status: 401, body: "", surface: "llm" });+ assert.equal(c.settingsTarget, "llms");+});++test("400 or 403 carrying an invalid-key signal is an auth failure (Gemini API_KEY_INVALID)", async () => {+ const gemini = await classify({+ provider: "Gemini",+ status: 400,+ body: { error: { status: "INVALID_ARGUMENT", details: [{ reason: "API_KEY_INVALID" }] } },+ });+ assert.equal(gemini.code, "PROVIDER_AUTH_FAILED");+ const forbidden = await classify({ status: 403, body: "invalid x-api-key" });+ assert.equal(forbidden.code, "PROVIDER_AUTH_FAILED");+});++test("other 403s are access denied", async () => {+ const c = await classify({ status: 403, body: '{"error":"model not allowed for this project"}' });+ assert.equal(c.code, "PROVIDER_ACCESS_DENIED");+ assert.equal(c.settingsTarget, "speechToText");+});++test("402 and billing-flavoured 400/429 are quota exhaustion", async () => {+ assert.equal((await classify({ status: 402, body: "" })).code, "PROVIDER_QUOTA_EXHAUSTED");+ const openai = await classify({+ provider: "OpenAI",+ status: 429,+ body: {+ error: {+ message: "You exceeded your current quota, please check your plan and billing details.",+ type: "insufficient_quota",+ },+ },+ });+ assert.equal(openai.code, "PROVIDER_QUOTA_EXHAUSTED");+ const anthropic = await classify({+ provider: "Anthropic",+ status: 400,+ surface: "llm",+ body: {+ type: "error",+ error: {+ type: "invalid_request_error",+ message: "Your credit balance is too low to access the Anthropic API.",+ },+ },+ });+ assert.equal(anthropic.code, "PROVIDER_QUOTA_EXHAUSTED");+});++test("self-hosted quota exhaustion gets its own sentence instead of \"Your Your server account\"", async () => {+ const { providerHttpError } = await load();+ const err = providerHttpError({+ provider: "self-hosted",+ selfHosted: true,+ status: 402,+ body: "",+ surface: "llm",+ });+ assert.equal(err.code, "PROVIDER_QUOTA_EXHAUSTED");+ assert.equal(err.messageKey, "providerErrors.selfHosted.quotaExhausted");+ assert.equal(err.message, "Your server says the account is out of credit.");+ assert.equal(err.message.includes("Your Your server"), false);+});++// Real bodies: both mention quota and billing, but only ask the user to wait.+const GEMINI_RATE_LIMIT_BODY = {+ error: {+ code: 429,+ message:+ "You exceeded your current quota, please check your plan and billing details. For more information on this error, head to: https://ai.google.dev/gemini-api/docs/rate-limits.\n* Quota exceeded for metric: generativelanguage.googleapis.com/generate_content_free_tier_requests, limit: 10, model: gemini-3.5-flash\nPlease retry in 52.4s.",+ status: "RESOURCE_EXHAUSTED",+ },+};+const GROQ_RATE_LIMIT_BODY = {+ error: {+ message:+ "Rate limit reached for model `whisper-large-v3-turbo` in organization `org_01` service tier `on_demand` on seconds of audio per hour (ASPH): Limit 7200, Used 7190, Requested 30. Please try again in 10s. Need more tokens? Upgrade to Dev Tier today at https://console.groq.com/settings/billing",+ type: "seconds",+ code: "rate_limit_exceeded",+ },+};++test("a Gemini free-tier quota 429 stays a rate limit", async () => {+ const c = await classify({ provider: "Gemini", status: 429, body: GEMINI_RATE_LIMIT_BODY });+ assert.equal(c.code, "PROVIDER_RATE_LIMITED");+ assert.equal(c.messageKey, "hooks.audioRecording.errorDescriptions.providerRateLimited");+ assert.equal(c.settingsTarget, undefined);+});++test("a Groq 429 that links to its billing page stays a rate limit", async () => {+ const c = await classify({ provider: "Groq", status: 429, body: GROQ_RATE_LIMIT_BODY });+ assert.equal(c.code, "PROVIDER_RATE_LIMITED");+ assert.equal(c.settingsTarget, undefined);+});++test("OpenAI's real out-of-quota 429 shares Gemini's wording but is quota exhaustion", async () => {+ const c = await classify({+ provider: "OpenAI",+ status: 429,+ body: {+ error: {+ message:+ "You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.",+ type: "insufficient_quota",+ param: null,+ code: "insufficient_quota",+ },+ },+ });+ assert.equal(c.code, "PROVIDER_QUOTA_EXHAUSTED");+});++test("rate-limit 429s from Gemini and Groq are still retried on the AI-model path", async () => {+ const { providerHttpError } = await load();+ const { createApiRetryStrategy } = await import("../../src/utils/retry.ts");+ const { shouldRetry } = createApiRetryStrategy();+ for (const [provider, body] of [+ ["Gemini", GEMINI_RATE_LIMIT_BODY],+ ["Groq", GROQ_RATE_LIMIT_BODY],+ ]) {+ const error = providerHttpError({ provider, status: 429, body, surface: "llm" });+ assert.equal(shouldRetry(error), true, `${provider} rate limit should retry`);+ }+});++test("404 and model-not-found 400 name the model", async () => {+ const notFound = await classify({ status: 404, body: "", model: "voxtral-max" });+ assert.equal(notFound.code, "PROVIDER_MODEL_NOT_FOUND");+ assert.equal(notFound.messageKey, "providerErrors.modelNotFound");+ assert.deepEqual(notFound.messageParams, { provider: "Mistral", model: "voxtral-max" });+ const badModel = await classify({+ provider: "OpenAI",+ status: 400,+ body: { error: { message: "The model `gpt-9` does not exist", code: "model_not_found" } },+ });+ assert.equal(badModel.code, "PROVIDER_MODEL_NOT_FOUND");+ assert.equal(badModel.messageKey, "providerErrors.modelNotFoundNoModel");+});++test("a self-hosted 404 without a model signal is a generic error, not a model error", async () => {+ const c = await classify({ status: 404, body: "<html>Not Found</html>", selfHosted: true });+ assert.equal(c.code, "PROVIDER_ERROR");+ assert.equal(c.messageKey, "providerErrors.selfHosted.unknown");+ assert.equal(c.messageParams.provider, "Your server");+});++test("413, other 4xx, timeouts, 5xx and unknown statuses", async () => {+ assert.equal((await classify({ status: 413, body: "" })).code, "PROVIDER_PAYLOAD_TOO_LARGE");+ for (const status of [400, 415, 422]) {+ assert.equal((await classify({ status, body: "bad audio" })).code, "PROVIDER_BAD_REQUEST");+ }+ for (const status of [408, 504]) {+ assert.equal((await classify({ status, body: "" })).code, "PROVIDER_TIMEOUT");+ }+ for (const status of [500, 502, 503, 529]) {+ assert.equal((await classify({ status, body: "" })).code, "PROVIDER_UNAVAILABLE");+ }+ assert.equal((await classify({ status: 418, body: "" })).code, "PROVIDER_ERROR");+});++test("technical details carry provider, status, request id and a trimmed body", async () => {+ const headers = new Headers({ "x-request-id": "req_123" });+ const c = await classify({ status: 500, body: "x".repeat(800), headers });+ assert.equal(c.technicalDetails.provider, "Mistral");+ assert.equal(c.technicalDetails.status, 500);+ assert.equal(c.technicalDetails.requestId, "req_123");+ assert.equal(c.technicalDetails.underlyingError.length, 501); // 500 chars + ellipsis+ const plain = await classify({ status: 500, body: "", headers: { "Request-Id": "abc" } });+ assert.equal(plain.technicalDetails.requestId, "abc");+ assert.equal(plain.technicalDetails.underlyingError, undefined);+});++test("HTML bodies collapse to a marker", async () => {+ const c = await classify({ status: 502, body: "<!DOCTYPE html><html><body>Bad gateway</body></html>" });+ assert.equal(c.technicalDetails.underlyingError, "<HTML response>");+});++test("keys echoed back in a body are redacted", async () => {+ const { redactProviderBody } = await load();+ const out = redactProviderBody(+ "Incorrect API key provided: sk-proj-ab***xyz. Also sk-ant-api03-zzzz gsk_abcd1234 AIzaSyA1234 xai-qwerty Authorization: Bearer eyJhbGciOi.abc"+ );+ for (const leaked of ["sk-proj-ab", "sk-ant-api03", "gsk_abcd", "AIzaSy", "xai-qwerty", "eyJhbGciOi"]) {+ assert.equal(out.includes(leaked), false, `${leaked} leaked: ${out}`);+ }+ assert.ok(out.includes("Bearer [redacted]"));+});++test("providerHttpError builds an Error carrying the classification and a short English message", async () => {+ const { providerHttpError } = await load();+ const err = providerHttpError({ provider: "Mistral", status: 401, body: "{}", surface: "transcription" });+ assert.ok(err instanceof Error);+ assert.equal(err.message, "Mistral rejected your API key.");+ assert.equal(err.code, "PROVIDER_AUTH_FAILED");+ assert.equal(err.status, 401);+ assert.equal(err.messageKey, "providerErrors.authFailed");+ assert.equal(err.settingsTarget, "speechToText");+ assert.equal(err.message.includes("{}"), false);+});++test("providerError builds key-missing errors per surface", async () => {+ const { providerError } = await load();+ const stt = providerError("API_KEY_MISSING", { provider: "Mistral", surface: "transcription" });+ assert.equal(stt.code, "API_KEY_MISSING");+ assert.equal(stt.messageKey, "hooks.audioRecording.errorDescriptions.providerKeyMissing");+ assert.equal(stt.settingsTarget, "speechToText");+ const llm = providerError("API_KEY_MISSING", { provider: "Anthropic", surface: "llm" });+ assert.equal(llm.messageKey, "providerErrors.keyMissing");+ assert.deepEqual(llm.messageParams, { provider: "Anthropic" });+ assert.equal(llm.settingsTarget, "llms");+});++test("asProviderError classifies AI SDK APICallError and RetryError", async () => {+ const { asProviderError } = await load();+ const apiCallError = Object.assign(new Error("Incorrect API key provided"), {+ name: "AI_APICallError",+ statusCode: 401,+ responseBody: '{"error":{"message":"Incorrect API key provided: sk-abcd1234"}}',+ responseHeaders: { "x-request-id": "r1" },+ });+ const direct = asProviderError(apiCallError, { provider: "OpenAI", model: "gpt-5.5", surface: "llm" });+ assert.equal(direct.code, "PROVIDER_AUTH_FAILED");+ assert.equal(direct.technicalDetails.requestId, "r1");+ assert.equal(direct.technicalDetails.underlyingError.includes("sk-abcd1234"), false);+ assert.equal(direct.cause, apiCallError);+ const retryError = Object.assign(new Error("Failed after 3 attempts"), {+ name: "AI_RetryError",+ lastError: Object.assign(new Error("overloaded"), { statusCode: 529, responseBody: "" }),+ });+ assert.equal(asProviderError(retryError, { provider: "Anthropic", surface: "llm" }).code, "PROVIDER_UNAVAILABLE");+});++test("asProviderError classifies timeouts and network failures", async () => {+ const { asProviderError } = await load();+ const ctx = { provider: "Groq", surface: "llm" };+ assert.equal(asProviderError(Object.assign(new Error("t"), { code: "LLM_REQUEST_TIMEOUT" }), ctx).code, "PROVIDER_TIMEOUT");+ assert.equal(asProviderError(Object.assign(new Error("t"), { name: "TimeoutError" }), ctx).code, "PROVIDER_TIMEOUT");+ const notFound = asProviderError(Object.assign(new Error("x"), { code: "ENOTFOUND" }), ctx);+ assert.equal(notFound.code, "PROVIDER_UNREACHABLE");+ assert.equal(notFound.technicalDetails.underlyingError, "ENOTFOUND");+ const refused = asProviderError(Object.assign(new Error("x"), { cause: { code: "ECONNREFUSED" } }), ctx);+ assert.equal(refused.code, "PROVIDER_UNREACHABLE");+ assert.equal(refused.technicalDetails.underlyingError, "ECONNREFUSED");+ const fetchFailed = asProviderError(new TypeError("fetch failed"), ctx);+ assert.equal(fetchFailed.code, "PROVIDER_UNREACHABLE");+ assert.deepEqual(fetchFailed.technicalDetails, { provider: "Groq" });+});++// Chromium reports a CORS-blocked HTTP error as "Failed to fetch" too: OpenAI's+// 401 for a bad sk- key carries no CORS header in the dictation window.+test("an online \"Failed to fetch\" points at the key and connection; offline it stays unreachable", async (t) => {+ const { asProviderError } = await load();+ const ctx = { provider: "OpenAI", surface: "transcription" };+ t.after(() => delete navigator.onLine);++ Object.defineProperty(navigator, "onLine", { configurable: true, value: true });+ const online = asProviderError(new TypeError("Failed to fetch"), ctx);+ assert.equal(online.code, "PROVIDER_NO_RESPONSE");+ assert.equal(online.message, "Couldn't get a response from OpenAI. Check your API key and connection.");+ assert.equal(online.settingsTarget, "speechToText");+ assert.deepEqual(online.technicalDetails, { provider: "OpenAI" }, "nothing beyond the message");++ Object.defineProperty(navigator, "onLine", { configurable: true, value: false });+ const offline = asProviderError(new TypeError("Failed to fetch"), ctx);+ assert.equal(offline.code, "PROVIDER_UNREACHABLE");+ assert.equal(offline.settingsTarget, undefined);+});++test("rate limits name the provider on the LLM surface and keep the dictation copy on transcription", async () => {+ const en = require("../../src/locales/en/translation.json");+ const llm = await classify({ provider: "Anthropic", status: 429, body: "", surface: "llm" });+ assert.equal(llm.code, "PROVIDER_RATE_LIMITED");+ assert.equal(llm.messageKey, "providerErrors.rateLimited");+ assert.deepEqual(llm.messageParams, { provider: "Anthropic" });+ const transcription = await classify({ status: 429, body: "", surface: "transcription" });+ assert.equal(transcription.messageKey, "hooks.audioRecording.errorDescriptions.providerRateLimited");+ const { providerHttpError } = await load();+ const error = providerHttpError({ provider: "Anthropic", status: 429, body: "", surface: "llm" });+ assert.equal(error.message, en.providerErrors.rateLimited.replace("{{provider}}", "Anthropic"));+});++test("asProviderError classifies Electron net::ERR_* rejections and leaves net::ERR_ABORTED alone", async () => {+ const { asProviderError } = await load();+ const ctx = { provider: "OpenAI", surface: "transcription" };+ for (const message of [+ "net::ERR_INTERNET_DISCONNECTED",+ "net::ERR_NAME_NOT_RESOLVED",+ "net::ERR_CONNECTION_REFUSED",+ ]) {+ const raw = new Error(message);+ const classified = asProviderError(raw, ctx);+ assert.equal(classified.code, "PROVIDER_UNREACHABLE", message);+ assert.equal(classified.messageKey, "providerErrors.unreachable");+ assert.equal(classified.cause, raw);+ // Main serialises only the message, so Copy details is the one place the code survives.+ assert.equal(classified.technicalDetails.underlyingError, message);+ }+ for (const message of ["net::ERR_TIMED_OUT", "net::ERR_CONNECTION_TIMED_OUT"]) {+ const timeout = asProviderError(new Error(message), ctx);+ assert.equal(timeout.code, "PROVIDER_TIMEOUT", message);+ assert.equal(timeout.technicalDetails.underlyingError, message);+ }+ const aborted = new Error("net::ERR_ABORTED");+ assert.equal(asProviderError(aborted, ctx), aborted);+});++test("asProviderError leaves classified, cancelled and unrelated errors untouched", async () => {+ const { asProviderError } = await load();+ const ctx = { provider: "OpenAI", surface: "llm" };+ const truncated = Object.assign(new Error("Model output was truncated"), {+ messageKey: "hooks.audioRecording.errorDescriptions.cleanupTruncated",+ });+ assert.equal(asProviderError(truncated, ctx), truncated);+ const abort = Object.assign(new Error("aborted"), { name: "AbortError" });+ assert.equal(asProviderError(abort, ctx), abort);+ const plain = new Error("something else");+ assert.equal(asProviderError(plain, ctx), plain);+ assert.equal(asProviderError(null, ctx), null);+});++test("isProviderSettingsTarget whitelists only the two sections", async () => {+ const { isProviderSettingsTarget } = await load();+ assert.equal(isProviderSettingsTarget("speechToText"), true);+ assert.equal(isProviderSettingsTarget("llms"), true);+ assert.equal(isProviderSettingsTarget("account"), false);+ assert.equal(isProviderSettingsTarget(undefined), false);+});++test("a 413 is a recording that's too large for transcription and a request that's too large for an AI model", async () => {+ const { providerHttpError } = await load();+ const recording = providerHttpError({ provider: "Mistral", status: 413, body: "", surface: "transcription" });+ assert.equal(recording.messageKey, "providerErrors.payloadTooLarge");+ assert.equal(recording.message, "This recording is too large for Mistral.");+ const request = providerHttpError({ provider: "Anthropic", status: 413, body: "", surface: "llm" });+ assert.equal(request.messageKey, "providerErrors.requestTooLarge");+ assert.equal(request.message, "This request is too large for Anthropic.");+ const selfHosted = providerHttpError({+ provider: "custom",+ selfHosted: true,+ status: 413,+ body: "",+ surface: "llm",+ });+ assert.equal(selfHosted.message, "This request is too large for your server.");+});++const en = require("../../src/locales/en/translation.json");+const LOCALES = ["en", "es", "fr", "de", "pt", "it", "ru", "zh-CN", "zh-TW", "ja", "ar"];+const lookup = (translation, key) => key.split(".").reduce((node, part) => node?.[part], translation);++// Every classification a provider failure can produce, on both surfaces, named and self-hosted.+async function everyClassification() {+ const { providerHttpError, providerError, PROVIDER_ERROR_CODES: C } = await load();+ const errors = [];+ for (const surface of ["transcription", "llm"]) {+ for (const selfHosted of [false, true]) {+ const base = { provider: "Mistral", surface, selfHosted };+ for (const status of [401, 403, 402, 429, 413, 400, 500, 504, 418]) {+ errors.push(providerHttpError({ ...base, status, body: "" }));+ }+ errors.push(providerHttpError({ ...base, status: 404, body: "model_not_found", model: "m-1" }));+ errors.push(providerHttpError({ ...base, status: 404, body: "model_not_found" }));+ for (const code of [+ C.TIMEOUT,+ C.UNREACHABLE,+ C.NO_RESPONSE,+ ...(selfHosted ? [] : [C.KEY_MISSING]),+ ]) {+ errors.push(providerError(code, base));+ }+ }+ }+ return errors;+}++test("each Error.message is the en translation of its messageKey", async () => {+ for (const error of await everyClassification()) {+ // The transcription-only hooks keys say "your transcription provider"; their twins name it.+ if (error.messageKey.startsWith("hooks.")) continue;+ const template = lookup(en, error.messageKey);+ assert.equal(typeof template, "string", `${error.messageKey} is missing from en`);+ const rendered = template.replace(/\{\{(\w+)\}\}/g, (_, name) => error.messageParams[name]);+ assert.equal(error.message, rendered, error.messageKey);+ }+});++test("self-hosted errors use sentences that name the server themselves, in every locale", async () => {+ const selfHostedKeys = new Set(+ (await everyClassification())+ .filter((error) => error.messageParams.provider === "Your server")+ .map((error) => error.messageKey)+ .filter((key) => key.startsWith("providerErrors."))+ );+ assert.ok(selfHostedKeys.size >= 10);+ for (const key of selfHostedKeys) {+ assert.match(key, /^providerErrors\.selfHosted\./);+ for (const locale of LOCALES) {+ const sentence = lookup(require(`../../src/locales/${locale}/translation.json`), key);+ assert.equal(typeof sentence, "string", `${locale}: ${key}`);+ // A substituted name can't take the case or article each sentence needs.+ assert.doesNotMatch(sentence, /\{\{provider\}\}/, `${locale}: ${key}`);+ }+ }+});++test("a model name is inserted literally, even with $ patterns", async () => {+ const { providerHttpError } = await load();+ const error = providerHttpError({+ provider: "OpenAI",+ status: 404,+ body: "",+ model: "we$&ird-$'model",+ surface: "llm",+ });+ assert.equal(error.message, "OpenAI doesn't recognize the model “we$&ird-$'model”.");+});diff --git a/test/helpers/retryTranscriptionHandler.test.js b/test/helpers/retryTranscriptionHandler.test.jsindex 57338f764..92cab32cb 100644--- a/test/helpers/retryTranscriptionHandler.test.js+++ b/test/helpers/retryTranscriptionHandler.test.js@@ -160,11 +160,13 @@ function buildFakeThis() {}let retryHandler;+let fakeThis;test.before(() => {delete require.cache[handlersModulePath];const IPCHandlers = require(handlersModulePath);const Ctor = IPCHandlers.default || IPCHandlers;- Ctor.prototype.setupHandlers.call(buildFakeThis());+ fakeThis = buildFakeThis();+ Ctor.prototype.setupHandlers.call(fakeThis);retryHandler = handlers.get("retry-transcription");assert.ok(retryHandler, "retry-transcription must be registered");});@@ -375,6 +377,74 @@ test("retry: mistral goes to Mistral with x-api-key", async () => {assert.equal(fetches[0].init.headers["x-api-key"], "mk-mistral");});+test("retry: a missing BYOK key on the generic provider branch is a classified error", async () => {+ fetches.length = 0;+ const originalGetMistralKey = fakeThis.environmentManager.getMistralKey;+ fakeThis.environmentManager.getMistralKey = () => "";+ try {+ const result = await invoke({+ cloudTranscriptionProvider: "mistral",+ cloudTranscriptionMode: "byok",+ transcriptionMode: "providers",+ });+ assert.equal(result.success, false);+ assert.equal(result.code, "API_KEY_MISSING");+ assert.equal(result.messageKey, "hooks.audioRecording.errorDescriptions.providerKeyMissing");+ assert.deepEqual(result.messageParams, { provider: "Mistral" });+ assert.equal(fetches.length, 0, "a missing key must fail before any request is sent");+ } finally {+ fakeThis.environmentManager.getMistralKey = originalGetMistralKey;+ }+});++test("retry: missing Corti credentials are a classified error", async () => {+ fetches.length = 0;+ const cortiCallsBefore = cortiCalls.length;+ const originalGetCortiClientId = fakeThis.environmentManager.getCortiClientId;+ fakeThis.environmentManager.getCortiClientId = () => "";+ try {+ const result = await invoke({+ cloudTranscriptionProvider: "corti",+ cloudTranscriptionMode: "byok",+ transcriptionMode: "providers",+ cortiEnvironment: "eu",+ cortiTenant: "acme",+ });+ assert.equal(result.success, false);+ assert.equal(result.code, "API_KEY_MISSING");+ assert.equal(result.messageKey, "hooks.audioRecording.errorDescriptions.providerKeyMissing");+ assert.deepEqual(result.messageParams, { provider: "Corti" });+ assert.equal(+ cortiCalls.length,+ cortiCallsBefore,+ "a missing credential must fail before calling Corti"+ );+ } finally {+ fakeThis.environmentManager.getCortiClientId = originalGetCortiClientId;+ }+});++test("proxy-corti-transcription: missing credentials are a classified error", async () => {+ const fn = handlers.get("proxy-corti-transcription");+ assert.ok(fn, "proxy-corti-transcription must be registered");+ const cortiCallsBefore = cortiCalls.length;+ const originalGetCortiClientId = fakeThis.environmentManager.getCortiClientId;+ fakeThis.environmentManager.getCortiClientId = () => "";+ try {+ const result = await fn({ sender: {} }, { audioBuffer: new ArrayBuffer(4) });+ assert.equal(result.code, "API_KEY_MISSING");+ assert.equal(result.messageKey, "hooks.audioRecording.errorDescriptions.providerKeyMissing");+ assert.deepEqual(result.messageParams, { provider: "Corti" });+ assert.equal(+ cortiCalls.length,+ cortiCallsBefore,+ "a missing credential must fail before calling Corti"+ );+ } finally {+ fakeThis.environmentManager.getCortiClientId = originalGetCortiClientId;+ }+});+test("proxy transcription handlers resolve to structured errors instead of rejecting", async () => {fetchResponse = () => ({ok: false,@@ -602,3 +672,110 @@ test("upload: a self-hosted Azure endpoint keeps its deployment URL", async () ="https://myorg.openai.azure.com/openai/deployments/my-deployment/audio/transcriptions?api-version=2025-03-01-preview");});++// Electron's net.fetch rejects with a plain Error whose message is the Chromium+// net error and no code; both BYOK handlers must classify it before replying.+async function withFetchRejecting(message, run) {+ const originalFetchResponse = fetchResponse;+ fetchResponse = () => {+ throw new Error(message);+ };+ try {+ return await run();+ } finally {+ fetchResponse = originalFetchResponse;+ }+}++test("retry: a net::ERR_* failure from a BYOK provider is classified as unreachable", async () => {+ const result = await withFetchRejecting("net::ERR_INTERNET_DISCONNECTED", () =>+ invoke({+ cloudTranscriptionProvider: "mistral",+ cloudTranscriptionMode: "byok",+ transcriptionMode: "providers",+ })+ );+ assert.equal(result.success, false);+ assert.equal(result.code, "PROVIDER_UNREACHABLE");+ assert.equal(result.messageKey, "providerErrors.unreachable");+ assert.equal(result.messageParams.provider, "Mistral");+ assert.equal(result.surface, "transcription");+});++test("retry: a self-hosted timeout names the user's server", async () => {+ const result = await withFetchRejecting("net::ERR_CONNECTION_TIMED_OUT", () =>+ invoke({+ transcriptionMode: "self-hosted",+ remoteTranscriptionUrl: "https://stt.example.com/v1",+ cloudTranscriptionProvider: "openai",+ cloudTranscriptionMode: "byok",+ })+ );+ assert.equal(result.code, "PROVIDER_TIMEOUT");+ assert.equal(result.messageKey, "providerErrors.selfHosted.timeout");+});++test("retry: a cancelled request (net::ERR_ABORTED) is not classified", async () => {+ const result = await withFetchRejecting("net::ERR_ABORTED", () =>+ invoke({+ cloudTranscriptionProvider: "mistral",+ cloudTranscriptionMode: "byok",+ transcriptionMode: "providers",+ })+ );+ assert.equal(result.success, false);+ assert.equal(result.messageKey, undefined);+ assert.equal(result.error, "net::ERR_ABORTED");+});++test("upload: a net::ERR_* failure from a BYOK provider is classified as unreachable", async () => {+ const result = await withFetchRejecting("net::ERR_NAME_NOT_RESOLVED", () =>+ invokeUpload({+ apiKey: "sk-openai",+ baseUrl: "https://api.openai.com/v1",+ model: "gpt-4o-mini-transcribe",+ provider: "openai",+ language: "",+ transcriptionMode: "providers",+ })+ );+ assert.equal(result.success, false);+ assert.equal(result.code, "PROVIDER_UNREACHABLE");+ assert.equal(result.messageParams.provider, "OpenAI");+ assert.equal(result.surface, "transcription");+ assert.equal(result.error, "Couldn't reach OpenAI. Check your connection.");+});++test("upload: an HTTP failure logs its status and a redacted body", async (t) => {+ const debugLogger = require("../../src/helpers/debugLogger");+ const warnings = [];+ t.mock.method(debugLogger, "warn", (message, meta) => warnings.push({ message, meta }));+ const originalFetchResponse = fetchResponse;+ t.after(() => {+ fetchResponse = originalFetchResponse;+ });+ const body = '{"error":{"message":"Incorrect API key provided: sk-proj-leakedKey12345"}}';+ fetchResponse = () => ({+ ok: false,+ status: 401,+ headers: new Headers(),+ text: async () => body,+ json: async () => JSON.parse(body),+ });++ const result = await invokeUpload({+ apiKey: "sk-openai",+ baseUrl: "https://api.openai.com/v1",+ model: "gpt-4o-mini-transcribe",+ provider: "openai",+ language: "",+ transcriptionMode: "providers",+ });++ assert.equal(result.code, "PROVIDER_AUTH_FAILED");+ const failure = warnings.find(({ message }) => message === "BYOK file transcription failed");+ assert.ok(failure, "the failure must be logged");+ assert.equal(failure.meta.status, 401);+ assert.match(failure.meta.body, /Incorrect API key provided/);+ assert.equal(failure.meta.body.includes("sk-proj-leakedKey12345"), false);+});diff --git a/test/helpers/tinfoilTranscription.test.js b/test/helpers/tinfoilTranscription.test.jsindex 2480dc51d..b41b3d130 100644--- a/test/helpers/tinfoilTranscription.test.js+++ b/test/helpers/tinfoilTranscription.test.js@@ -4,6 +4,7 @@ const Module = require("node:module");const transcriptionModulePath = require.resolve("../../src/helpers/tinfoilTranscription.js");const originalLoad = Module._load;+const warnings = [];function loadTranscription(fetchImpl) {delete require.cache[transcriptionModulePath];@@ -13,7 +14,12 @@ function loadTranscription(fetchImpl) {return { tinfoilSecureFetch: fetchImpl };}if (request === "./debugLogger") {- return { debug() {} };+ return {+ debug() {},+ warn(message, meta) {+ warnings.push({ message, meta });+ },+ };}return originalLoad.call(this, request, parent, isMain);};@@ -101,7 +107,7 @@ test("401 surfaces as INVALID_KEY", async () => {text: async () => "unauthorized",}));- await assert.rejects(() => transcribeWithTinfoil(AUDIO), { code: "INVALID_KEY" });+ await assert.rejects(() => transcribeWithTinfoil(AUDIO), { code: "PROVIDER_AUTH_FAILED" });});test("other failures carry the status and body", async () => {@@ -112,11 +118,11 @@ test("other failures carry the status and body", async () => {}));await assert.rejects(() => transcribeWithTinfoil(AUDIO), {- message: "Tinfoil API Error: 404 The model does not exist.",+ code: "PROVIDER_MODEL_NOT_FOUND",});});-test("429 surfaces as PROVIDER_RATE_LIMITED, 5xx as SERVER_ERROR", async () => {+test("429 surfaces as PROVIDER_RATE_LIMITED, 5xx as PROVIDER_UNAVAILABLE", async () => {const rateLimited = loadTranscription(async () => ({ok: false,status: 429,@@ -131,7 +137,9 @@ test("429 surfaces as PROVIDER_RATE_LIMITED, 5xx as SERVER_ERROR", async () => {status: 503,text: async () => "unavailable",}));- await assert.rejects(() => serverError.transcribeWithTinfoil(AUDIO), { code: "SERVER_ERROR" });+ await assert.rejects(() => serverError.transcribeWithTinfoil(AUDIO), {+ code: "PROVIDER_UNAVAILABLE",+ });});test("forwards the dictionary prompt, and omits it when blank", async () => {@@ -147,3 +155,20 @@ test("forwards the dictionary prompt, and omits it when blank", async () => {await transcribeWithTinfoil({ ...AUDIO, prompt: " " });assert.equal(form.get("prompt"), null);});++test("an HTTP failure logs its status and a redacted body", async () => {+ warnings.length = 0;+ const { transcribeWithTinfoil } = loadTranscription(async () => ({+ ok: false,+ status: 401,+ text: async () => '{"error":"Invalid API key: sk-leakedkey1234"}',+ }));++ await assert.rejects(() => transcribeWithTinfoil(AUDIO));++ const failure = warnings.find(({ message }) => message === "Tinfoil transcription failed");+ assert.ok(failure, "the failure must be logged");+ assert.equal(failure.meta.status, 401);+ assert.match(failure.meta.body, /Invalid API key/);+ assert.equal(failure.meta.body.includes("sk-leakedkey1234"), false);+});diff --git a/test/helpers/transcriptionFailureOutcome.test.js b/test/helpers/transcriptionFailureOutcome.test.jsnew file mode 100644index 000000000..581b260d4--- /dev/null+++ b/test/helpers/transcriptionFailureOutcome.test.js@@ -0,0 +1,30 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/helpers/transcriptionFailureOutcome.js");++test("a classified provider failure keeps its fields", async () => {+ const { transcriptionFailureOutcome } = await load();+ const error = Object.assign(new Error("Mistral rejected your API key."), {+ code: "PROVIDER_AUTH_FAILED",+ messageKey: "providerErrors.authFailed",+ messageParams: { provider: "Mistral" },+ settingsTarget: "speechToText",+ technicalDetails: { status: 401 },+ surface: "transcription",+ });+ const { report, keepAudio } = transcriptionFailureOutcome(error);+ assert.equal(keepAudio, true);+ assert.equal(report.code, "PROVIDER_AUTH_FAILED");+ assert.deepEqual(report.messageParams, { provider: "Mistral" });+ assert.equal(report.settingsTarget, "speechToText");+ assert.deepEqual(report.technicalDetails, { status: 401 });+ assert.equal(report.surface, "transcription");+});++test("an unclassified failure keeps today's description", async () => {+ const { transcriptionFailureOutcome } = await load();+ const { report } = transcriptionFailureOutcome(new Error("boom"));+ assert.equal(report.description, "Transcription failed: boom");+ assert.equal(report.title, "Transcription Error");+});diff --git a/test/services/cleanupOutputValidation.test.js b/test/services/cleanupOutputValidation.test.jsindex 2403e58fd..4e9200f5a 100644--- a/test/services/cleanupOutputValidation.test.js+++ b/test/services/cleanupOutputValidation.test.js@@ -142,6 +142,9 @@ test("cleanup validates completed provider output using the request's prompt setcompilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },}).outputText;const settingsModule = await vite.ssrLoadModule("/stores/settingsStore.ts");+ // The retry callback closes over this module-scope import (not a dynamic+ // `import()`), so it must be supplied as a global rather than via `require`.+ const { providerErrorToastProps } = await vite.ssrLoadModule("/utils/describeProviderError.ts");const toasts = [];let displayedRow;const retry = vm.runInNewContext(`${code}\nretry`, {@@ -165,6 +168,7 @@ test("cleanup validates completed provider output using the request's prompt set},toast: (value) => toasts.push(value),t: (key) => key,+ providerErrorToastProps,});await retry(row.id);assert.strictEqual(displayedRow, row);diff --git a/test/services/llmRequestDeadline.test.js b/test/services/llmRequestDeadline.test.jsindex b4b2c3147..b12cdef0e 100644--- a/test/services/llmRequestDeadline.test.js+++ b/test/services/llmRequestDeadline.test.js@@ -87,7 +87,9 @@ async function runDeadlineScenario(t, startRequest) {assert.equal(posts.length, 1, "a timed-out request must not be retried");assert.ok(outcome?.error, "the request should end in an error once the long deadline expires");- assert.match(outcome.error.message, /Request timed out after 600s/);+ // BYOK deadlines surface classified; the raw deadline rides along as the cause.+ assert.equal(outcome.error.code, "PROVIDER_TIMEOUT");+ assert.match(outcome.error.cause?.message ?? "", /Request timed out after 600s/);await request;}@@ -146,7 +148,8 @@ test("dictation cleanup keeps its 30-second deadline", async (t) => {await settle();await request;- assert.match(outcome?.error?.message ?? "", /Request timed out after 30s/);+ assert.equal(outcome?.error?.code, "PROVIDER_TIMEOUT");+ assert.match(outcome?.error?.cause?.message ?? "", /Request timed out after 30s/);});// The provider tests above prove each client honours the scope. This onediff --git a/test/services/openaiProviderErrorClassification.test.js b/test/services/openaiProviderErrorClassification.test.jsnew file mode 100644index 000000000..36fb35f0f--- /dev/null+++ b/test/services/openaiProviderErrorClassification.test.js@@ -0,0 +1,128 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/services/ai/inferenceProviders/openai.ts");++const providerContext = {+ getApiKey: async () => "test-key",+ getSystemPrompt: () => "Clean the transcript",+ getCustomDictionary: () => [],+ getPreferredLanguage: () => "en",+ getUiLanguage: () => "en",+ callChatCompletionsApi: async () => {+ throw new Error("Unexpected chat completions delegation");+ },+ calculateMaxTokens: () => 4096,+};++function jsonResponse(body, status = 200) {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json", "x-request-id": "req_classify_1" },+ });+}++test("a single-candidate custom /responses endpoint's 429 insufficient_quota survives as PROVIDER_QUOTA_EXHAUSTED with its requestId", async (t) => {+ const originalFetch = globalThis.fetch;+ t.after(() => {+ globalThis.fetch = originalFetch;+ });+ // Ending the base in "/responses" makes getEndpointCandidates return a+ // single candidate, so detectServerType's own "already a full endpoint"+ // check skips the GET /models probe entirely — one POST is all that fires.+ globalThis.fetch = async () =>+ jsonResponse(+ {+ error: {+ message: "You exceeded your current quota, please check your plan and billing details.",+ type: "insufficient_quota",+ },+ },+ 429+ );++ const { openaiProvider } = await load();+ await assert.rejects(+ openaiProvider.call({+ text: "raw transcript",+ model: "cleanup-model",+ agentName: null,+ config: {+ provider: "custom",+ baseUrl: "https://single-candidate.example/v1/responses",+ customApiKey: "test-key",+ },+ ctx: providerContext,+ }),+ (error) => {+ // Before the fix, the already-classified error was rebuilt from its own+ // English message, which doesn't contain the quota signal text and so+ // reclassified a 429 as a generic rate limit — dropping the requestId.+ assert.equal(error.code, "PROVIDER_QUOTA_EXHAUSTED");+ assert.equal(error.messageKey, "providerErrors.selfHosted.quotaExhausted");+ assert.equal(error.technicalDetails.requestId, "req_classify_1");+ return true;+ }+ );+});++test("OpenRouter is classified by its own name, never as self-hosted", async (t) => {+ const originalFetch = globalThis.fetch;+ t.after(() => {+ globalThis.fetch = originalFetch;+ });+ globalThis.fetch = async () =>+ jsonResponse({ error: { message: "The model `nope/nope` does not exist" } }, 404);++ const { openaiProvider } = await load();+ await assert.rejects(+ openaiProvider.call({+ text: "raw transcript",+ model: "nope/nope",+ agentName: null,+ config: { provider: "openrouter" },+ ctx: providerContext,+ }),+ (error) => {+ assert.equal(error.code, "PROVIDER_MODEL_NOT_FOUND");+ assert.equal(error.technicalDetails.provider, "OpenRouter");+ assert.doesNotMatch(error.messageKey, /selfHosted/);+ assert.match(error.message, /^OpenRouter /);+ return true;+ }+ );+});++test("a custom endpoint's error is classified self-hosted", async (t) => {+ const originalFetch = globalThis.fetch;+ t.after(() => {+ globalThis.fetch = originalFetch;+ });+ globalThis.fetch = async (_input, init = {}) => {+ const method = init.method || "GET";+ if (method === "GET") return jsonResponse({}, 404); // model discovery probe+ return jsonResponse({ error: { message: "Incorrect API key provided" } }, 401);+ };++ const { openaiProvider } = await load();+ await assert.rejects(+ openaiProvider.call({+ text: "raw transcript",+ model: "cleanup-model",+ agentName: null,+ config: {+ provider: "custom",+ baseUrl: "https://my-own-server.example/v1",+ customApiKey: "test-key",+ },+ ctx: providerContext,+ }),+ (error) => {+ assert.equal(error.code, "PROVIDER_AUTH_FAILED");+ assert.equal(error.messageKey, "providerErrors.selfHosted.authFailed");+ assert.equal(error.technicalDetails.provider, "Your server");+ assert.match(error.message, /^Your server /);+ return true;+ }+ );+});diff --git a/test/services/reasoningServiceEnforcement.test.js b/test/services/reasoningServiceEnforcement.test.jsindex 07fae0a67..f3ee18e19 100644--- a/test/services/reasoningServiceEnforcement.test.js+++ b/test/services/reasoningServiceEnforcement.test.js@@ -52,6 +52,16 @@ test("ReasoningService entry points enforce the org policy", async (t) => {});};+ // A custom endpoint's 400 body ("expected test stop") now classifies as a+ // provider bad-request error; its original text survives on+ // technicalDetails.underlyingError rather than as the top-level message.+ const rejectsExpectedTestStop = (promise) =>+ assert.rejects(promise, (err) => {+ assert.equal(err.code, "PROVIDER_BAD_REQUEST");+ assert.match(err.technicalDetails?.underlyingError ?? "", /expected test stop/);+ return true;+ });+await t.test("processText rejects a BYOK provider outside the allowlist", async () => {setPolicy({ llmModes: ["providers"], llmByokProviders: ["anthropic"] });await assert.rejects(@@ -203,13 +213,12 @@ test("ReasoningService entry points enforce the org policy", async (t) => {};try {- await assert.rejects(+ await rejectsExpectedTestStop(reasoningService.processText("hi", "other-model", null, {provider: "custom",baseUrl: "https://other-scope.example.com/v1",inferenceScope: "chatIntelligence",- }),- { message: "expected test stop" }+ }));assert.ok(requests.length > 0);for (const request of requests) {@@ -223,12 +232,11 @@ test("ReasoningService entry points enforce the org policy", async (t) => {// The cleanup endpoint itself still gets the shared key.requests.length = 0;- await assert.rejects(+ await rejectsExpectedTestStop(reasoningService.processText("hi", "cleanup-model", null, {provider: "custom",baseUrl: "https://cleanup.example.com/v1",- }),- { message: "expected test stop" }+ }));assert.ok(requests.some((request) => request.auth === "Bearer cleanup-secret"));} finally {@@ -256,9 +264,7 @@ test("ReasoningService entry points enforce the org policy", async (t) => {};try {- await assert.rejects(reasoningService.processText("hi", "custom-model"), {- message: "expected test stop",- });+ await rejectsExpectedTestStop(reasoningService.processText("hi", "custom-model"));assert.ok(requestedUrls.length > 0);assert.ok(requestedUrls.every((url) => url.startsWith("https://custom.example.com/v1/")));} finally {@@ -289,9 +295,8 @@ test("ReasoningService entry points enforce the org policy", async (t) => {};try {- await assert.rejects(- reasoningService.processText("hi", "llama-3.3-70b-versatile"),- { message: "expected test stop" }+ await rejectsExpectedTestStop(+ reasoningService.processText("hi", "llama-3.3-70b-versatile"));assert.ok(requestedUrls.length > 0);assert.ok(requestedUrls.every((url) => url.startsWith("https://api.openai.com/")));diff --git a/test/services/reasoningServiceErrorLogging.test.js b/test/services/reasoningServiceErrorLogging.test.jsnew file mode 100644index 000000000..da67d2d34--- /dev/null+++ b/test/services/reasoningServiceErrorLogging.test.js@@ -0,0 +1,172 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++async function loadReasoningService(t, cachePrefix, electronAPI = {}) {+ installBrowserGlobals(t, { window: { electronAPI } });+ const vite = await createRendererServer(t, { cachePrefix });+ const reasoningService = (await vite.ssrLoadModule("/services/ReasoningService.ts")).default;+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");+ usePolicyStore.setState({ status: "unmanaged", appVersion: "1.10.0", policy: null });+ const { default: logger } = await vite.ssrLoadModule("/utils/logger.ts");+ t.after(() => reasoningService.destroy());+ return { reasoningService, logger };+}++// callChatCompletionsApi (LAN/Groq/Corti) logged the server's error body as+// `errorMessage`. Some self-hosted servers nest a code/type object with no+// .message field, and stringifying an object directly prints the useless+// "[object Object]" rather than anything that helps debug the failure.+test("a nested error object with no .message logs its content, not [object Object]", async (t) => {+ const { reasoningService, logger } = await loadReasoningService(+ t,+ "openwhispr-error-logging-test-"+ );+ const logs = [];+ t.mock.method(logger, "logReasoning", (event, data) => logs.push({ event, data }));++ const originalFetch = globalThis.fetch;+ t.after(() => {+ globalThis.fetch = originalFetch;+ });+ globalThis.fetch = async () =>+ new Response(JSON.stringify({ error: { code: "invalid_request", type: "no_message_here" } }), {+ status: 400,+ headers: { "Content-Type": "application/json" },+ });++ await assert.rejects(+ reasoningService.processText("clean this up", "some-model", null, {+ lanUrl: "http://127.0.0.1:11434/v1",+ })+ );++ const detail = logs.find(({ event }) => event === "LAN_API_ERROR_DETAIL");+ assert.ok(detail, "LAN_API_ERROR_DETAIL must be logged");+ assert.equal(detail.data.errorMessage.includes("[object Object]"), false);+ assert.match(detail.data.errorMessage, /invalid_request/);+ assert.match(detail.data.errorMessage, /no_message_here/);+});++test("an error.message string still logs as-is", async (t) => {+ const { reasoningService, logger } = await loadReasoningService(+ t,+ "openwhispr-error-logging-message-test-"+ );+ const logs = [];+ t.mock.method(logger, "logReasoning", (event, data) => logs.push({ event, data }));++ const originalFetch = globalThis.fetch;+ t.after(() => {+ globalThis.fetch = originalFetch;+ });+ globalThis.fetch = async () =>+ new Response(JSON.stringify({ error: { message: "Incorrect API key provided" } }), {+ status: 401,+ headers: { "Content-Type": "application/json" },+ });++ await assert.rejects(+ reasoningService.processText("clean this up", "some-model", null, {+ lanUrl: "http://127.0.0.1:11434/v1",+ })+ );++ const detail = logs.find(({ event }) => event === "LAN_API_ERROR_DETAIL");+ assert.equal(detail.data.errorMessage, "Incorrect API key provided");+});++const LEAKED_KEY = "sk-proj-leakedKey12345";+const keyEchoResponse = () =>+ new Response(+ JSON.stringify({ error: { message: `Incorrect API key provided: ${LEAKED_KEY}` } }),+ { status: 401, headers: { "Content-Type": "application/json" } }+ );++function mockFetch(t, respond) {+ const originalFetch = globalThis.fetch;+ t.after(() => {+ globalThis.fetch = originalFetch;+ });+ globalThis.fetch = async () => respond();+}++test("a provider body that echoes the key is redacted in every API_ERROR_DETAIL field", async (t) => {+ const { reasoningService, logger } = await loadReasoningService(+ t,+ "openwhispr-error-logging-redact-test-"+ );+ const logs = [];+ t.mock.method(logger, "logReasoning", (event, data) => logs.push({ event, data }));+ mockFetch(t, keyEchoResponse);++ await assert.rejects(+ reasoningService.processText("clean this up", "some-model", null, {+ lanUrl: "http://127.0.0.1:11434/v1",+ })+ );++ const detail = logs.find(({ event }) => event === "LAN_API_ERROR_DETAIL");+ assert.equal(detail.data.status, 401);+ assert.match(detail.data.errorMessage, /Incorrect API key provided/);+ assert.equal(JSON.stringify(detail.data).includes(LEAKED_KEY), false);+});++test("a self-hosted chat stream failure logs a redacted body", async (t) => {+ const { reasoningService, logger } = await loadReasoningService(+ t,+ "openwhispr-error-logging-stream-test-"+ );+ const logs = [];+ t.mock.method(logger, "logReasoning", (event, data) => logs.push({ event, data }));+ mockFetch(t, keyEchoResponse);++ await assert.rejects(async () => {+ for await (const _chunk of reasoningService.processTextStreaming(+ [{ role: "user", content: "hi" }],+ "some-model",+ "lan",+ { systemPrompt: "be brief", lanUrl: "http://127.0.0.1:11434/v1" }+ )) {+ // drain+ }+ });++ const streamError = logs.find(({ event }) => event === "AGENT_STREAM_ERROR");+ assert.equal(streamError.data.status, 401);+ assert.match(streamError.data.body, /Incorrect API key provided/);+ assert.equal(streamError.data.body.includes(LEAKED_KEY), false);+});++test("a BYOK AI SDK stream failure logs its status and a redacted body", async (t) => {+ const { reasoningService, logger } = await loadReasoningService(+ t,+ "openwhispr-error-logging-sdk-stream-test-",+ { getOpenAIKey: async () => "sk-test" }+ );+ const warnings = [];+ t.mock.method(logger, "warn", (message, meta) => warnings.push({ message, meta }));+ mockFetch(t, keyEchoResponse);++ const error = await (async () => {+ for await (const _chunk of reasoningService.processTextStreamingAI(+ [{ role: "user", content: "hi" }],+ "gpt-5-mini",+ "openai",+ { systemPrompt: "be brief" }+ )) {+ // drain+ }+ })().then(+ () => assert.fail("expected the stream to fail"),+ (err) => err+ );++ assert.equal(error.code, "PROVIDER_AUTH_FAILED");+ const failure = warnings.find(({ message }) => message === "BYOK chat stream failed");+ assert.ok(failure, "the failure must be logged");+ assert.equal(failure.meta.status, 401);+ assert.match(failure.meta.body, /Incorrect API key provided/);+ assert.equal(failure.meta.body.includes(LEAKED_KEY), false);+});diff --git a/test/services/reasoningServiceProviderErrors.test.js b/test/services/reasoningServiceProviderErrors.test.jsnew file mode 100644index 000000000..76adae49e--- /dev/null+++ b/test/services/reasoningServiceProviderErrors.test.js@@ -0,0 +1,138 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++async function loadReasoningService(t, cachePrefix) {+ installBrowserGlobals(t, {+ window: {+ electronAPI: { getOpenAIKey: async () => "sk-test", getGeminiKey: async () => "AIza-test" },+ },+ });+ const vite = await createRendererServer(t, { cachePrefix });+ const reasoningService = (await vite.ssrLoadModule("/services/ReasoningService.ts")).default;+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");+ usePolicyStore.setState({ status: "unmanaged", appVersion: "1.10.0", policy: null });+ t.after(() => reasoningService.destroy());+ return reasoningService;+}++function mockFetch(t, behavior) {+ const calls = [];+ const originalFetch = globalThis.fetch;+ t.after(() => {+ globalThis.fetch = originalFetch;+ });+ globalThis.fetch = async (...args) => {+ calls.push(args);+ return behavior(...args);+ };+ return calls;+}++// LAN cleanup goes through callChatCompletionsApi, the path shared with Groq and Corti.+const runLanCleanup = (reasoningService) =>+ reasoningService.processText("clean this up", "some-model", null, {+ lanUrl: "http://127.0.0.1:11434/v1",+ });++test("a BYOK request that hits its client-side deadline surfaces as PROVIDER_TIMEOUT after one attempt", async (t) => {+ const reasoningService = await loadReasoningService(t, "openwhispr-provider-timeout-test-");+ // What fetch rejects with once the request's AbortController fires.+ const calls = mockFetch(t, async () => {+ throw new DOMException("The operation was aborted.", "AbortError");+ });++ const error = await runLanCleanup(reasoningService).then(+ () => assert.fail("expected a timeout"),+ (err) => err+ );++ assert.equal(calls.length, 1, "a deadline is never retried");+ assert.equal(error.code, "PROVIDER_TIMEOUT");+ assert.equal(error.messageKey, "providerErrors.selfHosted.timeout");+ assert.equal(error.surface, "llm");+ assert.doesNotMatch(error.message, /timed out after/);+});++test("a stopped self-hosted server surfaces as PROVIDER_NO_RESPONSE, still retried", async (t) => {+ const reasoningService = await loadReasoningService(t, "openwhispr-provider-unreachable-test-");+ const calls = mockFetch(t, async () => {+ throw new TypeError("Failed to fetch");+ });+ // Skip withRetry's real backoff delays.+ t.mock.timers.enable({ apis: ["setTimeout"] });++ let settled = false;+ const outcome = runLanCleanup(reasoningService).then(+ () => assert.fail("expected a network failure"),+ (err) => err+ );+ outcome.finally(() => {+ settled = true;+ });+ for (let i = 0; i < 100 && !settled; i++) {+ await new Promise((resolve) => setImmediate(resolve));+ t.mock.timers.tick(10_000);+ }+ const error = await outcome;++ assert.equal(calls.length, 4, "a network failure keeps its retries");+ assert.equal(error.code, "PROVIDER_NO_RESPONSE");+ assert.equal(error.messageKey, "providerErrors.selfHosted.noResponse");+ assert.equal(error.surface, "llm");+});++test("a stopped LAN server on a chat without tools is classified, not a raw fetch error", async (t) => {+ const reasoningService = await loadReasoningService(t, "openwhispr-lan-stream-fetch-test-");+ mockFetch(t, async () => {+ throw new TypeError("Failed to fetch");+ });++ const error = await (async () => {+ for await (const _chunk of reasoningService.processTextStreamingAI(+ [{ role: "user", content: "hi" }],+ "some-model",+ "lan",+ { systemPrompt: "be brief", lanUrl: "http://127.0.0.1:11434/v1" }+ )) {+ // drain+ }+ })().then(+ () => assert.fail("expected the stream to fail"),+ (err) => err+ );++ assert.equal(error.code, "PROVIDER_NO_RESPONSE");+ assert.equal(error.messageKey, "providerErrors.selfHosted.noResponse");+ assert.equal(error.surface, "llm");+});++for (const { provider, model, displayName } of [+ { provider: "openai", model: "gpt-5-mini", displayName: "OpenAI" },+ { provider: "gemini", model: "gemini-3.5-flash", displayName: "Gemini" },+]) {+ test(`a ${displayName} cleanup that hits its deadline surfaces as PROVIDER_TIMEOUT after one attempt`, async (t) => {+ const reasoningService = await loadReasoningService(+ t,+ `openwhispr-provider-timeout-${provider}-test-`+ );+ const calls = mockFetch(t, async () => {+ throw new DOMException("The operation was aborted.", "AbortError");+ });++ const error = await reasoningService+ .processText("clean this up", model, null, { provider })+ .then(+ () => assert.fail("expected a timeout"),+ (err) => err+ );++ // OpenAI's base is probed once with a GET /models before the request.+ const attempts = calls.filter(([, init]) => init?.method === "POST");+ assert.equal(attempts.length, 1, "a deadline is never retried");+ assert.equal(error.code, "PROVIDER_TIMEOUT");+ assert.equal(error.messageParams.provider, displayName);+ assert.equal(error.surface, "llm");+ });+}diff --git a/test/services/reasoningServiceStreamingThink.test.js b/test/services/reasoningServiceStreamingThink.test.jsindex b12a71254..a01c0be76 100644--- a/test/services/reasoningServiceStreamingThink.test.js+++ b/test/services/reasoningServiceStreamingThink.test.js@@ -470,7 +470,12 @@ test("a timeout-owned abort during raw response reading remains a timeout error"undefined);- await assert.rejects(collectAgentText(stream), /Streaming request timed out/);+ // A LAN/self-hosted timeout is now classified instead of the generic message.+ await assert.rejects(collectAgentText(stream), (err) => {+ assert.equal(err.code, "PROVIDER_TIMEOUT");+ assert.equal(err.messageKey, "providerErrors.selfHosted.timeout");+ return true;+ });});// Was "does not flush buffered text after error" and asserted the stream@@ -822,5 +827,53 @@ test("a provider error part rejects the agent stream instead of ending it silentregistry.toAISDKFormat());- await assert.rejects(collectAgentText(stream), /Incorrect API key/);+ // The AI SDK error part is now classified; the provider's original message+ // survives on the preserved cause rather than as the top-level message.+ await assert.rejects(collectAgentText(stream), (err) => {+ assert.equal(err.code, "PROVIDER_AUTH_FAILED");+ assert.match(err.cause?.message ?? "", /Incorrect API key/);+ return true;+ });+});++// A "custom" BYOK endpoint (config.baseUrl) is a user's own server just like+// LAN (config.lanUrl), but it takes a different route.kind ("provider", not+// "self-hosted"), so the mode check alone would miss it and report "OpenAI"+// (getProviderDisplayName("custom") has no registry entry to fall back on).+test("a custom BYOK endpoint's provider error part is classified self-hosted, not OpenAI", async (t) => {+ const { reasoningService } = await loadReasoningService(+ t,+ "openwhispr-stream-custom-selfhosted-test-"+ );++ const originalFetch = globalThis.fetch;+ t.after(() => {+ globalThis.fetch = originalFetch;+ });+ globalThis.fetch = async () =>+ new Response(+ JSON.stringify({ error: { message: "Incorrect API key provided", type: "invalid_request_error" } }),+ { status: 401, headers: { "content-type": "application/json" } }+ );++ const stream = reasoningService.processTextStreamingAI(+ [{ role: "user", content: "hello" }],+ "cleanup-model",+ "custom",+ {+ systemPrompt: "Answer the user.",+ baseUrl: "http://127.0.0.1:11434/v1",+ customApiKey: "test-key",+ disableThinking: true,+ },+ undefined+ );++ await assert.rejects(collectAgentText(stream), (err) => {+ assert.equal(err.code, "PROVIDER_AUTH_FAILED");+ assert.equal(err.messageKey, "providerErrors.selfHosted.authFailed");+ assert.equal(err.technicalDetails.provider, "Your server");+ assert.match(err.message, /^Your server /);+ return true;+ });});diff --git a/test/utils/describeProviderError.test.js b/test/utils/describeProviderError.test.jsnew file mode 100644index 000000000..6d96f3b41--- /dev/null+++ b/test/utils/describeProviderError.test.js@@ -0,0 +1,151 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/utils/describeProviderError.ts");++// A fake t that renders "key|json(params)" so the test sees exactly what was asked.+const t = (key, params) => (params ? `${key}|${JSON.stringify(params)}` : key);++test("a keyed error is translated with its params", async () => {+ const { describeProviderError } = await load();+ const out = describeProviderError(+ {+ message: "Mistral rejected your API key.",+ messageKey: "providerErrors.authFailed",+ messageParams: { provider: "Mistral" },+ settingsTarget: "speechToText",+ technicalDetails: { provider: "Mistral", status: 401 },+ },+ t+ );+ assert.equal(out.description, 'providerErrors.authFailed|{"provider":"Mistral"}');+ assert.equal(out.settingsTarget, "speechToText");+ assert.deepEqual(out.technicalDetails, { provider: "Mistral", status: 401 });+});++test("a self-hosted key is translated as is: its sentence names the server itself", async () => {+ const { describeProviderError } = await load();+ const out = describeProviderError(+ { messageKey: "providerErrors.selfHosted.unknown", messageParams: { provider: "Your server" } },+ t+ );+ assert.equal(out.description, 'providerErrors.selfHosted.unknown|{"provider":"Your server"}');+});++test("an unkeyed error renders its message unchanged and offers no settings link", async () => {+ const { describeProviderError } = await load();+ assert.deepEqual(describeProviderError(new Error("boom"), t), { description: "boom" });+ assert.deepEqual(describeProviderError("plain text", t), { description: "plain text" });+ assert.deepEqual(describeProviderError({ settingsTarget: "account", message: "x" }, t), {+ description: "x",+ });+});++test("formatProviderErrorDetails labels provider details generically", async () => {+ const { formatProviderErrorDetails } = await load();+ assert.equal(+ formatProviderErrorDetails(+ { provider: "Mistral", status: 401, requestId: "r1", underlyingError: '{"detail":"Invalid API Key"}' },+ t+ ),+ [+ "providerErrors.details.provider: Mistral",+ "reasoning.enterprise.technicalDetails.httpStatus: 401",+ "providerErrors.details.requestId: r1",+ 'reasoning.enterprise.technicalDetails.underlyingError: {"detail":"Invalid API Key"}',+ ].join("\n")+ );+});++test("formatProviderErrorDetails names a self-hosted server in the UI language", async () => {+ const { formatProviderErrorDetails } = await load();+ assert.equal(+ formatProviderErrorDetails({ provider: "Your server", status: 404 }, t),+ [+ "providerErrors.details.provider: settingsPage.aiModels.modes.selfHosted",+ "reasoning.enterprise.technicalDetails.httpStatus: 404",+ ].join("\n")+ );+});++test("formatProviderErrorDetails keeps AWS labels for Bedrock details", async () => {+ const { formatProviderErrorDetails } = await load();+ assert.equal(+ formatProviderErrorDetails({ exceptionType: "ThrottlingException", requestId: "aws-1" }, t),+ [+ "reasoning.enterprise.technicalDetails.awsException: ThrottlingException",+ "reasoning.enterprise.technicalDetails.awsRequestId: aws-1",+ ].join("\n")+ );+});++function withClipboard(ctx, writeClipboard) {+ const original = globalThis.window;+ globalThis.window = { electronAPI: { writeClipboard } };+ ctx.after(() => {+ globalThis.window = original;+ });+}++test("a fixable classified error gets Open Settings, then an icon-only Copy details that copies the details", async (ctx) => {+ const { providerErrorActions } = await load();+ const written = [];+ withClipboard(ctx, async (text) => {+ written.push(text);+ return { success: true };+ });+ const actions = providerErrorActions(+ { settingsTarget: "llms", technicalDetails: { provider: "OpenAI", status: 401 } },+ t+ );+ assert.deepEqual(+ actions.map(({ label, icon, iconOnly }) => ({ label, icon, iconOnly })),+ [+ { label: "providerErrors.openSettings", icon: "settings", iconOnly: undefined },+ { label: "providerErrors.copyDetails", icon: "copy", iconOnly: true },+ ]+ );+ assert.equal(actions[1].dismissOnClick, false);+ assert.equal(await actions[1].onClick(), true);+ assert.match(written[0], /providerErrors\.details\.provider: OpenAI/);+});++test("Copy details on a superseded card neither copies nor reports a result", async (ctx) => {+ const { providerErrorActions } = await load();+ let current = true;+ let writes = 0;+ withClipboard(ctx, async () => {+ writes += 1;+ current = false;+ return { success: true };+ });+ const [copy] = providerErrorActions(+ { technicalDetails: { provider: "Groq", status: 429 } },+ t,+ () => current+ );+ assert.equal(await copy.onClick(), undefined, "a click that outlived its card reports nothing");+ assert.equal(await copy.onClick(), undefined);+ assert.equal(writes, 1, "a click after the card was replaced never writes");+});++test("toast props: a classified error gets actions, an unclassified one stays a plain message", async () => {+ const { providerErrorToastProps } = await load();+ const classified = providerErrorToastProps(+ {+ messageKey: "providerErrors.rateLimited",+ messageParams: { provider: "Groq" },+ technicalDetails: { provider: "Groq", status: 429 },+ },+ t+ );+ assert.equal(classified.description, 'providerErrors.rateLimited|{"provider":"Groq"}');+ assert.deepEqual(+ classified.actions.map((action) => action.label),+ ["providerErrors.copyDetails"],+ "a rate limit has nothing to fix in Settings"+ );+ assert.deepEqual(providerErrorToastProps(new Error("Network down"), t), {+ description: "Network down",+ });+});diff --git a/test/utils/recordingErrors.test.js b/test/utils/recordingErrors.test.jsnew file mode 100644index 000000000..6c234d0f9--- /dev/null+++ b/test/utils/recordingErrors.test.js@@ -0,0 +1,34 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/utils/recordingErrors.ts");+const t = (key, params) => (params ? `${key}|${JSON.stringify(params)}` : key);++test("a classified provider failure gets the surface title and translated description", async () => {+ const { getRecordingErrorTitle, getRecordingErrorDescription } = await load();+ const report = {+ title: "Transcription Error",+ description: "Mistral rejected your API key.",+ code: "PROVIDER_AUTH_FAILED",+ surface: "transcription",+ messageKey: "providerErrors.authFailed",+ messageParams: { provider: "Mistral" },+ };+ assert.equal(getRecordingErrorTitle(report, t), "providerErrors.titles.transcription");+ assert.equal(getRecordingErrorDescription(report, t), 'providerErrors.authFailed|{"provider":"Mistral"}');+});++test("the rate-limit title is unchanged", async () => {+ const { getRecordingErrorTitle } = await load();+ assert.equal(+ getRecordingErrorTitle({ title: "x", code: "PROVIDER_RATE_LIMITED" }, t),+ "hooks.audioRecording.errorTitles.providerRateLimited"+ );+});++test("unclassified reports keep their own title and description", async () => {+ const { getRecordingErrorTitle, getRecordingErrorDescription } = await load();+ const report = { title: "Transcription Error", description: "Transcription failed: boom" };+ assert.equal(getRecordingErrorTitle(report, t), "Transcription Error");+ assert.equal(getRecordingErrorDescription(report, t), "Transcription failed: boom");+});