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(onboarding): check provider credentials automatically (#2652)
Joshua8d47617a85b0
diff --git a/docs/network-allowlist.md b/docs/network-allowlist.mdindex 97589cf30..f394379a7 100644--- a/docs/network-allowlist.md+++ b/docs/network-allowlist.md@@ -90,10 +90,10 @@ provider. Skip any provider not in use.| `api.groq.com` | HTTPS | 443 | Groq API key configured. || `atc.tinfoil.sh`, `*.tinfoil.sh` | WSS, HTTPS | 443 | Tinfoil API key configured. `atc.tinfoil.sh` serves the enclave attestation bundle (verified locally against an embedded sigstore root). Inference and realtime transcription connect to an enclave host assigned dynamically at runtime (e.g. `inference.tinfoil.sh`, `router.infN.tinfoil.sh`), so allowlist `*.tinfoil.sh` rather than pinning hosts. || `api.mistral.ai` | HTTPS | 443 | Mistral API key configured. |-| `api.deepgram.com` | WSS, HTTPS | 443 | Deepgram API key configured. Realtime-only: dictation and note recording open a WSS session (there is no file-upload or retry path); the Settings connection test calls `/v1/models` over HTTPS. |+| `api.deepgram.com` | WSS, HTTPS | 443 | Deepgram API key configured. Realtime-only: dictation and note recording open a WSS session (there is no file-upload or retry path); the key check calls `/v1/auth/token` over HTTPS. || `streaming.assemblyai.com` | WSS, HTTPS | 443 | AssemblyAI API key configured. `/v3/token` mints the short-lived session token over HTTPS; the live session is WSS. Realtime-only, like Deepgram. |-| `api.assemblyai.com` | HTTPS | 443 | AssemblyAI API key configured. Credential check when the key is tested in Settings (`/v2/transcript`). |-| `openrouter.ai` | HTTPS | 443 | OpenRouter selected as a reasoning provider (`/api/v1/models` is fetched even without a key). |+| `api.assemblyai.com` | HTTPS | 443 | AssemblyAI API key configured. Credential check when onboarding or Settings checks the key (`/v2/transcript`). |+| `openrouter.ai` | HTTPS | 443 | OpenRouter selected as a reasoning provider (`/api/v1/models` is fetched even without a key; the key check calls `/api/v1/key`). |## Notesdiff --git a/src/components/OpenAICompatiblePanel.tsx b/src/components/OpenAICompatiblePanel.tsxindex 1694e2833..6f6392108 100644--- a/src/components/OpenAICompatiblePanel.tsx+++ b/src/components/OpenAICompatiblePanel.tsx@@ -1,13 +1,26 @@-import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+ type FocusEvent,+ type ReactNode,+} from "react";import { useTranslation } from "react-i18next";import { Button } from "./ui/button";-import { Input } from "./ui/input";-import ApiKeyInput from "./ui/ApiKeyInput";import ModelCardList from "./ui/ModelCardList";import SearchableModelList, { MODEL_SEARCH_THRESHOLD } from "./ui/SearchableModelList";import { buildApiUrl, getModelListBaseCandidates, normalizeBaseUrl } from "../config/constants";import { isSecureHttpEndpoint } from "../utils/urlUtils";import { GetApiKeyLink } from "./ui/GetApiKeyLink";+import { ConnectionCheckAnnouncer } from "./ui/ConnectionCheckAnnouncer";+import { ProviderCheckField } from "./ui/ProviderCheckField";+import { usePanelVisible } from "./ui/usePanelVisible";+import { isWindowSwitchBlur, useFocusHold } from "../hooks/useFocusHold";+import { useConnectionAutoCheck } from "../hooks/useConnectionAutoCheck";+import { useCredentialDraft } from "../hooks/useCredentialDraft";+import { useTypingPause } from "../hooks/useTypingPause";interface ModelOption {value: string;@@ -31,12 +44,14 @@ interface OpenAICompatiblePanelProps {// Providers whose /models is public but whose inference needs a key.apiKeyRequired?: boolean;getKeyUrl?: string;+ // The connection the panel checks: the user's own server, or OpenRouter.+ provider?: "custom" | "openrouter";}export default function OpenAICompatiblePanel({baseUrl,setBaseUrl,- apiKey,+ apiKey: savedApiKey,setApiKey,model,setModel,@@ -46,6 +61,7 @@ export default function OpenAICompatiblePanel({lockedBaseUrl = false,apiKeyRequired = false,getKeyUrl,+ provider = "custom",}: OpenAICompatiblePanelProps) {const { t } = useTranslation();const [draftBase, setDraftBase] = useState(baseUrl);@@ -54,8 +70,20 @@ export default function OpenAICompatiblePanel({const [modelsError, setModelsError] = useState<string | null>(null);const isMountedRef = useRef(true);const lastLoadedBaseRef = useRef<string | null>(null);+ // The trimmed key the last list load was sent with.+ const lastLoadedKeyRef = useRef<string | null>(null);const pendingBaseRef = useRef<string | null>(null);const latestBaseRef = useRef<string>(normalizeBaseUrl(baseUrl));+ const keyDraft = useCredentialDraft();+ const apiKey = keyDraft.value("apiKey", savedApiKey);+ // The list reads the key and the address setter through refs, so neither a key change nor+ // a parent's new setter on each render reloads it.+ const apiKeyRef = useRef(apiKey);+ const setBaseUrlRef = useRef(setBaseUrl);+ useEffect(() => {+ apiKeyRef.current = apiKey;+ setBaseUrlRef.current = setBaseUrl;+ }, [apiKey, setBaseUrl]);useEffect(() => {isMountedRef.current = true;@@ -69,6 +97,37 @@ export default function OpenAICompatiblePanel({}, [baseUrl]);const normalizedBase = useMemo(() => normalizeBaseUrl(baseUrl), [baseUrl]);+ const visible = usePanelVisible();+ const editing = useFocusHold();+ // An address with no http:// or https:// is left to the model list, which says so.+ const checkReady =+ provider === "openrouter" ? Boolean(apiKey.trim()) : normalizedBase.includes("://");+ // The address applies when its field is left, so it is never half-typed here.+ const delayMs = useTypingPause({+ typed: apiKey,+ context: JSON.stringify([provider, normalizedBase, model, visible]),+ held: editing.held,+ });+ const check = useConnectionAutoCheck({+ // The model is this panel's own (or "" under a tab that is only browsed), so a saved model+ // the server no longer lists fails as modelNotFound.+ config: { scope: "reasoning", provider, baseUrl: normalizedBase, apiKey, model },+ // A hidden panel is not ready to ask; a shown one asks again, and the main process answers+ // a check it remembers at once.+ ready: checkReady && visible,+ delayMs,+ });+ const followKeyDraft = keyDraft.follow;+ const refused = check.failure?.errorCode === "credentialsRejected";+ useEffect(() => {+ followKeyDraft({+ phase: check.phase,+ checked: { apiKey },+ // Someone's own server may refuse a key for other reasons, so only OpenRouter's refusal+ // holds a key back.+ refused: refused && provider === "openrouter",+ });+ }, [check.phase, apiKey, refused, provider, followKeyDraft]);useEffect(() => {latestBaseRef.current = normalizedBase;@@ -78,6 +137,14 @@ export default function OpenAICompatiblePanel({const trimmedDraft = draftBase.trim();const hasSavedBase = Boolean((baseUrl || "").trim());const isDraftDirty = trimmedDraft !== (baseUrl || "").trim();+ // The status describes the applied address, so it waits while another one is typed.+ const endpointCheck = isDraftDirty ? { ...check, phase: "idle" as const, failure: null } : check;+ const failureReason =+ !apiKey.trim() && refused ? t("reasoning.custom.endpointUnauthorized") : undefined;+ // While the check covers the address, its reason under the field replaces the list's line.+ const listErrorShown =+ Boolean(modelsError) && (lockedBaseUrl || !checkReady || check.phase === "connected");+ const keyLabel = t(apiKeyRequired ? "common.apiKey" : "reasoning.custom.apiKeyOptional");const loadRemoteModels = useCallback(async (baseOverride?: string, force = false) => {@@ -109,8 +176,9 @@ export default function OpenAICompatiblePanel({setModelsError(null);}- const trimmedKey = apiKey?.trim();- const effectiveKey = trimmedKey && trimmedKey.length > 0 ? trimmedKey : undefined;+ const trimmedKey = apiKeyRef.current.trim();+ const effectiveKey = trimmedKey.length > 0 ? trimmedKey : undefined;+ lastLoadedKeyRef.current = effectiveKey ?? "";let activeBase = normalized;try {@@ -199,7 +267,7 @@ export default function OpenAICompatiblePanel({activeBase = resolvedBase;latestBaseRef.current = resolvedBase;setDraftBase(resolvedBase);- setBaseUrl(resolvedBase);+ setBaseUrlRef.current(resolvedBase);}setModelOptions(mapped);// `/models` is a discovery aid, not an allowlist — keep the user's@@ -229,7 +297,7 @@ export default function OpenAICompatiblePanel({}}},- [baseUrl, apiKey, lockedBaseUrl, setBaseUrl, t]+ [baseUrl, lockedBaseUrl, t]);useEffect(() => {@@ -246,6 +314,21 @@ export default function OpenAICompatiblePanel({loadRemoteModels();}, [hasBase, normalizedBase, loadRemoteModels]);+ // A key change retries a failed list load once the check for that key has settled, so the+ // list never gets a half-typed key, and a hidden panel asks nothing: its check is not ready,+ // so it never settles. It also runs when a load that was in flight settles (`modelsLoading`+ // drops), since a key typed during that load has a check that settled before the load did.+ useEffect(() => {+ if (check.phase !== "connected" && check.phase !== "unverified" && check.phase !== "failed") {+ return;+ }+ if (!hasBase) return;+ if (lastLoadedBaseRef.current === normalizedBase) return;+ if (pendingBaseRef.current === normalizedBase) return;+ if (apiKey.trim() === lastLoadedKeyRef.current) return;+ loadRemoteModels();+ }, [check.phase, apiKey, hasBase, normalizedBase, modelsLoading, loadRemoteModels]);+const applyBase = useCallback(() => {const normalized = trimmedDraft ? normalizeBaseUrl(trimmedDraft) : trimmedDraft;setDraftBase(normalized);@@ -254,12 +337,17 @@ export default function OpenAICompatiblePanel({loadRemoteModels(normalized, true);}, [trimmedDraft, setBaseUrl, loadRemoteModels]);- const handleBlur = useCallback(() => {- if (!trimmedDraft) return;- if (trimmedDraft !== (baseUrl || "").trim()) {- applyBase();- }- }, [trimmedDraft, baseUrl, applyBase]);+ const handleBlur = useCallback(+ (event: FocusEvent<HTMLInputElement>) => {+ // Switching to another app blurs the field mid-edit; the address applies once it is left.+ if (isWindowSwitchBlur(event)) return;+ if (!trimmedDraft) return;+ if (trimmedDraft !== (baseUrl || "").trim()) {+ applyBase();+ }+ },+ [trimmedDraft, baseUrl, applyBase]+ );const handleReset = useCallback(() => {const target = defaultBaseUrl ?? "";@@ -283,16 +371,20 @@ export default function OpenAICompatiblePanel({return (<>+ <ConnectionCheckAnnouncer announcement={check.announcement} />{!lockedBaseUrl && (- <div className="space-y-2">+ <div className="space-y-2" onFocus={editing.onFocus} onBlur={editing.onBlur}><h4 className="font-medium text-foreground">{t("reasoning.custom.endpointTitle")}</h4>- <Input- dir="ltr"+ <ProviderCheckField+ aria-label={t("reasoning.custom.endpointTitle")}+ check={endpointCheck}+ failureReason={failureReason}value={draftBase}onChange={(event) => setDraftBase(event.target.value)}onBlur={handleBlur}placeholder={baseUrlPlaceholder}- className="text-sm"+ autoComplete="off"+ spellCheck={false}/>{helpExamples ?? (<p className="text-xs text-muted-foreground">@@ -310,20 +402,30 @@ export default function OpenAICompatiblePanel({</div>)}- <div className="space-y-2 pt-3">+ <div className="space-y-2 pt-3" onFocus={editing.onFocus} onBlur={editing.onBlur}><div className="flex items-baseline justify-between">- <h4 className="font-medium text-foreground">- {t(apiKeyRequired ? "common.apiKey" : "reasoning.custom.apiKeyOptional")}- </h4>+ <h4 className="font-medium text-foreground">{keyLabel}</h4>{getKeyUrl && <GetApiKeyLink url={getKeyUrl} />}</div>- <ApiKeyInput- apiKey={apiKey}- setApiKey={setApiKey}- label=""- helpText={apiKeyRequired ? "" : t("reasoning.custom.apiKeyHelp")}+ <ProviderCheckField+ aria-label={keyLabel}+ // At a fixed address the key completes the connection, so it carries the status.+ check={lockedBaseUrl ? check : undefined}+ invalidOn="credentialsRejected"+ type="password"+ value={apiKey}+ onChange={(event) => keyDraft.change("apiKey", event.target.value.trim(), setApiKey)}+ onBlur={keyDraft.save}+ placeholder={t("apiKeyInput.placeholder")}+ autoComplete="off"+ spellCheck={false}/>- {apiKeyRequired && !apiKey?.trim() && (+ {!apiKeyRequired && (+ <p className="text-xs text-muted-foreground/70 mt-1">+ {t("reasoning.custom.apiKeyHelp")}+ </p>+ )}+ {apiKeyRequired && !apiKey.trim() && (<p className="text-xs text-warning">{t("reasoning.custom.keyRequiredHint")}</p>)}</div>@@ -375,7 +477,7 @@ export default function OpenAICompatiblePanel({{modelsLoading && (<p className="text-xs text-primary">{t("reasoning.custom.fetchingModels")}</p>)}- {modelsError && <p className="text-xs text-destructive">{modelsError}</p>}+ {listErrorShown && <p className="text-xs text-destructive">{modelsError}</p>}{!modelsLoading && !modelsError && modelOptions.length === 0 && (<p className="text-xs text-warning">{t("reasoning.custom.noModels")}</p>)}diff --git a/src/components/ReasoningModelSelector.tsx b/src/components/ReasoningModelSelector.tsxindex cb8813673..ddf889342 100644--- a/src/components/ReasoningModelSelector.tsx+++ b/src/components/ReasoningModelSelector.tsx@@ -9,7 +9,6 @@ import type {} from "../types/electron";import { Button } from "./ui/button";import { CircleAlert, Cloud, Lock, Zap } from "./icons";-import ApiKeyInput from "./ui/ApiKeyInput";import ModelCardList from "./ui/ModelCardList";import LocalModelPicker, { type LocalProvider } from "./LocalModelPicker";import { ProviderTabs, type ProviderTabItem } from "./ui/ProviderTabs";@@ -24,6 +23,13 @@ import {import { useTinfoilModels } from "../hooks/useTinfoilModels";import { getRemoteProviderIcon } from "../utils/providerIcons";import { GetApiKeyLink } from "./ui/GetApiKeyLink";+import { ConnectionCheckAnnouncer } from "./ui/ConnectionCheckAnnouncer";+import { ProviderCheckField } from "./ui/ProviderCheckField";+import { usePanelVisible } from "./ui/usePanelVisible";+import { useConnectionAutoCheck } from "../hooks/useConnectionAutoCheck";+import { useCredentialDraft } from "../hooks/useCredentialDraft";+import { useFocusHold } from "../hooks/useFocusHold";+import { useTypingPause } from "../hooks/useTypingPause";import { getCachedPlatform } from "../utils/platform";import { useSettingsStore } from "../stores/settingsStore";import {@@ -407,6 +413,76 @@ export default function ReasoningModelSelector({? selectedMode: (modeTabs[0]?.id as "cloud" | "local" | undefined));+ // One key per hosted provider, shared with every other panel. OpenRouter and Custom check+ // themselves in OpenAICompatiblePanel.+ const hostedKeys: Partial<+ Record<string, { value: string; set: (key: string) => void; url: string }>+ > = {+ openai: {+ value: openaiApiKey,+ set: setOpenaiApiKey,+ url: "https://platform.openai.com/api-keys",+ },+ anthropic: {+ value: anthropicApiKey,+ set: setAnthropicApiKey,+ url: "https://console.anthropic.com/settings/keys",+ },+ gemini: {+ value: geminiApiKey,+ set: setGeminiApiKey,+ url: "https://aistudio.google.com/app/api-keys",+ },+ groq: { value: groqApiKey, set: setGroqApiKey, url: "https://console.groq.com/keys" },+ tinfoil: {+ value: tinfoilApiKey,+ set: setTinfoilApiKey,+ url: "https://tinfoil.sh/inference?utm_source=referral&utm_campaign=openwhispr",+ },+ corti: {+ value: cortiApiKey,+ set: setCortiApiKey,+ url: "https://www.corti.ai/?utm_source=referral&utm_campaign=openwhispr",+ },+ };+ const hostedKey = hostedKeys[displayedCloudProvider];+ const keyDraft = useCredentialDraft();+ const typedKey = keyDraft.value(displayedCloudProvider, hostedKey?.value ?? "");+ const visible = usePanelVisible();+ const editing = useFocusHold();+ // A tab that is only being browsed has no model of this panel's: the key alone is checked.+ const checkedModel = localReasoningProvider === displayedCloudProvider ? reasoningModel : "";+ const delayMs = useTypingPause({+ typed: typedKey,+ context: JSON.stringify([displayedCloudProvider, effectiveMode, visible, checkedModel]),+ held: editing.held,+ });+ const check = useConnectionAutoCheck({+ config: {+ scope: "reasoning",+ provider: displayedCloudProvider,+ apiKey: typedKey,+ model: checkedModel,+ },+ // A hidden panel is not ready to ask; a shown one asks again, and the main process answers+ // a check it remembers at once.+ ready:+ effectiveMode === "cloud" &&+ providerAllowed(displayedCloudProvider) &&+ Boolean(typedKey.trim()) &&+ visible,+ delayMs,+ });+ const followKeyDraft = keyDraft.follow;+ const refused = check.failure?.errorCode === "credentialsRejected";+ useEffect(() => {+ followKeyDraft({+ phase: check.phase,+ checked: { [displayedCloudProvider]: typedKey },+ refused,+ });+ }, [check.phase, displayedCloudProvider, typedKey, refused, followKeyDraft]);+const localProviders = useMemo<LocalProvider[]>(() => {return modelRegistry.getAllProviders().map((provider) => ({id: provider.id,@@ -517,6 +593,7 @@ export default function ReasoningModelSelector({return (<div className="space-y-4">+ <ConnectionCheckAnnouncer announcement={check.announcement} />{!mode && (<div className="space-y-2">{modeTabs.length > 0 ? (@@ -568,6 +645,7 @@ export default function ReasoningModelSelector({setLocalReasoningProvider(OPENROUTER_TAB);setReasoningModel(m);}}+ provider="openrouter"lockedBaseUrlapiKeyRequiredgetKeyUrl={OPENROUTER_KEYS_URL}@@ -588,93 +666,34 @@ export default function ReasoningModelSelector({/>) : (<>- {displayedCloudProvider === "openai" && (- <div className="space-y-2">- <div className="flex items-baseline justify-between">- <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>- <GetApiKeyLink url="https://platform.openai.com/api-keys" />- </div>- <ApiKeyInput- apiKey={openaiApiKey}- setApiKey={setOpenaiApiKey}- label=""- helpText=""- />- </div>- )}-- {displayedCloudProvider === "anthropic" && (- <div className="space-y-2">- <div className="flex items-baseline justify-between">- <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>- <GetApiKeyLink url="https://console.anthropic.com/settings/keys" />- </div>- <ApiKeyInput- apiKey={anthropicApiKey}- setApiKey={setAnthropicApiKey}- label=""- helpText=""- />- </div>- )}-- {displayedCloudProvider === "gemini" && (- <div className="space-y-2">- <div className="flex items-baseline justify-between">- <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>- <GetApiKeyLink url="https://aistudio.google.com/app/api-keys" />- </div>- <ApiKeyInput- apiKey={geminiApiKey}- setApiKey={setGeminiApiKey}- label=""- helpText=""- />- </div>- )}-- {displayedCloudProvider === "groq" && (- <div className="space-y-2">- <div className="flex items-baseline justify-between">- <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>- <GetApiKeyLink url="https://console.groq.com/keys" />- </div>- <ApiKeyInput- apiKey={groqApiKey}- setApiKey={setGroqApiKey}- label=""- helpText=""- />- </div>- )}-- {displayedCloudProvider === "tinfoil" && (- <div className="space-y-2">- <div className="flex items-baseline justify-between">- <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>- <GetApiKeyLink url="https://tinfoil.sh/inference?utm_source=referral&utm_campaign=openwhispr" />- </div>- <ApiKeyInput- apiKey={tinfoilApiKey}- setApiKey={setTinfoilApiKey}- label=""- helpText=""- />- </div>- )}-- {displayedCloudProvider === "corti" && (- <div className="space-y-2">- <p className="text-xs text-muted-foreground">{t("reasoning.corti.euOnly")}</p>+ {hostedKey && (+ <div className="space-y-2" onFocus={editing.onFocus} onBlur={editing.onBlur}>+ {displayedCloudProvider === "corti" && (+ <p className="text-xs text-muted-foreground">+ {t("reasoning.corti.euOnly")}+ </p>+ )}<div className="flex items-baseline justify-between"><h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>- <GetApiKeyLink url="https://www.corti.ai/?utm_source=referral&utm_campaign=openwhispr" />+ <GetApiKeyLink url={hostedKey.url} /></div>- <ApiKeyInput- apiKey={cortiApiKey}- setApiKey={setCortiApiKey}- label=""- helpText=""+ <ProviderCheckField+ aria-label={t("common.apiKey")}+ check={check}+ invalidOn="credentialsRejected"+ type="password"+ value={typedKey}+ onChange={(event) =>+ keyDraft.change(+ displayedCloudProvider,+ event.target.value.trim(),+ hostedKey.set+ )+ }+ onBlur={keyDraft.save}+ placeholder={t("apiKeyInput.placeholder")}+ autoComplete="off"+ spellCheck={false}/></div>)}diff --git a/src/components/SelfHostedPanel.tsx b/src/components/SelfHostedPanel.tsxindex 7ed223b1d..72cf88f13 100644--- a/src/components/SelfHostedPanel.tsx+++ b/src/components/SelfHostedPanel.tsx@@ -1,5 +1,11 @@import { useTranslation } from "react-i18next";-import { Input } from "./ui/input";+import { ORUKEET_MODEL } from "../helpers/dictationStreamingRouting";+import { useConnectionAutoCheck } from "../hooks/useConnectionAutoCheck";+import { useFocusHold } from "../hooks/useFocusHold";+import { useTypingPause } from "../hooks/useTypingPause";+import { ConnectionCheckAnnouncer } from "./ui/ConnectionCheckAnnouncer";+import { ProviderCheckField } from "./ui/ProviderCheckField";+import { usePanelVisible } from "./ui/usePanelVisible";interface SelfHostedPanelProps {service: "transcription" | "reasoning";@@ -17,33 +23,74 @@ export default function SelfHostedPanel({onModelChange,}: SelfHostedPanelProps) {const { t } = useTranslation();+ const urlHold = useFocusHold();+ const editing = useFocusHold();+ const visible = usePanelVisible();+ const trimmedModel = (model ?? "").trim();+ // The address and model save as they are typed.+ const delayMs = useTypingPause({+ typed: `${url}\n${model ?? ""}`,+ context: JSON.stringify([service, visible]),+ held: editing.held,+ });+ const check = useConnectionAutoCheck({+ config: { scope: service, provider: "custom", baseUrl: url, model },+ ready:+ Boolean(onModelChange && url.trim() && trimmedModel) &&+ // The app sends this model's server a key this panel has no field for, so a check+ // could only ask without it.+ trimmedModel !== ORUKEET_MODEL &&+ // A hidden panel is not ready to ask; a shown one asks again, and the main process+ // answers a check it remembers at once.+ visible,+ // A half-typed address may belong to someone else: nothing is sent while it is edited.+ hold: urlHold.held,+ delayMs,+ });const placeholderUrl =service === "transcription" ? "http://192.168.1.126:8178" : "http://192.168.1.126:8080";return (- <div className="border border-border rounded-lg p-3 space-y-2.5">+ <div+ className="border border-border rounded-lg p-3 space-y-2.5"+ onFocus={editing.onFocus}+ onBlur={editing.onBlur}+ >+ <ConnectionCheckAnnouncer announcement={check.announcement} /><div className="space-y-1.5"><label className="block text-xs font-medium text-foreground">{t("settingsPage.selfHosted.serverUrl")}</label>- <Input- dir="ltr"+ <ProviderCheckField+ aria-label={t("settingsPage.selfHosted.serverUrl")}value={url}onChange={(e) => onUrlChange(e.target.value)}+ onFocus={urlHold.onFocus}+ onBlur={urlHold.onBlur}placeholder={placeholderUrl}- className="h-8 text-sm"+ autoComplete="off"+ spellCheck={false}/></div>{onModelChange && (<div className="space-y-1.5"><label className="block text-xs font-medium text-foreground">{t("common.model")}</label>- <Input- dir="ltr"+ <ProviderCheckField+ aria-label={t("common.model")}+ check={check}+ invalidOn="modelNotFound"+ // This server is sent no key, so a refusal means it wants one.+ failureReason={+ check.failure?.errorCode === "credentialsRejected"+ ? t("reasoning.custom.endpointUnauthorized")+ : undefined+ }value={model ?? ""}onChange={(e) => onModelChange(e.target.value)}placeholder="Whisper-Large-v3-Turbo"- className="h-8 text-sm"+ autoComplete="off"+ spellCheck={false}/></div>)}diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 521b53509..cf2766a43 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -116,6 +116,7 @@ import {} from "./ui/SettingsSection";import type { InferenceModeOption } from "./ui/SettingsSection";import { useSettingsLayout } from "./ui/useSettingsLayout";+import { TabPanel } from "./ui/TabPanel";import { useUsage } from "../hooks/useUsage";import { cn } from "./lib/utils";import { GRADIENT_CIRCLE } from "./ui/gradientCircle";@@ -927,10 +928,6 @@ function VADLabelWithInfo({ label, description }: { label: string; description:);}-function TabPanel({ active, children }: { active: boolean; children: React.ReactNode }) {- return <div className={active ? undefined : "hidden"}>{children}</div>;-}-// "Gabriel Stein" → "GS"; single names fall back to their first letter.function nameInitials(name: string): string {const parts = name.trim().split(/\s+/);diff --git a/src/components/TranscriptionModelPicker.tsx b/src/components/TranscriptionModelPicker.tsxindex 73338e9ba..8d5b1e57c 100644--- a/src/components/TranscriptionModelPicker.tsx+++ b/src/components/TranscriptionModelPicker.tsx@@ -1,14 +1,12 @@import { useState, useEffect, useCallback, useMemo, useRef, type ReactNode } from "react";import { useTranslation } from "react-i18next";import { Button } from "./ui/button";-import { Input } from "./ui/input";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";import { Download, Trash2, Cloud, Lock, X, Zap, Check, CircleAlert } from "./icons";import { ProviderIcon } from "./ui/ProviderIcon";import { ProviderTabs } from "./ui/ProviderTabs";import ModelCardList from "./ui/ModelCardList";import { DownloadProgressBar } from "./ui/DownloadProgressBar";-import ApiKeyInput from "./ui/ApiKeyInput";import { ConfirmDialog } from "./ui/dialog";import { useDialogs } from "../hooks/useDialogs";import { useModelDownload, type DownloadProgress } from "../hooks/useModelDownload";@@ -44,7 +42,18 @@ import { STREAMING_ONLY_PROVIDERS } from "../helpers/transcriptionRoute";import { getRemoteProviderIcon } from "../utils/providerIcons";import { createExternalLinkHandler } from "../utils/externalLinks";import { API_ENDPOINTS, normalizeBaseUrl } from "../config/constants";+import { isAzureOpenAIEndpoint } from "../utils/urlUtils";import { GetApiKeyLink } from "./ui/GetApiKeyLink";+import { ConnectionCheckAnnouncer } from "./ui/ConnectionCheckAnnouncer";+import { ProviderCheckField } from "./ui/ProviderCheckField";+import { usePanelVisible } from "./ui/usePanelVisible";+import { useCredentialDraft } from "../hooks/useCredentialDraft";+import { useFocusHold } from "../hooks/useFocusHold";+import { useTypingPause } from "../hooks/useTypingPause";+import {+ useConnectionAutoCheck,+ type ProviderConnectionConfig,+} from "../hooks/useConnectionAutoCheck";import { getCachedPlatform } from "../utils/platform";import { pickWhisperGpuBackend } from "../utils/whisperGpuPack";import logger from "../utils/logger";@@ -301,7 +310,7 @@ const PROVIDER_CREDENTIALS: Record<corti: {consoleUrl: "https://www.corti.ai/?utm_source=referral&utm_content=&utm_campaign=openwhispr",fields: [- { key: "cortiClientId", input: "secret", labelKey: "transcription.corti.clientId" },+ { key: "cortiClientId", input: "text", labelKey: "transcription.corti.clientId" },{ key: "cortiClientSecret", input: "secret", labelKey: "transcription.corti.clientSecret" },{key: "cortiEnvironment",@@ -1065,20 +1074,22 @@ export default function TranscriptionModelPicker({const providerCredentials =PROVIDER_CREDENTIALS[displayedCloudProvider] ?? PROVIDER_CREDENTIALS.openai;+ const keyDraft = useCredentialDraft();const credentialValues: Record<ProviderCredentialField["key"], string> = {- openaiApiKey,- groqApiKey,- xaiApiKey,- mistralApiKey,- geminiApiKey,- cortiClientId,- cortiClientSecret,+ openaiApiKey: keyDraft.value("openaiApiKey", openaiApiKey),+ groqApiKey: keyDraft.value("groqApiKey", groqApiKey),+ xaiApiKey: keyDraft.value("xaiApiKey", xaiApiKey),+ mistralApiKey: keyDraft.value("mistralApiKey", mistralApiKey),+ geminiApiKey: keyDraft.value("geminiApiKey", geminiApiKey),+ cortiClientId: keyDraft.value("cortiClientId", cortiClientId),+ cortiClientSecret: keyDraft.value("cortiClientSecret", cortiClientSecret),cortiEnvironment,- cortiTenant,- tinfoilApiKey,- deepgramApiKey,- assemblyaiApiKey,+ cortiTenant: keyDraft.value("cortiTenant", cortiTenant),+ tinfoilApiKey: keyDraft.value("tinfoilApiKey", tinfoilApiKey),+ deepgramApiKey: keyDraft.value("deepgramApiKey", deepgramApiKey),+ assemblyaiApiKey: keyDraft.value("assemblyaiApiKey", assemblyaiApiKey),};+ const customKey = keyDraft.value("customTranscriptionApiKey", customTranscriptionApiKey);const credentialSetters: Record<ProviderCredentialField["key"], (value: string) => void> = {openaiApiKey: setOpenaiApiKey,groqApiKey: setGroqApiKey,@@ -1094,6 +1105,107 @@ export default function TranscriptionModelPicker({assemblyaiApiKey: setAssemblyaiApiKey,};+ const endpointHold = useFocusHold();+ const editing = useFocusHold();+ const visible = usePanelVisible();+ // A tab that is only being browsed has no model of this panel's: the key alone is checked.+ const panelModel = selectedCloudProvider === displayedCloudProvider ? displayedCloudModel : "";+ const isCustom = displayedCloudProvider === "custom";+ const isCorti = displayedCloudProvider === "corti";+ const providerKey = credentialValues[providerCredentials.fields[0].key];+ // `typed` is what is typed into this provider's fields (a speech server's address and+ // model name included); `context` is what is chosen instead.+ const connection: {+ config: ProviderConnectionConfig;+ ready: boolean;+ typed: string;+ context: unknown[];+ } = isCustom+ ? {+ config: {+ scope: "transcription",+ provider: "custom",+ baseUrl: cloudTranscriptionBaseUrl,+ apiKey: customKey,+ model: panelModel,+ },+ // The check speaks only OpenAI's API; Azure gets its own URL and `api-key` header.+ ready:+ Boolean(cloudTranscriptionBaseUrl.trim() && panelModel.trim()) &&+ !isAzureOpenAIEndpoint(cloudTranscriptionBaseUrl),+ typed: `${cloudTranscriptionBaseUrl}\n${customKey}\n${panelModel}`,+ context: [],+ }+ : isCorti+ ? {+ config: {+ scope: "transcription",+ provider: "corti",+ clientId: credentialValues.cortiClientId,+ clientSecret: credentialValues.cortiClientSecret,+ environment: cortiEnvironment,+ tenant: credentialValues.cortiTenant,+ },+ ready: Boolean(+ credentialValues.cortiClientId.trim() && credentialValues.cortiClientSecret.trim()+ ),+ typed: `${credentialValues.cortiClientId}\n${credentialValues.cortiClientSecret}`,+ context: [cortiEnvironment, credentialValues.cortiTenant],+ }+ : {+ config: {+ scope: "transcription",+ provider: displayedCloudProvider,+ apiKey: providerKey,+ model: panelModel,+ },+ ready: Boolean(providerKey.trim()),+ typed: providerKey,+ context: [panelModel],+ };+ const delayMs = useTypingPause({+ typed: connection.typed,+ context: JSON.stringify([+ displayedCloudProvider,+ visible,+ effectiveLocal,+ ...connection.context,+ ]),+ held: editing.held,+ });+ const check = useConnectionAutoCheck({+ config: connection.config,+ // A hidden panel is not ready to ask; a shown one asks again, and the main process answers+ // a check it remembers at once.+ ready:+ !effectiveLocal && providerAllowed(displayedCloudProvider) && connection.ready && visible,+ // A half-typed address may belong to someone else: nothing is sent while it is edited.+ hold: isCustom && endpointHold.held,+ delayMs,+ });+ // The field that completes the connection carries the status.+ const checkedCredential = isCorti ? "cortiClientSecret" : providerCredentials.fields[0].key;+ const refused = check.failure?.errorCode === "credentialsRejected";+ // The typed values the check carries, as one string so the effect sees each new set.+ const checkedFields = JSON.stringify(+ isCustom+ ? { customTranscriptionApiKey: customKey }+ : Object.fromEntries(+ providerCredentials.fields.map((field) => [field.key, credentialValues[field.key]])+ )+ );+ const followKeyDraft = keyDraft.follow;+ useEffect(() => {+ followKeyDraft({+ phase: check.phase,+ checked: JSON.parse(checkedFields),+ // Someone's own server may refuse a key for other reasons, so its refusal holds nothing back.+ refused: refused && !isCustom,+ });+ }, [check.phase, checkedFields, isCustom, refused, followKeyDraft]);+ const customFailureReason =+ !customKey.trim() && refused ? t("reasoning.custom.endpointUnauthorized") : undefined;+const cloudModelOptions = useMemo(() => {if (!currentCloudProvider) return [];const { icon, invertInDark } = getRemoteProviderIcon(displayedCloudProvider);@@ -1277,6 +1389,7 @@ export default function TranscriptionModelPicker({return (<div className={`space-y-2 ${className}`}>+ <ConnectionCheckAnnouncer announcement={check.announcement} />{!mode && <ModeToggle useLocalWhisper={effectiveLocal} onModeChange={handleModeChange} />}{!effectiveLocal ? (@@ -1294,40 +1407,60 @@ export default function TranscriptionModelPicker({{providerAllowed(displayedCloudProvider) && (<div>{displayedCloudProvider === "custom" ? (- <div className="space-y-2">+ <div className="space-y-2" onFocus={editing.onFocus} onBlur={editing.onBlur}><div className="space-y-1.5"><label className="block text-xs font-medium text-foreground">{t("transcription.endpointUrl")}</label>- <Input- dir="ltr"+ <ProviderCheckField+ aria-label={t("transcription.endpointUrl")}value={cloudTranscriptionBaseUrl}onChange={(e) => setCloudTranscriptionBaseUrl?.(e.target.value)}- onBlur={handleBaseUrlBlur}+ onFocus={endpointHold.onFocus}+ onBlur={(event) => {+ endpointHold.onBlur(event);+ handleBaseUrlBlur();+ }}placeholder="https://your-api.example.com/v1"- className="h-8 text-sm"+ autoComplete="off"+ spellCheck={false}/></div>-- <ApiKeyInput- apiKey={customTranscriptionApiKey}- setApiKey={setCustomTranscriptionApiKey}- label={t("transcription.apiKeyOptional")}- helpText=""- />-<div className="space-y-1.5"><label className="block text-xs font-medium text-foreground">- {t("common.model")}+ {t("transcription.apiKeyOptional")}</label>- <Input- dir="ltr"- value={- selectedCloudProvider === displayedCloudProvider ? displayedCloudModel : ""+ <ProviderCheckField+ aria-label={t("transcription.apiKeyOptional")}+ type="password"+ value={customKey}+ onChange={(e) =>+ keyDraft.change(+ "customTranscriptionApiKey",+ e.target.value.trim(),+ setCustomTranscriptionApiKey+ )}+ onBlur={keyDraft.save}+ placeholder={t("apiKeyInput.placeholder")}+ autoComplete="off"+ spellCheck={false}+ />+ </div>+ <div className="space-y-1.5">+ <label className="block text-xs font-medium text-foreground">+ {t("common.model")}+ </label>+ <ProviderCheckField+ aria-label={t("common.model")}+ check={check}+ invalidOn="modelNotFound"+ failureReason={customFailureReason}+ value={panelModel}onChange={(e) => handleCloudModelSelect(e.target.value)}placeholder="whisper-1"- className="h-8 text-sm"+ autoComplete="off"+ spellCheck={false}/></div>@@ -1337,54 +1470,67 @@ export default function TranscriptionModelPicker({</div>) : (<div className="space-y-2">- {providerCredentials.fields.map((field, index) => (- <div key={field.key} className="space-y-1.5">- <div className="flex items-center justify-between">- <label className="text-xs font-medium text-foreground">- {field.labelKey ? t(field.labelKey) : t("common.apiKey")}- </label>- {index === 0 && (- <GetApiKeyLink- url={providerCredentials.consoleUrl}- labelKey="transcription.getKey"- className="text-xs text-primary/70 hover:text-primary transition-colors cursor-pointer"+ {providerCredentials.fields.map((field, index) => {+ const label = field.labelKey ? t(field.labelKey) : t("common.apiKey");+ return (+ <div key={field.key} className="space-y-1.5">+ <div className="flex items-center justify-between">+ <label className="text-xs font-medium text-foreground">{label}</label>+ {index === 0 && (+ <GetApiKeyLink+ url={providerCredentials.consoleUrl}+ labelKey="transcription.getKey"+ className="text-xs text-primary/70 hover:text-primary transition-colors cursor-pointer"+ />+ )}+ </div>+ {field.input === "select" ? (+ <Select+ value={credentialValues[field.key]}+ onValueChange={credentialSetters[field.key]}+ >+ <SelectTrigger className="h-8 text-sm">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {field.options?.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ ) : (+ <ProviderCheckField+ aria-label={label}+ check={field.key === checkedCredential ? check : undefined}+ invalidOn="credentialsRejected"+ type={field.input === "secret" ? "password" : "text"}+ value={credentialValues[field.key]}+ onChange={(e) =>+ keyDraft.change(+ field.key,+ e.target.value.trim(),+ credentialSetters[field.key]+ )+ }+ onFocus={editing.onFocus}+ onBlur={(event) => {+ editing.onBlur(event);+ keyDraft.save();+ }}+ placeholder={+ field.input === "secret"+ ? t("apiKeyInput.placeholder")+ : field.placeholder+ }+ autoComplete="off"+ spellCheck={false}/>)}</div>- {field.input === "secret" ? (- <ApiKeyInput- apiKey={credentialValues[field.key]}- setApiKey={credentialSetters[field.key]}- label=""- helpText=""- />- ) : field.input === "select" ? (- <Select- value={credentialValues[field.key]}- onValueChange={credentialSetters[field.key]}- >- <SelectTrigger className="h-8 text-sm">- <SelectValue />- </SelectTrigger>- <SelectContent>- {field.options?.map((option) => (- <SelectItem key={option.value} value={option.value}>- {option.label}- </SelectItem>- ))}- </SelectContent>- </Select>- ) : (- <Input- dir="ltr"- value={credentialValues[field.key]}- onChange={(e) => credentialSetters[field.key](e.target.value)}- placeholder={field.placeholder}- className="h-8 text-sm"- />- )}- </div>- ))}+ );+ })}<div className="space-y-1.5"><label className="text-xs font-medium text-foreground">diff --git a/src/components/onboarding/ProviderConnectionTest.tsx b/src/components/onboarding/ProviderConnectionTest.tsxdeleted file mode 100644index 8fdee9596..000000000--- a/src/components/onboarding/ProviderConnectionTest.tsx+++ /dev/null@@ -1,141 +0,0 @@-import { useEffect, useRef, useState } from "react";-import { CheckCircle, Loader2, XCircle } from "../icons";-import { useTranslation } from "react-i18next";-import { Button } from "../ui/button";--type ProviderConnectionConfig = Parameters<- NonNullable<Window["electronAPI"]["testProviderConnection"]>->[0];--type ConnectionTestResult = Awaited<- ReturnType<NonNullable<Window["electronAPI"]["testProviderConnection"]>>->;--interface ProviderConnectionTestProps {- config: ProviderConnectionConfig;- onSuccessChange: (connected: boolean) => void;- variant?: "default" | "inline";-}--export default function ProviderConnectionTest({- config,- onSuccessChange,- variant = "default",-}: ProviderConnectionTestProps) {- const { t } = useTranslation();- const [status, setStatus] = useState<"idle" | "testing" | "success" | "error">("idle");- const [error, setError] = useState<string | null>(null);- const requestIdRef = useRef(0);-- useEffect(() => {- requestIdRef.current += 1;- setStatus("idle");- setError(null);- onSuccessChange(false);- return () => {- requestIdRef.current += 1;- };- }, [- config.apiKey,- config.baseUrl,- config.clientId,- config.clientSecret,- config.environment,- config.model,- config.provider,- config.scope,- config.tenant,- onSuccessChange,- ]);-- const describeError = (result: ConnectionTestResult | undefined) => {- if (result?.errorCode) {- return t(`onboarding.rehaul.provider.errors.${result.errorCode}`, {- status: result.status,- defaultValue: result.error ?? t("onboarding.rehaul.provider.connectionFailed"),- });- }- return result?.error ?? t("onboarding.rehaul.provider.connectionFailed");- };-- const testConnection = async () => {- const requestId = ++requestIdRef.current;- setStatus("testing");- setError(null);- onSuccessChange(false);- try {- const result: ConnectionTestResult | undefined =- await window.electronAPI?.testProviderConnection?.(config);- if (requestId !== requestIdRef.current) return;- if (result?.success) {- setStatus("success");- onSuccessChange(true);- } else {- setStatus("error");- setError(describeError(result));- }- } catch {- if (requestId !== requestIdRef.current) return;- setStatus("error");- setError(t("onboarding.rehaul.provider.connectionFailed"));- }- };-- if (variant === "inline") {- return (- <div>- <div className="flex h-11 items-center justify-between rounded-xl border border-[var(--onboarding-control-border)] bg-[var(--onboarding-surface)] px-3">- <span className="text-xs font-medium text-[var(--onboarding-text-primary)]">- {t("onboarding.rehaul.provider.testConnection")}- </span>- <Button- type="button"- onClick={() => void testConnection()}- disabled={status === "testing"}- className="h-7 gap-1 px-2 text-[0.5625rem]"- >- {status === "testing" && <Loader2 className="size-3 animate-spin" />}- {status === "success" && <CheckCircle className="size-3" />}- {status === "error" && <XCircle className="size-3" />}- {status === "testing"- ? t("onboarding.rehaul.provider.testing")- : status === "success"- ? t("onboarding.rehaul.provider.connected")- : t("onboarding.rehaul.provider.runTest")}- </Button>- </div>- {error && (- <p role="alert" className="mt-1 px-1 text-xs text-destructive">- {error}- </p>- )}- </div>- );- }-- return (- <div className="space-y-2 rounded-xl border border-border bg-muted/30 p-3">- <Button- type="button"- variant="outline"- onClick={() => void testConnection()}- disabled={status === "testing"}- className="w-full rounded-lg"- >- {status === "testing" && <Loader2 className="size-4 animate-spin" />}- {status === "success" && <CheckCircle className="size-4 text-success" />}- {status === "error" && <XCircle className="size-4 text-destructive" />}- {status === "testing"- ? t("onboarding.rehaul.provider.testing")- : status === "success"- ? t("onboarding.rehaul.provider.connected")- : t("onboarding.rehaul.provider.runTest")}- </Button>- {error && (- <p role="alert" className="text-xs text-destructive">- {error}- </p>- )}- </div>- );-}diff --git a/src/components/onboarding/ProviderSetupStep.tsx b/src/components/onboarding/ProviderSetupStep.tsxindex 2500e8738..9138bff22 100644--- a/src/components/onboarding/ProviderSetupStep.tsx+++ b/src/components/onboarding/ProviderSetupStep.tsx@@ -1,11 +1,21 @@-import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+ type FocusEvent,+ type ReactNode,+} from "react";import { AudioLines, Check, CircleCheck, Download, MousePointer2 } from "../icons";import { useTranslation } from "react-i18next";-import ProviderConnectionTest from "./ProviderConnectionTest";+import { FieldLabel, ProviderCheckField } from "../ui/ProviderCheckField";+import { ConnectionCheckAnnouncer } from "../ui/ConnectionCheckAnnouncer";import { Button } from "../ui/button";-import { Input } from "../ui/input";import { ProviderIcon } from "../ui/ProviderIcon";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";+import { useConnectionAutoCheck } from "../../hooks/useConnectionAutoCheck";+import { isWindowSwitchBlur } from "../../hooks/useFocusHold";import { useModelDownload } from "../../hooks/useModelDownload";import type { ParakeetCheckResult } from "../../types/electron";import { useSettingsStore } from "../../stores/settingsStore";@@ -115,7 +125,7 @@ function StepPrimaryAction({type="button"onClick={onClick}disabled={disabled}- className="h-9 rounded-[38px] px-5 text-sm"+ className={`h-9 rounded-[38px] px-5 text-sm ${className}`}>{children}</Button>@@ -301,12 +311,6 @@ function resolveInitialLocalSelection(type HostedProvider = CloudProviderData | TranscriptionProviderData;-function FieldLabel({ children }: { children: ReactNode }) {- return (- <span className="mb-1.5 block text-xs text-[var(--onboarding-text-tertiary)]">{children}</span>- );-}-export function ByokProviderStep({stepId,selfHostedRequested = false,@@ -320,7 +324,7 @@ export function ByokProviderStep({/** Set when the user picked "Self-hosted" on setup-choice rather than BYOK. */selfHostedRequested?: boolean;onSelfHostedChange: (requested: boolean) => void;- onConnectionChange: (connected: boolean) => void;+ onConnectionChange: (usable: boolean) => void;onProceed: () => void;resumeState?: OnboardingByokDraft;onResumeStateChange?: (state: OnboardingByokDraft) => void;@@ -394,11 +398,7 @@ export function ByokProviderStep({const [draftCortiClientSecret, setDraftCortiClientSecret] = useState(seed.provider === "corti" ? store.cortiClientSecret : "");- const [connected, setConnected] = useState(false);-- useEffect(() => {- onConnectionChange(false);- }, [onConnectionChange]);+ const [endpointFocused, setEndpointFocused] = useState(false);// The card the saved setup picked goes on the session once, at mount (both deps are// stable), so the draft this visit writes reopens on it; later switches report@@ -435,9 +435,7 @@ export function ByokProviderStep({setSelfHosted(false);onSelfHostedChange(false);setDraftApiKey(providerCredential(selectedProvider, useSettingsStore.getState()).value);- setConnected(false);- onConnectionChange(false);- }, [onConnectionChange, onSelfHostedChange, selectedProvider, selfHosted, selfHostedAllowed]);+ }, [onSelfHostedChange, selectedProvider, selfHosted, selfHostedAllowed]);// Saved keys load asynchronously (initializeSettings), so an empty field takes its key// when it arrives; anything already in the field is kept.@@ -472,8 +470,7 @@ export function ByokProviderStep({setSelfHosted(next);onSelfHostedChange(next);setDraftApiKey(credentialFor(next, selectedProvider, draftBaseUrl));- setConnected(false);- onConnectionChange(false);+ setEndpointFocused(false); // the address field leaves with its card, sometimes without a blur};const chooseProvider = (providerId: string) => {@@ -483,24 +480,8 @@ export function ByokProviderStep({setDraftApiKey(providerCredential(providerId, store).value);setDraftCortiClientId(providerId === "corti" ? store.cortiClientId : "");setDraftCortiClientSecret(providerId === "corti" ? store.cortiClientSecret : "");- setConnected(false);- onConnectionChange(false);};- const chooseModel = (modelId: string) => {- setSelectedModel(modelId);- setConnected(false);- onConnectionChange(false);- };-- const handleConnected = useCallback(- (success: boolean) => {- setConnected(success);- onConnectionChange(success);- },- [onConnectionChange]- );-const testingProvider = selfHosted ? "custom" : selectedProvider;const testingKey = draftApiKey;const testingBaseUrl = selfHosted ? draftBaseUrl : undefined;@@ -518,6 +499,35 @@ export function ByokProviderStep({): Boolean(currentProvider && selectedModel && testingKey.trim());+ const check = useConnectionAutoCheck({+ config: {+ scope: assistant ? "reasoning" : "transcription",+ provider: testingProvider,+ apiKey: testingKey,+ baseUrl: testingBaseUrl,+ model: selfHosted ? draftCustomModel : selectedModel,+ clientId: isCortiTranscription ? draftCortiClientId : undefined,+ clientSecret: isCortiTranscription ? draftCortiClientSecret : undefined,+ environment: store.cortiEnvironment,+ tenant: store.cortiTenant,+ },+ ready: fieldsReady,+ // A half-typed address may belong to someone else: nothing is sent while it is edited.+ hold: selfHosted && endpointFocused,+ });+ // A provider that gave no verdict (busy, slow or unreachable) refused nothing, so its+ // setup can be used; only a failure that faults it keeps Proceed locked.+ const usable = check.phase === "connected" || check.phase === "unverified";+ useEffect(() => {+ onConnectionChange(usable);+ }, [usable, onConnectionChange]);++ // Switching to another app blurs the field but leaves it focused in the page, and the+ // address there may still be half typed.+ const releaseEndpoint = (event: FocusEvent<HTMLInputElement>) => {+ if (!isWindowSwitchBlur(event)) setEndpointFocused(false);+ };+const commitAndProceed = () => {if (selfHosted) {const committedBaseUrl = withHttpsScheme(draftBaseUrl);@@ -565,9 +575,6 @@ export function ByokProviderStep({onProceed();};- const inputClass =- "onboarding-provider-input h-9 rounded-xl! border px-3 text-xs shadow-none! focus:ring-2 focus:ring-[color-mix(in_srgb,var(--onboarding-accent)_15%,transparent)]";-return (<section className={`mt-5 ${SETUP_CARD_CLASS}`}><SetupStageStepper stepId={stepId} />@@ -601,39 +608,31 @@ export function ByokProviderStep({{selfHosted ? (<>- <label className="block">- <FieldLabel>{t("onboarding.rehaul.provider.endpointUrl")}</FieldLabel>- <Input- dir="ltr"- value={draftBaseUrl}- onChange={(event) => setDraftBaseUrl(event.target.value)}- placeholder={t("onboarding.rehaul.provider.endpointPlaceholder")}- className={inputClass}- />- </label>- <label className="block">- <FieldLabel>{t("onboarding.rehaul.provider.apiKey")}</FieldLabel>- <Input- dir="ltr"- type="password"- value={draftApiKey}- onChange={(event) => setDraftApiKey(event.target.value)}- placeholder={t("onboarding.rehaul.provider.optional")}- autoComplete="off"- spellCheck={false}- className={inputClass}- />- </label>- <label className="block">- <FieldLabel>{t("onboarding.rehaul.provider.modelId")}</FieldLabel>- <Input- dir="ltr"- value={draftCustomModel}- onChange={(event) => setDraftCustomModel(event.target.value)}- placeholder={t("onboarding.rehaul.provider.modelIdPlaceholder")}- className={inputClass}- />- </label>+ <ProviderCheckField+ label={t("onboarding.rehaul.provider.endpointUrl")}+ value={draftBaseUrl}+ onChange={(event) => setDraftBaseUrl(event.target.value)}+ onFocus={() => setEndpointFocused(true)}+ onBlur={releaseEndpoint}+ placeholder={t("onboarding.rehaul.provider.endpointPlaceholder")}+ />+ <ProviderCheckField+ label={t("onboarding.rehaul.provider.apiKey")}+ type="password"+ value={draftApiKey}+ onChange={(event) => setDraftApiKey(event.target.value)}+ placeholder={t("onboarding.rehaul.provider.optional")}+ autoComplete="off"+ spellCheck={false}+ />+ <ProviderCheckField+ label={t("onboarding.rehaul.provider.modelId")}+ check={check}+ invalidOn="modelNotFound"+ value={draftCustomModel}+ onChange={(event) => setDraftCustomModel(event.target.value)}+ placeholder={t("onboarding.rehaul.provider.modelIdPlaceholder")}+ /></>) : (<>@@ -676,7 +675,7 @@ export function ByokProviderStep({<FieldLabel>{t("onboarding.rehaul.provider.modelLabel")}</FieldLabel><Selectvalue={selectedModel || undefined}- onValueChange={chooseModel}+ onValueChange={setSelectedModel}disabled={!selectedProvider}><SelectTrigger@@ -704,75 +703,45 @@ export function ByokProviderStep({{isCortiTranscription ? (<div className="grid grid-cols-2 gap-2">- <label className="block">- <FieldLabel>{t("onboarding.rehaul.provider.clientId")}</FieldLabel>- <Input- dir="ltr"- value={draftCortiClientId}- onChange={(event) => setDraftCortiClientId(event.target.value)}- className={inputClass}- autoComplete="off"- />- </label>- <label className="block">- <FieldLabel>{t("onboarding.rehaul.provider.clientSecret")}</FieldLabel>- <Input- dir="ltr"- type="password"- value={draftCortiClientSecret}- onChange={(event) => setDraftCortiClientSecret(event.target.value)}- className={inputClass}- autoComplete="off"- />- </label>- </div>- ) : (- <label className="block">- <FieldLabel>{t("onboarding.rehaul.provider.apiKey")}</FieldLabel>- <Input- dir="ltr"+ <ProviderCheckField+ label={t("onboarding.rehaul.provider.clientId")}+ value={draftCortiClientId}+ onChange={(event) => setDraftCortiClientId(event.target.value)}+ autoComplete="off"+ />+ <ProviderCheckField+ label={t("onboarding.rehaul.provider.clientSecret")}+ check={check}+ invalidOn="credentialsRejected"type="password"- value={draftApiKey}- onChange={(event) => setDraftApiKey(event.target.value)}- placeholder={t("onboarding.rehaul.provider.apiKeyPlaceholder")}- disabled={!selectedProvider}+ value={draftCortiClientSecret}+ onChange={(event) => setDraftCortiClientSecret(event.target.value)}autoComplete="off"- spellCheck={false}- className={inputClass}/>- </label>+ </div>+ ) : (+ <ProviderCheckField+ label={t("onboarding.rehaul.provider.apiKey")}+ check={check}+ invalidOn="credentialsRejected"+ type="password"+ value={draftApiKey}+ onChange={(event) => setDraftApiKey(event.target.value)}+ placeholder={t("onboarding.rehaul.provider.apiKeyPlaceholder")}+ disabled={!selectedProvider}+ autoComplete="off"+ spellCheck={false}+ />)}</>)}- {/* Keyed per step+provider only; baseUrl/model changes reset through the- component's config effect instead of a remount, which used to run on- every keystroke in the self-hosted URL and model inputs. */}- <ProviderConnectionTest- key={`${stepId}:${testingProvider}`}- config={{- scope: assistant ? "reasoning" : "transcription",- provider: testingProvider,- apiKey: testingKey,- baseUrl: testingBaseUrl,- model: selfHosted ? draftCustomModel : selectedModel,- clientId: isCortiTranscription ? draftCortiClientId : undefined,- clientSecret: isCortiTranscription ? draftCortiClientSecret : undefined,- environment: store.cortiEnvironment,- tenant: store.cortiTenant,- }}- onSuccessChange={handleConnected}- variant="inline"- />-- <StepPrimaryAction- onClick={commitAndProceed}- disabled={!connected || !fieldsReady}- className="mt-4! w-full focus-visible:ring-0 focus-visible:ring-offset-0"- >+ <StepPrimaryAction onClick={commitAndProceed} disabled={!usable} className="mt-4! w-full">{t("onboarding.rehaul.provider.proceed")}</StepPrimaryAction></div>++ <ConnectionCheckAnnouncer announcement={check.announcement} /></section>);}diff --git a/src/components/ui/ApiKeyInput.tsx b/src/components/ui/ApiKeyInput.tsxindex d53c79421..c8ce00bf3 100644--- a/src/components/ui/ApiKeyInput.tsx+++ b/src/components/ui/ApiKeyInput.tsx@@ -2,6 +2,7 @@ import React, { useState, useEffect, useRef, useCallback } from "react";import { useTranslation } from "react-i18next";import { Check, X, KeyRound } from "../icons";import { Input } from "./input";+import { maskKey } from "../../utils/maskKey";import logger from "../../utils/logger";interface ApiKeyInputProps {@@ -15,11 +16,6 @@ interface ApiKeyInputProps {variant?: "default" | "purple";}-function maskKey(key: string): string {- if (key.length <= 8) return "••••••••";- return key.slice(0, 3) + "..." + key.slice(-4);-}-export default function ApiKeyInput({apiKey,setApiKey,diff --git a/src/components/ui/ConnectionCheckAnnouncer.tsx b/src/components/ui/ConnectionCheckAnnouncer.tsxnew file mode 100644index 000000000..6b68531b0--- /dev/null+++ b/src/components/ui/ConnectionCheckAnnouncer.tsx@@ -0,0 +1,24 @@+import { useTranslation } from "react-i18next";+import type { ConnectionAutoCheck } from "../../hooks/useConnectionAutoCheck";++/**+ * The voice of an automatic connection check, in a Settings panel or the onboarding+ * provider step: "Testing…" for a slow request, "Connected" once per result. It mounts with+ * its panel or step, so the region exists before it speaks, and a panel that TabPanel hides+ * is out of the accessibility tree. In a space-y column, render it first, where a last child+ * would add a margin under the column.+ */+export function ConnectionCheckAnnouncer({+ announcement,+}: Pick<ConnectionAutoCheck, "announcement">) {+ const { t } = useTranslation();+ return (+ <div role="status" aria-live="polite" aria-atomic="true" className="sr-only">+ {announcement === "connected"+ ? t("onboarding.rehaul.provider.connected")+ : announcement === "testing"+ ? t("onboarding.rehaul.provider.testing")+ : ""}+ </div>+ );+}diff --git a/src/components/ui/ConnectionStatusIcon.tsx b/src/components/ui/ConnectionStatusIcon.tsxnew file mode 100644index 000000000..555fe200b--- /dev/null+++ b/src/components/ui/ConnectionStatusIcon.tsx@@ -0,0 +1,34 @@+import "../../styles/connection-status-icon.css";+import { cn } from "../lib/utils";++type ConnectionStatusIconState = "checking" | "connected" | "unverified" | "failed";++/**+ * The status of a field that checks itself: a spinning arc while checking, which closes+ * into a tick on success or a ring with "!" on failure (amber when unverified). One SVG+ * changes state in place so the change animates. Decorative: the state must also be given+ * in text.+ */+export function ConnectionStatusIcon({+ state,+ className,+}: {+ state: ConnectionStatusIconState;+ className?: string;+}) {+ return (+ <svg+ viewBox="0 0 24 24"+ aria-hidden="true"+ data-state={state}+ className={cn("connection-status-icon", className)}+ >+ <g className="connection-status-icon-spin">+ <circle className="connection-status-icon-ring" cx="12" cy="12" r="9" pathLength={100} />+ </g>+ <path className="connection-status-icon-tick" d="M6.8 12.6l3.4 3.4 7-7.4" pathLength={100} />+ <path className="connection-status-icon-bang" d="M12 7.6v5.2" pathLength={100} />+ <circle className="connection-status-icon-dot" cx="12" cy="16.3" r="1.25" />+ </svg>+ );+}diff --git a/src/components/ui/ProviderCheckField.tsx b/src/components/ui/ProviderCheckField.tsxnew file mode 100644index 000000000..b00d91d20--- /dev/null+++ b/src/components/ui/ProviderCheckField.tsx@@ -0,0 +1,173 @@+import { useId, useRef, useState, type ComponentProps, type ReactNode } from "react";+import { useTranslation } from "react-i18next";+import type {+ ConnectionAutoCheck,+ ProviderConnectionResult,+} from "../../hooks/useConnectionAutoCheck";+import { isWindowSwitchBlur } from "../../hooks/useFocusHold";+import { maskKey } from "../../utils/maskKey";+import { cn } from "../lib/utils";+import { ConnectionStatusIcon } from "./ConnectionStatusIcon";+import { Input } from "./input";++export function FieldLabel({ children }: { children: ReactNode }) {+ return (+ <span className="mb-1.5 block text-xs text-[var(--onboarding-text-tertiary)]">{children}</span>+ );+}++// Onboarding's provider field, wherever it is used. Outside onboarding its colour names+// fall back to the app theme (.onboarding-provider-input in index.css).+const FIELD_CLASS =+ "onboarding-provider-input h-9 rounded-xl! border px-3 text-xs shadow-none! focus:ring-2 focus:ring-[color-mix(in_srgb,var(--onboarding-accent,var(--color-primary))_15%,transparent)]";++type ProviderCheckFieldProps = Omit<+ ComponentProps<typeof Input>,+ "dir" | "aria-invalid" | "aria-describedby" | "aria-label" | "ref"+> &+ // Onboarding captions the field itself; Settings names it after the heading above it.+ ({ label: string; "aria-label"?: never } | { label?: never; "aria-label": string }) & {+ /** The automatic check whose status this field carries; most fields carry none. */+ check?: Pick<ConnectionAutoCheck, "phase" | "failure" | "retry">;+ /**+ * Replaces the default reason for a refusal the value is not to blame for, such as a+ * server that refused a check sent without a key. The field is then not marked invalid.+ */+ failureReason?: string;+ /**+ * The failure that says this field's value is wrong: a refused key for a key or secret, a+ * missing model for a Model ID. Any other failure leaves the value valid. Omitted for a+ * field no failure can prove wrong, such as a server address.+ */+ invalidOn?: "credentialsRejected" | "modelNotFound";+ };++/**+ * The app's field for a credential. A saved secret shows its first and last characters+ * until it is focused, and focusing it selects all of it, so a paste replaces it. With a+ * check, the status sits at the field's end, and the reason for a failure or for no verdict,+ * with Retry, under it.+ */+export function ProviderCheckField({+ label,+ check,+ failureReason,+ invalidOn,+ className,+ onFocus,+ onBlur,+ ...inputProps+}: ProviderCheckFieldProps) {+ const { t } = useTranslation();+ const reasonId = useId();+ const [focused, setFocused] = useState(false);+ const inputRef = useRef<HTMLInputElement>(null);+ const phase = check?.phase ?? "idle";+ const failure = check?.failure ?? null;+ const secret = inputProps.type === "password";+ const value = String(inputProps.value ?? "");+ const masked = secret && value !== "" && !focused;+ const describe = (result: ProviderConnectionResult) =>+ result.errorCode+ ? t(`onboarding.rehaul.provider.errors.${result.errorCode}`, {+ status: result.status,+ defaultValue: result.error ?? t("onboarding.rehaul.provider.connectionFailed"),+ })+ : (result.error ?? t("onboarding.rehaul.provider.connectionFailed"));++ // The value reads left to right in every language, so its status sits at the field's end.+ const field = (+ <span dir="ltr" className="relative block">+ <Input+ dir="ltr"+ {...inputProps}+ ref={inputRef}+ onFocus={(event) => {+ // Regaining focus after a window switch keeps the caret where it was.+ if (secret && !focused) event.currentTarget.select();+ setFocused(true);+ onFocus?.(event);+ }}+ onBlur={(event) => {+ if (!isWindowSwitchBlur(event)) setFocused(false);+ onBlur?.(event);+ }}+ aria-invalid={+ !failureReason && invalidOn && failure?.errorCode === invalidOn ? true : undefined+ }+ aria-describedby={check ? reasonId : undefined}+ className={cn(+ FIELD_CLASS,+ className,+ phase !== "idle" && "pe-9",+ masked && "text-transparent!"+ )}+ />+ {masked && (+ <span+ aria-hidden="true"+ className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 font-mono text-xs tracking-wide text-[var(--onboarding-text-primary,var(--color-foreground))] opacity-70"+ >+ {maskKey(value)}+ </span>+ )}+ {phase !== "idle" && (+ <ConnectionStatusIcon+ state={phase === "waiting" ? "checking" : phase}+ className="pointer-events-none absolute end-2.5 top-1/2 -translate-y-1/2"+ />+ )}+ </span>+ );++ return (+ <div>+ {label ? (+ <label className="block">+ <FieldLabel>{label}</FieldLabel>+ {field}+ </label>+ ) : (+ field+ )}+ {check && (+ <p+ className={+ failure+ ? cn(+ "mt-1 px-1 text-xs leading-[1.4]",+ // Amber text needs the darker shade to stay readable on white.+ phase === "unverified" ? "text-amber-700 dark:text-amber-300" : "text-destructive"+ )+ : undefined+ }+ >+ <span id={reasonId} role="alert">+ {failure &&+ (phase === "unverified"+ ? t("onboarding.rehaul.provider.unverified", {+ reason: failureReason ?? describe(failure),+ })+ : (failureReason ?? describe(failure)))}+ </span>+ {failure && (+ <>+ {" "}+ <button+ type="button"+ // Retry goes away while the check runs, so focus moves to the field first.+ onClick={() => {+ inputRef.current?.focus();+ check.retry();+ }}+ className="font-medium underline underline-offset-2 hover:opacity-70"+ >+ {t("common.retry")}+ </button>+ </>+ )}+ </p>+ )}+ </div>+ );+}diff --git a/src/components/ui/TabPanel.tsx b/src/components/ui/TabPanel.tsxnew file mode 100644index 000000000..bbdb5e9c5--- /dev/null+++ b/src/components/ui/TabPanel.tsx@@ -0,0 +1,16 @@+import type { ReactNode } from "react";+import { PanelVisibleProvider, usePanelVisible } from "./usePanelVisible";++/**+ * Keeps an inactive tab mounted but hidden, and tells what it holds whether it is shown,+ * so a hidden panel's checks wait. A tab is shown only while every TabPanel around it is+ * active.+ */+export function TabPanel({ active, children }: { active: boolean; children: ReactNode }) {+ const shown = usePanelVisible() && active;+ return (+ <div className={active ? undefined : "hidden"}>+ <PanelVisibleProvider value={shown}>{children}</PanelVisibleProvider>+ </div>+ );+}diff --git a/src/components/ui/usePanelVisible.ts b/src/components/ui/usePanelVisible.tsnew file mode 100644index 000000000..6a304caa2--- /dev/null+++ b/src/components/ui/usePanelVisible.ts@@ -0,0 +1,8 @@+import React from "react";++// False inside a TabPanel that is mounted but hidden; anything outside a TabPanel is shown.+const PanelVisibleContext = React.createContext(true);++export const PanelVisibleProvider = PanelVisibleContext.Provider;++export const usePanelVisible = () => React.useContext(PanelVisibleContext);diff --git a/src/helpers/connectionCheckCache.js b/src/helpers/connectionCheckCache.jsnew file mode 100644index 000000000..0a097ba86--- /dev/null+++ b/src/helpers/connectionCheckCache.js@@ -0,0 +1,52 @@+const crypto = require("crypto");++// Settings keeps up to nine panels loaded, and several can show the same credentials.+// Identical checks share one request while it runs, and a Connected answer is reused for+// ten minutes. A failure is never reused, so the next ask, Retry included, reaches the+// provider again.+const CONNECTED_TTL_MS = 10 * 60 * 1000;+const CHECK_FIELDS = [+ "scope",+ "provider",+ "apiKey",+ "baseUrl",+ "model",+ "clientId",+ "clientSecret",+ "environment",+ "tenant",+];++// Everything that decides a check's answer. Only this digest is kept, never a credential.+function checkKey(config) {+ return crypto+ .createHash("sha256")+ .update(JSON.stringify(CHECK_FIELDS.map((field) => config?.[field] ?? null)))+ .digest("hex");+}++function createConnectionCheckCache({ ttlMs = CONNECTED_TTL_MS, now = Date.now } = {}) {+ const inFlight = new Map();+ const connectedUntil = new Map();+ return function cachedCheck(config, check) {+ const key = checkKey(config);+ if (now() < (connectedUntil.get(key) ?? 0)) return Promise.resolve({ success: true });+ connectedUntil.delete(key);+ let running = inFlight.get(key);+ if (!running) {+ // Started a microtask later, so even a check that throws at once is stored first and+ // removed when it settles.+ running = Promise.resolve()+ .then(check)+ .then((result) => {+ if (result?.success) connectedUntil.set(key, now() + ttlMs);+ return result;+ })+ .finally(() => inFlight.delete(key));+ inFlight.set(key, running);+ }+ return running;+ };+}++module.exports = { CONNECTED_TTL_MS, createConnectionCheckCache };diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 402230809..9a072ab62 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -238,7 +238,9 @@ const CONNECTION_TEST_MAX_OUTPUT_TOKENS = 16;const CLOUD_CHUNK_SEGMENT_SECONDS = 240;const { createAbortError } = require("./abortError");-const { testProviderConnection } = require("./providerConnectionTest");+const { describeCortiTokenFailure, testProviderConnection } = require("./providerConnectionTest");+const { createConnectionCheckCache } = require("./connectionCheckCache");+const { PAID_KEY_CHECKS_FILE, createPaidKeyCheck } = require("./paidKeyCheck");const { createUploadCancelRegistry } = require("./uploadCancelRegistry");const { applyOpenWhisprOriginHeader } = require("./sessionHeaders");const {@@ -1630,7 +1632,12 @@ class IPCHandlers {return true;});- ipcMain.handle("test-provider-connection", async (_event, config) => {+ // Every panel showing the same credentials and model shares one answer.+ const cachedConnectionCheck = createConnectionCheckCache();+ const runPaidKeyCheck = createPaidKeyCheck(() =>+ path.join(app.getPath("userData"), PAID_KEY_CHECKS_FILE)+ );+ const checkProviderConnection = async (config) => {if (config?.provider === "corti" && config?.scope === "transcription") {try {const clientId = String(config.clientId || "").trim();@@ -1650,35 +1657,14 @@ class IPCHandlers {}return { success: true };} catch (error) {- // errorCode is the machine-readable field the renderer maps to i18n;- // the English string stays for logs/back-compat. Only a response- // Corti actually sent counts as a rejection (getCortiToken prefixes- // those); a fetch that never reached it is a network problem, and- // reporting it as "credentials rejected" sends the user to re-type a- // key that was never the issue.- if (error?.name === "AbortError") {- return {- success: false,- errorCode: "timeout",- error: "The connection test timed out.",- };- }- if (!/^(Corti authentication failed|Invalid Corti)/.test(error?.message || "")) {- return {- success: false,- errorCode: "network",- error: "The provider could not be reached.",- };- }- return {- success: false,- errorCode: "credentialsRejected",- error: "Corti rejected these credentials.",- };+ return describeCortiTokenFailure(error);}}- return testProviderConnection(config);- });+ return testProviderConnection(config, fetch, runPaidKeyCheck);+ };+ ipcMain.handle("test-provider-connection", (_event, config) =>+ cachedConnectionCheck(config, () => checkProviderConnection(config))+ );ipcMain.handle("window-minimize", () => {if (this.windowManager.controlPanelWindow) {@@ -4393,6 +4379,7 @@ class IPCHandlers {"globe-preference-state.json",".system-audio-permission","account-scope-binding.json",+ PAID_KEY_CHECKS_FILE,]) {fs.rmSync(path.join(app.getPath("userData"), fileName), { force: true });}diff --git a/src/helpers/paidKeyCheck.js b/src/helpers/paidKeyCheck.jsnew file mode 100644index 000000000..9a6751850--- /dev/null+++ b/src/helpers/paidKeyCheck.js@@ -0,0 +1,56 @@+const crypto = require("crypto");+const fs = require("fs");++// In userData; Reset app data deletes it.+const PAID_KEY_CHECKS_FILE = "paid-key-checks.json";++// A key is a secret, so it is stored through a password hash; a long random key needs only a+// light one.+const digestOf = (key) =>+ crypto.scryptSync(key, "openwhispr-paid-key-check", 32, { N: 1024 }).toString("hex");++// A key check that spends the user's credits runs once per key. A key that passed is+// remembered by its digest, never the key itself, so showing a panel again or restarting the+// app costs nothing. Checks for the same key share one request while it runs, and a key that+// did not pass is asked about again next time. `filePath` returns where the digests live.+function createPaidKeyCheck(filePath) {+ const inFlight = new Map();+ let passed = null;+ const passedDigests = () => {+ if (!passed) {+ try {+ const stored = JSON.parse(fs.readFileSync(filePath(), "utf8")).passed;+ passed = new Set(Array.isArray(stored) ? stored : []);+ } catch {+ passed = new Set();+ }+ }+ return passed;+ };++ return function runPaidCheck(key, check) {+ const digest = digestOf(key);+ if (passedDigests().has(digest)) return Promise.resolve({ success: true });+ let running = inFlight.get(digest);+ if (!running) {+ running = Promise.resolve()+ .then(check)+ .then((result) => {+ if (result?.success) {+ passedDigests().add(digest);+ try {+ fs.writeFileSync(filePath(), JSON.stringify({ passed: [...passedDigests()] }));+ } catch {+ // Best effort: the key stays remembered until the app quits.+ }+ }+ return result;+ })+ .finally(() => inFlight.delete(digest));+ inFlight.set(digest, running);+ }+ return running;+ };+}++module.exports = { PAID_KEY_CHECKS_FILE, createPaidKeyCheck };diff --git a/src/helpers/providerConnectionTest.js b/src/helpers/providerConnectionTest.jsindex c014db101..c5b9d050b 100644--- a/src/helpers/providerConnectionTest.js+++ b/src/helpers/providerConnectionTest.js@@ -3,19 +3,25 @@ const ENDPOINTS = {groq: "https://api.groq.com/openai/v1/models",xai: "https://api.x.ai/v1/models",mistral: "https://api.mistral.ai/v1/models",- anthropic: "https://api.anthropic.com/v1/models",- gemini: "https://generativelanguage.googleapis.com/v1beta/models",- openrouter: "https://openrouter.ai/api/v1/models",+ // The largest page each API allows, so a valid but older model is still listed.+ anthropic: "https://api.anthropic.com/v1/models?limit=1000",+ gemini: "https://generativelanguage.googleapis.com/v1beta/models?pageSize=1000",+ // OpenRouter's model list is public, so it cannot vouch for a key. The key route+ // describes the key that calls it.+ openrouter: "https://openrouter.ai/api/v1/key",corti: "https://ai.eu.corti.app/v1/models",+ // Public too, so it vouches only for the model; testTinfoilKey checks the key.tinfoil: "https://inference.tinfoil.sh/v1/models",- deepgram: "https://api.deepgram.com/v1/models",+ // Deepgram's model list answers without a key, so it cannot vouch for one. This is+ // Deepgram's documented key check.+ deepgram: "https://api.deepgram.com/v1/auth/token",// AssemblyAI exposes no model list; listing transcripts is its 200-vs-401 probe.assemblyai: "https://api.assemblyai.com/v2/transcript?limit=1",};--// Neither response is OpenAI-shaped — Deepgram's /v1/models is {stt,tts}-keyed-// and AssemblyAI returns transcripts — so a 200 is the whole credential signal.-const MODEL_LIST_UNVERIFIABLE = new Set(["deepgram", "assemblyai"]);+// Listing the key's projects proves the key too: used only if Deepgram retires the route above.+const DEEPGRAM_PROJECTS_ENDPOINT = "https://api.deepgram.com/v1/projects";+// Turns a made-up key away before embedding anything; a valid key pays for one token.+const TINFOIL_KEY_ENDPOINT = "https://inference.tinfoil.sh/v1/embeddings";// Renderers translate errorCode via onboarding.rehaul.provider.errors.*; the// English `error` string stays for logs and older callers.@@ -151,16 +157,34 @@ function buildModelEndpoints(base) {});}+// Where the app sends a custom server's audio: buildApiUrl(normalizeBaseUrl(url),+// "/audio/transcriptions") in src/config/constants.ts and transcriptionRoute.ts.+// buildApiUrl normalises its base again, which strips a suffix a trailing slash hid+// from the first pass, so this address takes the same two passes.+function buildTranscriptionEndpoint(base) {+ const { path, query, hash } = splitUrlDecorators(normalizeBaseUrl(normalizeBaseUrl(base)));+ return joinUrlDecorators(`${path}/audio/transcriptions`, query, hash);+}+function resolveProviderRequest(config) {const provider = String(config?.provider || "").toLowerCase();const apiKey = typeof config?.apiKey === "string" ? config.apiKey.trim() : "";let endpoints = ENDPOINTS[provider] ? [ENDPOINTS[provider]] : [];+ // A hosted provider's fixed endpoint never redirects. Following one would carry+ // x-api-key or x-goog-api-key to whichever host it names (fetch drops only+ // Authorization across origins), so a redirect fails the check instead. Custom+ // servers may redirect within themselves, such as adding a trailing slash.+ let redirect = "error";+ let transcriptionEndpoint;if (provider === "openai") {const override = normalizeBaseUrl(process.env.OPENWHISPR_OPENAI_BASE_URL || process.env.OPENAI_BASE_URL);- if (override) endpoints = buildModelEndpoints(override);+ if (override) {+ endpoints = buildModelEndpoints(override);+ redirect = "follow";+ }}if (provider === "custom") {@@ -184,6 +208,8 @@ function resolveProviderRequest(config) {);}endpoints = buildModelEndpoints(parsed.toString());+ transcriptionEndpoint = buildTranscriptionEndpoint(parsed.toString());+ redirect = "follow";}if (endpoints.length === 0) {@@ -212,22 +238,32 @@ function resolveProviderRequest(config) {}}- return { endpoint: endpoints[0], endpoints, headers };+ return { endpoint: endpoints[0], endpoints, headers, redirect, transcriptionEndpoint };}-// When several candidate endpoints fail, report the most actionable failure.+// When several candidate endpoints fail, report the most actionable failure. An answer that+// faults the setup outranks no answer (unverified), so a busy candidate never hides a refused+// key or a missing model. No answer outranks a candidate without a model list, which may only+// be an address the server doesn't use.const FAILURE_PRIORITY = {- credentialsRejected: 4,- providerStatus: 3,- modelNotFound: 2.5,- endpointNotFound: 2,- timeout: 1,- network: 0,+ credentialsRejected: 6,+ providerStatus: 5,+ modelNotFound: 4,+ endpointNotFound: 0,};+const UNVERIFIED_PRIORITY = { providerStatus: 3, timeout: 2, network: 1 };function pickFailure(current, next) {if (!current) return next;- return FAILURE_PRIORITY[next.errorCode] > FAILURE_PRIORITY[current.errorCode] ? next : current;+ const rank = (failure) =>+ (failure.unverified ? UNVERIFIED_PRIORITY : FAILURE_PRIORITY)[failure.errorCode];+ return rank(next) > rank(current) ? next : current;+}++// A provider that is slow, busy or down gives no verdict on the credentials. Such a failure is+// marked unverified: the app may go ahead with them, and only a later check can tell.+function isUnverifiedStatus(status) {+ return status === 408 || status === 429 || status >= 500;}function describeStatusFailure(status, provider) {@@ -245,7 +281,64 @@ function describeStatusFailure(status, provider) {status,};}- return { errorCode: "providerStatus", error: `The provider returned status ${status}.`, status };+ const failure = {+ errorCode: "providerStatus",+ error: `The provider returned status ${status}.`,+ status,+ };+ return isUnverifiedStatus(status) ? { ...failure, unverified: true } : failure;+}++const MODEL_NOT_FOUND = {+ errorCode: "modelNotFound",+ error: "The selected model is not available from this provider.",+};+const TIMEOUT_FAILURE = {+ errorCode: "timeout",+ error: "The connection test timed out.",+ unverified: true,+};+const NETWORK_FAILURE = {+ errorCode: "network",+ error: "The provider could not be reached.",+ unverified: true,+};++// An empty or non-JSON body reads as undefined. A body that never arrives (the 12 s cap+// firing, a dropped connection) is not an answer, so its error goes on to probe's catch.+async function readJson(response) {+ try {+ return await response.json();+ } catch (error) {+ if (error instanceof SyntaxError) return undefined;+ throw error;+ }+}++// Gemini, xAI and Corti answer a made-up key with a 400, which on its own can also+// mean a malformed request. Their error bodies say which it was.+const KEY_REJECTED_BY_BODY = {+ gemini: (_, body) =>+ Array.isArray(body?.error?.details) &&+ body.error.details.some((detail) => detail?.reason === "API_KEY_INVALID"),+ xai: (status, body) =>+ status === 400 && typeof body?.error === "string" && /incorrect api key/i.test(body.error),+ // Corti's gateway turns an unknown key away before routing, with no body at all.+ corti: (status, body) => status === 400 && body === undefined,+};++async function describeResponseFailure(response, provider) {+ const failure = describeStatusFailure(response.status, provider);+ const keyRejected = KEY_REJECTED_BY_BODY[provider];+ // A 401 or 403 already says the key was refused; only a vaguer status needs the body.+ if (+ failure.errorCode !== "credentialsRejected" &&+ keyRejected &&+ keyRejected(response.status, await readJson(response))+ ) {+ return { ...describeStatusFailure(401, provider), status: response.status };+ }+ return failure;}function normalizeModelId(value) {@@ -269,17 +362,48 @@ function responseModelIds(payload) {.filter(Boolean);}-async function responseOffersModel(response, model) {+// Anthropic resolves an alias (claude-haiku-4-5) to a dated snapshot and lists only the+// snapshot (claude-haiku-4-5-20251001). Other servers match ids exactly.+function isDatedSnapshot(id, model) {+ return id.startsWith(model) && /^-\d{8}$/.test(id.slice(model.length));+}++async function responseOffersModel(response, model, provider) {if (!model) return true;+ const selected = normalizeModelId(model);+ return responseModelIds(await readJson(response)).some(+ (id) => id === selected || (provider === "anthropic" && isDatedSnapshot(id, selected))+ );+}++// One request (a GET unless `init` says otherwise) under the 12 s cap. `judge` reads the+// response inside that window, so a body that stalls cannot hold the check past the cap. It+// returns null when the check passes.+async function probe(endpoint, request, fetchImpl, judge, init = { method: "GET" }) {+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), 12000);try {- const payload = await response.json();- return responseModelIds(payload).includes(normalizeModelId(model));- } catch {- return false;+ const response = await fetchImpl(endpoint, {+ ...init,+ headers: request.headers,+ redirect: request.redirect,+ signal: controller.signal,+ });+ return await judge(response);+ } catch (error) {+ return error?.name === "AbortError" ? TIMEOUT_FAILURE : NETWORK_FAILURE;+ } finally {+ clearTimeout(timeout);}}-async function testProviderConnection(config, fetchImpl = fetch) {+// `runPaidCheck(key, check)` runs a check that spends the user's credits. The main process+// passes one that runs it once per key (paidKeyCheck.js).+async function testProviderConnection(+ config,+ fetchImpl = fetch,+ runPaidCheck = (_key, check) => check()+) {let request;try {request = resolveProviderRequest(config);@@ -292,44 +416,133 @@ async function testProviderConnection(config, fetchImpl = fetch) {}const provider = String(config?.provider || "").toLowerCase();+ if (provider === "deepgram") return testDeepgramKey(request, fetchImpl);+const model = String(config?.model || "").trim();let failure = null;+ let everyListMissing = true;for (const endpoint of request.endpoints) {- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), 12000);- try {- const response = await fetchImpl(endpoint, {- method: "GET",- headers: request.headers,- signal: controller.signal,- });- if (response.ok) {- if (MODEL_LIST_UNVERIFIABLE.has(provider)) return { success: true };- if (await responseOffersModel(response, model)) return { success: true };- failure = pickFailure(failure, {- errorCode: "modelNotFound",- error: "The selected model is not available from this provider.",- });- continue;- }- failure = pickFailure(failure, describeStatusFailure(response.status, provider));- } catch (error) {- if (error?.name === "AbortError") {- failure = pickFailure(failure, {- errorCode: "timeout",- error: "The connection test timed out.",- });- } else {- failure = pickFailure(failure, {- errorCode: "network",- error: "The provider could not be reached.",- });+ const next = await probe(endpoint, request, fetchImpl, async (response) => {+ if (!response.ok) return describeResponseFailure(response, provider);+ if (provider === "openrouter") return describeOpenRouterKey(response);+ // AssemblyAI's probe lists transcripts, not models, so a 200 is the whole signal.+ if (provider === "assemblyai" || (await responseOffersModel(response, model, provider))) {+ return null;}- } finally {- clearTimeout(timeout);+ return MODEL_NOT_FOUND;+ });+ if (!next) {+ return provider === "tinfoil"+ ? testTinfoilKey(request, config.apiKey.trim(), fetchImpl, runPaidCheck)+ : { success: true };}+ everyListMissing = everyListMissing && next.status === 404;+ failure = pickFailure(failure, next);+ }+ if (everyListMissing && provider === "custom" && config?.scope === "transcription") {+ return testTranscriptionEndpoint(request, model, fetchImpl);}return { success: false, ...failure };}-module.exports = { resolveProviderRequest, testProviderConnection };+// OpenRouter's key route describes the key that called it. A management key (formerly a+// provisioning key) only administers other keys and can never run a request. Only a 200+// carries that description; any other 2xx has no key to read, so it keeps its status.+async function describeOpenRouterKey(response) {+ if (response.status !== 200) return describeStatusFailure(response.status, "openrouter");+ const key = (await readJson(response))?.data;+ if (!key?.is_management_key && !key?.is_provisioning_key) return null;+ return { ...describeStatusFailure(401, "openrouter"), status: response.status };+}++// A speech-only server may publish no model list. Its transcription address answers a+// request that carries no audio with 400 or 422, which proves the address without+// transcribing anything. The model is not checked.+async function testTranscriptionEndpoint(request, model, fetchImpl) {+ const body = new FormData();+ body.append("model", model);+ const failure = await probe(+ request.transcriptionEndpoint,+ request,+ fetchImpl,+ async (response) => {+ if (response.status === 400 || response.status === 422) return null;+ // Nothing takes transcriptions at this address.+ if (response.status === 404 || response.status === 405) {+ return {+ errorCode: "transcriptionEndpointNotFound",+ error: "Nothing takes transcriptions at this address.",+ status: response.status,+ };+ }+ return describeStatusFailure(response.status, "custom");+ },+ { method: "POST", body }+ );+ return failure ? { success: false, ...failure } : { success: true };+}++// Deepgram is checked by key alone, since its model names don't match the app's model ids.+// A 404 means the key route was retired, not that the key is wrong, so the project list+// stands in.+async function testDeepgramKey(request, fetchImpl) {+ let retired = false;+ const failure = await probe(request.endpoint, request, fetchImpl, async (response) => {+ if (response.ok) return null;+ retired = response.status === 404;+ return describeStatusFailure(response.status, "deepgram");+ });+ if (!retired) return failure ? { success: false, ...failure } : { success: true };+ const fallback = await probe(DEEPGRAM_PROJECTS_ENDPOINT, request, fetchImpl, async (response) => {+ if (!response.ok) return describeStatusFailure(response.status, "deepgram");+ // No errorCode: the step shows its generic "could not be verified".+ return Array.isArray((await readJson(response))?.projects) ? null : {};+ });+ return fallback ? { success: false, ...fallback } : { success: true };+}++// Runs once Tinfoil's public model list has vouched for the model. A valid key pays for one+// embedded token, hence runPaidCheck. A 404 means this check's own model was retired, which+// says nothing about the key.+function testTinfoilKey(request, apiKey, fetchImpl, runPaidCheck) {+ const jsonRequest = {+ ...request,+ headers: { ...request.headers, "Content-Type": "application/json" },+ };+ return runPaidCheck(apiKey, async () => {+ const failure = await probe(+ TINFOIL_KEY_ENDPOINT,+ jsonRequest,+ fetchImpl,+ async (response) => {+ if (response.ok) return null;+ const statusFailure = describeStatusFailure(response.status, "tinfoil");+ return response.status === 404 ? { ...statusFailure, unverified: true } : statusFailure;+ },+ { method: "POST", body: JSON.stringify({ model: "nomic-embed-text", input: "." }) }+ );+ return failure ? { success: false, ...failure } : { success: true };+ });+}++// Corti's speech credentials are exchanged for a token (cortiAuth.js). Only an answer from+// Corti can refuse them, and getCortiToken prefixes those errors and attaches the status. A+// token request that never reached Corti, or found it busy or down, gives no verdict, and+// reporting it as "credentials rejected" sends the user to re-type a key that was never the+// issue.+function describeCortiTokenFailure(error) {+ if (error?.name === "AbortError") return { success: false, ...TIMEOUT_FAILURE };+ if (!/^(Corti authentication failed|Invalid Corti)/.test(error?.message || "")) {+ return { success: false, ...NETWORK_FAILURE };+ }+ if (isUnverifiedStatus(error.status)) {+ return { success: false, ...describeStatusFailure(error.status, "corti") };+ }+ return {+ success: false,+ errorCode: "credentialsRejected",+ error: "Corti rejected these credentials.",+ };+}++module.exports = { describeCortiTokenFailure, resolveProviderRequest, testProviderConnection };diff --git a/src/hooks/useConnectionAutoCheck.ts b/src/hooks/useConnectionAutoCheck.tsnew file mode 100644index 000000000..01a74d4e5--- /dev/null+++ b/src/hooks/useConnectionAutoCheck.ts@@ -0,0 +1,116 @@+import { useCallback, useEffect, useRef, useState } from "react";+import { useDelayedFlag } from "./useDelayedFlag";++type TestProviderConnection = NonNullable<Window["electronAPI"]["testProviderConnection"]>;+export type ProviderConnectionConfig = Parameters<TestProviderConnection>[0];+export type ProviderConnectionResult = Awaited<ReturnType<TestProviderConnection>>;+/**+ * "waiting": the pause runs and nothing is sent; "checking": a request is out; "unverified":+ * the provider gave no verdict, so the entry may be used but is not known to work.+ */+type ConnectionCheckPhase = "idle" | "waiting" | "checking" | "connected" | "unverified" | "failed";++export interface ConnectionAutoCheck {+ phase: ConnectionCheckPhase;+ /** The answer while phase is "failed" or "unverified". */+ failure: ProviderConnectionResult | null;+ /** Re-sends the current entry at once. */+ retry: () => void;+ /** For one polite live region. */+ announcement: "testing" | "connected" | null;+}++/** The quiet time after the last change before the request is sent; a paste is one change. */+export const CONNECTION_CHECK_DELAY_MS = 500;+/**+ * "Testing…" is announced only for a request still out after this long, so quick answers+ * don't chatter.+ */+const CONNECTION_CHECK_ANNOUNCE_DELAY_MS = 1000;++interface ConnectionAutoCheckOptions {+ config: ProviderConnectionConfig;+ /** Every required field is filled. */+ ready: boolean;+ /** Send nothing yet, e.g. while an address is still being typed. */+ hold?: boolean;+ /** Defaults to CONNECTION_CHECK_DELAY_MS; 0 checks at once. */+ delayMs?: number;+}++/**+ * Checks a provider connection by itself, once `config` has gone `delayMs` without a change.+ * Every change starts over, and an answer for an earlier entry is never shown.+ */+export function useConnectionAutoCheck({+ config,+ ready,+ hold = false,+ delayMs = CONNECTION_CHECK_DELAY_MS,+}: ConnectionAutoCheckOptions): ConnectionAutoCheck {+ // Any change, even one back to an earlier value or one that empties a field, starts a new+ // revision. An answer is shown only for the revision it was sent for.+ const configKey = JSON.stringify(config);+ const [tracked, setTracked] = useState({ configKey, ready, revision: 0 });+ if (tracked.configKey !== configKey || tracked.ready !== ready) {+ setTracked({ configKey, ready, revision: tracked.revision + 1 });+ }+ const { revision } = tracked;+ const [inFlight, setInFlight] = useState<number | null>(null);+ const [outcome, setOutcome] = useState<{+ revision: number;+ result: ProviderConnectionResult;+ } | null>(null);+ const latest = useRef({ config, revision });+ useEffect(() => {+ latest.current = { config, revision };+ });++ const send = useCallback(async (sentRevision: number) => {+ setOutcome(null);+ setInFlight(sentRevision);+ let result: ProviderConnectionResult;+ try {+ result = (await window.electronAPI?.testProviderConnection?.(latest.current.config)) ?? {+ success: false,+ };+ } catch {+ result = { success: false };+ }+ if (sentRevision !== latest.current.revision) return;+ setOutcome({ revision: sentRevision, result });+ setInFlight(null);+ }, []);++ const settled = outcome?.revision === revision ? outcome.result : null;+ const phase: ConnectionCheckPhase = !ready+ ? "idle"+ : settled+ ? settled.success+ ? "connected"+ : settled.unverified+ ? "unverified"+ : "failed"+ : inFlight === revision+ ? "checking"+ : hold+ ? "idle"+ : "waiting";++ useEffect(() => {+ if (phase !== "waiting") return;+ const timer = setTimeout(() => void send(revision), delayMs);+ return () => clearTimeout(timer);+ }, [delayMs, phase, revision, send]);++ const retry = useCallback(() => void send(latest.current.revision), [send]);+ const slow = useDelayedFlag(phase === "checking", CONNECTION_CHECK_ANNOUNCE_DELAY_MS);++ return {+ phase,+ failure: phase === "failed" || phase === "unverified" ? settled : null,+ retry,+ announcement:+ phase === "connected" ? "connected" : phase === "checking" && slow ? "testing" : null,+ };+}diff --git a/src/hooks/useCredentialDraft.ts b/src/hooks/useCredentialDraft.tsnew file mode 100644index 000000000..130262789--- /dev/null+++ b/src/hooks/useCredentialDraft.ts@@ -0,0 +1,126 @@+import { useCallback, useEffect, useRef, useState } from "react";+import type { ConnectionAutoCheck } from "./useConnectionAutoCheck";++type Drafts = Record<string, { value: string; save: (value: string) => void }>;++export interface CredentialCheckReport {+ phase: ConnectionAutoCheck["phase"];+ /** The fields the check's request carries (Corti's region too), with their values. */+ checked: Record<string, string>;+ refused: boolean;+}++const refusalKey = (field: string, request: string, value: string) =>+ JSON.stringify([field, request, value]);++/**+ * Credentials while they are typed. A saved key reaches the main process and every other+ * window, so a panel saves a draft when its field is left (a window switch included) or its+ * check passes; until then it reads the typed value. Each field keeps its own draft.+ *+ * The panel reports its check through `follow`, and an answer settles only drafts that still+ * hold the values the check carried. The fields one check carries are one credential (Corti's+ * ID, secret and tenant): a refusal holds back every typed value it carried, and while any of+ * them is refused none of the credential is saved, until a check of it passes. A field left+ * while its check runs waits for the answer; if the check stops carrying it first (another+ * provider, a hidden panel), no answer is coming, so it is saved as it stands. Closing+ * Settings saves whatever wasn't refused.+ */+export function useCredentialDraft() {+ const [drafts, setDrafts] = useState<Drafts>({});+ // Kept in step with every change and save, ahead of the render that shows them.+ const latest = useRef(drafts);+ const refusals = useRef(new Set<string>());+ // Each field's last answered request and the one it makes now: a value refused in either is+ // held back.+ const answered = useRef<Record<string, string>>({});+ const asking = useRef<Record<string, string>>({});+ // The fields each field was last checked with: one credential.+ const groups = useRef<Record<string, readonly string[]>>({});+ const left = useRef(new Set<string>());+ const carried = useRef<readonly string[]>([]);+ const pending = useRef(false);+ const editing = useRef<string | null>(null);++ // Saves the drafts of `fields`, except those of a credential with a refused draft. With+ // `values`, only drafts that still hold the value an answer was for.+ const settle = useCallback((fields: readonly string[], values?: Record<string, string>) => {+ const refused = (field: string) => {+ const draft = latest.current[field];+ return (+ Boolean(draft) &&+ [answered.current[field], asking.current[field]].some(+ (request) =>+ request !== undefined && refusals.current.has(refusalKey(field, request, draft.value))+ )+ );+ };+ const saved = new Set<Drafts[string]>();+ for (const field of fields) {+ const draft = latest.current[field];+ if (!draft || (values && draft.value !== values[field])) continue;+ if ((groups.current[field] ?? [field]).some(refused)) continue;+ draft.save(draft.value);+ saved.add(draft);+ left.current.delete(field);+ }+ if (saved.size === 0) return;+ const keep = (current: Drafts) =>+ Object.fromEntries(Object.entries(current).filter(([, draft]) => !saved.has(draft)));+ latest.current = keep(latest.current);+ setDrafts(keep);+ }, []);++ // Unmounting fires no blur, as when Escape closes Settings.+ useEffect(() => () => settle(Object.keys(latest.current)), [settle]);++ const save = useCallback(() => {+ const field = editing.current;+ // The field typed in last may have been saved since; leaving it again marks nothing.+ if (!field || !latest.current[field]) return;+ left.current.add(field);+ if (!(pending.current && carried.current.includes(field))) settle([field]);+ }, [settle]);++ const follow = useCallback(+ ({ phase, checked, refused }: CredentialCheckReport) => {+ const now = phase === "idle" ? [] : Object.keys(checked);+ const dropped = carried.current.filter((field) => !now.includes(field));+ carried.current = now;+ const request = JSON.stringify(checked);+ for (const field of now) {+ asking.current[field] = request;+ groups.current[field] = now;+ }+ pending.current = phase === "waiting" || phase === "checking";+ settle(dropped.filter((field) => left.current.has(field)));+ if (pending.current || phase === "idle") return;+ for (const field of now) {+ answered.current[field] = request;+ const key = refusalKey(field, request, checked[field]);+ if (refused && checked[field] && latest.current[field]?.value === checked[field]) {+ refusals.current.add(key);+ } else if (phase === "connected") {+ refusals.current.delete(key);+ }+ }+ // A pass saves every field it carried; any other answer saves them once one was left.+ const leftOne = now.some((field) => left.current.has(field));+ settle(phase === "connected" || leftOne ? now : [], checked);+ },+ [settle]+ );++ return {+ value: (field: string, saved: string) => drafts[field]?.value ?? saved,+ change: (field: string, value: string, save: (value: string) => void) => {+ editing.current = field;+ left.current.delete(field);+ const draft = { value, save };+ latest.current = { ...latest.current, [field]: draft };+ setDrafts((current) => ({ ...current, [field]: draft }));+ },+ save,+ follow,+ };+}diff --git a/src/hooks/useFocusHold.ts b/src/hooks/useFocusHold.tsnew file mode 100644index 000000000..a66f2849c--- /dev/null+++ b/src/hooks/useFocusHold.ts@@ -0,0 +1,29 @@+import { useState, type FocusEvent } from "react";++/**+ * True when a blur only means the window lost focus: the page's focus is still inside the+ * element, and the user is coming back to it.+ */+export function isWindowSwitchBlur(event: FocusEvent<HTMLElement>) {+ const element = event.currentTarget;+ return element.contains(element.ownerDocument.activeElement);+}++/**+ * Held from the moment focus enters an element until it really leaves. A window switch+ * keeps it, and so does focus moving to another field inside the element, so one hold can+ * cover a group of fields. Settings uses it to hold a half-typed server address, and to+ * keep the check's pause only while credentials are being typed.+ */+export function useFocusHold() {+ const [held, setHeld] = useState(false);+ return {+ held,+ onFocus: () => setHeld(true),+ onBlur: (event: FocusEvent<HTMLElement>) => {+ if (isWindowSwitchBlur(event)) return;+ if (event.currentTarget.contains(event.relatedTarget)) return;+ setHeld(false);+ },+ };+}diff --git a/src/hooks/useTypingPause.ts b/src/hooks/useTypingPause.tsnew file mode 100644index 000000000..9683b070b--- /dev/null+++ b/src/hooks/useTypingPause.ts@@ -0,0 +1,38 @@+import { useState } from "react";+import { CONNECTION_CHECK_DELAY_MS } from "./useConnectionAutoCheck";++export interface TypingPauseInputs {+ /** The credential strings a user types for this check. */+ typed: string;+ /** Everything else the check depends on, as one string (e.g. a JSON array). */+ context: string;+ /** Focus is inside the panel's credential fields. */+ held: boolean;+}++/**+ * The pause before a panel's check. A change to a typed credential waits+ * CONNECTION_CHECK_DELAY_MS, wherever it was typed: hosted keys are shared, so another shown+ * panel may be typing this one's key. Leaving the panel's fields, showing the panel, or any+ * other change to the check (a tab, a model, a region) checks at once.+ */+export function useTypingPause({ typed, context, held }: TypingPauseInputs): number {+ const [tracked, setTracked] = useState({ typed, context, held, pause: false });+ if (tracked.typed !== typed || tracked.context !== context || tracked.held !== held) {+ // A context change wins over a typed change in the same render: a tab switch shows+ // another provider's key, which is not being typed. So does the hold's drop: a keystroke+ // never coincides with leaving the fields, only a value tidied and saved on blur does.+ const pause =+ tracked.context !== context+ ? false+ : tracked.held && !held+ ? false+ : tracked.typed !== typed+ ? true+ : tracked.pause;+ setTracked({ typed, context, held, pause });+ }+ // `held` on its own keeps the pause too: focus moving between two field groups wired to+ // the same hold drops and restores it within one task, before any 0 ms timer can fire.+ return held || tracked.pause ? CONNECTION_CHECK_DELAY_MS : 0;+}diff --git a/src/index.css b/src/index.cssindex 79f2a33bb..3eaca4c1a 100644--- a/src/index.css+++ b/src/index.css@@ -916,18 +916,21 @@ h1 {background-color: var(--onboarding-surface-secondary) !important;}+/* The shared credential field (ui/ProviderCheckField.tsx). Outside onboarding these names+ are unset, so each falls back to the app theme: the mapping .onboarding-embedded-auth+ gives the control panel's sign-in dialog. Onboarding defines them, so it keeps its own. */.onboarding-provider-input,.onboarding-provider-input:hover,.onboarding-provider-input:focus-visible,.onboarding-provider-input:disabled {- border-color: var(--onboarding-control-border) !important;- background-color: var(--onboarding-surface-secondary) !important;- color: var(--onboarding-text-primary) !important;+ border-color: var(--onboarding-control-border, var(--color-border)) !important;+ background-color: var(--onboarding-surface-secondary, var(--color-muted)) !important;+ color: var(--onboarding-text-primary, var(--color-foreground)) !important;opacity: 1 !important;}.onboarding-provider-input::placeholder {- color: var(--onboarding-text-secondary) !important;+ color: var(--onboarding-text-secondary, var(--color-muted-foreground)) !important;}.onboarding-provider-icon-monochrome {diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.jsonindex 47e415068..a3f439a00 100644--- a/src/locales/ar/translation.json+++ b/src/locales/ar/translation.json@@ -2801,15 +2801,14 @@"optional": "اختياري","modelId": "معرف النموذج","modelIdPlaceholder": "اكتب معرف النموذج الخاص بك",- "testConnection": "اختبار الاتصال","proceed": "متابعة","clinical": "للتفريغ السريري","clientId": "معرف العميل (Client ID)","clientSecret": "سر العميل (Client Secret)",- "runTest": "إجراء الاختبار","testing": "جاري الاختبار...","connected": "متصل","connectionFailed": "تعذر التحقق من الاتصال.",+ "unverified": "تعذر التحقق: {{reason}}","errors": {"endpointRequired": "أدخل عنوان URL لنقطة النهاية قبل الاختبار.","invalidUrl": "يجب أن تكون نقطة النهاية عنوان URL صالحًا لـ HTTP أو HTTPS.",@@ -2818,6 +2817,7 @@"apiKeyRequired": "أضف مفتاح API قبل الاختبار.","credentialsRejected": "رفض المزود بيانات الاعتماد هذه.","endpointNotFound": "لا توفر نقطة النهاية قائمة نماذج متوافقة مع OpenAI.",+ "transcriptionEndpointNotFound": "لا يستقبل هذا العنوان طلبات التفريغ الصوتي.","modelNotFound": "النموذج المحدد غير متوفر من هذا المزود.","providerStatus": "أعاد المزود رمز الحالة {{status}}.","timeout": "انتهت مهلة اختبار الاتصال.",diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 800c126b6..1d626a382 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -412,15 +412,14 @@"optional": "Optional","modelId": "Modell-ID","modelIdPlaceholder": "Modell-ID eingeben",- "testConnection": "Verbindung testen","proceed": "Fortfahren","clinical": "FÜR KLINISCHE TRANSKRIPTION","clientId": "Client ID","clientSecret": "Client Secret",- "runTest": "Test starten","testing": "Test läuft…","connected": "Verbunden","connectionFailed": "Die Verbindung konnte nicht überprüft werden.",+ "unverified": "Konnte nicht überprüft werden: {{reason}}","errors": {"endpointRequired": "Gib vor dem Test eine Endpoint-URL ein.","invalidUrl": "Der Endpoint muss eine gültige HTTP- oder HTTPS-URL sein.",@@ -429,6 +428,7 @@"apiKeyRequired": "Füge vor dem Test einen API-Schlüssel hinzu.","credentialsRejected": "Der Anbieter hat diese Zugangsdaten abgelehnt.","endpointNotFound": "Der Endpoint stellt keine OpenAI-kompatible Modellliste bereit.",+ "transcriptionEndpointNotFound": "Unter dieser Adresse werden keine Transkriptionen angenommen.","modelNotFound": "Das ausgewählte Modell ist bei diesem Anbieter nicht verfügbar.","providerStatus": "Der Anbieter hat den Status {{status}} zurückgegeben.","timeout": "Der Verbindungstest hat das Zeitlimit überschritten.",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 2c0de2e10..70455c24f 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -412,15 +412,14 @@"optional": "Optional","modelId": "Model ID","modelIdPlaceholder": "Write your model ID",- "testConnection": "Test Connection","proceed": "Proceed","clinical": "FOR CLINICAL TRANSCRIPTION","clientId": "Client ID","clientSecret": "Client secret",- "runTest": "Run Test","testing": "Testing…","connected": "Connected","connectionFailed": "The connection could not be verified.",+ "unverified": "Couldn't verify: {{reason}}","errors": {"endpointRequired": "Enter an endpoint URL before testing.","invalidUrl": "The endpoint must be a valid HTTP or HTTPS URL.",@@ -429,6 +428,7 @@"apiKeyRequired": "Add an API key before testing.","credentialsRejected": "The provider rejected these credentials.","endpointNotFound": "The endpoint does not expose an OpenAI-compatible model list.",+ "transcriptionEndpointNotFound": "Nothing takes transcriptions at this address.","modelNotFound": "The selected model is not available from this provider.","providerStatus": "The provider returned status {{status}}.","timeout": "The connection test timed out.",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 74e51cc14..017cade55 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -412,15 +412,14 @@"optional": "Opcional","modelId": "ID del modelo","modelIdPlaceholder": "Escribe el ID de tu modelo",- "testConnection": "Probar conexión","proceed": "Continuar","clinical": "PARA TRANSCRIPCIÓN CLÍNICA","clientId": "Client ID","clientSecret": "Client secret",- "runTest": "Ejecutar prueba","testing": "Probando…","connected": "Conectado","connectionFailed": "No se pudo verificar la conexión.",+ "unverified": "No se pudo verificar: {{reason}}","errors": {"endpointRequired": "Introduce la URL del endpoint antes de probar.","invalidUrl": "El endpoint debe ser una URL HTTP o HTTPS válida.",@@ -429,6 +428,7 @@"apiKeyRequired": "Añade una clave API antes de probar.","credentialsRejected": "El proveedor rechazó estas credenciales.","endpointNotFound": "El endpoint no expone una lista de modelos compatible con OpenAI.",+ "transcriptionEndpointNotFound": "Esta dirección no acepta transcripciones.","modelNotFound": "El modelo seleccionado no está disponible en este proveedor.","providerStatus": "El proveedor devolvió el estado {{status}}.","timeout": "La prueba de conexión agotó el tiempo de espera.",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 40ec737c0..9368ed72c 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -412,15 +412,14 @@"optional": "Facultatif","modelId": "ID du modèle","modelIdPlaceholder": "Saisissez l’ID de votre modèle",- "testConnection": "Tester la connexion","proceed": "Continuer","clinical": "POUR LA TRANSCRIPTION CLINIQUE","clientId": "Client ID","clientSecret": "Client secret",- "runTest": "Lancer le test","testing": "Test en cours…","connected": "Connecté","connectionFailed": "La connexion n’a pas pu être vérifiée.",+ "unverified": "Vérification impossible : {{reason}}","errors": {"endpointRequired": "Saisissez l’URL de l’endpoint avant de lancer le test.","invalidUrl": "L’endpoint doit être une URL HTTP ou HTTPS valide.",@@ -429,6 +428,7 @@"apiKeyRequired": "Ajoutez une clé API avant de lancer le test.","credentialsRejected": "Le fournisseur a rejeté ces identifiants.","endpointNotFound": "L’endpoint n’expose pas de liste de modèles compatible OpenAI.",+ "transcriptionEndpointNotFound": "Cette adresse n’accepte pas de transcriptions.","modelNotFound": "Le modèle sélectionné n’est pas disponible auprès de ce fournisseur.","providerStatus": "Le fournisseur a renvoyé le statut {{status}}.","timeout": "Le test de connexion a expiré.",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 81eda6140..6e9f2dedd 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -412,15 +412,14 @@"optional": "Facoltativo","modelId": "ID modello","modelIdPlaceholder": "Scrivi l’ID del tuo modello",- "testConnection": "Prova la connessione","proceed": "Procedi","clinical": "PER LA TRASCRIZIONE CLINICA","clientId": "Client ID","clientSecret": "Client secret",- "runTest": "Esegui test","testing": "Test in corso…","connected": "Connesso","connectionFailed": "Non è stato possibile verificare la connessione.",+ "unverified": "Impossibile verificare: {{reason}}","errors": {"endpointRequired": "Inserisci l’URL dell’endpoint prima di eseguire il test.","invalidUrl": "L’endpoint deve essere un URL HTTP o HTTPS valido.",@@ -429,6 +428,7 @@"apiKeyRequired": "Aggiungi una chiave API prima di eseguire il test.","credentialsRejected": "Il provider ha rifiutato queste credenziali.","endpointNotFound": "L’endpoint non espone un elenco di modelli compatibile con OpenAI.",+ "transcriptionEndpointNotFound": "Questo indirizzo non accetta trascrizioni.","modelNotFound": "Il modello selezionato non è disponibile presso questo provider.","providerStatus": "Il provider ha restituito lo stato {{status}}.","timeout": "Il test di connessione è scaduto.",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex f5344e512..50c9d5049 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -412,15 +412,14 @@"optional": "任意","modelId": "モデル ID","modelIdPlaceholder": "モデル ID を入力",- "testConnection": "接続をテスト","proceed": "次へ進む","clinical": "臨床文字起こし向け","clientId": "Client ID","clientSecret": "Client secret",- "runTest": "テストを実行","testing": "テスト中…","connected": "接続済み","connectionFailed": "接続を確認できませんでした。",+ "unverified": "確認できませんでした:{{reason}}","errors": {"endpointRequired": "テストの前にエンドポイント URL を入力してください。","invalidUrl": "エンドポイントは有効な HTTP または HTTPS の URL である必要があります。",@@ -429,6 +428,7 @@"apiKeyRequired": "テストの前に API キーを追加してください。","credentialsRejected": "プロバイダーがこの認証情報を拒否しました。","endpointNotFound": "このエンドポイントは OpenAI 互換のモデル一覧を公開していません。",+ "transcriptionEndpointNotFound": "このアドレスでは文字起こしを受け付けていません。","modelNotFound": "選択したモデルはこのプロバイダーでは利用できません。","providerStatus": "プロバイダーがステータス {{status}} を返しました。","timeout": "接続テストがタイムアウトしました。",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex e3689a223..a5b674b00 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -391,15 +391,14 @@"optional": "Opcional","modelId": "ID do modelo","modelIdPlaceholder": "Escreva o ID do seu modelo",- "testConnection": "Testar conexão","proceed": "Prosseguir","clinical": "PARA TRANSCRIÇÃO CLÍNICA","clientId": "Client ID","clientSecret": "Client secret",- "runTest": "Executar teste","testing": "Testando…","connected": "Conectado","connectionFailed": "Não foi possível verificar a conexão.",+ "unverified": "Não foi possível verificar: {{reason}}","errors": {"endpointRequired": "Insira a URL do endpoint antes de testar.","invalidUrl": "O endpoint deve ser uma URL HTTP ou HTTPS válida.",@@ -408,6 +407,7 @@"apiKeyRequired": "Adicione uma chave de API antes de testar.","credentialsRejected": "O provedor rejeitou essas credenciais.","endpointNotFound": "O endpoint não expõe uma lista de modelos compatível com OpenAI.",+ "transcriptionEndpointNotFound": "Este endereço não aceita transcrições.","modelNotFound": "O modelo selecionado não está disponível neste provedor.","providerStatus": "O provedor retornou o status {{status}}.","timeout": "O teste de conexão expirou.",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex c3b1a09d3..c17247669 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -412,15 +412,14 @@"optional": "Необязательно","modelId": "ID модели","modelIdPlaceholder": "Укажите ID своей модели",- "testConnection": "Проверить подключение","proceed": "Продолжить","clinical": "ДЛЯ КЛИНИЧЕСКОЙ РАСШИФРОВКИ","clientId": "Client ID","clientSecret": "Client secret",- "runTest": "Запустить тест","testing": "Проверка…","connected": "Подключено","connectionFailed": "Не удалось проверить подключение.",+ "unverified": "Не удалось проверить: {{reason}}","errors": {"endpointRequired": "Перед тестом введите URL endpoint.","invalidUrl": "Endpoint должен быть корректным HTTP- или HTTPS-URL.",@@ -429,6 +428,7 @@"apiKeyRequired": "Перед тестом добавьте API-ключ.","credentialsRejected": "Провайдер отклонил эти учётные данные.","endpointNotFound": "Endpoint не предоставляет список моделей, совместимый с OpenAI.",+ "transcriptionEndpointNotFound": "По этому адресу не принимаются запросы на транскрипцию.","modelNotFound": "Выбранная модель недоступна у этого провайдера.","providerStatus": "Провайдер вернул статус {{status}}.","timeout": "Время ожидания проверки подключения истекло.",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 8f9bf3b8d..766e4fa35 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -412,15 +412,14 @@"optional": "可选","modelId": "模型 ID","modelIdPlaceholder": "填写你的模型 ID",- "testConnection": "测试连接","proceed": "继续","clinical": "用于临床转录","clientId": "Client ID","clientSecret": "Client secret",- "runTest": "运行测试","testing": "测试中…","connected": "已连接","connectionFailed": "无法验证此连接。",+ "unverified": "无法验证:{{reason}}","errors": {"endpointRequired": "测试前请先输入端点 URL。","invalidUrl": "端点必须是有效的 HTTP 或 HTTPS URL。",@@ -429,6 +428,7 @@"apiKeyRequired": "测试前请先添加 API Key。","credentialsRejected": "服务商拒绝了这些凭据。","endpointNotFound": "该端点未提供兼容 OpenAI 的模型列表。",+ "transcriptionEndpointNotFound": "此地址不接受转录请求。","modelNotFound": "所选模型无法从此服务商获得。","providerStatus": "服务商返回了状态码 {{status}}。","timeout": "连接测试超时。",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 8d5009a70..a58678d70 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -412,15 +412,14 @@"optional": "選填","modelId": "模型 ID","modelIdPlaceholder": "填寫你的模型 ID",- "testConnection": "測試連線","proceed": "繼續","clinical": "用於臨床逐字稿","clientId": "Client ID","clientSecret": "Client secret",- "runTest": "執行測試","testing": "測試中…","connected": "已連接","connectionFailed": "無法驗證這個連線。",+ "unverified": "無法驗證:{{reason}}","errors": {"endpointRequired": "測試前請先輸入端點 URL。","invalidUrl": "端點必須是有效的 HTTP 或 HTTPS URL。",@@ -429,6 +428,7 @@"apiKeyRequired": "測試前請先新增 API Key。","credentialsRejected": "服務商拒絕了這些憑證。","endpointNotFound": "這個端點未提供相容 OpenAI 的模型清單。",+ "transcriptionEndpointNotFound": "此位址不接受轉錄請求。","modelNotFound": "所選模型無法從此服務商取得。","providerStatus": "服務商回傳了狀態碼 {{status}}。","timeout": "連線測試逾時。",diff --git a/src/styles/connection-status-icon.css b/src/styles/connection-status-icon.cssnew file mode 100644index 000000000..90bd1d23d--- /dev/null+++ b/src/styles/connection-status-icon.css@@ -0,0 +1,105 @@+/* Status mark for a field that checks itself (ConnectionStatusIcon.tsx). A grey arc spins+ while checking. On success it closes into a ring, turns green, then shrinks and fades+ while a tick draws in (about 0.6 s). On failure it closes into a red ring with "!", and+ into an amber one when the provider gave no verdict (unverified).+ One SVG changes state in place, so each change animates. Under reduced motion the+ global block in index.css stops the spin and drops the dash and transform+ transitions, so the final shapes appear at once and only colour and opacity fade.+ The arc uses the onboarding grey (the app's muted grey elsewhere); the tick and the ring use+ the app's success, destructive and warning colours, which keep readable contrast in light+ mode. */+.connection-status-icon {+ width: 1.25rem;+ height: 1.25rem;+ flex: none;+ overflow: visible;+ color: var(--onboarding-text-secondary, var(--color-muted-foreground));+ transition: color 0.2s ease;+}++.connection-status-icon-spin {+ transform-origin: 12px 12px;+ animation: spinner-rotate 0.75s linear infinite;+}++.connection-status-icon-ring {+ fill: none;+ stroke: currentColor;+ stroke-width: 2.2;+ stroke-linecap: round;+ stroke-dasharray: 26 100;+ transform-origin: 12px 12px;+ transition:+ stroke-dasharray 0.2s ease,+ opacity 0.15s ease,+ transform 0.15s ease;+}++.connection-status-icon-tick,+.connection-status-icon-bang {+ fill: none;+ stroke: currentColor;+ stroke-width: 2.4;+ stroke-linecap: round;+ stroke-linejoin: round;+ stroke-dasharray: 100;+ stroke-dashoffset: 100;+ transition: stroke-dashoffset 0.12s ease;+}++.connection-status-icon-dot {+ fill: currentColor;+ opacity: 0;+ transition: opacity 0.12s ease;+}++.connection-status-icon[data-state="connected"] .connection-status-icon-spin,+.connection-status-icon[data-state="unverified"] .connection-status-icon-spin,+.connection-status-icon[data-state="failed"] .connection-status-icon-spin {+ animation-play-state: paused;+}++.connection-status-icon[data-state="connected"] {+ color: var(--color-success);+}++.connection-status-icon[data-state="connected"] .connection-status-icon-ring {+ stroke-dasharray: 100 0;+ opacity: 0;+ transform: scale(0.55);+ transition:+ stroke-dasharray 0.24s cubic-bezier(0.4, 0, 0.2, 1),+ opacity 0.22s ease 0.26s,+ transform 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.22s;+}++.connection-status-icon[data-state="connected"] .connection-status-icon-tick {+ stroke-dashoffset: 0;+ transition: stroke-dashoffset 0.32s cubic-bezier(0.65, 0, 0.35, 1) 0.3s;+}++.connection-status-icon[data-state="failed"] {+ color: var(--color-destructive);+}++.connection-status-icon[data-state="unverified"] {+ color: var(--color-warning);+}++.connection-status-icon[data-state="unverified"] .connection-status-icon-ring,+.connection-status-icon[data-state="failed"] .connection-status-icon-ring {+ stroke-dasharray: 100 0;+ transition: stroke-dasharray 0.24s cubic-bezier(0.4, 0, 0.2, 1);+}++.connection-status-icon[data-state="unverified"] .connection-status-icon-bang,+.connection-status-icon[data-state="failed"] .connection-status-icon-bang {+ stroke-dashoffset: 0;+ transition: stroke-dashoffset 0.2s ease 0.24s;+}++.connection-status-icon[data-state="unverified"] .connection-status-icon-dot,+.connection-status-icon[data-state="failed"] .connection-status-icon-dot {+ opacity: 1;+ transition: opacity 0.15s ease 0.4s;+}diff --git a/src/types/electron.ts b/src/types/electron.tsindex e57eaedc9..fd4c107aa 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -1363,7 +1363,14 @@ declare global {clientSecret?: string;environment?: string;tenant?: string;- }) => Promise<{ success: boolean; error?: string; errorCode?: string; status?: number }>;+ }) => Promise<{+ success: boolean;+ error?: string;+ errorCode?: string;+ status?: number;+ /** The provider gave no verdict (busy, down, unreachable); the setup may be used. */+ unverified?: boolean;+ }>;pasteText: (text: string,options?: {diff --git a/src/utils/maskKey.ts b/src/utils/maskKey.tsnew file mode 100644index 000000000..2bc7a42c4--- /dev/null+++ b/src/utils/maskKey.ts@@ -0,0 +1,5 @@+/** A saved key's first three and last four characters, the way Settings has always shown it. */+export function maskKey(key: string): string {+ if (key.length <= 8) return "••••••••";+ return key.slice(0, 3) + "..." + key.slice(-4);+}diff --git a/test/components/byokConnectionCheck.test.js b/test/components/byokConnectionCheck.test.jsnew file mode 100644index 000000000..7d224a89e--- /dev/null+++ b/test/components/byokConnectionCheck.test.js@@ -0,0 +1,251 @@+const assert = require("node:assert/strict");+const test = require("node:test");+const { mountByokStep } = require("../lib/byokStepHarness");++const PLACEHOLDER = {+ endpoint: "onboarding.rehaul.provider.endpointPlaceholder",+ modelId: "onboarding.rehaul.provider.modelIdPlaceholder",+ hostedKey: "onboarding.rehaul.provider.apiKeyPlaceholder",+};+const LABEL = {+ apiKey: "onboarding.rehaul.provider.apiKey",+ clientSecret: "onboarding.rehaul.provider.clientSecret",+ modelId: "onboarding.rehaul.provider.modelId",+};+const HOSTED_GROQ = {+ useLocalWhisper: "false",+ transcriptionMode: "providers",+ cloudTranscriptionMode: "byok",+ cloudTranscriptionProvider: "groq",+ cloudTranscriptionModel: "whisper-large-v3-turbo",+};+const CORTI = {+ ...HOSTED_GROQ,+ cloudTranscriptionProvider: "corti",+ cloudTranscriptionModel: "corti-transcribe",+};+const REJECTED = { success: false, errorCode: "credentialsRejected", status: 401 };+const phase = (step, label) => step.checkField(label)?.props.check.phase;+const sent = (step, field) => step.connectionRequests().map((config) => config[field]);++test("a saved hosted key is checked on arrival, and only Connected unlocks Proceed", async (t) => {+ const step = await mountByokStep(t, {+ settings: HOSTED_GROQ,+ secrets: { groqApiKey: "gsk-saved" },+ });+ assert.equal(phase(step, LABEL.apiKey), "waiting");+ assert.equal(step.proceedDisabled(), true);+ await step.wait(500);+ const [config] = step.connectionRequests();+ assert.equal(config.provider, "groq");+ assert.equal(config.apiKey, "gsk-saved");+ assert.equal(config.model, "whisper-large-v3-turbo");+ await step.answerConnection({ success: true });+ assert.equal(phase(step, LABEL.apiKey), "connected");+ assert.equal(step.proceedDisabled(), false);+ assert.equal(step.proceeded(), 0, "nothing advances by itself");+ await step.proceed();+ assert.equal(step.proceeded(), 1);+});++test("typing a key sends nothing until typing pauses for half a second", async (t) => {+ const step = await mountByokStep(t, { settings: HOSTED_GROQ });+ assert.equal(phase(step, LABEL.apiKey), "idle", "an empty key shows no status");+ for (const key of ["g", "gs", "gsk", "gsk-typed"]) {+ await step.type(PLACEHOLDER.hostedKey, key);+ await step.wait(300);+ }+ assert.equal(step.connectionRequests().length, 0);+ await step.wait(200);+ assert.deepEqual(sent(step, "apiKey"), ["gsk-typed"]);+});++test("a provider change mid-check discards the earlier answer", async (t) => {+ const step = await mountByokStep(t, {+ settings: HOSTED_GROQ,+ secrets: { groqApiKey: "gsk-saved", openaiApiKey: "sk-saved" },+ });+ await step.wait(500);+ await step.chooseProvider("openai");+ await step.answerConnection({ success: true }, 0);+ assert.notEqual(phase(step, LABEL.apiKey), "connected");+ assert.equal(step.proceedDisabled(), true);+ await step.wait(500);+ assert.deepEqual(sent(step, "provider"), ["groq", "openai"]);+ await step.answerConnection(REJECTED, 1);+ assert.equal(phase(step, LABEL.apiKey), "failed");+ assert.equal(step.proceedDisabled(), true);+});++test("a key that loads after mount is checked when it arrives", async (t) => {+ const step = await mountByokStep(t, { settings: HOSTED_GROQ });+ await step.wait(1000);+ assert.equal(step.connectionRequests().length, 0);+ await step.setStore({ groqApiKey: "gsk-late" });+ assert.equal(phase(step, LABEL.apiKey), "waiting");+ await step.wait(500);+ assert.deepEqual(sent(step, "apiKey"), ["gsk-late"]);+});++test("a rejected key keeps Proceed off; Retry and an edit both check again", async (t) => {+ const step = await mountByokStep(t, {+ settings: HOSTED_GROQ,+ secrets: { groqApiKey: "gsk-saved" },+ });+ await step.wait(500);+ await step.answerConnection(REJECTED);+ assert.equal(step.checkField(LABEL.apiKey).props.check.failure.errorCode, "credentialsRejected");+ assert.equal(step.proceedDisabled(), true);+ await step.retryCheck(LABEL.apiKey);+ assert.equal(step.connectionRequests().length, 2, "Retry does not wait for the pause");+ await step.answerConnection(REJECTED);+ await step.type(PLACEHOLDER.hostedKey, "gsk-fixed");+ assert.equal(phase(step, LABEL.apiKey), "waiting");+ await step.wait(500);+ assert.deepEqual(sent(step, "apiKey"), ["gsk-saved", "gsk-saved", "gsk-fixed"]);+});++test("Corti checks once both the client ID and secret are filled, in the secret", async (t) => {+ const step = await mountByokStep(t, { settings: CORTI, secrets: { cortiClientId: "corti-id" } });+ assert.ok(step.checkField(LABEL.apiKey) === undefined, "Corti has no API key field");+ assert.equal(phase(step, LABEL.clientSecret), "idle");+ await step.wait(1000);+ assert.equal(step.connectionRequests().length, 0);+ await step.setStore({ cortiClientSecret: "corti-secret" });+ assert.equal(phase(step, LABEL.clientSecret), "waiting");+ await step.wait(500);+ const [config] = step.connectionRequests();+ assert.deepEqual(+ [config.scope, config.provider, config.clientId, config.clientSecret],+ ["transcription", "corti", "corti-id", "corti-secret"]+ );+});++test("self-hosted: nothing is sent while the address has focus; leaving it checks", async (t) => {+ const step = await mountByokStep(t, { selfHostedRequested: true });+ await step.type(PLACEHOLDER.modelId, "local-model");+ await step.focusEndpoint();+ for (const url of ["http://192.168.1.1", "http://192.168.1.10:8000/v1"]) {+ await step.type(PLACEHOLDER.endpoint, url);+ await step.wait(2000);+ }+ assert.equal(step.connectionRequests().length, 0);+ assert.equal(phase(step, LABEL.modelId), "idle", "no status while the address is edited");+ await step.blurEndpoint();+ assert.equal(phase(step, LABEL.modelId), "waiting");+ await step.wait(500);+ assert.deepEqual(sent(step, "baseUrl"), ["http://192.168.1.10:8000/v1"]);+});++test("switching to another app while editing the address keeps the hold", async (t) => {+ const step = await mountByokStep(t, { selfHostedRequested: true });+ await step.type(PLACEHOLDER.modelId, "local-model");+ await step.focusEndpoint();+ await step.type(PLACEHOLDER.endpoint, "https://my-server.exa");+ await step.blurEndpoint({ windowSwitch: true });+ await step.wait(2000);+ assert.equal(step.connectionRequests().length, 0);+ await step.blurEndpoint();+ await step.wait(500);+ assert.equal(step.connectionRequests().length, 1);+});++test("focusing the address while Connected keeps Connected until an edit", async (t) => {+ const step = await mountByokStep(t, { selfHostedRequested: true });+ await step.type(PLACEHOLDER.endpoint, "http://127.0.0.1:8791/v1");+ await step.type(PLACEHOLDER.modelId, "local-model");+ await step.passConnectionTest();+ await step.focusEndpoint();+ await step.wait(2000);+ assert.equal(phase(step, LABEL.modelId), "connected");+ assert.equal(step.proceedDisabled(), false);+ assert.equal(step.connectionRequests().length, 1);+ await step.type(PLACEHOLDER.endpoint, "http://127.0.0.1:8792/v1");+ assert.equal(phase(step, LABEL.modelId), "idle");+ assert.equal(step.proceedDisabled(), true);+});++test("a mode switch with the address focused still checks both forms", async (t) => {+ const step = await mountByokStep(t, {+ settings: HOSTED_GROQ,+ secrets: { groqApiKey: "gsk-saved" },+ });+ await step.toggleSelfHosted();+ await step.type(PLACEHOLDER.endpoint, "http://127.0.0.1:8791/v1");+ await step.type(PLACEHOLDER.modelId, "local-model");+ await step.focusEndpoint();+ await step.toggleSelfHosted(); // the address field unmounts without a blur+ await step.wait(500);+ assert.deepEqual(sent(step, "provider"), ["groq"]);+ await step.toggleSelfHosted();+ assert.equal(phase(step, LABEL.modelId), "waiting");+ await step.wait(500);+ assert.deepEqual(sent(step, "provider"), ["groq", "custom"]);+});++test("each checked field is marked invalid only by a failure about its own value", async (t) => {+ for (const [name, options, label, invalidOn] of [+ ["hosted key", { settings: HOSTED_GROQ }, LABEL.apiKey, "credentialsRejected"],+ ["Corti secret", { settings: CORTI }, LABEL.clientSecret, "credentialsRejected"],+ ["self-hosted model", { selfHostedRequested: true }, LABEL.modelId, "modelNotFound"],+ ]) {+ await t.test(name, async (t) => {+ const step = await mountByokStep(t, options);+ assert.equal(step.checkField(label).props.invalidOn, invalidOn);+ });+ }+});++test("the live region is always there and says only what the check found", async (t) => {+ await t.test("empty on arrival", async (t) => {+ const region = (await mountByokStep(t, { settings: HOSTED_GROQ })).liveRegion();+ assert.equal(region.props["aria-live"], "polite");+ assert.equal(region.props["aria-atomic"], "true");+ assert.match(region.props.className, /\bsr-only\b/);+ assert.equal(region.props.children, "");+ });+ await t.test("a slow check, then its result, then an edit", async (t) => {+ const step = await mountByokStep(t, {+ settings: HOSTED_GROQ,+ secrets: { groqApiKey: "gsk-saved" },+ });+ // Two waits: the 1 s timer starts only once React has applied the send.+ await step.wait(500);+ await step.wait(999);+ assert.equal(step.liveRegion().props.children, "");+ await step.wait(1);+ assert.equal(step.liveRegion().props.children, "onboarding.rehaul.provider.testing");+ await step.answerConnection({ success: true });+ assert.equal(step.liveRegion().props.children, "onboarding.rehaul.provider.connected");+ await step.type(PLACEHOLDER.hostedKey, "gsk-other");+ assert.equal(step.liveRegion().props.children, "");+ });+});++test("no verdict unlocks Proceed; an answer that faults the setup does not", async (t) => {+ const step = await mountByokStep(t, {+ settings: HOSTED_GROQ,+ secrets: { groqApiKey: "gsk-saved" },+ });+ await step.wait(500);+ await step.answerConnection({+ success: false,+ errorCode: "providerStatus",+ status: 503,+ unverified: true,+ });+ assert.equal(phase(step, LABEL.apiKey), "unverified");+ assert.equal(step.proceedDisabled(), false);++ for (const answer of [{ success: false, errorCode: "providerStatus", status: 402 }, REJECTED]) {+ await step.retryCheck(LABEL.apiKey);+ await step.answerConnection(answer);+ assert.equal(phase(step, LABEL.apiKey), "failed", answer.errorCode);+ assert.equal(step.proceedDisabled(), true, answer.errorCode);+ }++ await step.retryCheck(LABEL.apiKey);+ await step.answerConnection({ success: false, errorCode: "network", unverified: true });+ await step.proceed();+ assert.equal(step.proceeded(), 1);+});diff --git a/test/components/byokSavedConfig.test.js b/test/components/byokSavedConfig.test.jsindex 8e12da597..1ce7a4c60 100644--- a/test/components/byokSavedConfig.test.js+++ b/test/components/byokSavedConfig.test.js@@ -503,6 +503,27 @@ test("policy removing self-hosting mid-step keeps the hosted half and loads itsassert.equal(step.value(PLACEHOLDER.hostedKey), "gsk-saved-key");});+test("a policy that ends self-hosting mid-edit still checks the hosted half", async (t) => {+ const step = await mountByokStep(t, {+ settings: HOSTED_GROQ,+ secrets: { groqApiKey: "gsk-saved-key" },+ });+ await step.toggleSelfHosted();+ await step.type(PLACEHOLDER.endpoint, "http://127.0.0.1:8791/v1");+ await step.type(PLACEHOLDER.modelId, "local-model");+ await step.focusEndpoint();++ await applyTranscriptionPolicy(step, {+ allowedModes: ["providers"],+ allowedByokProviders: ["groq"],+ });+ await step.wait(500);+ assert.deepEqual(+ step.connectionRequests().map((config) => config.provider),+ ["groq"]+ );+});+test("a seeded provider that policy removes after mount cannot be saved", async (t) => {for (const [name, settings, secrets] of [["an API-key provider", HOSTED_GROQ, { groqApiKey: "gsk-saved-key" }],diff --git a/test/components/connectionStatusIcon.test.js b/test/components/connectionStatusIcon.test.jsnew file mode 100644index 000000000..d89eacfb8--- /dev/null+++ b/test/components/connectionStatusIcon.test.js@@ -0,0 +1,58 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const path = require("node:path");+const React = require("react");+const { renderToStaticMarkup } = require("react-dom/server");+const { createRendererServer } = require("../lib/rendererTestHarness");++const repoRoot = path.join(__dirname, "../..");+const source = (relativePath) => fs.readFileSync(path.join(repoRoot, relativePath), "utf8");+const ICON_CSS = "src/styles/connection-status-icon.css";++async function loadIcon(t) {+ const vite = await createRendererServer(t, { cachePrefix: "openwhispr-status-icon-" });+ const module = await vite.ssrLoadModule("/components/ui/ConnectionStatusIcon.tsx");+ return module.ConnectionStatusIcon;+}++test("one decorative SVG carries every state, so a change animates in place", async (t) => {+ const ConnectionStatusIcon = await loadIcon(t);+ for (const state of ["checking", "connected", "unverified", "failed"]) {+ const markup = renderToStaticMarkup(React.createElement(ConnectionStatusIcon, { state }));+ const root = markup.match(/^<svg[^>]*>/)?.[0] ?? "";+ assert.match(root, /aria-hidden="true"/, state);+ assert.match(root, new RegExp(`data-state="${state}"`));+ assert.match(root, /class="connection-status-icon"/);+ for (const part of ["spin", "ring", "tick", "bang", "dot"]) {+ assert.match(markup, new RegExp(`class="connection-status-icon-${part}"`));+ }+ assert.equal(markup.match(/pathLength="100"/g)?.length, 3);+ assert.doesNotMatch(markup, />[^<]+</, "the icon carries no words");+ }+});++test("it uses the onboarding grey and the app's readable status colours", () => {+ const css = source(ICON_CSS);+ assert.match(css, /var\(--onboarding-text-secondary, var\(--color-muted-foreground\)\)/);+ assert.match(css, /color: var\(--color-success\);/);+ assert.match(css, /color: var\(--color-destructive\);/);+ assert.match(css, /\[data-state="unverified"\] \{\s*color: var\(--color-warning\);/);+ assert.doesNotMatch(css, /--onboarding-(success|danger)/);+ assert.match(css, /animation: spinner-rotate 0\.75s linear infinite/);+ assert.match(source("src/index.css"), /@keyframes spinner-rotate \{[\s\S]*?rotate\(360deg\)/);+});++test("reduced motion stops the spin and settles the shapes at once", () => {+ // The icon relies on the app-wide block; it must not fight it.+ assert.doesNotMatch(source(ICON_CSS), /!important|prefers-reduced-motion/);+ const css = source("src/index.css");+ const reduced = css.slice(css.indexOf("@media (prefers-reduced-motion: reduce)"));+ const properties = reduced.match(/transition-property:\s*([^;]+);/)[1];+ for (const fade of ["opacity", "color", "stroke"]) {+ assert.match(properties, new RegExp(`\\b${fade}\\b`), fade);+ }+ assert.doesNotMatch(properties, /stroke-dash|transform/);+ assert.match(reduced, /animation-duration: 0\.01ms !important;/);+ assert.match(reduced, /animation-iteration-count: 1 !important;/);+});diff --git a/test/components/fieldDirectionPolicy.test.js b/test/components/fieldDirectionPolicy.test.jsindex 4e33e26b9..34004e389 100644--- a/test/components/fieldDirectionPolicy.test.js+++ b/test/components/fieldDirectionPolicy.test.js@@ -65,15 +65,11 @@ const EXPECTED_SHARED_FIELD_DIRECTIONS = {"src/components/ForgotPasswordView.tsx": ["ltr"],"src/components/InviteTeammateDialog.tsx": ["ltr"],"src/components/LeaderboardSection.tsx": ["ltr"],- "src/components/OpenAICompatiblePanel.tsx": ["ltr"],- "src/components/SelfHostedPanel.tsx": ["ltr", "ltr"],"src/components/SettingsPage.tsx": ["ltr", "ltr", "ltr", "ltr", "ltr", "ltr"],"src/components/SnippetsView.tsx": ["auto", "auto", "auto", "auto"],- "src/components/TranscriptionModelPicker.tsx": ["ltr", "ltr", "ltr"],"src/components/notes/ActionManagerDialog.tsx": ["auto", "auto", "auto"],"src/components/notes/DeleteSpaceDialog.tsx": ["auto"],"src/components/notes/UploadAudioView.tsx": ["auto"],- "src/components/onboarding/ProviderSetupStep.tsx": ["ltr", "ltr", "ltr", "ltr", "ltr", "ltr"],"src/components/settings/DictationAgentSettings.tsx": ["auto"],"src/components/settings/EnterpriseCheckoutDialog.tsx": ["inherit"],"src/components/settings/ProfileSection.tsx": ["auto", "ltr", "ltr", "ltr"],@@ -82,6 +78,7 @@ const EXPECTED_SHARED_FIELD_DIRECTIONS = {"src/components/ui/ApiKeyInput.tsx": ["ltr"],"src/components/ui/CustomModelInput.tsx": ["ltr"],"src/components/ui/PromptStudio.tsx": ["auto", "auto"],+ "src/components/ui/ProviderCheckField.tsx": ["ltr"],"src/components/ui/SearchableModelList.tsx": ["ltr"],};@@ -169,8 +166,8 @@ test("representative prose, identity, secret, and rich-editor surfaces keep thei/<Input\s+dir="ltr"\s+type="password"/);assert.match(- source("src/components/onboarding/ProviderSetupStep.tsx"),- /<Input\s+dir="ltr"\s+type="password"/+ source("src/components/ui/ProviderCheckField.tsx"),+ /<Input\s+dir="ltr"\s+\{\.\.\.inputProps\}/);assert.match(source("src/components/DictionaryView.tsx"),diff --git a/test/components/localModelSetupStep.test.js b/test/components/localModelSetupStep.test.jsindex e8e215b5f..a2a479b3a 100644--- a/test/components/localModelSetupStep.test.js+++ b/test/components/localModelSetupStep.test.js@@ -108,7 +108,6 @@ async function createSetupHarness(export function useTranslation() { return { t }; }export const initReactI18next = { type: "3rdParty", init() {} };`,- "/ProviderConnectionTest": `export default function ProviderConnectionTest() { return null; }`,"/OnboardingShell": `export function BrandMark() { return null; }`,"/ui/ProviderIcon": `export function ProviderIcon() { return null; }`,},diff --git a/test/components/openAICompatiblePanelCheck.test.js b/test/components/openAICompatiblePanelCheck.test.jsnew file mode 100644index 000000000..3c7948152--- /dev/null+++ b/test/components/openAICompatiblePanelCheck.test.js@@ -0,0 +1,274 @@+const assert = require("node:assert/strict");+const test = require("node:test");+const { mountSettingsPanel } = require("../lib/settingsPanelHarness");++const PANEL = "/components/OpenAICompatiblePanel.tsx";+const ENDPOINT = "reasoning.custom.endpointTitle";+const OPTIONAL_KEY = "reasoning.custom.apiKeyOptional";+const BASE = "http://127.0.0.1:11434/v1";+const REJECTED = { success: false, errorCode: "credentialsRejected", status: 401 };+const props = (overrides = {}) => ({+ baseUrl: BASE,+ setBaseUrl() {},+ apiKey: "",+ setApiKey() {},+ model: "",+ setModel() {},+ ...overrides,+});+// The panel's own model-list load uses the renderer's fetch.+const respond =+ (status, body = {}) =>+ async () => ({+ ok: status === 200,+ status,+ statusText: "",+ json: async () => body,+ text: async () => "",+ });+const modelList = respond(200, { data: [{ id: "llama-test" }] });+const listError = (panel) =>+ panel.find((node) => node.props?.className === "text-xs text-destructive")[0];+const mount = (t, { overrides, ...options } = {}) =>+ mountSettingsPanel(t, { module: PANEL, props: props(overrides), fetch: modelList, ...options });+// The key setter saves straight into the panel's props, as the store does for its parent.+const savingKey = (saved) => {+ const live = props({+ setApiKey: (value) => {+ saved.push(value);+ live.apiKey = value;+ },+ });+ return live;+};++test("an applied address is checked at once; its field holds the status", async (t) => {+ const panel = await mount(t);+ await panel.wait(0);+ assert.deepEqual(panel.requests(), [+ { scope: "reasoning", provider: "custom", baseUrl: BASE, apiKey: "", model: "" },+ ]);+ assert.ok(panel.field(ENDPOINT).props.check);+ assert.equal(panel.field(OPTIONAL_KEY).props.check, undefined);+ await panel.answer({ success: true });+ assert.equal(panel.field(ENDPOINT).props.check.phase, "connected");+});++test("the panel's model is part of the check, and a new model checks at once", async (t) => {+ const panel = await mount(t, { overrides: { model: "llama-test" } });+ await panel.wait(0);+ assert.equal(panel.requests().at(-1).model, "llama-test");+ await panel.answer({ success: true });+ await panel.setProps({ model: "llama-other" });+ assert.equal(panel.field(ENDPOINT).props.check.phase, "waiting");+ await panel.wait(0); // a model pick is not typing, so nothing waits+ assert.deepEqual(+ panel.requests().map((config) => config.model),+ ["llama-test", "llama-other"]+ );+});++test("a new address waits until the field is left; a window switch applies nothing", async (t) => {+ const applied = [];+ const panel = await mount(t, { overrides: { setBaseUrl: (value) => applied.push(value) } });+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.type(ENDPOINT, "http://127.0.0.1:8080");+ assert.equal(panel.field(ENDPOINT).props.check.phase, "idle", "the old status leaves");+ await panel.blur(ENDPOINT, { windowSwitch: true });+ await panel.wait(2000);+ assert.deepEqual(applied, []);+ assert.equal(panel.requests().length, 1);+ await panel.blur(ENDPOINT);+ assert.deepEqual(applied, ["http://127.0.0.1:8080"]);+ await panel.setProps({ baseUrl: "http://127.0.0.1:8080" });+ await panel.wait(0); // leaving the field checks at once+ assert.equal(panel.requests().at(-1).baseUrl, "http://127.0.0.1:8080");+});++test("a server that refuses a keyless check says it wants a key", async (t) => {+ const panel = await mount(t);+ await panel.wait(0);+ await panel.answer(REJECTED);+ const unauthorized = "reasoning.custom.endpointUnauthorized";+ assert.equal(panel.field(ENDPOINT).props.failureReason, unauthorized);+ assert.equal(+ panel.field(ENDPOINT).props.invalidOn,+ undefined,+ "no failure proves an address wrong"+ );+ await panel.setProps({ apiKey: "sk-server" });+ await panel.wait(0);+ await panel.answer(REJECTED);+ assert.equal(panel.field(ENDPOINT).props.failureReason, undefined, "with a key, a rejection");+});++test("the list's error line gives way to the check's reason", async (t) => {+ const panel = await mount(t, { fetch: respond(401) });+ await panel.wait(0); // the list loads and the check goes out+ assert.equal(listError(panel), undefined, "nothing twice while the check runs");+ await panel.answer(REJECTED);+ assert.equal(listError(panel), undefined);+ await panel.retry();+ await panel.answer({ success: true });+ assert.ok(listError(panel), "a list that fails behind a passing check still says so");+});++test("an address without http:// or https:// keeps the list's message, unchecked", async (t) => {+ const panel = await mount(t, { overrides: { baseUrl: "localhost:11434/v1" } });+ await panel.wait(1000);+ assert.equal(panel.requests().length, 0);+ assert.equal(listError(panel).props.children, "reasoning.custom.endpointWithProtocol");+});++test("OpenRouter checks its key, which holds the status", async (t) => {+ const panel = await mount(t, {+ overrides: {+ provider: "openrouter",+ baseUrl: "https://openrouter.ai/api/v1",+ lockedBaseUrl: true,+ apiKeyRequired: true,+ apiKey: "sk-or-saved",+ },+ });+ assert.equal(panel.field(ENDPOINT), undefined);+ await panel.wait(0);+ assert.deepEqual(+ panel.requests().map((config) => [config.provider, config.apiKey]),+ [["openrouter", "sk-or-saved"]]+ );+ assert.ok(panel.field("common.apiKey").props.check);+ assert.equal(panel.field("common.apiKey").props.invalidOn, "credentialsRejected");+});++test("a hidden server panel sends nothing until it is shown, then asks again", async (t) => {+ const panel = await mount(t, { visible: false });+ await panel.wait(5000);+ assert.equal(panel.requests().length, 0);+ await panel.setVisible(true);+ await panel.wait(0);+ assert.equal(panel.requests().length, 1);+ await panel.answer({ success: true });+ await panel.setVisible(false);+ await panel.setVisible(true);+ await panel.wait(0);+ assert.equal(panel.requests().length, 2, "a shown panel asks again");+});++test("a key typed into a failed list waits for its check to settle", async (t) => {+ const saved = [];+ const panel = await mount(t, { fetch: respond(401), props: savingKey(saved) });+ await panel.wait(0); // the list fails without a key; the check goes out+ assert.equal(globalThis.fetch.mock.calls.length, 1);+ await panel.answer(REJECTED);+ for (const key of ["s", "sk"]) await panel.type(OPTIONAL_KEY, key);+ await panel.wait(499);+ assert.equal(globalThis.fetch.mock.calls.length, 1, "the list never sees a half-typed key");+ assert.equal(panel.requests().length, 1, "nor does the check");+ await panel.wait(1);+ assert.equal(panel.requests().at(-1).apiKey, "sk");+ assert.equal(globalThis.fetch.mock.calls.length, 1, "the list waits for the check's answer");+ assert.deepEqual(saved, [], "nor is it saved");+ await panel.answer({ success: true });+ assert.deepEqual(saved, ["sk"], "a passing key saves at once");+ assert.equal(globalThis.fetch.mock.calls.length, 2, "a settled key retries the failed list");+ const [, init] = globalThis.fetch.mock.calls[1].arguments;+ assert.equal(init.headers.Authorization, "Bearer sk");+});++test("a parent's new setter on each render never reloads a failed list", async (t) => {+ const panel = await mount(t, { fetch: respond(401) });+ await panel.wait(0); // the list fails without a key+ await panel.answer(REJECTED);+ for (const key of ["s", "sk"]) {+ await panel.type(OPTIONAL_KEY, key);+ // InferenceConfigEditor passes setField("cloudBaseUrl"), a new function on each render.+ await panel.setProps({ setBaseUrl() {} });+ }+ assert.equal(globalThis.fetch.mock.calls.length, 1, "the list never sees a half-typed key");+});++test("a key typed while the list is still loading retries once the load settles", async (t) => {+ // The first list load answers only when the test says so; later loads answer at once.+ let settle;+ const slow = new Promise((resolve) => {+ settle = resolve;+ });+ const panel = await mount(t, {+ fetch: (...args) => (globalThis.fetch.mock.calls.length > 1 ? modelList(...args) : slow),+ props: savingKey([]),+ });+ await panel.wait(0); // the list is still loading; the check goes out+ await panel.answer(REJECTED);+ await panel.type(OPTIONAL_KEY, "sk-late");+ await panel.wait(500);+ assert.equal(panel.requests().at(-1).apiKey, "sk-late");+ await panel.answer({ success: true });+ assert.equal(globalThis.fetch.mock.calls.length, 1, "the retry waits for the loading list");+ settle(await respond(401)());+ await panel.wait(0);+ assert.equal(globalThis.fetch.mock.calls.length, 2, "the settled list retries with the key");+ const [, init] = globalThis.fetch.mock.calls[1].arguments;+ assert.equal(init.headers.Authorization, "Bearer sk-late");+ await panel.wait(5000);+ assert.equal(globalThis.fetch.mock.calls.length, 2, "once");+});++test("a hidden panel's failed list stays quiet when its key changes elsewhere", async (t) => {+ const panel = await mount(t, { fetch: respond(401), visible: false });+ await panel.wait(0);+ assert.equal(globalThis.fetch.mock.calls.length, 1, "the list loads once at mount");+ await panel.setProps({ apiKey: "sk-elsewhere" });+ await panel.wait(5000);+ assert.equal(globalThis.fetch.mock.calls.length, 1);+ assert.equal(panel.requests().length, 0);+});++test("a server key saves trimmed once its field is left, and the address is checked again", async (t) => {+ const saved = [];+ const panel = await mount(t, { props: savingKey(saved) });+ await panel.type(OPTIONAL_KEY, " sk-ser");+ await panel.type(OPTIONAL_KEY, " sk-server ");+ await panel.wait(500); // the key still has focus, so the pause runs+ assert.deepEqual(+ panel.requests().map((config) => config.apiKey),+ ["sk-server"]+ );+ assert.deepEqual(saved, [], "nothing is saved while the key is typed");+ await panel.blur(OPTIONAL_KEY);+ assert.deepEqual(saved, [], "a key left while its check runs waits for the answer");+ await panel.answer({ success: false, errorCode: "network", unverified: true });+ assert.deepEqual(saved, ["sk-server"], "leaving the field saves it");+});++test("a key someone's own server refuses still saves once its field is left", async (t) => {+ const saved = [];+ const panel = await mount(t, { props: savingKey(saved) });+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.type(OPTIONAL_KEY, "sk-wrong");+ await panel.blur(OPTIONAL_KEY);+ await panel.wait(0);+ await panel.answer(REJECTED);+ assert.deepEqual(saved, ["sk-wrong"]);+});++test("a key OpenRouter refuses is never saved", async (t) => {+ const saved = [];+ const live = Object.assign(savingKey(saved), {+ provider: "openrouter",+ baseUrl: "https://openrouter.ai/api/v1",+ lockedBaseUrl: true,+ apiKeyRequired: true,+ apiKey: "sk-or-saved",+ });+ const panel = await mount(t, { props: live });+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.type("common.apiKey", "sk-or-wrong");+ await panel.blur("common.apiKey");+ await panel.wait(0);+ await panel.answer(REJECTED);+ await panel.unmount();+ assert.deepEqual(saved, []);+});diff --git a/test/components/providerCheckField.test.js b/test/components/providerCheckField.test.jsnew file mode 100644index 000000000..7b28b43f2--- /dev/null+++ b/test/components/providerCheckField.test.js@@ -0,0 +1,328 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const path = require("node:path");+const React = require("react");+const { renderToStaticMarkup } = require("react-dom/server");+const { createRoot } = require("react-dom/client");+const {+ createRendererServer,+ installBrowserGlobals,+ installHookDom,+} = require("../lib/rendererTestHarness");+const { installInteractiveDom, findElement } = require("../lib/interactiveDom");++const LABEL = "onboarding.rehaul.provider.apiKey";++async function loadField(t) {+ installBrowserGlobals(t);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-provider-check-field-",+ noExternal: ["react-i18next"],+ mockModules: {+ "react-i18next": `+ const t = (key, options) => (options?.reason ? key + "(" + options.reason + ")" : key);+ export function useTranslation() { return { t }; }+ `,+ },+ });+ const module = await vite.ssrLoadModule("/components/ui/ProviderCheckField.tsx");+ return module.ProviderCheckField;+}++const markup = (Field, check, extra = {}) =>+ renderToStaticMarkup(+ React.createElement(Field, {+ label: LABEL,+ check: { failure: null, retry() {}, ...check },+ invalidOn: "credentialsRejected",+ type: "password",+ value: "sk-test",+ readOnly: true,+ ...extra,+ })+ );++const failed = (errorCode) => ({+ phase: "failed",+ failure: { success: false, ...(errorCode && { errorCode, status: 400 }) },+});++test("an idle field shows no status but keeps its reason target", async (t) => {+ const html = markup(await loadField(t), { phase: "idle" });+ assert.doesNotMatch(html, /<svg/);+ assert.doesNotMatch(html, /aria-invalid="/);+ assert.doesNotMatch(html, /\bpe-9\b/);+ const reasonId = html.match(/aria-describedby="([^"]+)"/)[1];+ assert.match(html, new RegExp(`<span id="${reasonId}" role="alert"></span>`));+});++test("the status sits at the field's own end and changes with the check", async (t) => {+ const Field = await loadField(t);+ for (const [phase, state] of [+ ["waiting", "checking"],+ ["checking", "checking"],+ ["connected", "connected"],+ ]) {+ const html = markup(Field, { phase });+ assert.match(html, new RegExp(`data-state="${state}"`), phase);+ assert.match(html, /<span dir="ltr" class="relative block">/);+ const input = html.match(/<input[^>]*>/)[0];+ assert.match(input, /dir="ltr"/);+ assert.match(input, /\bpe-9\b/);+ assert.match(html, /class="connection-status-icon pointer-events-none absolute end-2\.5/);+ assert.match(html, /role="alert"><\/span>/, "no reason while not failed");+ }+});++test("the field's own failure shows the reason, Retry and aria-invalid", async (t) => {+ const Field = await loadField(t);+ for (const errorCode of ["credentialsRejected", "modelNotFound"]) {+ const html = markup(Field, failed(errorCode), { invalidOn: errorCode });+ assert.match(html, /data-state="failed"/);+ assert.match(html, /aria-invalid="true"/);+ const reason = `role="alert">onboarding\\.rehaul\\.provider\\.errors\\.${errorCode}<`;+ assert.match(html, new RegExp(reason));+ assert.match(html, /<button type="button"[^>]*>common\.retry<\/button>/);+ }+});++test("a failure about another field shows its reason but leaves this value valid", async (t) => {+ const Field = await loadField(t);+ for (const [errorCode, invalidOn] of [+ ["modelNotFound", "credentialsRejected"],+ ["credentialsRejected", "modelNotFound"],+ ]) {+ const html = markup(Field, failed(errorCode), { invalidOn });+ assert.doesNotMatch(html, /aria-invalid="/, `${errorCode} in a ${invalidOn} field`);+ assert.match(html, new RegExp(`errors\\.${errorCode}<`));+ }+});++test("network, timeout and status failures never mark the value invalid", async (t) => {+ const Field = await loadField(t);+ for (const errorCode of ["network", "timeout", "providerStatus", "endpointNotFound"]) {+ const html = markup(Field, failed(errorCode));+ assert.doesNotMatch(html, /aria-invalid="/, errorCode);+ assert.match(html, new RegExp(`errors\\.${errorCode}<`));+ }+ const unverified = markup(Field, failed());+ assert.match(unverified, /role="alert">onboarding\.rehaul\.provider\.connectionFailed</);+});++test("Retry runs the check again, and the icon changes state in place", async (t) => {+ let root;+ t.after(() => root && React.act(async () => root.unmount())); // first: before globals go+ const Field = await loadField(t);+ const container = installInteractiveDom(t);+ root = createRoot(container);+ let retries = 0;+ const render = (check) =>+ React.act(async () =>+ root.render(+ React.createElement(Field, {+ label: LABEL,+ check: { failure: null, retry: () => (retries += 1), ...check },+ invalidOn: "credentialsRejected",+ value: "sk-test",+ readOnly: true,+ })+ )+ );+ const icon = () => findElement(container, (element) => element.tagName === "SVG");+ await render({ phase: "checking" });+ const first = icon();+ await render(failed("network"));+ assert.ok(icon() === first, "the same SVG moves from spinning to failed");+ assert.equal(first.getAttribute("data-state"), "failed");+ const retry = findElement(container, (element) => element.tagName === "BUTTON");+ await React.act(async () => retry.dispatchEvent({ type: "click", bubbles: true }));+ assert.equal(retries, 1);+ const input = findElement(container, (element) => element.tagName === "INPUT");+ assert.ok(container.ownerDocument.activeElement === input, "focus moves off Retry to the field");+});++const SAVED_KEY = "sk-proj-abcd1234wxyz";+const SAVED_KEY_ENDS = /<span aria-hidden="true" class="pointer-events-none[^"]*">sk-\.\.\.wxyz</;+const LOOK = ["onboarding-provider-input", "h-9", "rounded-xl!", "text-xs", "shadow-none!"];+const CAPTION = /^<div><label class="block"><span class="mb-1\.5 block text-xs[^"]*">/;+const source = (relativePath) =>+ fs.readFileSync(path.join(__dirname, "../..", relativePath), "utf8");+const inputTag = (html) => html.match(/<input[^>]*>/)[0];++function findAll(node, predicate, found = []) {+ if (Array.isArray(node)) {+ for (const child of node) findAll(child, predicate, found);+ } else if (node && typeof node === "object") {+ if (predicate(node)) found.push(node);+ findAll(node.props?.children, predicate, found);+ }+ return found;+}++// Runs the field's own hooks with its children unmounted, as the step harness does: the+// element tree is the test boundary.+async function mountField(t, props) {+ let root;+ t.after(async () => {+ if (root) await React.act(async () => root.unmount());+ }); // first: before globals go+ const Field = await loadField(t);+ const container = installHookDom(t);+ let tree;+ function Harness() {+ tree = Field(props);+ return null;+ }+ root = createRoot(container);+ await React.act(async () => root.render(React.createElement(Harness)));+ const find = (predicate) => findAll(tree, predicate);+ const input = () => find((node) => typeof node.props?.onBlur === "function")[0];+ return {+ input,+ mask: () => find((node) => node.type === "span" && node.props["aria-hidden"] === "true")[0],+ focus: (element) => React.act(async () => input().props.onFocus({ currentTarget: element })),+ blur: (element) => React.act(async () => input().props.onBlur({ currentTarget: element })),+ };+}++test("the field brings its look, falling back to the app theme outside onboarding", async (t) => {+ const Field = await loadField(t);+ const props = { "aria-label": "common.apiKey", value: "", readOnly: true };+ const input = inputTag(renderToStaticMarkup(React.createElement(Field, props)));+ for (const name of LOOK) {+ assert.match(input, new RegExp(`[" ]${name}[" ]`), name);+ }+ const css = source("src/index.css");+ const rule = css.slice(+ css.indexOf(".onboarding-provider-input,"),+ css.indexOf(".onboarding-provider-icon-monochrome")+ );+ for (const [token, fallback] of [+ ["--onboarding-control-border", "--color-border"],+ ["--onboarding-surface-secondary", "--color-muted"],+ ["--onboarding-text-primary", "--color-foreground"],+ ["--onboarding-text-secondary", "--color-muted-foreground"],+ ]) {+ assert.match(rule, new RegExp(`var\\(${token}, var\\(${fallback}\\)\\)`), token);+ }+ const field = source("src/components/ui/ProviderCheckField.tsx");+ assert.match(field, /var\(--onboarding-accent,var\(--color-primary\)\)/);+ assert.match(field, /var\(--onboarding-text-primary,var\(--color-foreground\)\)/);+});++test("Settings names a field from its heading; onboarding keeps its caption", async (t) => {+ const Field = await loadField(t);+ const settings = renderToStaticMarkup(+ React.createElement(Field, { "aria-label": "common.apiKey", value: "", readOnly: true })+ );+ assert.doesNotMatch(settings, /<label/);+ assert.match(inputTag(settings), /aria-label="common\.apiKey"/);+ const onboarding = renderToStaticMarkup(+ React.createElement(Field, { label: LABEL, value: "", readOnly: true })+ );+ assert.match(onboarding, CAPTION);+ assert.match(onboarding, />onboarding\.rehaul\.provider\.apiKey<\/span>/);+});++test("a field without a check is the field alone", async (t) => {+ const Field = await loadField(t);+ const html = renderToStaticMarkup(+ React.createElement(Field, { "aria-label": "Client ID", value: "corti-id", readOnly: true })+ );+ assert.doesNotMatch(html, /<svg|role="alert"|aria-describedby|\bpe-9\b/);+});++test("a saved secret shows its first three and last four characters until focused", async (t) => {+ const Field = await loadField(t);+ const render = (props) =>+ renderToStaticMarkup(+ React.createElement(Field, { "aria-label": "common.apiKey", readOnly: true, ...props })+ );+ const saved = render({ type: "password", value: SAVED_KEY });+ assert.match(saved, SAVED_KEY_ENDS);+ assert.match(inputTag(saved), /text-transparent!/);+ assert.match(render({ type: "password", value: "sk-short" }), />••••••••</);+ for (const props of [+ { type: "password", value: "" },+ { type: "text", value: SAVED_KEY },+ ]) {+ const html = render(props);+ assert.doesNotMatch(html, /aria-hidden="true"/, JSON.stringify(props));+ assert.doesNotMatch(html, /text-transparent!/);+ }+});++test("focusing a saved secret selects all of it, so a paste replaces it", async (t) => {+ const field = await mountField(t, {+ "aria-label": "common.apiKey",+ type: "password",+ value: SAVED_KEY,+ readOnly: true,+ });+ assert.ok(field.mask());+ let selects = 0;+ const element = { select: () => (selects += 1), contains: (node) => node === element };+ element.ownerDocument = { activeElement: element };+ await field.focus(element);+ assert.equal(selects, 1);+ assert.equal(field.mask(), undefined);+ assert.doesNotMatch(field.input().props.className, /text-transparent!/);+ await field.blur(element); // the window lost focus; the field is still the page's focus+ assert.equal(field.mask(), undefined, "switching apps keeps the field open");+ await field.focus(element);+ assert.equal(selects, 1, "coming back keeps the caret where it was");+ element.ownerDocument = { activeElement: null };+ await field.blur(element);+ assert.ok(field.mask(), "leaving the field shows the ends again");+});++test("the caller's own focus handlers still run", async (t) => {+ const calls = [];+ const field = await mountField(t, {+ label: "onboarding.rehaul.provider.endpointUrl",+ value: "http://127.0.0.1:8791/v1",+ onFocus: () => calls.push("focus"),+ onBlur: () => calls.push("blur"),+ });+ const element = { select() {}, contains: (node) => node === element };+ element.ownerDocument = { activeElement: null };+ await field.focus(element);+ await field.blur(element);+ assert.deepEqual(calls, ["focus", "blur"]);+});++test("a reason override replaces the default text and leaves the field valid", async (t) => {+ const Field = await loadField(t);+ const html = markup(Field, failed("credentialsRejected"), {+ failureReason: "reasoning.custom.endpointUnauthorized",+ });+ assert.match(html, /role="alert">reasoning\.custom\.endpointUnauthorized</);+ assert.doesNotMatch(html, /aria-invalid="/, "the value is not what is wrong");+ const plain = markup(Field, failed("credentialsRejected"));+ assert.match(plain, /aria-invalid="true"/, "without an override, a rejection marks it");+});++test("no verdict shows its reason in amber with Retry, and the value stays valid", async (t) => {+ const Field = await loadField(t);+ for (const errorCode of ["timeout", "network", "providerStatus"]) {+ const html = markup(Field, {+ phase: "unverified",+ failure: { success: false, errorCode, status: 503, unverified: true },+ });+ assert.match(html, /data-state="unverified"/, errorCode);+ assert.doesNotMatch(html, /aria-invalid="/, errorCode);+ assert.match(+ html,+ /<p class="mt-1 px-1 text-xs leading-\[1\.4\] text-amber-700 dark:text-amber-300">/,+ errorCode+ );+ const reason = `role="alert">onboarding\\.rehaul\\.provider\\.unverified\\(onboarding\\.rehaul\\.provider\\.errors\\.${errorCode}\\)<`;+ assert.match(html, new RegExp(reason), errorCode);+ assert.match(html, /<button type="button"[^>]*>common\.retry<\/button>/, errorCode);+ }+ assert.match(+ markup(Field, failed("credentialsRejected")),+ /<p class="mt-1 px-1 text-xs leading-\[1\.4\] text-destructive">/+ );+});diff --git a/test/components/reasoningModelSelectorCheck.test.js b/test/components/reasoningModelSelectorCheck.test.jsnew file mode 100644index 000000000..6c6b790f0--- /dev/null+++ b/test/components/reasoningModelSelectorCheck.test.js@@ -0,0 +1,347 @@+const assert = require("node:assert/strict");+const test = require("node:test");+const { mountSettingsPanel } = require("../lib/settingsPanelHarness");++const SELECTOR = "/components/ReasoningModelSelector.tsx";+const KEY = "common.apiKey";+const REJECTED = { success: false, errorCode: "credentialsRejected", status: 401 };+const props = (overrides = {}) => ({+ reasoningModel: "gpt-test",+ setReasoningModel() {},+ localReasoningProvider: "openai",+ setLocalReasoningProvider() {},+ cloudReasoningBaseUrl: "",+ setCloudReasoningBaseUrl() {},+ mode: "cloud",+ ...overrides,+});+const mount = (t, { overrides, ...options } = {}) =>+ mountSettingsPanel(t, { module: SELECTOR, props: props(overrides), ...options });++test("a saved key is checked once the panel is shown, with the panel's model", async (t) => {+ const panel = await mount(t, { secrets: { openaiApiKey: "sk-saved" } });+ assert.equal(panel.phase(), "waiting");+ await panel.wait(0);+ assert.deepEqual(panel.requests(), [+ { scope: "reasoning", provider: "openai", apiKey: "sk-saved", model: "gpt-test" },+ ]);+ await panel.answer({ success: true });+ assert.equal(panel.phase(), "connected");+ assert.equal(panel.announcement(), "connected");+});++test("a provider tab that is only browsed checks its key alone", async (t) => {+ const panel = await mount(t, {+ secrets: { openaiApiKey: "sk-saved", anthropicApiKey: "sk-ant-saved" },+ });+ await panel.selectTab("anthropic");+ await panel.wait(0);+ assert.deepEqual(panel.requests(), [+ { scope: "reasoning", provider: "anthropic", apiKey: "sk-ant-saved", model: "" },+ ]);+});++test("a hidden panel waits until it is shown, and asks again each time it is shown", async (t) => {+ const panel = await mount(t, { secrets: { openaiApiKey: "sk-saved" }, visible: false });+ await panel.wait(5000);+ assert.equal(panel.requests().length, 0);+ assert.equal(panel.phase(), "idle");+ await panel.setVisible(true);+ assert.equal(panel.phase(), "waiting");+ await panel.wait(0);+ assert.equal(panel.requests().length, 1);+ await panel.answer({ success: true });+ assert.equal(panel.phase(), "connected");+ await panel.setVisible(false);+ assert.equal(panel.phase(), "idle", "nothing is shown while hidden");+ await panel.setVisible(true);+ assert.equal(panel.phase(), "waiting");+ await panel.wait(0);+ // The main process answers a check it remembers at once, without asking the provider.+ assert.equal(panel.requests().length, 2, "a shown panel asks again");+ await panel.answer({ success: true });+ assert.equal(panel.phase(), "connected");+});++test("a shown panel with a remembered answer shows it at once, with no pause", async (t) => {+ const panel = await mount(t, { secrets: { openaiApiKey: "sk-saved" }, visible: false });+ await panel.setVisible(true);+ await panel.wait(0); // no time passes+ assert.equal(panel.requests().length, 1, "asked as soon as it is shown");+ // The main process answers a check it remembers at once, without asking the provider.+ await panel.answer({ success: true });+ assert.equal(panel.phase(), "connected");+ assert.equal(panel.announcement(), "connected");+});++test("a key saves trimmed once its check passes or its field is left, never half typed", async (t) => {+ const panel = await mount(t);+ assert.equal(panel.phase(), "idle", "no key, no status");+ await panel.type(KEY, " sk-pas");+ await panel.type(KEY, " sk-pasted ");+ await panel.wait(500);+ assert.equal(panel.requests().at(-1).apiKey, "sk-pasted");+ assert.equal(panel.state().openaiApiKey, "", "nothing is saved while the key is typed");+ await panel.answer({ success: true });+ assert.equal(panel.state().openaiApiKey, "sk-pasted", "a passing key saves at once");+ await panel.type(KEY, "sk-other");+ await panel.blur(KEY, { windowSwitch: true });+ await panel.wait(500); // the field keeps its pause while another window has focus+ assert.equal(panel.state().openaiApiKey, "sk-pasted", "nothing is saved before its answer");+ await panel.answer({ success: false, errorCode: "network", unverified: true });+ assert.equal(panel.state().openaiApiKey, "sk-other", "leaving the window saves it");+});++test("a typed key is kept when another provider takes its field, and saves on unmount", async (t) => {+ const panel = await mount(t);+ await panel.type(KEY, "sk-typed");+ // The scope's provider changes elsewhere, so the focused field shows Anthropic's key.+ await panel.setProps({ localReasoningProvider: "anthropic" });+ await panel.type(KEY, "sk-ant-typed");+ await panel.wait(500);+ await panel.answer({ success: true });+ assert.equal(panel.state().anthropicApiKey, "sk-ant-typed");+ assert.equal(panel.state().openaiApiKey, "", "another provider's answer settles nothing here");+ await panel.setProps({ localReasoningProvider: "openai" });+ assert.equal(panel.field(KEY).props.value, "sk-typed", "and is still there to come back to");+ await panel.unmount(); // Escape closing Settings fires no blur+ assert.equal(panel.state().openaiApiKey, "sk-typed");+ assert.equal(panel.state().anthropicApiKey, "sk-ant-typed");+});++test("typing keeps the 0.5 s pause, and leaving the field sends at once", async (t) => {+ const panel = await mount(t);+ await panel.type(KEY, "sk-first");+ assert.equal(panel.phase(), "waiting");+ await panel.wait(499);+ assert.equal(panel.requests().length, 0, "nothing while the pause runs");+ await panel.wait(1);+ assert.deepEqual(+ panel.requests().map((config) => config.apiKey),+ ["sk-first"]+ );+ await panel.type(KEY, "sk-second");+ await panel.wait(200);+ await panel.blur(KEY); // mid-pause+ await panel.wait(0);+ assert.deepEqual(+ panel.requests().map((config) => config.apiKey),+ ["sk-first", "sk-second"]+ );+});++test("a key typed in another shown panel still waits for the pause", async (t) => {+ const panel = await mount(t, { secrets: { anthropicApiKey: "sk-ant-saved" } });+ // The hosted key is shared: another shown panel types it, so no field here has focus.+ await panel.setStore({ openaiApiKey: "s" });+ assert.equal(panel.phase(), "waiting");+ await panel.wait(499);+ assert.equal(panel.requests().length, 0, "a half-typed key is not sent");+ await panel.setStore({ openaiApiKey: "sk" });+ await panel.wait(499);+ assert.equal(panel.requests().length, 0, "each change starts the pause over");+ await panel.wait(1);+ assert.deepEqual(+ panel.requests().map((config) => config.apiKey),+ ["sk"]+ );+ await panel.selectTab("anthropic");+ await panel.wait(0); // a tab switch checks at once, though it shows another key+ assert.deepEqual(+ panel.requests().map((config) => config.apiKey),+ ["sk", "sk-ant-saved"]+ );+});++test("a rejected key keeps its reason and Retry, and stays saved", async (t) => {+ const panel = await mount(t, { secrets: { openaiApiKey: "sk-saved" } });+ await panel.wait(0);+ await panel.answer(REJECTED);+ assert.equal(panel.checkField().props.check.failure.errorCode, "credentialsRejected");+ assert.equal(panel.checkField().props.invalidOn, "credentialsRejected", "the key is at fault");+ assert.equal(panel.state().openaiApiKey, "sk-saved");+ await panel.retry();+ assert.equal(panel.requests().length, 2, "Retry does not wait for the pause");+});++test("each hosted provider shows one shared key field under Settings' heading", async (t) => {+ for (const [provider, url] of [+ ["openai", "https://platform.openai.com/api-keys"],+ ["anthropic", "https://console.anthropic.com/settings/keys"],+ ["gemini", "https://aistudio.google.com/app/api-keys"],+ ["groq", "https://console.groq.com/keys"],+ ["corti", "https://www.corti.ai/?utm_source=referral&utm_campaign=openwhispr"],+ ]) {+ await t.test(provider, async (t) => {+ const panel = await mount(t, { overrides: { localReasoningProvider: provider } });+ assert.equal(panel.field(KEY).props.type, "password");+ assert.ok(panel.field(KEY).props.check, "the key carries the status");+ assert.equal(panel.find((node) => node.props?.url === url).length, 1);+ const euOnly = panel.find((node) => node.props?.children === "reasoning.corti.euOnly");+ assert.equal(euOnly.length, provider === "corti" ? 1 : 0);+ });+ }+});++test("local mode, OpenRouter and Custom send nothing from this panel", async (t) => {+ for (const [name, overrides] of [+ ["local", { mode: "local", localReasoningProvider: "qwen" }],+ ["openrouter", { localReasoningProvider: "openrouter" }],+ ["custom", { localReasoningProvider: "custom" }],+ ]) {+ await t.test(name, async (t) => {+ const panel = await mount(t, {+ overrides,+ secrets: { openaiApiKey: "sk-saved", openrouterApiKey: "sk-or-saved" },+ });+ await panel.wait(1000);+ assert.equal(panel.requests().length, 0);+ assert.equal(panel.field(KEY), undefined);+ if (name === "openrouter") {+ assert.equal(panel.find((node) => node.props?.provider === "openrouter").length, 1);+ }+ });+ }+});++test("a key the provider refuses is never saved, and the saved key stays in use", async (t) => {+ const panel = await mount(t, { secrets: { openaiApiKey: "sk-saved" } });+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.type(KEY, "sk-wrong");+ await panel.wait(500);+ await panel.answer(REJECTED);+ await panel.blur(KEY);+ assert.equal(panel.state().openaiApiKey, "sk-saved", "leaving the field keeps the saved key");+ assert.equal(panel.field(KEY).props.value, "sk-wrong", "the refused key stays to be fixed");+ // Another provider takes the field, then Settings closes: neither saves the refused key.+ await panel.setProps({ localReasoningProvider: "anthropic" });+ await panel.type(KEY, "sk-ant-typed");+ await panel.unmount();+ assert.equal(panel.state().openaiApiKey, "sk-saved");+ assert.equal(panel.state().anthropicApiKey, "sk-ant-typed");+});++for (const [answered, answer, saved] of [+ ["a refusal", REJECTED, "sk-saved"],+ ["no verdict", { success: false, errorCode: "network", unverified: true }, "sk-typed"],+ [+ "a failure about the account",+ { success: false, errorCode: "providerStatus", status: 402 },+ "sk-typed",+ ],+]) {+ test(`a key left while its check runs waits for the answer: ${answered}`, async (t) => {+ const panel = await mount(t, { secrets: { openaiApiKey: "sk-saved" } });+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.type(KEY, "sk-typed");+ await panel.blur(KEY);+ await panel.wait(0); // leaving the field checks at once+ assert.equal(panel.state().openaiApiKey, "sk-saved", "nothing is saved before the answer");+ await panel.answer(answer);+ assert.equal(panel.state().openaiApiKey, saved);+ });+}++test("a refused key saves once a later check of it passes", async (t) => {+ const panel = await mount(t, { secrets: { openaiApiKey: "sk-saved" } });+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.type(KEY, "sk-new");+ await panel.wait(500);+ await panel.answer(REJECTED);+ await panel.blur(KEY);+ await panel.retry(); // the key was only just activated+ await panel.answer({ success: true });+ assert.equal(panel.state().openaiApiKey, "sk-new");+});++test("a refused key stays unsaved when a later check gives no verdict", async (t) => {+ const panel = await mount(t, { secrets: { openaiApiKey: "sk-saved" } });+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.type(KEY, "sk-wrong");+ await panel.wait(500);+ await panel.answer(REJECTED);+ await panel.blur(KEY);+ await panel.retry();+ await panel.answer({+ success: false,+ errorCode: "providerStatus",+ status: 503,+ unverified: true,+ });+ await panel.unmount();+ assert.equal(panel.state().openaiApiKey, "sk-saved");+});++test("a key left before its answer is saved as it stands when its panel is hidden", async (t) => {+ const panel = await mount(t, { secrets: { openaiApiKey: "sk-old" } });+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.type(KEY, "sk-new");+ await panel.blur(KEY);+ await panel.wait(0); // leaving the field checks at once+ assert.equal(panel.state().openaiApiKey, "sk-old");+ await panel.setVisible(false); // another Settings tab: no answer is coming for it+ assert.equal(panel.state().openaiApiKey, "sk-new");+});++test("a refused key stays in its field across a hidden panel and is never saved", async (t) => {+ const panel = await mount(t, { secrets: { openaiApiKey: "sk-saved" } });+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.type(KEY, "sk-wrong");+ await panel.wait(500);+ await panel.answer(REJECTED);+ await panel.blur(KEY);+ await panel.setVisible(false);+ await panel.setStore({ openaiApiKey: "sk-fixed" }); // another panel saves a working key+ await panel.setVisible(true);+ await panel.wait(0);+ assert.equal(panel.field(KEY).props.value, "sk-wrong", "the refused key waits to be fixed");+ await panel.answer(REJECTED);+ await panel.unmount();+ assert.equal(panel.state().openaiApiKey, "sk-fixed");+});++test("every refused key stays refused, not only the last one", async (t) => {+ const panel = await mount(t, { secrets: { openaiApiKey: "sk-saved" } });+ await panel.wait(0);+ await panel.answer({ success: true });+ for (const key of ["sk-bad1", "sk-bad2"]) {+ await panel.type(KEY, key);+ await panel.wait(500);+ await panel.answer(REJECTED);+ }+ await panel.type(KEY, "sk-bad1");+ await panel.blur(KEY);+ await panel.wait(0);+ await panel.answer({ success: false, errorCode: "network", unverified: true });+ await panel.unmount();+ assert.equal(panel.state().openaiApiKey, "sk-saved");+});++test("closing Settings saves a key typed for a provider that is no longer shown", async (t) => {+ const panel = await mount(t);+ await panel.type(KEY, "sk-typed");+ await panel.setProps({ localReasoningProvider: "anthropic" }); // the field stays focused+ await panel.unmount();+ assert.equal(panel.state().openaiApiKey, "sk-typed");+});++test("a refused key typed again is held back before its new answer", async (t) => {+ const panel = await mount(t, { secrets: { openaiApiKey: "sk-saved" } });+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.type(KEY, "sk-bad");+ await panel.wait(500);+ await panel.answer(REJECTED);+ await panel.type(KEY, "sk-saved");+ await panel.wait(500);+ await panel.answer({ success: true });+ await panel.type(KEY, "sk-bad"); // pasted back, and Settings closes before the check+ await panel.unmount();+ assert.equal(panel.state().openaiApiKey, "sk-saved");+});diff --git a/test/components/selfHostedPanelCheck.test.js b/test/components/selfHostedPanelCheck.test.jsnew file mode 100644index 000000000..d492f0417--- /dev/null+++ b/test/components/selfHostedPanelCheck.test.js@@ -0,0 +1,90 @@+const assert = require("node:assert/strict");+const test = require("node:test");+const { mountSettingsPanel } = require("../lib/settingsPanelHarness");++const PANEL = "/components/SelfHostedPanel.tsx";+const URL_FIELD = "settingsPage.selfHosted.serverUrl";+const MODEL = "common.model";+const SERVER = "http://192.168.1.20:8178";+const props = (overrides = {}) => ({+ service: "transcription",+ url: "",+ onUrlChange() {},+ model: "",+ onModelChange() {},+ ...overrides,+});+const mount = (t, { overrides, ...options } = {}) =>+ mountSettingsPanel(t, { module: PANEL, props: props(overrides), ...options });++test("the model holds the status, and the address waits until it is left", async (t) => {+ const panel = await mount(t, { overrides: { model: "whisper-large-v3" } });+ assert.ok(panel.field(MODEL).props.check);+ assert.equal(panel.field(MODEL).props.invalidOn, "modelNotFound");+ assert.equal(panel.field(URL_FIELD).props.check, undefined);+ await panel.focus(URL_FIELD);+ await panel.setProps({ url: SERVER });+ await panel.wait(2000);+ await panel.blur(URL_FIELD, { windowSwitch: true });+ await panel.wait(2000);+ assert.equal(panel.requests().length, 0);+ await panel.blur(URL_FIELD);+ await panel.wait(0); // leaving the fields checks at once+ assert.deepEqual(panel.requests(), [+ { scope: "transcription", provider: "custom", baseUrl: SERVER, model: "whisper-large-v3" },+ ]);+});++test("this server takes no key, so a refusal says it wants one", async (t) => {+ const panel = await mount(t, { overrides: { url: SERVER, model: "whisper-large-v3" } });+ await panel.wait(0);+ await panel.answer({ success: false, errorCode: "credentialsRejected", status: 403 });+ assert.equal(panel.field(MODEL).props.failureReason, "reasoning.custom.endpointUnauthorized");+});++test("an incomplete or hidden self-hosted panel sends nothing", async (t) => {+ for (const [name, options] of [+ ["no model", { overrides: { url: SERVER } }],+ ["hidden", { overrides: { url: SERVER, model: "whisper-large-v3" }, visible: false }],+ ]) {+ await t.test(name, async (t) => {+ const panel = await mount(t, options);+ await panel.wait(5000);+ assert.equal(panel.requests().length, 0);+ });+ }+});++test("a self-hosted panel asks again each time it is shown", async (t) => {+ const panel = await mount(t, { overrides: { url: SERVER, model: "whisper-large-v3" } });+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.setVisible(false);+ assert.equal(panel.phase(), "idle", "nothing is shown while hidden");+ await panel.setVisible(true);+ await panel.wait(0);+ assert.equal(panel.requests().length, 2, "a shown panel asks again");+});++test("a self-hosted server for the streaming Orukeet model is left unchecked", async (t) => {+ const panel = await mount(t, { overrides: { url: SERVER, model: "orukeet-v0.1.0" } });+ await panel.wait(5000);+ assert.equal(panel.requests().length, 0);+ assert.equal(panel.phase(), "idle");+});++test("the address and model save as they are typed", async (t) => {+ const saved = [];+ const panel = await mount(t, {+ overrides: {+ onUrlChange: (value) => saved.push(["url", value]),+ onModelChange: (value) => saved.push(["model", value]),+ },+ });+ await panel.type(URL_FIELD, "http://192.168.1.20 ");+ await panel.type(MODEL, "whisper ");+ assert.deepEqual(saved, [+ ["url", "http://192.168.1.20 "],+ ["model", "whisper "],+ ]);+});diff --git a/test/components/settingsConnectionCheck.test.js b/test/components/settingsConnectionCheck.test.jsnew file mode 100644index 000000000..dcfe38d5e--- /dev/null+++ b/test/components/settingsConnectionCheck.test.js@@ -0,0 +1,69 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const path = require("node:path");+const React = require("react");+const { renderToStaticMarkup } = require("react-dom/server");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++const source = (relativePath) =>+ fs.readFileSync(path.join(__dirname, "../..", relativePath), "utf8");++async function load(t) {+ installBrowserGlobals(t);+ return createRendererServer(t, {+ cachePrefix: "openwhispr-settings-check-plumbing-",+ noExternal: ["react-i18next"],+ mockModules: {+ "react-i18next": `+ const t = (key) => key;+ export function useTranslation() { return { t }; }+ `,+ },+ });+}++test("a TabPanel hides its panel, and a nested one shows only while all are active", async (t) => {+ const vite = await load(t);+ const { TabPanel } = await vite.ssrLoadModule("/components/ui/TabPanel.tsx");+ const { usePanelVisible } = await vite.ssrLoadModule("/components/ui/usePanelVisible.ts");+ function Probe() {+ return React.createElement("i", null, usePanelVisible() ? "shown" : "held");+ }+ const nest = (outer, inner) =>+ renderToStaticMarkup(+ React.createElement(+ TabPanel,+ { active: outer },+ React.createElement(TabPanel, { active: inner }, React.createElement(Probe))+ )+ );+ assert.equal(renderToStaticMarkup(React.createElement(Probe)), "<i>shown</i>");+ assert.equal(nest(true, true), "<div><div><i>shown</i></div></div>");+ assert.equal(nest(true, false), '<div><div class="hidden"><i>held</i></div></div>');+ assert.equal(nest(false, true), '<div class="hidden"><div><i>held</i></div></div>');+});++test("the announcer is there from the start and says only what the check found", async (t) => {+ const vite = await load(t);+ const { ConnectionCheckAnnouncer } = await vite.ssrLoadModule(+ "/components/ui/ConnectionCheckAnnouncer.tsx"+ );+ const say = (announcement) =>+ renderToStaticMarkup(React.createElement(ConnectionCheckAnnouncer, { announcement }));+ assert.equal(+ say(null),+ '<div role="status" aria-live="polite" aria-atomic="true" class="sr-only"></div>'+ );+ for (const announcement of ["testing", "connected"]) {+ const spoken = `class="sr-only">onboarding.rehaul.provider.${announcement}</div>`;+ assert.ok(say(announcement).endsWith(spoken), announcement);+ }+});++test("Settings' sections and sub-tabs use the shared TabPanel", () => {+ const settings = source("src/components/SettingsPage.tsx");+ assert.match(settings, /import \{ TabPanel \} from "\.\/ui\/TabPanel";/);+ assert.doesNotMatch(settings, /function TabPanel\(/);+ assert.equal(settings.match(/<TabPanel active=/g).length, 10);+});diff --git a/test/components/transcriptionModelPickerCheck.test.js b/test/components/transcriptionModelPickerCheck.test.jsnew file mode 100644index 000000000..c53bde63f--- /dev/null+++ b/test/components/transcriptionModelPickerCheck.test.js@@ -0,0 +1,498 @@+const assert = require("node:assert/strict");+const test = require("node:test");+const { mountSettingsPanel } = require("../lib/settingsPanelHarness");++const PICKER = "/components/TranscriptionModelPicker.tsx";+const KEY = "common.apiKey";+const ENDPOINT = "transcription.endpointUrl";+const CUSTOM_KEY = "transcription.apiKeyOptional";+const MODEL = "common.model";+const CLIENT_ID = "transcription.corti.clientId";+const CLIENT_SECRET = "transcription.corti.clientSecret";+const TENANT = "transcription.corti.tenant";+const REJECTED = { success: false, errorCode: "credentialsRejected", status: 401 };+// The picker's download hooks subscribe at mount.+const DOWNLOADS = {+ onWhisperDownloadProgress: () => () => {},+ onParakeetDownloadProgress: () => () => {},+};+const props = (overrides = {}) => ({+ transcriptionContext: "dictation",+ selectedCloudProvider: "groq",+ onCloudProviderSelect() {},+ selectedCloudModel: "whisper-large-v3-turbo",+ onCloudModelSelect() {},+ selectedLocalModel: "",+ onLocalModelSelect() {},+ useLocalWhisper: false,+ onModeChange() {},+ cloudTranscriptionBaseUrl: "",+ setCloudTranscriptionBaseUrl() {},+ mode: "cloud",+ ...overrides,+});+const mount = (t, { overrides, ...options } = {}) =>+ mountSettingsPanel(t, {+ module: PICKER,+ props: props(overrides),+ electronAPI: DOWNLOADS,+ ...options,+ });++test("a key is checked with the panel's model, or alone under a browsed tab", async (t) => {+ const panel = await mount(t, { secrets: { groqApiKey: "gsk-saved", openaiApiKey: "sk-saved" } });+ await panel.wait(0);+ assert.deepEqual(panel.requests(), [+ {+ scope: "transcription",+ provider: "groq",+ apiKey: "gsk-saved",+ model: "whisper-large-v3-turbo",+ },+ ]);+ assert.equal(panel.checkField().props.invalidOn, "credentialsRejected");+ await panel.selectTab("openai");+ await panel.wait(0);+ assert.deepEqual(panel.requests().at(-1), {+ scope: "transcription",+ provider: "openai",+ apiKey: "sk-saved",+ model: "",+ });+});++test("a hidden picker sends nothing until it is shown, then asks again", async (t) => {+ const panel = await mount(t, { secrets: { groqApiKey: "gsk-saved" }, visible: false });+ await panel.wait(5000);+ assert.equal(panel.requests().length, 0);+ await panel.setVisible(true);+ await panel.wait(0);+ assert.equal(panel.requests().length, 1);+ await panel.answer({ success: true });+ await panel.setVisible(false);+ await panel.setVisible(true);+ await panel.wait(0);+ assert.equal(panel.requests().length, 2, "a shown panel asks again");+});++test("a key saves trimmed once its check passes, never half typed", async (t) => {+ const panel = await mount(t);+ await panel.type(KEY, " gsk-pas");+ await panel.type(KEY, " gsk-pasted ");+ await panel.wait(500); // the key still has focus, so the pause runs+ assert.deepEqual(+ panel.requests().map((config) => config.apiKey),+ ["gsk-pasted"]+ );+ assert.equal(panel.state().groqApiKey, "", "nothing is saved while the key is typed");+ await panel.answer({ success: true });+ assert.equal(panel.state().groqApiKey, "gsk-pasted", "a passing key saves at once");+});++test("Corti: the secret holds the status, checked with ID, region and tenant", async (t) => {+ const panel = await mount(t, {+ overrides: { selectedCloudProvider: "corti", selectedCloudModel: "corti-transcribe" },+ secrets: {+ cortiClientId: "corti-id",+ cortiClientSecret: "corti-secret",+ cortiEnvironment: "eu",+ cortiTenant: "",+ },+ });+ assert.ok(panel.field(CLIENT_SECRET).props.check);+ assert.equal(panel.field(CLIENT_SECRET).props.invalidOn, "credentialsRejected");+ assert.equal(panel.field(CLIENT_SECRET).props.type, "password");+ assert.equal(panel.field(CLIENT_ID).props.check, undefined);+ assert.equal(panel.field(CLIENT_ID).props.type, "text", "a client ID is not a secret");+ assert.equal(panel.field(TENANT).props.check, undefined);+ await panel.wait(0);+ assert.deepEqual(panel.requests(), [+ {+ scope: "transcription",+ provider: "corti",+ clientId: "corti-id",+ clientSecret: "corti-secret",+ environment: "eu",+ tenant: "",+ },+ ]);+ await panel.choose("us");+ await panel.wait(0); // choosing a region checks at once+ assert.equal(panel.requests().at(-1).environment, "us");+ await panel.type(CLIENT_ID, " corti-id-2 ");+ assert.equal(panel.state().cortiClientId, "corti-id", "nothing is saved while it is typed");+ await panel.blur(CLIENT_ID);+ await panel.wait(0); // leaving the field checks at once+ await panel.answer({ success: false, errorCode: "network", unverified: true });+ assert.equal(panel.state().cortiClientId, "corti-id-2", "leaving the field saves it");+});++test("Custom: the model holds the status, and the address waits until it is left", async (t) => {+ const typed = [];+ const panel = await mount(t, {+ overrides: {+ selectedCloudProvider: "custom",+ selectedCloudModel: "whisper-1",+ setCloudTranscriptionBaseUrl: (value) => typed.push(value),+ },+ });+ assert.ok(panel.field(MODEL).props.check);+ assert.equal(+ panel.field(MODEL).props.invalidOn,+ "modelNotFound",+ "a missing model is the model's fault"+ );+ await panel.focus(ENDPOINT);+ for (const url of ["http://127.0.0.1", "http://127.0.0.1:8000/v1"]) {+ await panel.type(ENDPOINT, url);+ await panel.setProps({ cloudTranscriptionBaseUrl: url });+ await panel.wait(2000);+ }+ assert.deepEqual(typed, ["http://127.0.0.1", "http://127.0.0.1:8000/v1"]);+ assert.equal(panel.requests().length, 0);+ assert.equal(panel.phase(), "idle");+ await panel.blur(ENDPOINT, { windowSwitch: true });+ await panel.wait(2000);+ assert.equal(panel.requests().length, 0, "switching apps keeps the hold");+ await panel.blur(ENDPOINT);+ assert.equal(panel.phase(), "waiting");+ await panel.wait(0); // leaving the fields checks at once+ assert.deepEqual(panel.requests(), [+ {+ scope: "transcription",+ provider: "custom",+ baseUrl: "http://127.0.0.1:8000/v1",+ apiKey: "",+ model: "whisper-1",+ },+ ]);+ await panel.answer(REJECTED);+ assert.equal(panel.field(MODEL).props.failureReason, "reasoning.custom.endpointUnauthorized");+});++test("Custom: an Azure endpoint is not checked, any other address is", async (t) => {+ const panel = await mount(t, {+ overrides: {+ selectedCloudProvider: "custom",+ selectedCloudModel: "whisper-deployment",+ cloudTranscriptionBaseUrl: "https://my-resource.cognitiveservices.azure.com",+ },+ });+ await panel.wait(5000);+ assert.equal(panel.requests().length, 0, "Azure takes its own URL and api-key header");+ assert.equal(panel.phase(), "idle");+ await panel.setProps({ cloudTranscriptionBaseUrl: "http://127.0.0.1:8000/v1" });+ await panel.wait(500);+ assert.deepEqual(+ panel.requests().map((config) => config.baseUrl),+ ["http://127.0.0.1:8000/v1"]+ );+});++test("leaving an address that is tidied on blur checks at once", async (t) => {+ // The setter saves straight into the picker's props, as the store does for its parent, so+ // the tidied address and the hold's drop reach the picker in one render.+ const live = props({+ selectedCloudProvider: "custom",+ selectedCloudModel: "whisper-1",+ cloudTranscriptionBaseUrl: "http://127.0.0.1:8080/v1/",+ });+ live.setCloudTranscriptionBaseUrl = (value) => {+ live.cloudTranscriptionBaseUrl = value;+ };+ const panel = await mountSettingsPanel(t, {+ module: PICKER,+ props: live,+ electronAPI: DOWNLOADS,+ });+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.focus(ENDPOINT);+ await panel.blur(ENDPOINT); // the hold drops and the address is saved without its slash+ assert.equal(live.cloudTranscriptionBaseUrl, "http://127.0.0.1:8080/v1");+ await panel.wait(0);+ assert.deepEqual(+ panel.requests().map((config) => config.baseUrl),+ ["http://127.0.0.1:8080/v1/", "http://127.0.0.1:8080/v1"],+ "leaving the address checks it at once"+ );+});++test("moving focus between the panel's own fields keeps the pause", async (t) => {+ const panel = await mount(t, {+ overrides: {+ selectedCloudProvider: "custom",+ selectedCloudModel: "whisper-1",+ cloudTranscriptionBaseUrl: "http://127.0.0.1:8000/v1",+ },+ });+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.type(CUSTOM_KEY, "sk-server");+ await panel.wait(300);+ await panel.focus(MODEL); // focus moves from the key to the model, inside the panel+ await panel.wait(199);+ assert.equal(panel.requests().length, 1, "nothing before the pause ends");+ await panel.wait(1);+ assert.deepEqual(+ panel.requests().map((config) => config.apiKey),+ ["", "sk-server"]+ );+});++test("Note Recording checks its streaming providers' keys too", async (t) => {+ const panel = await mount(t, {+ overrides: {+ transcriptionContext: "meeting",+ streamingOnly: true,+ selectedCloudProvider: "deepgram",+ selectedCloudModel: "nova-3",+ },+ secrets: { deepgramApiKey: "dg-saved" },+ });+ await panel.wait(0);+ assert.deepEqual(panel.requests(), [+ { scope: "transcription", provider: "deepgram", apiKey: "dg-saved", model: "nova-3" },+ ]);+});++test("Corti: nothing of a refused setup is saved, not even its client ID", async (t) => {+ const panel = await mount(t, {+ overrides: { selectedCloudProvider: "corti", selectedCloudModel: "corti-transcribe" },+ secrets: {+ cortiClientId: "corti-id",+ cortiClientSecret: "corti-secret",+ cortiEnvironment: "eu",+ cortiTenant: "",+ },+ });+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.type(CLIENT_SECRET, "wrong-secret");+ await panel.blur(CLIENT_SECRET);+ await panel.wait(0);+ await panel.answer(REJECTED);+ assert.equal(panel.state().cortiClientSecret, "corti-secret");+ // A refusal can't say which part is wrong, so it holds back every part that was typed.+ await panel.type(CLIENT_ID, "corti-id-2");+ await panel.blur(CLIENT_ID);+ await panel.wait(0);+ await panel.answer(REJECTED);+ assert.equal(panel.state().cortiClientId, "corti-id");+ await panel.type(CLIENT_SECRET, "other-secret"); // the refused ID still holds the setup back+ await panel.unmount();+ assert.deepEqual(+ [panel.state().cortiClientId, panel.state().cortiClientSecret],+ ["corti-id", "corti-secret"],+ "the working setup stays"+ );+});++test("Custom: a key the server refuses still saves once its field is left", async (t) => {+ const panel = await mount(t, {+ overrides: {+ selectedCloudProvider: "custom",+ selectedCloudModel: "whisper-1",+ cloudTranscriptionBaseUrl: "http://127.0.0.1:8000/v1",+ },+ secrets: { customTranscriptionApiKey: "sk-local" },+ });+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.type(CUSTOM_KEY, "sk-wrong");+ await panel.blur(CUSTOM_KEY);+ await panel.wait(0);+ await panel.answer(REJECTED);+ assert.equal(panel.state().customTranscriptionApiKey, "sk-wrong");+});++test("Corti: a refused secret stays in its field while another field is fixed", async (t) => {+ const panel = await mount(t, {+ overrides: { selectedCloudProvider: "corti", selectedCloudModel: "corti-transcribe" },+ secrets: {+ cortiClientId: "id",+ cortiClientSecret: "",+ cortiEnvironment: "eu",+ cortiTenant: "",+ },+ });+ await panel.type(CLIENT_SECRET, "right-secret");+ await panel.blur(CLIENT_SECRET);+ await panel.wait(0);+ await panel.answer(REJECTED); // refused because the tenant is wrong+ await panel.type(TENANT, "acme");+ assert.equal(panel.field(CLIENT_SECRET).props.value, "right-secret");+ assert.equal(panel.state().cortiClientSecret, "", "and it is not saved");+ await panel.blur(TENANT);+ await panel.wait(0);+ assert.deepEqual(+ [panel.requests().at(-1).clientSecret, panel.requests().at(-1).tenant],+ ["right-secret", "acme"]+ );+ await panel.answer({ success: true });+ assert.equal(panel.state().cortiClientSecret, "right-secret", "a passing check saves both");+ assert.equal(panel.state().cortiTenant, "acme");+});++test("Corti: emptying the client ID to retype it keeps the typed secret", async (t) => {+ const panel = await mount(t, {+ overrides: { selectedCloudProvider: "corti", selectedCloudModel: "corti-transcribe" },+ secrets: { cortiClientId: "wrong-id", cortiClientSecret: "", cortiEnvironment: "eu" },+ });+ await panel.type(CLIENT_SECRET, "right-secret");+ await panel.blur(CLIENT_SECRET);+ await panel.wait(0);+ await panel.answer(REJECTED); // the ID is the wrong half+ for (const id of ["wrong-i", "w", ""]) {+ await panel.type(CLIENT_ID, id);+ await panel.wait(500); // a part-typed ID is checked, but never answered here+ }+ assert.equal(panel.field(CLIENT_SECRET).props.value, "right-secret");+ assert.equal(panel.state().cortiClientSecret, "", "the refused secret is not saved");+ await panel.type(CLIENT_ID, "right-id");+ await panel.blur(CLIENT_ID);+ await panel.wait(0);+ assert.deepEqual(+ [panel.requests().at(-1).clientId, panel.requests().at(-1).clientSecret],+ ["right-id", "right-secret"]+ );+ await panel.answer({ success: true });+ assert.equal(panel.state().cortiClientSecret, "right-secret");+});++test("Corti: a secret and the ID it was checked with are saved together", async (t) => {+ const panel = await mount(t, {+ overrides: { selectedCloudProvider: "corti", selectedCloudModel: "corti-transcribe" },+ secrets: { cortiClientId: "id", cortiClientSecret: "good", cortiEnvironment: "eu" },+ });+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.type(CLIENT_SECRET, "bad");+ await panel.blur(CLIENT_SECRET);+ await panel.wait(0);+ await panel.answer(REJECTED);+ await panel.type(CLIENT_ID, "id2"); // still in the field+ await panel.wait(500);+ await panel.answer({ success: false, errorCode: "network", unverified: true });+ assert.deepEqual(+ [panel.state().cortiClientId, panel.state().cortiClientSecret],+ ["id2", "bad"],+ "never the refused pair (id, bad)"+ );+});++for (const [field, typo, key] of [+ [CLIENT_ID, "good-idd", "cortiClientId"],+ [TENANT, "acm", "cortiTenant"],+]) {+ test(`Corti: a refused ${key} typed over a saved setup is never saved`, async (t) => {+ const saved = {+ cortiClientId: "good-id",+ cortiClientSecret: "good-secret",+ cortiTenant: "acme",+ };+ const panel = await mount(t, {+ overrides: { selectedCloudProvider: "corti", selectedCloudModel: "corti-transcribe" },+ secrets: { ...saved, cortiEnvironment: "eu" },+ });+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.type(field, typo);+ await panel.blur(field);+ await panel.wait(0);+ await panel.answer(REJECTED); // the secret is as saved, so the typo takes the blame+ assert.equal(panel.state()[key], saved[key]);+ assert.equal(panel.field(field).props.value, typo);+ await panel.unmount();+ assert.equal(panel.state()[key], saved[key], "nor when Settings closes");+ });+}++const CORTI_SAVED = { cortiClientId: "good-id", cortiClientSecret: "good-secret", cortiTenant: "" };+const mountCorti = (t) =>+ mount(t, {+ overrides: { selectedCloudProvider: "corti", selectedCloudModel: "corti-transcribe" },+ secrets: { ...CORTI_SAVED, cortiEnvironment: "eu" },+ });+const cortiPair = (panel) => [panel.state().cortiClientId, panel.state().cortiClientSecret];++test("Corti: a new secret after a refused ID is saved with that ID", async (t) => {+ const panel = await mountCorti(t);+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.type(CLIENT_ID, "id-right");+ await panel.blur(CLIENT_ID);+ await panel.wait(0);+ await panel.answer(REJECTED);+ await panel.type(CLIENT_SECRET, "s2");+ await panel.blur(CLIENT_SECRET);+ await panel.wait(0);+ await panel.answer({ success: false, errorCode: "network", unverified: true });+ assert.deepEqual(cortiPair(panel), ["id-right", "s2"]);+});++test("Corti: closing Settings while a refused ID waits keeps the working setup", async (t) => {+ const panel = await mountCorti(t);+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.type(CLIENT_ID, "id-right");+ await panel.blur(CLIENT_ID);+ await panel.wait(0);+ await panel.answer(REJECTED);+ await panel.type(CLIENT_SECRET, "s2");+ await panel.unmount(); // before the new pair is answered+ assert.deepEqual(cortiPair(panel), ["good-id", "good-secret"]);+});++test("Corti: a refused ID typo is held back whatever the secret field holds", async (t) => {+ const panel = await mountCorti(t);+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.type(CLIENT_SECRET, "new-secret");+ await panel.blur(CLIENT_SECRET);+ await panel.wait(0);+ await panel.answer(REJECTED); // the new secret belongs to a new ID+ await panel.type(CLIENT_SECRET, "good-secret"); // and back to the saved one+ await panel.type(CLIENT_ID, "good-idd");+ await panel.blur(CLIENT_ID);+ await panel.wait(0);+ await panel.answer(REJECTED);+ await panel.unmount();+ assert.deepEqual(cortiPair(panel), ["good-id", "good-secret"]);+});++test("Corti: a refused setup stays held back after its panel is hidden", async (t) => {+ const panel = await mountCorti(t);+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.type(CLIENT_ID, "id-right");+ await panel.blur(CLIENT_ID);+ await panel.wait(0);+ await panel.answer(REJECTED);+ await panel.type(CLIENT_SECRET, "s2");+ await panel.blur(CLIENT_SECRET);+ await panel.setVisible(false); // the Note Recording tab, before the new pair is answered+ await panel.unmount();+ assert.deepEqual(cortiPair(panel), ["good-id", "good-secret"]);+});++test("Corti: leaving a field that was already saved lets no answer save one still typed", async (t) => {+ const panel = await mount(t, {+ overrides: { selectedCloudProvider: "corti", selectedCloudModel: "corti-transcribe" },+ secrets: {+ cortiClientId: "id0",+ cortiClientSecret: "s0",+ cortiEnvironment: "eu",+ cortiTenant: "",+ },+ });+ await panel.wait(0);+ await panel.answer({ success: true });+ await panel.type(CLIENT_ID, "id1");+ await panel.wait(500);+ await panel.answer({ success: true }); // saves the ID while its field has focus+ await panel.type(TENANT, "ac"); // leaving the ID marks nothing: it has no draft+ await panel.wait(500);+ await panel.answer({ success: false, errorCode: "network", unverified: true });+ assert.equal(panel.state().cortiTenant, "", "a half-typed tenant waits until it is left");+});diff --git a/test/helpers/connectionCheckCache.test.js b/test/helpers/connectionCheckCache.test.jsnew file mode 100644index 000000000..113dd76d9--- /dev/null+++ b/test/helpers/connectionCheckCache.test.js@@ -0,0 +1,84 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { deferred } = require("./harness/deferred");+const {+ CONNECTED_TTL_MS,+ createConnectionCheckCache,+} = require("../../src/helpers/connectionCheckCache");++const CONFIG = { scope: "reasoning", provider: "openai", apiKey: "sk-made-up", model: "gpt-test" };+const PASS = { success: true };+const REJECTED = { success: false, errorCode: "credentialsRejected", status: 401 };++// A cache on a hand-moved clock, and a provider that gives `answer` and counts each ask.+function setup() {+ let clock = 0;+ const cache = createConnectionCheckCache({ now: () => clock });+ const sent = [];+ const ask = (config, answer = PASS) =>+ cache(config, async () => {+ sent.push(config);+ return answer;+ });+ return { cache, sent, ask, advance: (ms) => (clock += ms) };+}++test("identical checks in flight share one request", async () => {+ const { cache } = setup();+ const answer = deferred();+ let calls = 0;+ const check = () => {+ calls += 1;+ return answer.promise;+ };+ const pending = [cache(CONFIG, check), cache({ ...CONFIG }, check)];+ answer.resolve(PASS);+ assert.deepEqual(await Promise.all(pending), [PASS, PASS]);+ assert.equal(calls, 1);+});++test("every part of a check is part of its identity", async () => {+ const { ask, sent } = setup();+ const variants = [+ CONFIG,+ { ...CONFIG, scope: "transcription" },+ { ...CONFIG, provider: "groq" },+ { ...CONFIG, apiKey: "sk-other" },+ { ...CONFIG, baseUrl: "http://127.0.0.1:1234/v1" },+ { ...CONFIG, model: "gpt-other" },+ { ...CONFIG, clientId: "corti-id" },+ { ...CONFIG, clientSecret: "corti-secret" },+ { ...CONFIG, environment: "eu" },+ { ...CONFIG, tenant: "acme" },+ ];+ await Promise.all(variants.map((config) => ask(config)));+ assert.equal(sent.length, variants.length);+});++test("Connected is reused for ten minutes, then asked again", async () => {+ const { ask, sent, advance } = setup();+ await ask(CONFIG);+ advance(CONNECTED_TTL_MS - 1);+ assert.deepEqual(await ask(CONFIG), PASS);+ assert.equal(sent.length, 1, "a remembered Connected sends nothing");+ advance(1);+ await ask(CONFIG);+ assert.equal(sent.length, 2);+});++test("a failure is never reused, so Retry reaches the provider", async () => {+ const { ask, sent } = setup();+ assert.deepEqual(await ask(CONFIG, REJECTED), REJECTED);+ assert.deepEqual(await ask(CONFIG), PASS);+ assert.equal(sent.length, 2);+});++test("a check that throws is forgotten, and the next ask goes out", async () => {+ const { cache, ask, sent } = setup();+ const broken = () => {+ throw new Error("bridge failed");+ };+ await assert.rejects(cache(CONFIG, broken));+ await ask(CONFIG);+ assert.equal(sent.length, 1);+});diff --git a/test/helpers/deviceCleanupContract.test.js b/test/helpers/deviceCleanupContract.test.jsindex 2b9bb29a8..a33ca5698 100644--- a/test/helpers/deviceCleanupContract.test.js+++ b/test/helpers/deviceCleanupContract.test.js@@ -39,6 +39,7 @@ test("explicit device cleanup covers models, credentials, caches, and browser se);assert.ok(source.includes('"connectors"'), "device cleanup removes encrypted connector logins");+ assert.ok(source.includes("PAID_KEY_CHECKS_FILE"), "device cleanup removes paid key checks");});// cleanup-app can't run outside Electron (it closes the database, clearsdiff --git a/test/helpers/paidKeyCheck.test.js b/test/helpers/paidKeyCheck.test.jsnew file mode 100644index 000000000..ce9beb338--- /dev/null+++ b/test/helpers/paidKeyCheck.test.js@@ -0,0 +1,88 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+const { createPaidKeyCheck } = require("../../src/helpers/paidKeyCheck");+const { deferred } = require("./harness/deferred");++function scratchFile(t) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "paid-key-check-"));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ return path.join(dir, "paid-key-checks.json");+}++function countingCheck(result) {+ const check = async () => {+ check.runs += 1;+ return result;+ };+ check.runs = 0;+ return check;+}++test("a key that passed is never checked again, even after a restart", async (t) => {+ const file = scratchFile(t);+ const check = countingCheck({ success: true });+ const runPaidCheck = createPaidKeyCheck(() => file);+ assert.deepEqual(await runPaidCheck("tf-key", check), { success: true });+ assert.deepEqual(await runPaidCheck("tf-key", check), { success: true });+ assert.deepEqual(await createPaidKeyCheck(() => file)("tf-key", check), { success: true });+ assert.equal(check.runs, 1);++ await runPaidCheck("tf-other", check);+ assert.equal(check.runs, 2, "each key is paid for once");+});++test("only the key's digest is stored", async (t) => {+ const file = scratchFile(t);+ await createPaidKeyCheck(() => file)("tf-secret-key", countingCheck({ success: true }));+ const stored = fs.readFileSync(file, "utf8");+ assert.doesNotMatch(stored, /tf-secret-key/);+ assert.match(JSON.parse(stored).passed[0], /^[0-9a-f]{64}$/);+});++test("a key that did not pass is asked about again", async (t) => {+ for (const result of [+ { success: false, errorCode: "credentialsRejected", status: 401 },+ { success: false, errorCode: "timeout", unverified: true },+ ]) {+ const file = scratchFile(t);+ const check = countingCheck(result);+ const runPaidCheck = createPaidKeyCheck(() => file);+ assert.deepEqual(await runPaidCheck("tf-key", check), result);+ assert.deepEqual(await runPaidCheck("tf-key", check), result);+ assert.equal(check.runs, 2, result.errorCode);+ assert.equal(fs.existsSync(file), false, result.errorCode);+ }+});++test("checks for one key share a request while it runs", async (t) => {+ const file = scratchFile(t);+ const runPaidCheck = createPaidKeyCheck(() => file);+ const answer = deferred();+ let runs = 0;+ const check = () => {+ runs += 1;+ return answer.promise;+ };+ const first = runPaidCheck("tf-key", check);+ const second = runPaidCheck("tf-key", check);+ answer.resolve({ success: true });+ assert.deepEqual(await Promise.all([first, second]), [{ success: true }, { success: true }]);+ assert.equal(runs, 1);+});++test("an unreadable or unwritable file only costs another check", async (t) => {+ const file = scratchFile(t);+ fs.writeFileSync(file, "not json");+ const check = countingCheck({ success: true });+ await createPaidKeyCheck(() => file)("tf-key", check);+ assert.equal(check.runs, 1);++ // The directory's own path cannot be written as a file; the key is still remembered here.+ const unwritable = createPaidKeyCheck(() => path.dirname(file));+ await unwritable("tf-key", check);+ await unwritable("tf-key", check);+ assert.equal(check.runs, 2);+});diff --git a/test/helpers/providerConnectionIpc.test.js b/test/helpers/providerConnectionIpc.test.jsnew file mode 100644index 000000000..459157550--- /dev/null+++ b/test/helpers/providerConnectionIpc.test.js@@ -0,0 +1,202 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const Module = require("node:module");+const os = require("node:os");+const path = require("node:path");+const { deferred } = require("./harness/deferred");++const handlersModulePath = require.resolve("../../src/helpers/ipcHandlers");+const originalLoad = Module._load;+const handlers = new Map();+const probes = [];+const tokens = [];+let probeAnswer = async () => ({ success: true });+let tokenAnswer = async () => "token";+const userData = fs.mkdtempSync(path.join(os.tmpdir(), "provider-connection-ipc-"));++const electronStub = {+ app: {+ getPath: () => userData,+ getName: () => "test",+ getVersion: () => "0.0.0",+ isPackaged: false,+ on: () => {},+ requestSingleInstanceLock: () => true,+ },+ ipcMain: {+ handle: (channel, handler) => handlers.set(channel, handler),+ on: () => {},+ removeHandler: () => {},+ },+ net: { fetch: async () => ({ ok: true, status: 200, json: async () => ({}) }) },+ 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 {},+};++function anything() {+ return new Proxy(function () {}, {+ get: (_target, property) => {+ if (property === Symbol.toPrimitive || property === "toString") return () => "";+ if (property === "then") return undefined;+ return anything();+ },+ apply: () => anything(),+ });+}++Module._load = function loadWithMocks(request, parent, isMain) {+ if (request === "electron") return electronStub;+ if (parent?.filename === handlersModulePath) {+ if (request === "./connectionCheckCache" || request === "./paidKeyCheck") {+ return originalLoad.call(this, request, parent, isMain);+ }+ if (request === "./providerConnectionTest") {+ const { describeCortiTokenFailure } = originalLoad.call(this, request, parent, isMain);+ return {+ describeCortiTokenFailure,+ testProviderConnection: (config, _fetch, runPaidCheck) => {+ probes.push(config);+ return probeAnswer(config, runPaidCheck);+ },+ };+ }+ if (request === "./cortiAuth") {+ return {+ getCortiToken: async (target) => {+ tokens.push(target);+ return tokenAnswer(target);+ },+ };+ }+ if (request.startsWith("./") || request.startsWith("../")) return anything();+ }+ return originalLoad.call(this, request, parent, isMain);+};++test.before(() => {+ delete require.cache[handlersModulePath];+ const IPCHandlers = require(handlersModulePath);+ const Ctor = IPCHandlers.default || IPCHandlers;+ Ctor.prototype.setupHandlers.call(+ new Proxy({}, { get: (value, property) => (property in value ? value[property] : anything()) })+ );+ assert.ok(handlers.get("test-provider-connection"));+});++test.after(() => {+ Module._load = originalLoad;+ fs.rmSync(userData, { recursive: true, force: true });+});++const check = (config) => handlers.get("test-provider-connection")({}, config);++test("panels asking the same check share one request, and Connected is reused", async () => {+ const answer = deferred();+ probeAnswer = () => answer.promise;+ const config = { scope: "reasoning", provider: "openai", apiKey: "sk-shared", model: "m" };+ const before = probes.length;+ const pending = [check(config), check({ ...config })];+ answer.resolve({ success: true });+ assert.deepEqual(await Promise.all(pending), [{ success: true }, { success: true }]);+ assert.deepEqual(await check(config), { success: true });+ assert.equal(probes.length - before, 1);+});++test("a failure from the handler is never remembered", async () => {+ probeAnswer = async () => ({ success: false, errorCode: "credentialsRejected", status: 401 });+ const config = { scope: "reasoning", provider: "openai", apiKey: "sk-rejected" };+ const before = probes.length;+ await check(config);+ await check(config);+ assert.equal(probes.length - before, 2);+});++test("Corti's token request is shared and remembered the same way", async () => {+ const config = {+ scope: "transcription",+ provider: "corti",+ clientId: "corti-id",+ clientSecret: "corti-secret",+ environment: "eu",+ tenant: "",+ };+ assert.deepEqual(await Promise.all([check(config), check(config)]), [+ { success: true },+ { success: true },+ ]);+ assert.deepEqual(await check(config), { success: true });+ assert.deepEqual(tokens, [+ { environment: "eu", tenant: "base", clientId: "corti-id", clientSecret: "corti-secret" },+ ]);+ assert.equal(+ probes.some((probe) => probe.provider === "corti"),+ false+ );+});++test("Tinfoil's paid key check runs once per key, across checks the cache keeps apart", async () => {+ let paid = 0;+ probeAnswer = (_config, runPaidCheck) =>+ runPaidCheck("tf-key", async () => {+ paid += 1;+ return { success: true };+ });+ for (const model of ["voxtral-small-24b", "gpt-oss-120b"]) {+ const config = { scope: "transcription", provider: "tinfoil", apiKey: "tf-key", model };+ assert.deepEqual(await check(config), { success: true });+ }+ assert.equal(paid, 1);+ const stored = fs.readFileSync(path.join(userData, "paid-key-checks.json"), "utf8");+ assert.doesNotMatch(stored, /tf-key/);+});++test("Corti's own refusal and its no-verdict failures reach the panel, never remembered", async () => {+ const corti = {+ scope: "transcription",+ provider: "corti",+ clientId: "corti-id-3",+ clientSecret: "corti-secret-3",+ environment: "eu",+ tenant: "",+ };+ const busy = Object.assign(new Error("Corti authentication failed: 503"), { status: 503 });+ tokenAnswer = async () => {+ throw busy;+ };+ try {+ const before = tokens.length;+ for (let attempt = 0; attempt < 2; attempt += 1) {+ const result = await check(corti);+ assert.equal(result.errorCode, "providerStatus");+ assert.equal(result.unverified, true);+ }+ assert.equal(tokens.length - before, 2, "no verdict is asked again");+ tokenAnswer = async () => {+ throw Object.assign(new Error("Corti authentication failed: 401"), { status: 401 });+ };+ const refusedFrom = tokens.length;+ assert.equal((await check(corti)).errorCode, "credentialsRejected");+ assert.equal((await check(corti)).errorCode, "credentialsRejected");+ assert.equal(tokens.length - refusedFrom, 2, "a refusal is asked again too");+ } finally {+ tokenAnswer = async () => "token";+ }+});diff --git a/test/helpers/providerConnectionTest.test.js b/test/helpers/providerConnectionTest.test.jsindex e275ba8bb..c18671deb 100644--- a/test/helpers/providerConnectionTest.test.js+++ b/test/helpers/providerConnectionTest.test.js@@ -1,8 +1,9 @@const assert = require("node:assert/strict");+const http = require("node:http");const test = require("node:test");const providerTest = require("../../src/helpers/providerConnectionTest.js");-const { resolveProviderRequest, testProviderConnection } = providerTest;+const { describeCortiTokenFailure, resolveProviderRequest, testProviderConnection } = providerTest;test("builds provider tests without placing credentials in the URL", () => {const request = resolveProviderRequest({ provider: "openai", apiKey: "secret" });@@ -16,6 +17,7 @@ test("honors OpenAI base URL overrides from the environment", () => {try {const request = resolveProviderRequest({ provider: "openai", apiKey: "secret" });assert.deepEqual(request.endpoints, ["https://proxy.example.com/v1/models"]);+ assert.equal(request.redirect, "follow");} finally {delete process.env.OPENAI_BASE_URL;}@@ -23,7 +25,7 @@ test("honors OpenAI base URL overrides from the environment", () => {test("the realtime STT providers use their own auth schemes, not Bearer", () => {const deepgram = resolveProviderRequest({ provider: "deepgram", apiKey: "dg-secret" });- assert.equal(deepgram.endpoint, "https://api.deepgram.com/v1/models");+ assert.equal(deepgram.endpoint, "https://api.deepgram.com/v1/auth/token");assert.equal(deepgram.endpoint.includes("dg-secret"), false);assert.equal(deepgram.headers.Authorization, "Token dg-secret");@@ -33,11 +35,10 @@ test("the realtime STT providers use their own auth schemes, not Bearer", () =>assert.equal(assemblyai.headers.Authorization, "aai-secret");});-// Neither payload is OpenAI-shaped, so responseOffersModel would report+// AssemblyAI's payload is not OpenAI-shaped, so responseOffersModel would report// modelNotFound for a perfectly valid key.test("a 200 is the whole signal for providers with no OpenAI-shaped model list", async () => {for (const [provider, model, payload] of [- ["deepgram", "nova-3", { stt: [{ name: "nova-3", canonical_name: "nova-3-general" }] }],["assemblyai", "universal-streaming-english", { transcripts: [], page_details: {} }],]) {assert.deepEqual(@@ -165,7 +166,12 @@ test("maps authentication and transport failures to safe messages", async () =>await testProviderConnection({ provider: "openai", apiKey: "bad" }, async () => {throw new Error("secret upstream detail");}),- { success: false, errorCode: "network", error: "The provider could not be reached." }+ {+ success: false,+ errorCode: "network",+ error: "The provider could not be reached.",+ unverified: true,+ });assert.deepEqual(@@ -178,10 +184,121 @@ test("maps authentication and transport failures to safe messages", async () =>errorCode: "providerStatus",error: "The provider returned status 500.",status: 500,+ unverified: true,});});+test("a provider that is slow, busy or down gives no verdict, so the failure is unverified", async () => {+ for (const status of [408, 429, 500, 502, 503, 504]) {+ const result = await testProviderConnection({ provider: "openai", apiKey: "k" }, async () => ({+ ok: false,+ status,+ }));+ assert.equal(result.success, false, String(status));+ assert.equal(result.errorCode, "providerStatus", String(status));+ assert.equal(result.unverified, true, String(status));+ }+ const aborted = Object.assign(new Error("This operation was aborted"), { name: "AbortError" });+ for (const [error, errorCode] of [+ [aborted, "timeout"],+ [new TypeError("fetch failed"), "network"],+ ]) {+ const result = await testProviderConnection({ provider: "openai", apiKey: "k" }, async () => {+ throw error;+ });+ assert.equal(result.errorCode, errorCode);+ assert.equal(result.unverified, true, errorCode);+ }+});++test("an answer that faults the key or the setup is never unverified", async () => {+ const cases = [+ [+ { provider: "openai", apiKey: "bad" },+ () => ({ ok: false, status: 401 }),+ "credentialsRejected",+ ],+ [+ { provider: "openai", apiKey: "bad" },+ () => ({ ok: false, status: 403 }),+ "credentialsRejected",+ ],+ [{ provider: "openai", apiKey: "k" }, () => ({ ok: false, status: 400 }), "providerStatus"],+ [{ provider: "openai", apiKey: "k" }, () => ({ ok: false, status: 402 }), "providerStatus"],+ [{ provider: "openai", apiKey: "k" }, () => ({ ok: false, status: 404 }), "providerStatus"],+ [+ { provider: "openai", apiKey: "k", model: "gone" },+ () => ({ ok: true, status: 200, json: async () => ({ data: [{ id: "other" }] }) }),+ "modelNotFound",+ ],+ [+ { provider: "custom", baseUrl: "http://localhost:1234" },+ () => ({ ok: false, status: 404 }),+ "endpointNotFound",+ ],+ [+ { provider: "gemini", apiKey: "made-up" },+ () => ({+ ok: false,+ status: 400,+ json: async () => ({ error: { details: [{ reason: "API_KEY_INVALID" }] } }),+ }),+ "credentialsRejected",+ ],+ ];+ for (const [config, answer, errorCode] of cases) {+ const result = await testProviderConnection(config, async () => answer());+ assert.equal(result.errorCode, errorCode, `${config.provider} ${errorCode}`);+ assert.equal(result.unverified, undefined, `${config.provider} ${errorCode}`);+ }+});++test("across a custom server's addresses, an answer outranks no answer", async () => {+ const base = "http://localhost:1234";+ const aborted = Object.assign(new Error("This operation was aborted"), { name: "AbortError" });+ const answer = (models, v1) => async (url) => {+ const reply = url.includes("/v1/models") ? v1 : models;+ if (reply instanceof Error) throw reply;+ return reply;+ };+ const check = (config, fetchImpl) =>+ testProviderConnection({ provider: "custom", baseUrl: base, ...config }, fetchImpl);+ const listWithout = {+ ok: true,+ status: 200,+ json: async () => ({ data: [{ id: "other" }] }),+ };++ // A busy address never hides a refused key or a missing model on the other one.+ const missing = await check({ model: "m" }, answer({ ok: false, status: 503 }, listWithout));+ assert.equal(missing.errorCode, "modelNotFound");+ assert.equal(missing.unverified, undefined);+ const refused = await check({ apiKey: "bad" }, answer(aborted, { ok: false, status: 401 }));+ assert.equal(refused.errorCode, "credentialsRejected");++ // A real status wins whichever address answered it.+ for (const [first, second] of [+ [400, 503],+ [503, 400],+ ]) {+ const result = await check(+ {},+ answer({ ok: false, status: first }, { ok: false, status: second })+ );+ assert.equal(result.status, 400, `${first} then ${second}`);+ assert.equal(result.unverified, undefined, `${first} then ${second}`);+ }++ // No answer outranks an address without a model list, which the server may not use.+ const busy = await check({}, answer({ ok: false, status: 404 }, { ok: false, status: 503 }));+ assert.equal(busy.status, 503);+ assert.equal(busy.unverified, true);+ const slow = await check({}, answer({ ok: false, status: 404 }, aborted));+ assert.equal(slow.errorCode, "timeout");+ assert.equal(slow.unverified, true);+});+test("succeeds when only the /v1 candidate responds", async () => {const attempted = [];const result = await testProviderConnection(@@ -228,6 +345,27 @@ test("accepts selected models from OpenAI and Gemini model-list shapes", async (}});+// Anthropic's model list carries only dated snapshots of the aliases the registry uses.+test("accepts an Anthropic alias by its dated snapshot, but not a prefix", async () => {+ const check = (config, id) =>+ testProviderConnection({ apiKey: "k", ...config }, async () => ({+ ok: true,+ status: 200,+ json: async () => ({ data: [{ id }] }),+ }));+ const snapshot = "claude-opus-4-5-20251101";+ assert.deepEqual(await check({ provider: "anthropic", model: "claude-opus-4-5" }, snapshot), {+ success: true,+ });+ assert.equal(+ (await check({ provider: "anthropic", model: "claude-opus-4" }, snapshot)).errorCode,+ "modelNotFound"+ );+ // A custom server matches ids exactly, so it would reject the undated id.+ const custom = { provider: "custom", baseUrl: "http://localhost:1234/v1", model: "foo" };+ assert.equal((await check(custom, "foo-20251001")).errorCode, "modelNotFound");+});+test("continues to a compatible candidate when an earlier model list omits the selection", async () => {const attempted = [];const result = await testProviderConnection(@@ -279,3 +417,625 @@ test("reports endpointNotFound only after every candidate 404s", async () => {});});++const jsonResponse = (status, body) => ({+ ok: status >= 200 && status < 300,+ status,+ // undefined is an empty body; a string is raw text (JSON.parse throws on non-JSON).+ json: async () => {+ if (body === undefined) throw new SyntaxError("Unexpected end of JSON input");+ return typeof body === "string" ? JSON.parse(body) : body;+ },+});++function recordingFetch(answer) {+ const calls = [];+ const fetchImpl = async (url, init) => {+ calls.push({ url, init });+ return answer(url, init);+ };+ return { calls, fetchImpl };+}++async function listen(t, handler) {+ const server = http.createServer(handler);+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));+ t.after(() => {+ server.closeAllConnections();+ server.close();+ });+ return `http://127.0.0.1:${server.address().port}`;+}++const GEMINI_INVALID_KEY = {+ error: {+ code: 400,+ status: "INVALID_ARGUMENT",+ details: [+ {+ "@type": "type.googleapis.com/google.rpc.ErrorInfo",+ reason: "API_KEY_INVALID",+ domain: "googleapis.com",+ },+ ],+ },+};+const GEMINI_OTHER_REASON = {+ error: { code: 400, details: [{ reason: "API_KEY_SERVICE_BLOCKED" }] },+};+const XAI_BAD_KEY = { code: "invalid-argument", error: "Incorrect API key provided: xa***00." };+const CORTI_MALFORMED_HEADER = { message: "Missing or malformed Authorization header" };++test("any 2xx from Deepgram's key check passes, whatever the body or model", async () => {+ const { calls, fetchImpl } = recordingFetch(() => ({ ok: true, status: 200 }));+ const config = { provider: "deepgram", apiKey: "dg-key", model: "nova-3" };+ assert.deepEqual(await testProviderConnection(config, fetchImpl), { success: true });+ assert.deepEqual(+ calls.map((call) => call.url),+ ["https://api.deepgram.com/v1/auth/token"]+ );+});++test("Deepgram rejects a made-up key without trying the fallback", async () => {+ for (const status of [401, 403]) {+ const { calls, fetchImpl } = recordingFetch(() => jsonResponse(status));+ const config = { provider: "deepgram", apiKey: "made-up" };+ const result = await testProviderConnection(config, fetchImpl);+ assert.equal(result.errorCode, "credentialsRejected");+ assert.equal(result.status, status);+ assert.deepEqual(+ calls.map((call) => call.url),+ ["https://api.deepgram.com/v1/auth/token"]+ );+ }+});++test("a retired Deepgram key route falls back to the key's project list", async () => {+ const { calls, fetchImpl } = recordingFetch((url) =>+ url.endsWith("/v1/auth/token") ? jsonResponse(404) : jsonResponse(200, { projects: [] })+ );+ const config = { provider: "deepgram", apiKey: "dg-key" };+ assert.deepEqual(await testProviderConnection(config, fetchImpl), { success: true });+ assert.deepEqual(+ calls.map((call) => [call.url, call.init.headers.Authorization, call.init.redirect]),+ [+ ["https://api.deepgram.com/v1/auth/token", "Token dg-key", "error"],+ ["https://api.deepgram.com/v1/projects", "Token dg-key", "error"],+ ]+ );+});++test("the project-list fallback passes only with its project list", async () => {+ const afterRetiredRoute = (answer) =>+ recordingFetch((url) => (url.endsWith("/v1/auth/token") ? jsonResponse(404) : answer))+ .fetchImpl;+ const config = { provider: "deepgram", apiKey: "dg-key" };+ assert.deepEqual(+ await testProviderConnection(config, afterRetiredRoute(jsonResponse(200, { data: [] }))),+ { success: false }+ );+ const rejected = await testProviderConnection(config, afterRetiredRoute(jsonResponse(401)));+ assert.equal(rejected.errorCode, "credentialsRejected");+});++test("a network failure on Deepgram's key check does not try the fallback", async () => {+ const { calls, fetchImpl } = recordingFetch(() => {+ throw new TypeError("fetch failed");+ });+ const result = await testProviderConnection({ provider: "deepgram", apiKey: "k" }, fetchImpl);+ assert.equal(result.errorCode, "network");+ assert.deepEqual(+ calls.map((call) => call.url),+ ["https://api.deepgram.com/v1/auth/token"]+ );+});++test("Deepgram's other failures keep their status and skip the fallback", async () => {+ for (const status of [400, 429, 500]) {+ const { calls, fetchImpl } = recordingFetch(() => jsonResponse(status));+ const result = await testProviderConnection({ provider: "deepgram", apiKey: "k" }, fetchImpl);+ assert.equal(result.errorCode, "providerStatus", String(status));+ assert.equal(calls.length, 1, String(status));+ }+});++test("Anthropic and Gemini are asked for their largest page of models", () => {+ assert.equal(+ resolveProviderRequest({ provider: "anthropic", apiKey: "k" }).endpoint,+ "https://api.anthropic.com/v1/models?limit=1000"+ );+ assert.equal(+ resolveProviderRequest({ provider: "gemini", apiKey: "k" }).endpoint,+ "https://generativelanguage.googleapis.com/v1beta/models?pageSize=1000"+ );+});++test("Gemini, xAI and Corti rejections are read from the provider's error body", async () => {+ const cases = [+ ["gemini", 400, GEMINI_INVALID_KEY, "credentialsRejected"],+ ["gemini", 400, { error: { status: "FAILED_PRECONDITION" } }, "providerStatus"],+ ["gemini", 400, GEMINI_OTHER_REASON, "providerStatus"],+ ["gemini", 400, undefined, "providerStatus"],+ ["xai", 400, XAI_BAD_KEY, "credentialsRejected"],+ ["xai", 400, { error: "incorrect api KEY provided." }, "credentialsRejected"],+ ["xai", 400, { error: "Model grok-x does not exist" }, "providerStatus"],+ ["xai", 400, "Bad Request", "providerStatus"],+ ["xai", 500, XAI_BAD_KEY, "providerStatus"],+ ["corti", 400, undefined, "credentialsRejected"],+ ["corti", 400, "Bad Request", "credentialsRejected"],+ ["corti", 400, { message: "Unsupported model" }, "providerStatus"],+ ["corti", 401, CORTI_MALFORMED_HEADER, "credentialsRejected"],+ ["corti", 500, undefined, "providerStatus"],+ ];+ for (const [provider, status, body, errorCode] of cases) {+ const fetchImpl = async () => jsonResponse(status, body);+ const result = await testProviderConnection({ provider, apiKey: "made-up" }, fetchImpl);+ assert.equal(result.errorCode, errorCode, `${provider} ${status} ${JSON.stringify(body)}`);+ assert.equal(result.status, status);+ }+});++test("an error body that never arrives is a timeout or a network failure", async () => {+ const aborted = Object.assign(new Error("This operation was aborted"), { name: "AbortError" });+ for (const [error, errorCode] of [+ [aborted, "timeout"],+ [new TypeError("terminated"), "network"],+ ]) {+ for (const provider of ["gemini", "xai", "corti"]) {+ const fetchImpl = async () => ({+ ok: false,+ status: 400,+ json: async () => {+ throw error;+ },+ });+ const result = await testProviderConnection({ provider, apiKey: "made-up" }, fetchImpl);+ assert.equal(result.errorCode, errorCode, `${provider} ${error.name}`);+ }+ }+});++test("a 401 or 403 is a rejection whatever its body does", async () => {+ let reads = 0;+ for (const provider of ["gemini", "xai", "corti"]) {+ for (const status of [401, 403]) {+ const fetchImpl = async () => ({+ ok: false,+ status,+ json: async () => {+ reads += 1;+ throw new TypeError("terminated");+ },+ });+ const result = await testProviderConnection({ provider, apiKey: "made-up" }, fetchImpl);+ assert.equal(result.errorCode, "credentialsRejected", `${provider} ${status}`);+ }+ }+ assert.equal(reads, 0, "the status alone decides");+});++test("the 12 s cap covers the whole answer, body included", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout"] });+ const aborted = Object.assign(new Error("This operation was aborted"), { name: "AbortError" });+ // Like fetch's own promises, these settle only when the probe's signal aborts.+ const whenAborted = (signal) =>+ new Promise((resolve, reject) => signal.addEventListener("abort", () => reject(aborted)));+ const stalls = {+ headers: (url, init) => whenAborted(init.signal),+ body: async (url, init) => ({ ok: false, status: 400, json: () => whenAborted(init.signal) }),+ };+ for (const [stage, fetchImpl] of Object.entries(stalls)) {+ const pending = testProviderConnection({ provider: "gemini", apiKey: "made-up" }, fetchImpl);+ await new Promise(setImmediate);+ t.mock.timers.tick(12000);+ const settled = await Promise.race([+ pending,+ new Promise((resolve) => setImmediate(resolve, { errorCode: "still pending" })),+ ]);+ assert.equal(settled.errorCode, "timeout", stage);+ }+});++test("other providers' error bodies are never read", async () => {+ let reads = 0;+ const fetchImpl = async () => ({+ ok: false,+ status: 400,+ json: async () => {+ reads += 1;+ return { error: { message: "Incorrect API key provided: sk-ma****" } };+ },+ });+ for (const provider of ["openai", "groq", "mistral", "anthropic", "assemblyai", "deepgram"]) {+ const result = await testProviderConnection({ provider, apiKey: "k" }, fetchImpl);+ assert.equal(result.errorCode, "providerStatus", provider);+ }+ assert.equal(reads, 0);+});++test("a Corti key of only spaces is never sent", async () => {+ let calls = 0;+ const fetchImpl = async () => {+ calls += 1;+ };+ const result = await testProviderConnection({ provider: "corti", apiKey: " " }, fetchImpl);+ assert.equal(result.errorCode, "apiKeyRequired");+ assert.equal(calls, 0);+});++test("hosted providers refuse redirects; custom servers keep following them", async () => {+ const hosted = [+ "openai",+ "groq",+ "xai",+ "mistral",+ "anthropic",+ "gemini",+ "openrouter",+ "corti",+ "tinfoil",+ "deepgram",+ "assemblyai",+ ];+ for (const provider of hosted) {+ assert.equal(resolveProviderRequest({ provider, apiKey: "k" }).redirect, "error", provider);+ }+ const custom = resolveProviderRequest({ provider: "custom", baseUrl: "http://localhost:1234" });+ assert.equal(custom.redirect, "follow");++ const { calls, fetchImpl } = recordingFetch(() => jsonResponse(200, { data: [{ id: "m" }] }));+ await testProviderConnection({ provider: "openai", apiKey: "k", model: "m" }, fetchImpl);+ assert.equal(calls[0].init.redirect, "error");+});++test("a hosted provider's redirect fails before the key reaches another host", async (t) => {+ const received = [];+ const target = await listen(t, (request, response) => {+ received.push(request.headers["x-api-key"]);+ response.end("{}");+ });+ const origin = await listen(t, (request, response) => {+ response.writeHead(302, { location: `${target}/v1/models` }).end();+ });+ const inits = [];+ // Only the host changes: the real request, headers and redirect mode go to the local origin.+ const viaOrigin = (url, init) => {+ inits.push(init);+ return fetch(`${origin}${new URL(url).pathname}`, init);+ };+ const config = { provider: "anthropic", apiKey: "sk-ant-test", model: "claude-test" };+ assert.equal((await testProviderConnection(config, viaOrigin)).errorCode, "network");+ assert.deepEqual(received, []);+ // The same request allowed to follow would hand the key over, so this test can fail.+ await fetch(`${origin}/v1/models`, { ...inits[0], redirect: "follow", signal: undefined });+ assert.deepEqual(received, ["sk-ant-test"]);+});++test("a custom server can still redirect within itself", async (t) => {+ const base = await listen(t, (request, response) => {+ if (request.url === "/v1/models") {+ response.writeHead(308, { location: "/v1/models/" }).end();+ return;+ }+ response.writeHead(200, { "content-type": "application/json" });+ response.end(JSON.stringify({ data: [{ id: "local-model" }] }));+ });+ const config = { provider: "custom", baseUrl: `${base}/v1`, model: "local-model" };+ assert.deepEqual(await testProviderConnection(config), { success: true });+});++test("OpenRouter is checked at its key route, which a made-up key cannot pass", async () => {+ const request = resolveProviderRequest({ provider: "openrouter", apiKey: "sk-or-made-up" });+ assert.equal(request.endpoint, "https://openrouter.ai/api/v1/key");+ assert.equal(request.headers.Authorization, "Bearer sk-or-made-up");+ assert.equal(request.redirect, "error");+ for (const status of [401, 403]) {+ const fetchImpl = async () => jsonResponse(status, { error: { message: "User not found." } });+ const config = { provider: "openrouter", apiKey: "sk-or-made-up" };+ const result = await testProviderConnection(config, fetchImpl);+ assert.equal(result.errorCode, "credentialsRejected", String(status));+ }+});++test("an OpenRouter management key is refused, since it cannot run requests", async () => {+ for (const flag of ["is_management_key", "is_provisioning_key"]) {+ const fetchImpl = async () => jsonResponse(200, { data: { label: "admin", [flag]: true } });+ const config = { provider: "openrouter", apiKey: "k" };+ const result = await testProviderConnection(config, fetchImpl);+ assert.equal(result.errorCode, "credentialsRejected", flag);+ }+});++const ORDINARY_KEY = { data: { label: "laptop", is_free_tier: true, limit_remaining: null } };++test("any other OpenRouter key passes, with no model check", async () => {+ const { calls, fetchImpl } = recordingFetch(() => jsonResponse(200, ORDINARY_KEY));+ const config = { provider: "openrouter", apiKey: "sk-or-key", model: "anthropic/claude-test" };+ assert.deepEqual(await testProviderConnection(config, fetchImpl), { success: true });+ assert.deepEqual(+ calls.map((call) => call.url),+ ["https://openrouter.ai/api/v1/key"]+ );+ const unreadable = async () => jsonResponse(200, "not json");+ assert.deepEqual(await testProviderConnection(config, unreadable), { success: true });+ const outage = await testProviderConnection(config, async () => jsonResponse(503));+ assert.equal(outage.errorCode, "providerStatus");+});++// The key route answers 200 with the key's description. Any other 2xx carries no key to+// read, so an empty 204 must not pass as an ordinary key.+test("only a 200 from the OpenRouter key route can pass", async () => {+ const config = { provider: "openrouter", apiKey: "sk-or-key" };+ for (const status of [204, 202]) {+ const result = await testProviderConnection(config, async () => jsonResponse(status));+ assert.deepEqual(+ result,+ {+ success: false,+ errorCode: "providerStatus",+ error: `The provider returned status ${status}.`,+ status,+ },+ String(status)+ );+ }+});++// A stand-in speech server with no model list. Its transcription address answers `status`,+// and every request it gets is recorded with its body.+async function speechServer(t, status) {+ const received = [];+ const base = await listen(t, (request, response) => {+ let body = "";+ request.on("data", (chunk) => (body += chunk));+ request.on("end", () => {+ received.push({ method: request.method, url: request.url, headers: request.headers, body });+ response.writeHead(request.method === "POST" ? status : 404).end("{}");+ });+ });+ return { base, received };+}++const speech = (baseUrl, extra = {}) => ({+ scope: "transcription",+ provider: "custom",+ baseUrl,+ model: "whisper-large-v3",+ ...extra,+});++test("a speech server with no model list is checked at its transcription address", async (t) => {+ for (const status of [400, 422]) {+ const { base, received } = await speechServer(t, status);+ const result = await testProviderConnection(speech(base, { apiKey: "sk-local" }));+ assert.deepEqual(result, { success: true }, String(status));+ assert.deepEqual(+ received.map((entry) => `${entry.method} ${entry.url}`),+ ["GET /models", "GET /v1/models", "POST /audio/transcriptions"]+ );+ const post = received[2];+ assert.match(post.headers["content-type"], /^multipart\/form-data; boundary=/);+ assert.equal(post.headers.authorization, "Bearer sk-local");+ assert.match(post.body, /name="model"\r\n\r\nwhisper-large-v3\r\n/);+ assert.doesNotMatch(post.body, /filename=/, "no audio is sent");+ }+});++test("the transcription address is the one the app sends audio to", async (t) => {+ const { base, received } = await speechServer(t, 422);+ assert.deepEqual(await testProviderConnection(speech(`${base}/v1`)), { success: true });+ assert.deepEqual(+ received.map((entry) => `${entry.method} ${entry.url}`),+ ["GET /v1/models", "POST /v1/audio/transcriptions"]+ );+ assert.equal(received[1].headers.authorization, undefined, "no key, no header");++ // The full address with a trailing slash: the slash hides the suffix from one pass of+ // normalizeBaseUrl, and the app's second pass is what strips it.+ const typedInFull = await speechServer(t, 422);+ const fullAddress = `${typedInFull.base}/v1/audio/transcriptions/`;+ assert.deepEqual(await testProviderConnection(speech(fullAddress)), { success: true });+ assert.deepEqual(+ typedInFull.received+ .filter((entry) => entry.method === "POST")+ .map((entry) => `${entry.method} ${entry.url}`),+ ["POST /v1/audio/transcriptions"]+ );+});++test("the transcription address's answers keep their meaning", async (t) => {+ const nothingHere = "Nothing takes transcriptions at this address.";+ for (const [status, errorCode, error] of [+ [401, "credentialsRejected", "The provider rejected these credentials."],+ [403, "credentialsRejected", "The provider rejected these credentials."],+ [404, "transcriptionEndpointNotFound", nothingHere],+ [405, "transcriptionEndpointNotFound", nothingHere],+ [500, "providerStatus", "The provider returned status 500."],+ [200, "providerStatus", "The provider returned status 200."],+ ]) {+ const { base } = await speechServer(t, status);+ const result = await testProviderConnection(speech(base));+ assert.equal(result.errorCode, errorCode, String(status));+ assert.equal(result.status, status);+ assert.equal(result.error, error, String(status));+ }+ const flaky = recordingFetch((url, init) => {+ if (init.method === "POST") throw new TypeError("fetch failed");+ return jsonResponse(404);+ });+ const offline = await testProviderConnection(speech("http://127.0.0.1:9"), flaky.fetchImpl);+ assert.equal(offline.errorCode, "network");+ assert.deepEqual([flaky.calls[2].init.method, flaky.calls[2].init.redirect], ["POST", "follow"]);+});++test("only a speech check with every model list missing asks that address", async (t) => {+ const { base, received } = await speechServer(t, 422);+ // A language-model server keeps today's answer.+ const reasoning = await testProviderConnection({ ...speech(base), scope: "reasoning" });+ assert.equal(reasoning.errorCode, "endpointNotFound");+ assert.equal(+ received.some((entry) => entry.method === "POST"),+ false+ );++ const keyed = recordingFetch((url) => jsonResponse(url.endsWith("/v1/models") ? 401 : 404));+ const config = speech("http://127.0.0.1:9", { apiKey: "k" });+ const rejected = await testProviderConnection(config, keyed.fetchImpl);+ assert.equal(rejected.errorCode, "credentialsRejected");+ assert.equal(keyed.calls.length, 2, "a list that answered anything but 404 already said why");++ const down = recordingFetch(() => {+ throw new TypeError("fetch failed");+ });+ const unreachable = await testProviderConnection(speech("http://127.0.0.1:9"), down.fetchImpl);+ assert.equal(unreachable.errorCode, "network");+ assert.equal(down.calls.length, 2);+});++const TINFOIL_MODELS = { data: [{ id: "voxtral-small-24b" }, { id: "gpt-oss-120b" }] };+const TINFOIL_KEY_ROUTE = "https://inference.tinfoil.sh/v1/embeddings";++function tinfoilFetch(keyAnswer, models = jsonResponse(200, TINFOIL_MODELS)) {+ return recordingFetch((url) => (url === TINFOIL_KEY_ROUTE ? keyAnswer() : models));+}++test("a made-up Tinfoil key is refused, though Tinfoil's model list is public", async () => {+ const { calls, fetchImpl } = tinfoilFetch(() => jsonResponse(401));+ const result = await testProviderConnection(+ { provider: "tinfoil", apiKey: " made-up ", model: "voxtral-small-24b" },+ fetchImpl+ );+ assert.equal(result.errorCode, "credentialsRejected");+ assert.deepEqual(+ calls.map((call) => [call.url, call.init.method]),+ [+ ["https://inference.tinfoil.sh/v1/models", "GET"],+ [TINFOIL_KEY_ROUTE, "POST"],+ ]+ );+ const keyCheck = calls[1].init;+ assert.equal(keyCheck.headers.Authorization, "Bearer made-up");+ assert.equal(keyCheck.headers["Content-Type"], "application/json");+ assert.deepEqual(JSON.parse(keyCheck.body), { model: "nomic-embed-text", input: "." });+ assert.equal(keyCheck.redirect, "error");+});++test("Tinfoil's key check spends a token, so it runs through runPaidCheck", async () => {+ const paid = [];+ const runPaidCheck = async (key, check) => {+ paid.push(key);+ return check();+ };+ const { fetchImpl } = tinfoilFetch(() => jsonResponse(200, { data: [] }));+ assert.deepEqual(+ await testProviderConnection(+ { provider: "tinfoil", apiKey: " tf-key ", model: "gpt-oss-120b" },+ fetchImpl,+ runPaidCheck+ ),+ { success: true }+ );+ assert.deepEqual(paid, ["tf-key"], "keyed by the trimmed key");++ // A key the caller already paid for is not checked again.+ const { calls, fetchImpl: remembered } = tinfoilFetch(() => assert.fail("paid twice"));+ assert.deepEqual(+ await testProviderConnection(+ { provider: "tinfoil", apiKey: "tf-key", model: "gpt-oss-120b" },+ remembered,+ async () => ({ success: true })+ ),+ { success: true }+ );+ assert.equal(calls.length, 1, "the free model list still runs");+});++test("Tinfoil's model is checked on its public list before anything is paid for", async () => {+ for (const [models, errorCode] of [+ [jsonResponse(200, TINFOIL_MODELS), "modelNotFound"],+ [jsonResponse(503), "providerStatus"],+ ]) {+ const { calls, fetchImpl } = tinfoilFetch(() => assert.fail("paid"), models);+ const result = await testProviderConnection(+ { provider: "tinfoil", apiKey: "tf-key", model: "retired-model" },+ fetchImpl,+ () => assert.fail("paid")+ );+ assert.equal(result.errorCode, errorCode);+ assert.equal(calls.length, 1);+ }+});++test("a busy Tinfoil, or a retired check model, gives no verdict on the key", async () => {+ for (const status of [404, 429, 503]) {+ const { fetchImpl } = tinfoilFetch(() => jsonResponse(status));+ const result = await testProviderConnection(+ { provider: "tinfoil", apiKey: "tf-key", model: "gpt-oss-120b" },+ fetchImpl+ );+ assert.equal(result.errorCode, "providerStatus", String(status));+ assert.equal(result.unverified, true, String(status));+ }+ const { fetchImpl } = tinfoilFetch(() => jsonResponse(402));+ const unpaid = await testProviderConnection(+ { provider: "tinfoil", apiKey: "tf-key", model: "gpt-oss-120b" },+ fetchImpl+ );+ assert.equal(unpaid.status, 402);+ assert.equal(unpaid.unverified, undefined, "an account Tinfoil refuses is an answer");+});++test("only Corti's own answer refuses its credentials; no answer is unverified", () => {+ const cortiError = (message, status) => Object.assign(new Error(message), { status });+ const aborted = Object.assign(new Error("This operation was aborted"), { name: "AbortError" });+ for (const [error, errorCode, unverified] of [+ [aborted, "timeout", true],+ [new TypeError("fetch failed"), "network", true],+ [+ cortiError("Corti authentication failed: 503 Service Unavailable", 503),+ "providerStatus",+ true,+ ],+ [cortiError("Corti authentication failed: 429", 429), "providerStatus", true],+ [cortiError("Corti authentication failed: 401 invalid_client", 401), "credentialsRejected"],+ [+ cortiError("Corti authentication failed: 400 unauthorized_client", 400),+ "credentialsRejected",+ ],+ [cortiError("Corti authentication failed: no access token in response"), "credentialsRejected"],+ [cortiError("Invalid Corti tenant name"), "credentialsRejected"],+ ]) {+ const result = describeCortiTokenFailure(error);+ assert.equal(result.success, false, error.message);+ assert.equal(result.errorCode, errorCode, error.message);+ assert.equal(result.unverified, unverified, error.message);+ assert.doesNotMatch(result.error, /invalid_client|unauthorized_client/, "no upstream detail");+ }+});++test("a model list whose body never arrives is no verdict, not a missing model", async () => {+ const aborted = Object.assign(new Error("This operation was aborted"), { name: "AbortError" });+ for (const [error, errorCode] of [+ [aborted, "timeout"],+ [new TypeError("terminated"), "network"],+ ]) {+ const fetchImpl = async () => ({+ ok: true,+ status: 200,+ json: async () => {+ throw error;+ },+ });+ const result = await testProviderConnection(+ { provider: "openai", apiKey: "k", model: "gpt-test" },+ fetchImpl+ );+ assert.equal(result.errorCode, errorCode);+ assert.equal(result.unverified, true);+ }+ const unreadable = await testProviderConnection(+ { provider: "openai", apiKey: "k", model: "gpt-test" },+ async () => jsonResponse(200, "not json")+ );+ assert.equal(unreadable.errorCode, "modelNotFound", "a list that can't be read offers nothing");+});diff --git a/test/hooks/useConnectionAutoCheck.test.js b/test/hooks/useConnectionAutoCheck.test.jsnew file mode 100644index 000000000..92823706f--- /dev/null+++ b/test/hooks/useConnectionAutoCheck.test.js@@ -0,0 +1,256 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const React = require("react");+const { createRoot } = require("react-dom/client");+const {+ createRendererServer,+ installBrowserGlobals,+ installHookDom,+} = require("../lib/rendererTestHarness");++const CONFIG = { scope: "transcription", provider: "groq", apiKey: "gsk-a", model: "m" };+const PASS = { success: true };+const REJECTED = { success: false, errorCode: "credentialsRejected", status: 401 };++async function mountCheck(t, initialProps = {}) {+ let root;+ // After hooks run in order: unmount and stop the mock clock before the server closes.+ t.after(async () => {+ if (root) await React.act(async () => root.unmount());+ t.mock.timers.reset();+ });+ const requests = [];+ installBrowserGlobals(t, {+ window: {+ electronAPI: {+ testProviderConnection: (config) =>+ new Promise((resolve, reject) => requests.push({ config, resolve, reject })),+ },+ },+ });+ const container = installHookDom(t);+ const vite = await createRendererServer(t, { cachePrefix: "openwhispr-auto-check-" });+ const { useConnectionAutoCheck } = await vite.ssrLoadModule("/hooks/useConnectionAutoCheck.ts");+ t.mock.timers.enable({ apis: ["setTimeout"] });++ let props = { config: CONFIG, ready: true, ...initialProps };+ let check;+ function Harness() {+ check = useConnectionAutoCheck(props);+ return null;+ }+ root = createRoot(container);+ const render = async (next = {}) => {+ props = { ...props, ...next };+ await React.act(async () => root.render(React.createElement(Harness)));+ };+ await render();+ return {+ requests,+ state: () => check,+ render,+ edit: (apiKey) => render({ config: { ...props.config, apiKey } }),+ wait: (ms) => React.act(async () => t.mock.timers.tick(ms)),+ answer: (result, index = requests.length - 1) =>+ React.act(async () => requests[index].resolve(result)),+ fail: (index = requests.length - 1) =>+ React.act(async () => requests[index].reject(new Error("bridge failed"))),+ retry: () => React.act(async () => check.retry()),+ unmount: async () => {+ await React.act(async () => root.unmount());+ root = null;+ },+ };+}++test("a complete form spins at once and sends one request after the pause", async (t) => {+ const auto = await mountCheck(t);+ assert.equal(auto.state().phase, "waiting");+ await auto.wait(499);+ assert.equal(auto.requests.length, 0);+ await auto.wait(1);+ assert.deepEqual(+ auto.requests.map((request) => request.config),+ [CONFIG]+ );+ assert.equal(auto.state().phase, "checking");+ await auto.answer(PASS);+ assert.equal(auto.state().phase, "connected");+ assert.equal(auto.state().failure, null);+});++test("typing sends nothing until the typing pauses", async (t) => {+ const auto = await mountCheck(t, { config: { ...CONFIG, apiKey: "g" } });+ for (const apiKey of ["gs", "gsk", "gsk-", "gsk-a"]) {+ await auto.wait(300);+ await auto.edit(apiKey);+ }+ assert.equal(auto.requests.length, 0);+ await auto.wait(500);+ assert.deepEqual(+ auto.requests.map((request) => request.config.apiKey),+ ["gsk-a"]+ );+});++test("an answer for an earlier entry is discarded", async (t) => {+ const auto = await mountCheck(t);+ await auto.wait(500);+ await auto.edit("gsk-b");+ await auto.answer(PASS, 0);+ assert.equal(auto.state().phase, "waiting");+ await auto.wait(500);+ await auto.answer(REJECTED, 1);+ assert.equal(auto.state().phase, "failed");+ assert.equal(auto.state().failure.errorCode, "credentialsRejected");+});++test("a late answer for an earlier entry leaves the newer request alone", async (t) => {+ const auto = await mountCheck(t);+ await auto.wait(500);+ await auto.edit("gsk-b");+ await auto.wait(500);+ await auto.answer(PASS, 0);+ assert.equal(auto.state().phase, "checking");+ await auto.wait(2000);+ assert.equal(auto.requests.length, 2, "no second request for the current entry");+ await auto.answer(REJECTED, 1);+ assert.equal(auto.state().phase, "failed");+});++test("returning to an earlier value still checks again", async (t) => {+ const auto = await mountCheck(t);+ await auto.wait(500);+ await auto.answer(PASS);+ await auto.edit("gsk-b");+ await auto.edit("gsk-a");+ assert.equal(auto.state().phase, "waiting");+ await auto.wait(500);+ assert.equal(auto.requests.length, 2);+});++test("an incomplete form shows nothing and sends nothing", async (t) => {+ const auto = await mountCheck(t, { ready: false });+ await auto.wait(5000);+ assert.equal(auto.state().phase, "idle");+ assert.equal(auto.requests.length, 0);+});++test("a form completed later, as by a saved key arriving, is checked on arrival", async (t) => {+ const auto = await mountCheck(t, { ready: false });+ await auto.render({ ready: true });+ assert.equal(auto.state().phase, "waiting");+ await auto.wait(500);+ assert.equal(auto.requests.length, 1);+});++test("a hold sends nothing and shows nothing until it is released", async (t) => {+ const auto = await mountCheck(t, { hold: true });+ assert.equal(auto.state().phase, "idle");+ await auto.wait(5000);+ assert.equal(auto.requests.length, 0);+ await auto.render({ hold: false });+ assert.equal(auto.state().phase, "waiting");+ await auto.wait(500);+ assert.equal(auto.requests.length, 1);+});++test("a hold arriving during the pause cancels the pending request", async (t) => {+ const auto = await mountCheck(t);+ await auto.wait(300);+ await auto.render({ hold: true });+ await auto.wait(1000);+ assert.equal(auto.requests.length, 0);+ assert.equal(auto.state().phase, "idle");+});++test("a hold never undoes a result; only an edit does", async (t) => {+ const auto = await mountCheck(t);+ await auto.wait(500);+ await auto.answer(PASS);+ await auto.render({ hold: true });+ await auto.wait(5000);+ assert.equal(auto.state().phase, "connected");+ assert.equal(auto.requests.length, 1);+ await auto.edit("gsk-b");+ assert.equal(auto.state().phase, "idle");+});++test("a request already sent finishes under a hold", async (t) => {+ const auto = await mountCheck(t);+ await auto.wait(500);+ await auto.render({ hold: true });+ assert.equal(auto.state().phase, "checking");+ await auto.answer(PASS);+ assert.equal(auto.state().phase, "connected");+});++test("retry runs the same check again at once", async (t) => {+ const auto = await mountCheck(t);+ await auto.wait(500);+ await auto.answer(REJECTED);+ assert.equal(auto.state().announcement, null, "a failure speaks through its alert");+ await auto.retry();+ assert.equal(auto.state().phase, "checking");+ assert.deepEqual(auto.requests[1].config, CONFIG);+ await auto.answer(PASS);+ assert.equal(auto.state().phase, "connected");+});++test("a missing or failing bridge reads as a failed check", async (t) => {+ await t.test("missing", async (t) => {+ const auto = await mountCheck(t);+ delete globalThis.window.electronAPI.testProviderConnection; // lint: no bare `window`+ await auto.wait(500);+ assert.equal(auto.state().phase, "failed");+ assert.deepEqual(auto.state().failure, { success: false });+ });+ await t.test("rejected", async (t) => {+ const auto = await mountCheck(t);+ await auto.wait(500);+ await auto.fail();+ assert.equal(auto.state().phase, "failed");+ });+});++test("Testing… is announced only for a request still running after a second", async (t) => {+ const auto = await mountCheck(t);+ await auto.wait(500);+ await auto.wait(999);+ assert.equal(auto.state().announcement, null);+ await auto.wait(1);+ assert.equal(auto.state().announcement, "testing");+ await auto.answer(PASS);+ assert.equal(auto.state().announcement, "connected");+});++test("a quick check announces only its result, and an edit clears it", async (t) => {+ const auto = await mountCheck(t);+ await auto.wait(800);+ await auto.answer(PASS);+ assert.equal(auto.state().announcement, "connected");+ await auto.edit("gsk-b");+ assert.equal(auto.state().announcement, null);+});++test("unmounting cancels the pending request", async (t) => {+ const auto = await mountCheck(t);+ await auto.unmount();+ await auto.wait(1000);+ assert.equal(auto.requests.length, 0);+});++test("no verdict settles as unverified, keeps its reason and announces nothing", async (t) => {+ const auto = await mountCheck(t);+ await auto.wait(500);+ const noVerdict = { success: false, errorCode: "timeout", unverified: true };+ await auto.answer(noVerdict);+ assert.equal(auto.state().phase, "unverified");+ assert.deepEqual(auto.state().failure, noVerdict);+ assert.equal(auto.state().announcement, null);+ await auto.retry();+ assert.equal(auto.requests.length, 2, "Retry asks again");+ await auto.answer(PASS);+ assert.equal(auto.state().phase, "connected");+ assert.equal(auto.state().failure, null);+});diff --git a/test/hooks/useCredentialDraft.test.js b/test/hooks/useCredentialDraft.test.jsnew file mode 100644index 000000000..fa1ab249a--- /dev/null+++ b/test/hooks/useCredentialDraft.test.js@@ -0,0 +1,46 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const React = require("react");+const { createRoot } = require("react-dom/client");+const {+ createRendererServer,+ installBrowserGlobals,+ installHookDom,+} = require("../lib/rendererTestHarness");++async function mountDraft(t) {+ let root;+ t.after(async () => {+ if (root) await React.act(async () => root.unmount());+ });+ installBrowserGlobals(t);+ const container = installHookDom(t);+ const vite = await createRendererServer(t, { cachePrefix: "openwhispr-credential-draft-" });+ const { useCredentialDraft } = await vite.ssrLoadModule("/hooks/useCredentialDraft.ts");+ let draft;+ function Harness() {+ draft = useCredentialDraft();+ return null;+ }+ root = createRoot(container);+ await React.act(async () => root.render(React.createElement(Harness)));+ return { draft: () => draft, act: (run) => React.act(async () => run(draft)) };+}++const report = (phase, apiKey) => ({ phase, checked: { apiKey }, refused: false });++test("an answer settles only a draft that still holds the value it was for", async (t) => {+ const hook = await mountDraft(t);+ const saved = [];+ const save = (value) => saved.push(value);+ await hook.act((draft) => draft.change("apiKey", "abc", save));+ await hook.act((draft) => draft.follow(report("checking", "abc")));+ // A keystroke lands before the pass for "abc" reaches the hook.+ await hook.act((draft) => draft.change("apiKey", "abcd", save));+ await hook.act((draft) => draft.follow(report("connected", "abc")));+ assert.deepEqual(saved, []);+ assert.equal(hook.draft().value("apiKey", ""), "abcd");+ await hook.act((draft) => draft.follow(report("waiting", "abcd")));+ await hook.act((draft) => draft.follow(report("connected", "abcd")));+ assert.deepEqual(saved, ["abcd"]);+});diff --git a/test/hooks/useFocusHold.test.js b/test/hooks/useFocusHold.test.jsnew file mode 100644index 000000000..72b020ad1--- /dev/null+++ b/test/hooks/useFocusHold.test.js@@ -0,0 +1,84 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const React = require("react");+const { createRoot } = require("react-dom/client");+const {+ createRendererServer,+ installBrowserGlobals,+ installHookDom,+} = require("../lib/rendererTestHarness");++// Stand-in DOM nodes on one page: a node contains itself and every node under it.+function fakePage() {+ const page = { activeElement: null };+ page.node = (parent = null) => {+ const self = {+ parent,+ ownerDocument: page,+ contains: (other) => {+ for (let node = other; node; node = node.parent) {+ if (node === self) return true;+ }+ return false;+ },+ };+ return self;+ };+ return page;+}++async function mountHold(t) {+ let root;+ t.after(async () => {+ if (root) await React.act(async () => root.unmount());+ });+ installBrowserGlobals(t);+ const container = installHookDom(t);+ const vite = await createRendererServer(t, { cachePrefix: "openwhispr-focus-hold-" });+ const { useFocusHold } = await vite.ssrLoadModule("/hooks/useFocusHold.ts");+ let hold;+ function Harness() {+ hold = useFocusHold();+ return null;+ }+ root = createRoot(container);+ await React.act(async () => root.render(React.createElement(Harness)));+ return {+ held: () => hold.held,+ focus: () => React.act(async () => hold.onFocus()),+ // currentTarget: the element the hold is bound to; relatedTarget: where focus went.+ blur: (currentTarget, relatedTarget = null) =>+ React.act(async () => hold.onBlur({ currentTarget, relatedTarget })),+ };+}++test("a focus hold lasts until focus really leaves, a window switch included", async (t) => {+ const hold = await mountHold(t);+ const page = fakePage();+ const field = page.node();+ assert.equal(hold.held(), false);+ await hold.focus();+ assert.equal(hold.held(), true);+ page.activeElement = field; // the window lost focus, but the field is still the page's focus+ await hold.blur(field);+ assert.equal(hold.held(), true, "switching to another app keeps the hold");+ page.activeElement = null;+ await hold.blur(field);+ assert.equal(hold.held(), false);+});++test("focus moving to another field inside the held element keeps the hold", async (t) => {+ const hold = await mountHold(t);+ const page = fakePage();+ const fields = page.node();+ const next = page.node(fields);+ await hold.focus();+ await hold.blur(fields, next);+ assert.equal(hold.held(), true, "focus moved to another of its fields");+ page.activeElement = next; // a window switch with a field inside it focused+ await hold.blur(fields);+ assert.equal(hold.held(), true, "switching apps keeps it");+ page.activeElement = null;+ await hold.blur(fields, page.node());+ assert.equal(hold.held(), false, "focus left its fields");+});diff --git a/test/hooks/useTypingPause.test.js b/test/hooks/useTypingPause.test.jsnew file mode 100644index 000000000..4dc4c43cb--- /dev/null+++ b/test/hooks/useTypingPause.test.js@@ -0,0 +1,82 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const React = require("react");+const { createRoot } = require("react-dom/client");+const {+ createRendererServer,+ installBrowserGlobals,+ installHookDom,+} = require("../lib/rendererTestHarness");++const PAUSE = 500;++async function mountPause(t, initialArgs = {}) {+ let root;+ t.after(async () => {+ if (root) await React.act(async () => root.unmount());+ });+ installBrowserGlobals(t);+ const container = installHookDom(t);+ const vite = await createRendererServer(t, { cachePrefix: "openwhispr-typing-pause-" });+ const { useTypingPause } = await vite.ssrLoadModule("/hooks/useTypingPause.ts");+ let args = { typed: "", context: "a", held: false, ...initialArgs };+ let delay;+ function Harness() {+ delay = useTypingPause(args);+ return null;+ }+ root = createRoot(container);+ const render = async (next = {}) => {+ args = { ...args, ...next };+ await React.act(async () => root.render(React.createElement(Harness)));+ };+ await render();+ return { delay: () => delay, render };+}++test("a typed change waits, wherever it was typed", async (t) => {+ const pause = await mountPause(t);+ assert.equal(pause.delay(), 0, "nothing typed yet");+ await pause.render({ typed: "s" });+ assert.equal(pause.delay(), PAUSE, "the field is not focused here, but the key changed");+ await pause.render({ typed: "sk" });+ assert.equal(pause.delay(), PAUSE);+});++test("a tab, model or shown panel checks at once, even with a new key", async (t) => {+ const pause = await mountPause(t, { typed: "sk-one" });+ await pause.render({ typed: "sk-two", context: "b" });+ assert.equal(pause.delay(), 0, "a context change wins over a typed change in the same render");+});++test("leaving the fields sends at once, and focus alone starts no pause", async (t) => {+ const pause = await mountPause(t);+ await pause.render({ held: true });+ assert.equal(pause.delay(), PAUSE, "a focused field keeps the pause");+ await pause.render({ typed: "sk" });+ assert.equal(pause.delay(), PAUSE);+ await pause.render({ held: false });+ assert.equal(pause.delay(), 0, "the fields were left");+ await pause.render({ held: true });+ assert.equal(pause.delay(), PAUSE, "focus alone pauses only while it lasts");+ await pause.render({ held: false });+ assert.equal(pause.delay(), 0, "no typed change, so nothing waits");+});++test("a value saved on leaving the fields sends at once", async (t) => {+ const pause = await mountPause(t, { typed: "http://127.0.0.1:8080/v1/", held: true });+ // Leaving the address tidies and saves it in the same event as the hold's drop.+ await pause.render({ typed: "http://127.0.0.1:8080/v1", held: false });+ assert.equal(pause.delay(), 0, "the fields were left, so the save is not typing");+});++test("the pause outlives the field's focus until the check changes some other way", async (t) => {+ const pause = await mountPause(t);+ await pause.render({ typed: "sk" });+ assert.equal(pause.delay(), PAUSE);+ await pause.render({});+ await pause.render({});+ assert.equal(pause.delay(), PAUSE, "an unrelated rerender keeps the pause");+ await pause.render({ context: "b" });+ assert.equal(pause.delay(), 0, "a tab or model change checks at once");+});diff --git a/test/lib/byokStepHarness.js b/test/lib/byokStepHarness.jsindex 3f3cf8338..4e761b346 100644--- a/test/lib/byokStepHarness.js+++ b/test/lib/byokStepHarness.js@@ -1,3 +1,4 @@+const assert = require("node:assert/strict");const React = require("react");const { createRoot } = require("react-dom/client");const {@@ -7,6 +8,7 @@ const {} = require("./rendererTestHarness");const MIGRATED = { _providerSettingsMigrated: "1", uploadTranscriptionMigrated: "true" };+const ENDPOINT_PLACEHOLDER = "onboarding.rehaul.provider.endpointPlaceholder";function findAll(node, predicate, found = []) {if (Array.isArray(node)) {@@ -33,32 +35,25 @@ async function mountByokStep(secrets = {},} = {}) {- // Registered first so it runs first: after hooks run in order, and unmounting once- // the globals are gone would run the step's cleanup without a window.let unmount = async () => {};- t.after(() => unmount());- // Saving a key schedules its secret write and a .env persist; those would run- // against a window that is already gone, so whatever is still pending is dropped- // rather than waited out.- const pendingTimers = new Set();- const { setTimeout: realSetTimeout, clearTimeout: realClearTimeout } = globalThis;- globalThis.setTimeout = (...args) => {- const id = realSetTimeout(...args);- pendingTimers.add(id);- return id;- };- globalThis.clearTimeout = (id) => {- pendingTimers.delete(id);- realClearTimeout(id);- };- t.after(() => {- for (const id of pendingTimers) realClearTimeout(id);- globalThis.setTimeout = realSetTimeout;- globalThis.clearTimeout = realClearTimeout;+ // After hooks run in order: unmount while the window still exists, then stop the mock+ // clock before the renderer server closes.+ t.after(async () => {+ await unmount();+ t.mock.timers.reset();});+ const connections = [];installBrowserGlobals(t, {initialStorage: { ...MIGRATED, ...settings },- window: { electronAPI: { getPlatform: () => "linux" }, dispatchEvent: () => true },+ window: {+ electronAPI: {+ getPlatform: () => "linux",+ // Each automatic check waits here until the test answers it.+ testProviderConnection: (config) =>+ new Promise((resolve) => connections.push({ config, resolve })),+ },+ dispatchEvent: () => true,+ },});const container = installHookDom(t);const vite = await createRendererServer(t, {@@ -70,7 +65,6 @@ async function mountByokStep(export function useTranslation() { return { t }; }export const initReactI18next = { type: "3rdParty", init() {} };`,- "/ProviderConnectionTest": `export default function ProviderConnectionTest() { return null; }`,"/OnboardingShell": `export function BrandMark() { return null; }`,"/ui/ProviderIcon": `export function ProviderIcon() { return null; }`,// Saving a key clears ReasoningService's key cache through a lazy import.@@ -82,6 +76,15 @@ async function mountByokStep(const { ByokProviderStep } = await vite.ssrLoadModule("/components/onboarding/ProviderSetupStep.tsx");+ const { CONNECTION_CHECK_DELAY_MS } = await vite.ssrLoadModule(+ "/hooks/useConnectionAutoCheck.ts"+ );+ // The step's timers run on a mock clock. Anything still pending when the test ends (a+ // key's secret write, a draft flush) is dropped rather than waited out. One mount per+ // test context: the clock can be enabled only once.+ t.mock.timers.enable({ apis: ["setTimeout"] });++ let proceeded = 0;let tree;const drafts = [];@@ -93,7 +96,9 @@ async function mountByokStep(resumeState,onSelfHostedChange: (requested) => selfHostedChanges.push(requested),onConnectionChange() {},- onProceed() {},+ onProceed: () => {+ proceeded += 1;+ },onResumeStateChange: (draft) => drafts.push(draft),});return null;@@ -112,6 +117,11 @@ async function mountByokStep(const act = (fn) => React.act(async () => fn());const proceedButton = () =>find((node) => node.props?.children === "onboarding.rehaul.provider.proceed")[0];+ const wait = (ms) => act(() => t.mock.timers.tick(ms));+ const answerConnection = (result, index = connections.length - 1) =>+ act(() => connections[index].resolve(result));+ const checkField = (label) => find((node) => node.props?.check && node.props.label === label)[0];+ const endpoint = () => input(ENDPOINT_PLACEHOLDER);return {vite,selfHostedChanges,@@ -133,14 +143,33 @@ async function mountByokStep(providerId)),- passConnectionTest: () =>- act(() =>- find((node) => typeof node.props?.onSuccessChange === "function")[0].props.onSuccessChange(- true- )- ),+ connectionRequests: () => connections.map((connection) => connection.config),+ wait,+ answerConnection,+ // The step checks by itself: wait out the pause, then answer the request it sent.+ passConnectionTest: async () => {+ const sent = connections.length;+ await wait(CONNECTION_CHECK_DELAY_MS);+ assert.equal(connections.length, sent + 1, "the step sends one check after the pause");+ await answerConnection({ success: true });+ },+ checkField,+ retryCheck: (label) => act(() => checkField(label).props.check.retry()),+ liveRegion: () => {+ const [announcer] = find((node) => node.type?.name === "ConnectionCheckAnnouncer");+ return announcer.type(announcer.props);+ },+ focusEndpoint: () => act(() => endpoint().props.onFocus()),+ // windowSwitch: the window lost focus but the field is still the page's focus.+ blurEndpoint: ({ windowSwitch = false } = {}) =>+ act(() => {+ const field = { contains: (node) => node === field };+ field.ownerDocument = { activeElement: windowSwitch ? field : null };+ endpoint().props.onBlur({ currentTarget: field });+ }),proceedDisabled: () => proceedButton().props.disabled,proceed: () => act(() => proceedButton().props.onClick()),+ proceeded: () => proceeded,// Unmounting flushes the debounced draft write, as advancing past the step does.unmountForDrafts: async () => {await unmount();diff --git a/test/lib/settingsPanelHarness.js b/test/lib/settingsPanelHarness.jsnew file mode 100644index 000000000..21374818c--- /dev/null+++ b/test/lib/settingsPanelHarness.js@@ -0,0 +1,215 @@+const path = require("node:path");+const React = require("react");+const { createRoot } = require("react-dom/client");+const {+ createRendererServer,+ installBrowserGlobals,+ installHookDom,+} = require("./rendererTestHarness");++const MIGRATED = { _providerSettingsMigrated: "1", uploadTranscriptionMigrated: "true" };++function findAll(node, predicate, found = []) {+ if (Array.isArray(node)) {+ for (const child of node) findAll(child, predicate, found);+ } else if (node && typeof node === "object") {+ if (predicate(node)) found.push(node);+ findAll(node.props?.children, predicate, found);+ }+ return found;+}++// The elements from the tree's root down to the first one matching `predicate`.+function trailTo(node, predicate, trail = []) {+ if (Array.isArray(node)) {+ for (const child of node) {+ const found = trailTo(child, predicate, trail);+ if (found) return found;+ }+ return null;+ }+ if (!node || typeof node !== "object") return null;+ const here = [...trail, node];+ return predicate(node) ? here : trailTo(node.props?.children, predicate, here);+}++// A stand-in DOM node for the last element of `trail`. Like an element, it contains every+// node whose trail runs through it.+const domNode = (trail, page) => ({+ trail,+ ownerDocument: page,+ contains: (other) => Boolean(other && other.trail.includes(trail.at(-1))),+});++/**+ * Runs one Settings panel's real hooks under React's lifecycle with its children left+ * unmounted, as byokStepHarness does for onboarding: the element tree, the settings store+ * and the checks sent are the test boundary. `visible` plays the TabPanel around it. One+ * mount per test context: the mock clock can be enabled only once.+ */+async function mountSettingsPanel(+ t,+ { module, props, settings = {}, secrets = {}, visible = true, electronAPI = {}, fetch } = {}+) {+ let unmount = async () => {};+ // After hooks run in order: unmount while the window still exists, then stop the clock.+ t.after(async () => {+ await unmount();+ t.mock.timers.reset();+ });+ if (fetch) t.mock.method(globalThis, "fetch", fetch);+ const connections = [];+ installBrowserGlobals(t, {+ initialStorage: { ...MIGRATED, ...settings },+ window: {+ location: { search: "" },+ electronAPI: {+ getPlatform: () => "linux",+ // Each automatic check waits here until the test answers it.+ testProviderConnection: (config) =>+ new Promise((resolve) => connections.push({ config, resolve })),+ ...electronAPI,+ },+ dispatchEvent: () => true,+ },+ });+ const container = installHookDom(t);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-settings-check-",+ noExternal: ["react-i18next"],+ resolveAlias: { "@": path.resolve(__dirname, "../../src") },+ mockModules: {+ "react-i18next": `+ const t = (key) => key;+ export function useTranslation() { return { t }; }+ export const initReactI18next = { type: "3rdParty", init() {} };+ `,+ "/ui/ProviderIcon": `export function ProviderIcon() { return null; }`,+ // Saving a key clears ReasoningService's key cache through a lazy import.+ "/services/ReasoningService": `export default { clearApiKeyCache() {} };`,+ },+ });+ const { useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");+ useSettingsStore.setState(secrets);+ const { default: Panel } = await vite.ssrLoadModule(module);+ const { PanelVisibleProvider } = await vite.ssrLoadModule("/components/ui/usePanelVisible.ts");+ const { ToastContext } = await vite.ssrLoadModule("/components/ui/useToast.ts");+ t.mock.timers.enable({ apis: ["setTimeout"] });++ let tree;+ let current = props;+ let shown = visible;+ function Harness() {+ tree = Panel(current);+ return null;+ }+ const root = createRoot(container);+ const act = (fn) => React.act(async () => fn());+ const render = () =>+ act(() =>+ root.render(+ React.createElement(+ PanelVisibleProvider,+ { value: shown },+ React.createElement(+ ToastContext.Provider,+ { value: { toast() {} } },+ React.createElement(Harness)+ )+ )+ )+ );+ await render();+ let mounted = true;+ unmount = async () => {+ if (!mounted) return;+ mounted = false;+ await act(() => root.unmount());+ };++ const find = (predicate) => findAll(tree, predicate);+ const named = (name) => (node) => node.props?.["aria-label"] === name;+ const field = (name) => find(named(name))[0];+ const checkField = () => find((node) => node.props?.check)[0];++ let focused = null;+ // A focus event reaches the field's own handler, then each element around it, innermost+ // first, as React's do. Component elements are skipped: their handlers belong to+ // children that are not mounted.+ const dispatch = (name, type, { to = null, windowSwitch = false } = {}) =>+ act(() => {+ const page = { activeElement: null };+ const trail = trailTo(tree, named(name));+ const target = domNode(trail, page);+ // windowSwitch: the window lost focus, but the field is still the page's focus.+ if (windowSwitch) page.activeElement = target;+ const relatedTarget = to ? domNode(trailTo(tree, named(to)), page) : null;+ for (let depth = trail.length - 1; depth >= 0; depth -= 1) {+ const element = trail[depth];+ const handler = element.props?.[type];+ const host = typeof element.type === "string";+ if (typeof handler !== "function" || (depth < trail.length - 1 && !host)) continue;+ const currentTarget = domNode(trail.slice(0, depth + 1), page);+ handler({ target, relatedTarget, currentTarget });+ }+ });+ const blur = async (name, { windowSwitch = false, to = null } = {}) => {+ await dispatch(name, "onBlur", { to, windowSwitch });+ if (!windowSwitch) focused = null;+ };+ // Focus moving between fields blurs the first, with the second as relatedTarget, then+ // focuses the second, as the browser does.+ const focus = async (name) => {+ if (focused && focused !== name) await blur(focused, { to: name });+ focused = name;+ await dispatch(name, "onFocus");+ };+ // A tab, a model card or an option takes focus away from the fields.+ const leaveFields = async () => {+ if (focused) await blur(focused);+ };++ return {+ state: () => useSettingsStore.getState(),+ setStore: (patch) => act(() => useSettingsStore.setState(patch)),+ setProps: (patch) => {+ current = { ...current, ...patch };+ return render();+ },+ setVisible: (value) => {+ shown = value;+ return render();+ },+ unmount,+ find,+ field,+ checkField,+ phase: () => checkField()?.props.check.phase,+ focus,+ blur,+ // Typing needs the field's focus, so a field not yet focused is focused first.+ type: async (name, value) => {+ if (focused !== name) await focus(name);+ await act(() => field(name).props.onChange({ target: { value } }));+ },+ selectTab: async (id) => {+ await leaveFields();+ const tabs = find((node) => node.props?.providers?.some?.((tab) => tab.id === id))[0];+ await act(() => tabs.props.onSelect(id));+ },+ choose: async (value) => {+ await leaveFields();+ const select = find((node) => typeof node.props?.onValueChange === "function")[0];+ await act(() => select.props.onValueChange(value));+ },+ requests: () => connections.map((connection) => connection.config),+ answer: (result, index = connections.length - 1) =>+ act(() => connections[index].resolve(result)),+ retry: () => act(() => checkField().props.check.retry()),+ wait: (ms) => act(() => t.mock.timers.tick(ms)),+ announcement: () =>+ find((node) => node.props && "announcement" in node.props)[0]?.props.announcement,+ };+}++module.exports = { mountSettingsPanel };