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
fix(onboarding): sign in without restarting onboarding, and reopen BYOK steps on the saved setup (#2144)
void1655513c8d4d
diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsxindex 2726fd16e..fd4768b11 100644--- a/src/components/ControlPanel.tsx+++ b/src/components/ControlPanel.tsx@@ -61,6 +61,7 @@ import { getCachedPlatform } from "../utils/platform";import { isAccessibilitySkipped } from "../utils/permissions";import { useGpuBannerAvailability } from "../hooks/useGpuBannerAvailability";import { useCreateNote } from "../hooks/useCreateNote";+import { useSignInCloudNudge } from "../hooks/useSignInCloudNudge";import {setActiveNoteId,setActiveFolderId,@@ -198,6 +199,12 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelProinstallUpdate,} = useUpdater();+ const openTranscriptionSettings = useCallback(() => {+ setSettingsSection("transcription");+ setShowSettings(true);+ }, []);+ useSignInCloudNudge(isSignedIn, openTranscriptionSettings);+const agentAllowedByPolicy = usePolicyStore(isAgentAllowed);const { createNote } = useCreateNote();// The note is created before the view switches so Notes mounts with it already open.diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 087345f38..04070327f 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -101,7 +101,6 @@ import { Skeleton } from "./ui/skeleton";import { Progress } from "./ui/progress";import { useToast } from "./ui/useToast";import { useTheme } from "../hooks/useTheme";-import { useStartOnboarding } from "../hooks/useStartOnboarding";import type {ChineseScriptPreference,GpuDevice,@@ -145,6 +144,7 @@ import {} from "../stores/policyRules";import { usePolicyModeOptions, usePolicySnapshot } from "../hooks/usePolicy";import { usePolicyStore } from "../stores/policyStore";+import { requestSignIn } from "../utils/requestSignIn";import { canManageSystemAudioInApp } from "../utils/systemAudioAccess";import WorkspaceSection from "./settings/WorkspaceSection";import { enterpriseTileCta, type EnterpriseTileCta } from "../lib/workspaceBilling";@@ -485,7 +485,6 @@ function GranolaImportSection({interface TranscriptionSectionProps {isSignedIn: boolean;- startOnboarding: () => void;cloudTranscriptionMode: string;setCloudTranscriptionMode: (mode: string) => void;useLocalWhisper: boolean;@@ -523,7 +522,6 @@ interface TranscriptionSectionProps {function TranscriptionSection({isSignedIn,- startOnboarding,cloudTranscriptionMode,setCloudTranscriptionMode,useLocalWhisper,@@ -616,7 +614,7 @@ function TranscriptionSection({const handleTranscriptionModeSelect = (mode: InferenceMode) => {if (!isModeAllowed(mode)) return;if (mode === "openwhispr" && !isSignedIn) {- startOnboarding();+ requestSignIn();return;}if (mode === effectiveTranscriptionMode) return;@@ -1893,8 +1891,6 @@ export default function SettingsPage({} | null>(null);const [previewLoading, setPreviewLoading] = useState(false);- const startOnboarding = useStartOnboarding();-const handleSwitchPlan = useCallback(async (plan: "monthly" | "annual", tier: "pro" | "business") => {setPreviewLoading(true);@@ -2273,7 +2269,7 @@ export default function SettingsPage({{t("settingsPage.account.trialCta.description")}</p></div>- <Button onClick={startOnboarding} size="sm" className="w-full">+ <Button onClick={requestSignIn} size="sm" className="w-full"><UserCircle className="me-1.5 h-3.5 w-3.5" />{t("settingsPage.account.trialCta.button")}</Button>@@ -2602,7 +2598,7 @@ export default function SettingsPage({</ul>{!isSignedIn ? (<Button- onClick={startOnboarding}+ onClick={requestSignIn}variant="outline"size="sm"className="mt-2 w-full h-6 text-[10px]"@@ -2710,7 +2706,7 @@ export default function SettingsPage({</Button>) : proCardCta === "signUp" ? (<Button- onClick={startOnboarding}+ onClick={requestSignIn}size="sm"className="mt-2 w-full h-6 text-[10px]">@@ -2796,7 +2792,7 @@ export default function SettingsPage({</ul>{!isSignedIn ? (<Button- onClick={startOnboarding}+ onClick={requestSignIn}size="sm"className="mt-2 w-full h-6 text-[10px]">@@ -4931,7 +4927,6 @@ EOF`,<div className="space-y-6"><TranscriptionSectionisSignedIn={isSignedIn ?? false}- startOnboarding={startOnboarding}cloudTranscriptionMode={cloudTranscriptionMode}setCloudTranscriptionMode={setCloudTranscriptionMode}useLocalWhisper={useLocalWhisper}diff --git a/src/components/notes/UploadAudioView.tsx b/src/components/notes/UploadAudioView.tsxindex a1dec6fdd..588033ae5 100644--- a/src/components/notes/UploadAudioView.tsx+++ b/src/components/notes/UploadAudioView.tsx@@ -36,7 +36,7 @@ import {import { useAuth } from "../../hooks/useAuth";import { useUsage } from "../../hooks/useUsage";import { useSettings } from "../../hooks/useSettings";-import { useStartOnboarding } from "../../hooks/useStartOnboarding";+import { requestSignIn } from "../../utils/requestSignIn";import {getAllReasoningModels,getBatchTranscriptionModel,@@ -941,8 +941,6 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa}};- const handleCreateAccount = useStartOnboarding();-const switchToCloud = () => {setUploadTranscriptionMode("openwhispr");setUploadCloudTranscriptionMode("openwhispr");@@ -1158,7 +1156,7 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: UploarequiresAccount={requiresAccount}isProUser={!!isProUser}onUpgrade={() => usage?.openCheckout()}- onCreateAccount={handleCreateAccount}+ onCreateAccount={requestSignIn}onSwitchToCloud={switchToCloud}onOpenSettings={onOpenSettings}/>diff --git a/src/components/onboarding/ProviderSetupStep.tsx b/src/components/onboarding/ProviderSetupStep.tsxindex 1461096f1..df0b365d4 100644--- a/src/components/onboarding/ProviderSetupStep.tsx+++ b/src/components/onboarding/ProviderSetupStep.tsx@@ -9,6 +9,8 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from ".import { useModelDownload } from "../../hooks/useModelDownload";import type { ParakeetCheckResult } from "../../types/electron";import { useSettingsStore } from "../../stores/settingsStore";+import { normalizeBaseUrl } from "../../config/constants";+import { withHttpsScheme } from "../../utils/urlUtils";import { usePolicySnapshot } from "../../hooks/usePolicy";import {filterByokProviderOptionsByPolicy,@@ -45,6 +47,7 @@ import {rememberPendingLocalModel,} from "./pendingLocalModels";import { isLocalStageDownloadActive } from "./localDownloadState";+import { isBlankByokDraft, resolveSavedByokConfig } from "./savedByokConfig";export function SetupStageStepper({ stepId }: { stepId: OnboardingStepId }) {const { t } = useTranslation();@@ -226,6 +229,24 @@ function providerCredential(provider: string, store: ReturnType<typeof useSettin}}+/**+ * One server's variants — missing scheme, host case, trailing slash, pasted API path —+ * compare equal. Parsing lowercases the scheme and host; the path keeps its case.+ */+function endpointIdentity(baseUrl: string): string {+ const normalized = normalizeBaseUrl(withHttpsScheme(baseUrl));+ try {+ return new URL(normalized).href;+ } catch {+ return normalized;+ }+}++function isSameEndpoint(baseUrl: string, savedBaseUrl: string): boolean {+ const saved = endpointIdentity(savedBaseUrl);+ return Boolean(saved) && endpointIdentity(baseUrl) === saved;+}+/*** The provider/model a local step opens on: the draft this step last wrote, then* a selection whose download is still pending, then whatever the store already@@ -321,35 +342,57 @@ export function ByokProviderStep({),[assistant, policy, scope]);- const initialProvider =- providers.find((provider) => provider.id === resumeState?.selectedProvider)?.id ?? "";- const initialProviderModels =- providers.find((provider) => provider.id === initialProvider)?.models ?? [];- const initialModel = initialProviderModels.some(- (model) => model.id === resumeState?.selectedModel- )- ? (resumeState?.selectedModel ?? "")- : (initialProviderModels[0]?.id ?? "");- const initiallySelfHosted = selfHostedRequested && selfHostedAllowed;- const [selfHosted, setSelfHosted] = useState(initiallySelfHosted);- const [selectedProvider, setSelectedProvider] = useState(- initiallySelfHosted ? "" : initialProvider- );- const [selectedModel, setSelectedModel] = useState(initiallySelfHosted ? "" : initialModel);+ // The session's draft wins; without one (onboarding was restarted, or an older build+ // left it blank) the step reopens on what the user already saved, the same order+ // LocalModelSetupStep uses. The draft never records keys, so the stored custom key is+ // tracked by the endpoint it was saved under — the draft, and anything typed after it,+ // can name a different server than the saved settings do.+ const [seed] = useState(() => {+ const saved = resolveSavedByokConfig(stepId, store);+ const hasDraft = Boolean(resumeState && !isBlankByokDraft(resumeState));+ const draft = hasDraft ? resumeState : saved?.draft;+ const providerData = providers.find((provider) => provider.id === draft?.selectedProvider);+ // After a restart the session only knows which setup-choice tile was clicked, so a+ // saved endpoint opens its own card whichever tile that was; a draft carries the+ // card the session recorded for it.+ const selfHostedWanted =+ hasDraft || !saved ? selfHostedRequested : Boolean(saved.draft.baseUrl);+ const selfHosted = selfHostedWanted && selfHostedAllowed;+ return {+ provider: providerData?.id ?? "",+ model: providerData?.models?.some((model) => model.id === draft?.selectedModel)+ ? (draft?.selectedModel ?? "")+ : pickDefaultModelId(providerData),+ baseUrl: draft?.baseUrl ?? "",+ customModel: draft?.customModel ?? "",+ selfHosted,+ cardDiffersFromSession: selfHosted !== selfHostedRequested,+ keyedBaseUrl: saved?.usesCustomKey ? saved.draft.baseUrl : "",+ };+ });+ // Hosted and self-hosted share the key field, so each mode shows its own saved key.+ // The stored custom key belongs to the one endpoint it was saved under: offering it for+ // a key-less server, a hosted provider, a first setup, or an endpoint the user has since+ // typed would send a key they never typed to that server, and move the save onto the+ // keyed route.+ const credentialFor = (selfHostedMode: boolean, providerId: string, baseUrl: string) => {+ if (!selfHostedMode) return providerCredential(providerId, store).value;+ if (!isSameEndpoint(baseUrl, seed.keyedBaseUrl)) return "";+ return assistant ? store.chatAgentCustomApiKey : store.customTranscriptionApiKey;+ };+ const [selfHosted, setSelfHosted] = useState(seed.selfHosted);+ const [selectedProvider, setSelectedProvider] = useState(seed.provider);+ const [selectedModel, setSelectedModel] = useState(seed.model);const [draftApiKey, setDraftApiKey] = useState(() =>- initiallySelfHosted- ? assistant- ? store.chatAgentCustomApiKey- : store.customTranscriptionApiKey- : providerCredential(initialProvider, store).value+ credentialFor(seed.selfHosted, seed.provider, seed.baseUrl));- const [draftBaseUrl, setDraftBaseUrl] = useState(resumeState?.baseUrl ?? "");- const [draftCustomModel, setDraftCustomModel] = useState(resumeState?.customModel ?? "");+ const [draftBaseUrl, setDraftBaseUrl] = useState(seed.baseUrl);+ const [draftCustomModel, setDraftCustomModel] = useState(seed.customModel);const [draftCortiClientId, setDraftCortiClientId] = useState(- initialProvider === "corti" ? store.cortiClientId : ""+ seed.provider === "corti" ? store.cortiClientId : "");const [draftCortiClientSecret, setDraftCortiClientSecret] = useState(- initialProvider === "corti" ? store.cortiClientSecret : ""+ seed.provider === "corti" ? store.cortiClientSecret : "");const [connected, setConnected] = useState(false);@@ -357,6 +400,13 @@ export function ByokProviderStep({onConnectionChange(false);}, [onConnectionChange]);+ // 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+ // through toggleSelfHosted.+ useEffect(() => {+ if (seed.cardDiffersFromSession) onSelfHostedChange(seed.selfHosted);+ }, [onSelfHostedChange, seed]);+// Base URL and custom model are typed, so the write is debounced the way the// auth draft is; the flush covers the pending write this card drops when the// step advances and unmounts it.@@ -378,32 +428,50 @@ export function ByokProviderStep({useEffect(() => flushByokDraft, [flushByokDraft]);- // A live policy update can remove self-hosting while this card is open.+ // A live policy update can remove self-hosting while this card is open. The hosted+ // half of the form is kept, so it only needs its provider's key.useEffect(() => {if (!selfHosted || selfHostedAllowed) return;setSelfHosted(false);onSelfHostedChange(false);- setDraftApiKey("");- setDraftBaseUrl("");- setDraftCustomModel("");+ setDraftApiKey(providerCredential(selectedProvider, useSettingsStore.getState()).value);setConnected(false);onConnectionChange(false);- }, [onConnectionChange, onSelfHostedChange, selfHosted, selfHostedAllowed]);+ }, [onConnectionChange, 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.+ const savedKey = credentialFor(selfHosted, selectedProvider, draftBaseUrl);+ // Retyping the endpoint strands the copy of the stored key this card prefilled, so it is+ // taken back out. Only a byte-identical copy goes — never a key the user typed, and+ // never while the field still names the endpoint the key was saved under.+ const strandedKey =+ selfHosted && !savedKey+ ? assistant+ ? store.chatAgentCustomApiKey+ : store.customTranscriptionApiKey+ : "";+ const savedCortiClientId = selectedProvider === "corti" ? store.cortiClientId : "";+ const savedCortiClientSecret = selectedProvider === "corti" ? store.cortiClientSecret : "";+ useEffect(() => {+ if (savedKey) setDraftApiKey((current) => current || savedKey);+ else if (strandedKey) setDraftApiKey((current) => (current === strandedKey ? "" : current));+ if (savedCortiClientId) setDraftCortiClientId((current) => current || savedCortiClientId);+ if (savedCortiClientSecret) {+ setDraftCortiClientSecret((current) => current || savedCortiClientSecret);+ }+ }, [savedCortiClientId, savedCortiClientSecret, savedKey, strandedKey]);const currentProvider = providers.find((provider) => provider.id === selectedProvider);const models = currentProvider?.models ?? [];const knownCredential = providerCredential(selectedProvider, store);+ // Both halves of the form survive a mode switch, so switching back shows the saved or+ // typed values again; only the shared key field follows the mode.const toggleSelfHosted = () => {const next = !selfHosted;setSelfHosted(next);onSelfHostedChange(next);- setSelectedProvider("");- setSelectedModel("");- setDraftApiKey("");- setDraftBaseUrl("");- setDraftCustomModel("");- setDraftCortiClientId("");- setDraftCortiClientSecret("");+ setDraftApiKey(credentialFor(next, selectedProvider, draftBaseUrl));setConnected(false);onConnectionChange(false);};@@ -437,31 +505,45 @@ export function ByokProviderStep({const testingKey = draftApiKey;const testingBaseUrl = selfHosted ? draftBaseUrl : undefined;const isCortiTranscription = !assistant && !selfHosted && selectedProvider === "corti";+ // A provider counts only while policy still lists it: a policy that loads after mount+ // can remove the one this card opened on.const fieldsReady = selfHosted? Boolean(draftBaseUrl.trim() && draftCustomModel.trim()): isCortiTranscription- ? Boolean(draftCortiClientId.trim() && draftCortiClientSecret.trim() && selectedModel)- : Boolean(selectedProvider && selectedModel && testingKey.trim());+ ? Boolean(+ currentProvider &&+ draftCortiClientId.trim() &&+ draftCortiClientSecret.trim() &&+ selectedModel+ )+ : Boolean(currentProvider && selectedModel && testingKey.trim());const commitAndProceed = () => {if (selfHosted) {- // The connection test parses scheme-less input as https- // (providerConnectionTest.js), so commit the same URL it validated —- // the runtime's isSecureHttpEndpoint gate rejects a bare host.- const committedBaseUrl = draftBaseUrl.includes("://")- ? draftBaseUrl.trim()- : `https://${draftBaseUrl.trim()}`;+ const committedBaseUrl = withHttpsScheme(draftBaseUrl);if (assistant) {store.setChatAgentRemoteUrl(committedBaseUrl);store.setChatAgentCustomApiKey(draftApiKey);store.setChatAgentModel(draftCustomModel);store.setChatAgentMode("self-hosted");store.setChatAgentProvider("custom");- } else {+ } else if (draftApiKey.trim()) {store.setCloudTranscriptionBaseUrl(committedBaseUrl);store.setCustomTranscriptionApiKey(draftApiKey);+ // Switch before setting the model: a switch files the current model under the+ // outgoing provider and loads the incoming one's, replacing what was typed here.+ store.switchCloudTranscriptionProvider("dictation", "custom");store.setCloudTranscriptionModel(draftCustomModel);+ // A Settings server routes ahead of the keyed Custom endpoint, and sends no key.+ store.setRemoteTranscriptionUrl("");+ store.setCloudTranscriptionMode("byok");+ } else {+ // Key-less, so it is the Settings self-hosted server; the Custom endpoint and its+ // key stay as they were. byok + custom is what derives the self-hosted mode.store.switchCloudTranscriptionProvider("dictation", "custom");+ store.setRemoteTranscriptionUrl(committedBaseUrl);+ store.setRemoteTranscriptionModel(draftCustomModel);+ store.setRemoteTranscriptionType("openai-compatible");store.setCloudTranscriptionMode("byok");}} else if (assistant) {diff --git a/src/components/onboarding/flow.ts b/src/components/onboarding/flow.tsindex cbd1b078c..95a1466d8 100644--- a/src/components/onboarding/flow.ts+++ b/src/components/onboarding/flow.ts@@ -1,3 +1,4 @@+import { SIGN_IN_PROMPTED_AT_KEY } from "../../utils/requestSignIn";import { PENDING_LOCAL_MODELS_KEY } from "./pendingLocalModels";export const ONBOARDING_SESSION_KEY = "onboardingSessionV2";@@ -215,6 +216,8 @@ export function resetOnboardingProgress(storage: OnboardingStorage): void {storage.removeItem("skipAuth");storage.removeItem("localSetupPending");storage.removeItem(PENDING_LOCAL_MODELS_KEY);+ // A restart is not the sign-in that marker announces.+ storage.removeItem(SIGN_IN_PROMPTED_AT_KEY);// AppRouter uses this marker to distinguish an explicit restart from a// returning signed-in user, while useOnboardingSession migrates it to auth.storage.setItem(LEGACY_ONBOARDING_STEP_KEY, "0");diff --git a/src/components/onboarding/savedByokConfig.ts b/src/components/onboarding/savedByokConfig.tsnew file mode 100644index 000000000..65b6612a8--- /dev/null+++ b/src/components/onboarding/savedByokConfig.ts@@ -0,0 +1,97 @@+import { API_ENDPOINTS } from "../../config/constants.ts";+import { isSelfHostedTranscription } from "../../helpers/selfHostedTranscription.js";+import type { SettingsState } from "../../stores/settingsStore.ts";+import type { OnboardingByokDraft, OnboardingByokStepId } from "./flow.ts";++/** The saved settings a BYOK step reads to reopen on what the user already configured. */+export type SavedByokSnapshot = Pick<+ SettingsState,+ | "useLocalWhisper"+ | "transcriptionMode"+ | "cloudTranscriptionProvider"+ | "cloudTranscriptionModel"+ | "cloudTranscriptionBaseUrl"+ | "remoteTranscriptionUrl"+ | "remoteTranscriptionModel"+ | "chatAgentMode"+ | "chatAgentProvider"+ | "chatAgentModel"+ | "chatAgentRemoteUrl"+>;++export interface SavedByokConfig {+ draft: OnboardingByokDraft;+ /**+ * The saved endpoint authenticates with the step's stored custom API key. False for+ * the Settings self-hosted transcription server, which sends none, and for a hosted+ * provider, whose key belongs to the provider rather than to the endpoint field.+ */+ usesCustomKey: boolean;+}++const hostedConfig = (provider: string, model: string): SavedByokConfig => ({+ draft: { selectedProvider: provider, selectedModel: model, baseUrl: "", customModel: "" },+ usesCustomKey: false,+});++const endpointConfig = (+ baseUrl: string,+ model: string,+ usesCustomKey = false+): SavedByokConfig => ({+ draft: { selectedProvider: "", selectedModel: "", baseUrl, customModel: model },+ usesCustomKey,+});++// Same precedence as resolveTranscriptionRoute, so the step reopens on the endpoint+// dictation actually uses. Local is read from useLocalWhisper because Settings also+// writes cloudTranscriptionMode "byok" for Local.+function resolveSavedDictation(s: SavedByokSnapshot): SavedByokConfig | null {+ if (isSelfHostedTranscription(s)) {+ return endpointConfig(s.remoteTranscriptionUrl.trim(), s.remoteTranscriptionModel);+ }+ if (s.useLocalWhisper) return null;+ if (s.transcriptionMode !== "providers" && s.transcriptionMode !== "self-hosted") return null;+ if (s.cloudTranscriptionProvider === "custom") {+ const baseUrl = (s.cloudTranscriptionBaseUrl || "").trim();+ // The untouched store default is not a configured endpoint, as in the custom route.+ if (!baseUrl || baseUrl === API_ENDPOINTS.TRANSCRIPTION_BASE) return null;+ return endpointConfig(baseUrl, s.cloudTranscriptionModel, true);+ }+ // Self-hosted mode without its own URL only routes for the custom provider.+ if (s.transcriptionMode === "self-hosted") return null;+ return hostedConfig(s.cloudTranscriptionProvider, s.cloudTranscriptionModel);+}++// A Custom provider under "providers" is left out: this step can only save a+// self-hosted endpoint, which would move it to a different URL setting.+function resolveSavedAssistant(s: SavedByokSnapshot): SavedByokConfig | null {+ if (s.chatAgentMode === "self-hosted") {+ // The assistant has one self-hosted route and it carries chatAgentCustomApiKey,+ // so unlike dictation there is no key-less endpoint to tell apart.+ const baseUrl = s.chatAgentRemoteUrl.trim();+ return baseUrl ? endpointConfig(baseUrl, s.chatAgentModel, true) : null;+ }+ if (s.chatAgentMode === "providers" && s.chatAgentProvider && s.chatAgentProvider !== "custom") {+ return hostedConfig(s.chatAgentProvider, s.chatAgentModel);+ }+ return null;+}++/**+ * The provider setup already saved for a BYOK step, as the draft the step opens on. Null+ * when there is nothing to reopen: a first run, OpenWhispr Cloud, local or enterprise.+ * The draft never carries a key; the step reads keys from the store.+ */+export function resolveSavedByokConfig(+ stepId: OnboardingByokStepId,+ settings: SavedByokSnapshot+): SavedByokConfig | null {+ return stepId === "byok-assistant"+ ? resolveSavedAssistant(settings)+ : resolveSavedDictation(settings);+}++export function isBlankByokDraft(draft: OnboardingByokDraft): boolean {+ return !(draft.selectedProvider || draft.selectedModel || draft.baseUrl || draft.customModel);+}diff --git a/src/components/settings/InferenceConfigEditor.tsx b/src/components/settings/InferenceConfigEditor.tsxindex 70702da69..02b74f815 100644--- a/src/components/settings/InferenceConfigEditor.tsx+++ b/src/components/settings/InferenceConfigEditor.tsx@@ -31,10 +31,10 @@ import {enterpriseProviderName,} from "../../models/ModelRegistry";import { useManagedScopeResolution } from "../../stores/enterpriseIdentityStore";+import { requestSignIn } from "../../utils/requestSignIn";import TestConnectionButton from "../TestConnectionButton";import { getEnterpriseCallSettings } from "../../services/ai/enterpriseSettings";import { Button } from "../ui/button";-import { useStartOnboarding } from "../../hooks/useStartOnboarding";const MODE_LABEL_PREFIX: Record<InferenceScope, string> = {dictationCleanup: "settingsPage.aiModels.modes",@@ -58,7 +58,6 @@ export default function InferenceConfigEditor({allowedModes,}: InferenceConfigEditorProps) {const { t } = useTranslation();- const startOnboarding = useStartOnboarding();const policyState = usePolicySnapshot();const config = useSettingsStore(useShallow((settings): ResolvedLLMConfig => {@@ -135,7 +134,7 @@ export default function InferenceConfigEditor({(mode: InferenceMode) => {if (!isModeAllowed(mode)) return;if (mode === "openwhispr" && !isSignedIn) {- startOnboarding();+ requestSignIn();return;}if (mode === effectiveMode) return;@@ -156,15 +155,7 @@ export default function InferenceConfigEditor({onModeChange?.(mode);},- [- scope,- config.provider,- effectiveMode,- isSignedIn,- onModeChange,- isModeAllowed,- startOnboarding,- ]+ [scope, config.provider, effectiveMode, isSignedIn, onModeChange, isModeAllowed]);const setMode = setField("mode");diff --git a/src/components/settings/MeetingSettings.tsx b/src/components/settings/MeetingSettings.tsxindex 4bd7909db..c15a5dea8 100644--- a/src/components/settings/MeetingSettings.tsx+++ b/src/components/settings/MeetingSettings.tsx@@ -4,12 +4,12 @@ import { Cloud, Key, Cpu, Network } from "../icons";import { useSettingsStore } from "../../stores/settingsStore";import { usePolicyModeOptions, usePolicySnapshot } from "../../hooks/usePolicy";import { isModeAllowedByPolicy } from "../../stores/policyRules";+import { requestSignIn } from "../../utils/requestSignIn";import { InferenceModeSelector, SettingsRow } from "../ui/SettingsSection";import type { InferenceModeOption } from "../ui/SettingsSection";import { Toggle } from "../ui/toggle";import TranscriptionModelPicker from "../TranscriptionModelPicker";import type { InferenceMode } from "../../types/electron";-import { useStartOnboarding } from "../../hooks/useStartOnboarding";import { getMeetingStreamingTranscriptionProviders } from "../../models/ModelRegistry";const MEETING_BYOK_PROVIDER_IDS = getMeetingStreamingTranscriptionProviders().map(@@ -35,7 +35,6 @@ const noop = () => {};export function MeetingTranscriptionPanel() {const { t } = useTranslation();- const startOnboarding = useStartOnboarding();const policySnapshot = usePolicySnapshot();const {@@ -102,7 +101,7 @@ export function MeetingTranscriptionPanel() {if (!isModeAllowed(mode)) return;if (mode === "self-hosted") return;if (mode === "openwhispr" && !isSignedIn) {- startOnboarding();+ requestSignIn();return;}if (mode === effectiveTranscriptionMode) return;diff --git a/src/components/settings/UploadSettings.tsx b/src/components/settings/UploadSettings.tsxindex 210562698..237c889d3 100644--- a/src/components/settings/UploadSettings.tsx+++ b/src/components/settings/UploadSettings.tsx@@ -8,16 +8,15 @@ import {} from "../../stores/settingsStore";import { usePolicyModeOptions, usePolicySnapshot } from "../../hooks/usePolicy";import { isEnterpriseTranscriptionOfferable } from "../../stores/policyRules";+import { requestSignIn } from "../../utils/requestSignIn";import { InferenceModeSelector } from "../ui/SettingsSection";import type { InferenceModeOption } from "../ui/SettingsSection";import TranscriptionModelPicker from "../TranscriptionModelPicker";import SelfHostedPanel from "../SelfHostedPanel";import type { InferenceMode } from "../../types/electron";-import { useStartOnboarding } from "../../hooks/useStartOnboarding";export function UploadTranscriptionPanel() {const { t } = useTranslation();- const startOnboarding = useStartOnboarding();const policySnapshot = usePolicySnapshot();const {@@ -99,7 +98,7 @@ export function UploadTranscriptionPanel() {const handleTranscriptionModeSelect = (mode: InferenceMode) => {if (!isModeAllowed(mode)) return;if (mode === "openwhispr" && !isSignedIn) {- startOnboarding();+ requestSignIn();return;}if (mode === effectiveTranscriptionMode) return;diff --git a/src/components/ui/Toast.tsx b/src/components/ui/Toast.tsxindex 8cbfcbe24..c2a6668f9 100644--- a/src/components/ui/Toast.tsx+++ b/src/components/ui/Toast.tsx@@ -18,6 +18,25 @@ import { useCopyFeedback } from "../../hooks/useCopyFeedback";import { DictationErrorCard } from "../dictation/DictationErrorCard";import { TechnicalErrorDetails } from "./TechnicalErrorDetails";+/** The inline action beside a toast's text; dismissing is left to the caller. */+export function ToastActionButton({+ onClick,+ children,+}: {+ onClick: () => void | Promise<void>;+ children: React.ReactNode;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ className="rounded-sm border border-white/20 bg-white/10 px-2.5 py-1 text-[10px] font-medium whitespace-nowrap text-white/90 transition-colors hover:border-white/35 hover:bg-white/20 hover:text-white"+ >+ {children}+ </button>+ );+}+interface ToastState extends ToastProps {id: string;isExiting?: boolean;diff --git a/src/hooks/useMainProcessNotifications.tsx b/src/hooks/useMainProcessNotifications.tsxindex e818fb58f..6db590f23 100644--- a/src/hooks/useMainProcessNotifications.tsx+++ b/src/hooks/useMainProcessNotifications.tsx@@ -1,5 +1,6 @@import { useEffect } from "react";import type { TFunction } from "i18next";+import { ToastActionButton } from "../components/ui/Toast";import type { ToastContextType } from "../components/ui/useToast";/**@@ -42,7 +43,7 @@ export function useMainProcessNotifications({description: t("app.toasts.gpuFallback.description"),duration: 10000,action: (- <button+ <ToastActionButtononClick={async () => {try {const result = await window.electronAPI?.whisperGpuRetry?.();@@ -51,10 +52,9 @@ export function useMainProcessNotifications({// silently fail — toast stays up for another attempt}}}- className="rounded-sm border border-white/20 bg-white/10 px-2.5 py-1 text-[10px] font-medium whitespace-nowrap text-white/90 transition-colors hover:border-white/35 hover:bg-white/20 hover:text-white">{t("app.toasts.gpuFallback.retry")}- </button>+ </ToastActionButton>),});};diff --git a/src/hooks/useSignInCloudNudge.tsx b/src/hooks/useSignInCloudNudge.tsxnew file mode 100644index 000000000..c16448694--- /dev/null+++ b/src/hooks/useSignInCloudNudge.tsx@@ -0,0 +1,58 @@+import { useEffect } from "react";+import { useTranslation } from "react-i18next";+import { ToastActionButton } from "../components/ui/Toast";+import { useToast } from "../components/ui/useToast";+import { selectPolicyEffectiveSettings, useSettingsStore } from "../stores/settingsStore";+import { SIGN_IN_PROMPTED_AT_KEY } from "../utils/requestSignIn";+import { decideSignInCloudNudge } from "../utils/signInCloudNudge";+import { usePolicySnapshot } from "./usePolicy";++/**+ * Tells a user who just signed in that OpenWhispr Cloud is available, once, without+ * switching anything: a post-sign-in cloud switch is what overrode Local for #2086.+ * The marker requestSignIn left behind survives the reload that sign-in goes through.+ */+export function useSignInCloudNudge(+ isSignedIn: boolean,+ onOpenTranscriptionSettings: () => void+): void {+ const { t } = useTranslation();+ const { toast, dismiss } = useToast();+ const policy = usePolicySnapshot();+ // Policy-effective, because a managed user the policy already clamps onto Cloud is+ // there whatever their own preference still says.+ const transcriptionMode = useSettingsStore(+ (settings) => selectPolicyEffectiveSettings(settings, policy).transcriptionMode+ );++ useEffect(() => {+ const promptedAt = localStorage.getItem(SIGN_IN_PROMPTED_AT_KEY);+ if (promptedAt === null) return;+ const decision = decideSignInCloudNudge({+ promptedAt: Number(promptedAt),+ now: Date.now(),+ isSignedIn,+ policy,+ transcriptionMode,+ });+ if (decision === "wait") return;+ localStorage.removeItem(SIGN_IN_PROMPTED_AT_KEY);+ if (decision === "skip") return;++ const toastId = toast({+ title: t("controlPanel.cloudNudge.title"),+ description: t("controlPanel.cloudNudge.description"),+ duration: 10000,+ action: (+ <ToastActionButton+ onClick={() => {+ dismiss(toastId);+ onOpenTranscriptionSettings();+ }}+ >+ {t("controlPanel.cloudNudge.action")}+ </ToastActionButton>+ ),+ });+ }, [dismiss, isSignedIn, onOpenTranscriptionSettings, policy, t, toast, transcriptionMode]);+}diff --git a/src/hooks/useStartOnboarding.ts b/src/hooks/useStartOnboarding.tsdeleted file mode 100644index 3d4ebf187..000000000--- a/src/hooks/useStartOnboarding.ts+++ /dev/null@@ -1,13 +0,0 @@-import { useCallback } from "react";-import { resetOnboardingProgress } from "../components/onboarding/flow";--// Restart onboarding from the auth step so the user can sign in for OpenWhispr-// Cloud. The restarted flow's setup-choice step commits whatever the user picks-// via setCloudTranscriptionForAllScopes, so nothing is pre-armed here: a-// pre-armed cloud switch is what overrode Local for #2086.-export function useStartOnboarding(): () => void {- return useCallback(() => {- resetOnboardingProgress(localStorage);- window.location.reload();- }, []);-}diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.jsonindex 26244145b..752351efe 100644--- a/src/locales/ar/translation.json+++ b/src/locales/ar/translation.json@@ -576,6 +576,11 @@"title": "النماذج المطلوبة مفقودة","description": "تتطلب مؤسستك هذه النماذج على هذا الجهاز: {{models}}.","download": "تنزيل"+ },+ "cloudNudge": {+ "title": "تم تسجيل دخولك",+ "description": "لا يزال الإملاء يعمل على إعدادك الخاص. يمكنك التبديل إلى OpenWhispr Cloud في أي وقت.",+ "action": "فتح الإعدادات"}},"integrations": {diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 380c7388d..b70d6b83c 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -702,6 +702,11 @@"title": "Erforderliche Modelle fehlen","description": "Ihre Organisation erfordert diese Modelle auf diesem Gerät: {{models}}.","download": "Herunterladen"+ },+ "cloudNudge": {+ "title": "Du bist angemeldet",+ "description": "Das Diktieren läuft weiter über deine eigene Einrichtung. Du kannst jederzeit zu OpenWhispr Cloud wechseln.",+ "action": "Einstellungen öffnen"}},"reasoning": {diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 3c0821a33..68c830c2d 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -702,6 +702,11 @@"title": "Required models missing","description": "Your organization requires these models on this device: {{models}}.","download": "Download"+ },+ "cloudNudge": {+ "title": "You're signed in",+ "description": "Dictation still runs on your own setup. You can switch to OpenWhispr Cloud anytime.",+ "action": "Open Settings"}},"reasoning": {diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 4e1851607..40f6123f7 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -702,6 +702,11 @@"title": "Faltan modelos requeridos","description": "Tu organización requiere estos modelos en este dispositivo: {{models}}.","download": "Descargar"+ },+ "cloudNudge": {+ "title": "Has iniciado sesión",+ "description": "El dictado sigue usando tu propia configuración. Puedes cambiar a OpenWhispr Cloud cuando quieras.",+ "action": "Abrir Ajustes"}},"reasoning": {diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 5aa6b64e7..2c2f39336 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -702,6 +702,11 @@"title": "Modèles requis manquants","description": "Votre organisation exige ces modèles sur cet appareil : {{models}}.","download": "Télécharger"+ },+ "cloudNudge": {+ "title": "Vous êtes connecté",+ "description": "La dictée utilise toujours votre propre configuration. Vous pouvez passer à OpenWhispr Cloud à tout moment.",+ "action": "Ouvrir les Réglages"}},"reasoning": {diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 42b1221cd..f17ea73ac 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -702,6 +702,11 @@"title": "Modelli richiesti mancanti","description": "La tua organizzazione richiede questi modelli su questo dispositivo: {{models}}.","download": "Scarica"+ },+ "cloudNudge": {+ "title": "Accesso effettuato",+ "description": "La dettatura usa ancora la tua configurazione. Puoi passare a OpenWhispr Cloud in qualsiasi momento.",+ "action": "Apri Impostazioni"}},"reasoning": {diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex a6f86f63c..32a47033a 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -702,6 +702,11 @@"title": "必須モデルがありません","description": "組織では、このデバイスにこれらのモデルが必要です:{{models}}。","download": "ダウンロード"+ },+ "cloudNudge": {+ "title": "サインインしました",+ "description": "音声入力は引き続きご自身の設定で動作します。いつでも OpenWhispr Cloud に切り替えられます。",+ "action": "設定を開く"}},"reasoning": {diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex 5d8d7b33c..0698428c4 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -681,6 +681,11 @@"title": "Modelos exigidos ausentes","description": "Sua organização exige estes modelos neste dispositivo: {{models}}.","download": "Baixar"+ },+ "cloudNudge": {+ "title": "Você entrou",+ "description": "O ditado continua usando sua própria configuração. Você pode mudar para o OpenWhispr Cloud a qualquer momento.",+ "action": "Abrir Configurações"}},"reasoning": {diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 29eb51c14..c03494837 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -702,6 +702,11 @@"title": "Отсутствуют обязательные модели","description": "Ваша организация требует наличия этих моделей на этом устройстве: {{models}}.","download": "Скачать"+ },+ "cloudNudge": {+ "title": "Вы вошли",+ "description": "Диктовка по-прежнему работает на вашей собственной настройке. Вы можете переключиться на OpenWhispr Cloud в любой момент.",+ "action": "Открыть Настройки"}},"reasoning": {diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 32b51f4eb..d0e0bb7fe 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -702,6 +702,11 @@"title": "缺少必需的模型","description": "您的组织要求在此设备上安装这些模型:{{models}}。","download": "下载"+ },+ "cloudNudge": {+ "title": "你已登录",+ "description": "听写仍在使用你自己的配置。你可以随时切换到 OpenWhispr Cloud。",+ "action": "打开设置"}},"reasoning": {diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex bfedaebd8..3e351bf34 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -702,6 +702,11 @@"title": "缺少必要的模型","description": "您的組織要求在此裝置上安裝這些模型:{{models}}。","download": "下載"+ },+ "cloudNudge": {+ "title": "你已登入",+ "description": "聽寫仍在使用你自己的設定。你可以隨時切換至 OpenWhispr Cloud。",+ "action": "開啟設定"}},"reasoning": {diff --git a/src/utils/requestSignIn.ts b/src/utils/requestSignIn.tsnew file mode 100644index 000000000..d3f8ef4ca--- /dev/null+++ b/src/utils/requestSignIn.ts@@ -0,0 +1,19 @@+// Stored rather than kept in memory: signing in always crosses a reload, both here+// and again for Google, Microsoft, Apple and SSO (applySessionTokenAndRefresh in main.js).+export const SIGN_IN_PROMPTED_AT_KEY = "signInPromptedAt";++/**+ * Logs a guest out instead of restarting onboarding.+ *+ * Every signed-out "sign in" button used to reset onboarding progress (#2128), and+ * re-walking the wizard rewrote the provider setup the user had configured. Dropping+ * the guest flag leaves onboarding finished, so AppRouter routes to the same+ * reauthentication screen a signed-out account already gets, with every setting intact.+ * Its "Continue without an account" writes the flag back.+ */+export function requestSignIn(): void {+ localStorage.setItem(SIGN_IN_PROMPTED_AT_KEY, String(Date.now()));+ localStorage.removeItem("authenticationSkipped");+ localStorage.removeItem("skipAuth");+ window.location.reload();+}diff --git a/src/utils/signInCloudNudge.ts b/src/utils/signInCloudNudge.tsnew file mode 100644index 000000000..78de236ed--- /dev/null+++ b/src/utils/signInCloudNudge.ts@@ -0,0 +1,35 @@+import { isModeAllowedByPolicy, type PolicyDecisionSnapshot } from "../stores/policyRules";+import type { InferenceMode } from "../types/electron";++/** How long after opening the sign-in prompt a finished sign-in still earns the nudge. */+export const SIGN_IN_CLOUD_NUDGE_WINDOW_MS = 15 * 60 * 1000;++export type SignInCloudNudgeDecision = "wait" | "nudge" | "skip";++export interface SignInCloudNudgeInputs {+ /** When the prompt was opened (epoch ms). */+ promptedAt: number;+ now: number;+ isSignedIn: boolean;+ policy: PolicyDecisionSnapshot;+ transcriptionMode: InferenceMode;+}++// Signing in from the prompt never switches a setting: a post-sign-in cloud switch is+// what overrode Local for #2086. Users whose dictation already runs on their own setup+// are told Cloud is available instead, once the account's policy says it is.+export function decideSignInCloudNudge({+ promptedAt,+ now,+ isSignedIn,+ policy,+ transcriptionMode,+}: SignInCloudNudgeInputs): SignInCloudNudgeDecision {+ if (Number.isNaN(promptedAt) || now - promptedAt > SIGN_IN_CLOUD_NUDGE_WINDOW_MS) return "skip";+ // A failed load is retried on the next identity refresh, inside the prompt window.+ if (!isSignedIn || (policy.status !== "managed" && policy.status !== "unmanaged")) {+ return "wait";+ }+ if (transcriptionMode === "openwhispr") return "skip";+ return isModeAllowedByPolicy(policy, "transcription", "openwhispr") ? "nudge" : "skip";+}diff --git a/src/utils/urlUtils.ts b/src/utils/urlUtils.tsindex ece2b3429..a07455ef4 100644--- a/src/utils/urlUtils.ts+++ b/src/utils/urlUtils.ts@@ -59,14 +59,22 @@ export function isSecureHttpEndpoint(url: string): boolean {}}-// Scheme-less input is normalized to https so a bare "host/path" base still-// matches, and a subdomain counts as the same provider.+/**+ * Scheme-less input is read as https: the connection test does the same, so a commit+ * that stores this value stores the URL it validated, and the runtime's+ * isSecureHttpEndpoint gate never sees a bare host.+ */+export function withHttpsScheme(url: string): string {+ const trimmed = url.trim();+ return !trimmed || trimmed.includes("://") ? trimmed : `https://${trimmed}`;+}++// A bare "host/path" base still matches, and a subdomain counts as the same provider.export function matchesHost(url: string | null | undefined, host: string): boolean {if (!url) return false;try {- const normalized = url.includes("://") ? url : `https://${url}`;- const hostname = new URL(normalized).hostname.toLowerCase();+ const hostname = new URL(withHttpsScheme(url)).hostname.toLowerCase();return hostname === host || hostname.endsWith(`.${host}`);} catch {return false;diff --git a/test/components/byokResumeDraft.test.js b/test/components/byokResumeDraft.test.jsindex dbfba82a7..4acc802b8 100644--- a/test/components/byokResumeDraft.test.js+++ b/test/components/byokResumeDraft.test.js@@ -1,12 +1,6 @@const assert = require("node:assert/strict");const test = require("node:test");-const React = require("react");-const { createRoot } = require("react-dom/client");-const {- createRendererServer,- installBrowserGlobals,- installHookDom,-} = require("../lib/rendererTestHarness");+const { mountByokStep } = require("../lib/byokStepHarness");// The onboarding session is plain-text localStorage, while every one of these is a// safeStorage secret. Named literally so a leak shows up as the value, not just as@@ -21,56 +15,6 @@ const SECRETS = {const ALLOWED_DRAFT_KEYS = ["baseUrl", "customModel", "selectedModel", "selectedProvider"];-async function collectByokDrafts(t, { stepId, selfHostedRequested, resumeState }) {- installBrowserGlobals(t, {- window: { electronAPI: { getPlatform: () => "linux" } },- });- const container = installHookDom(t);- const vite = await createRendererServer(t, {- cachePrefix: "openwhispr-byok-resume-draft-",- noExternal: ["react-i18next"],- mockModules: {- "react-i18next": `- const t = (key) => key;- 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; }`,- },- });- const { useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");- useSettingsStore.setState(SECRETS);- const { ByokProviderStep } = await vite.ssrLoadModule(- "/components/onboarding/ProviderSetupStep.tsx"- );-- const drafts = [];- function Harness() {- // Execute the real component and hooks with React lifecycle, while leaving- // native controls unmounted: the persisted draft is the test boundary.- ByokProviderStep({- stepId,- selfHostedRequested,- resumeState,- onSelfHostedChange() {},- onConnectionChange() {},- onProceed() {},- onResumeStateChange: (draft) => drafts.push(draft),- });- return null;- }- const root = createRoot(container);- await React.act(async () => {- root.render(React.createElement(Harness));- });- // The typed fields are debounced, and unmounting flushes the pending write — the- // same path the step takes when onboarding advances past it.- await React.act(async () => root.unmount());- return drafts;-}-// Each case has to actually load a credential or the value assertions guard// nothing: the step only seeds the one its step and mode select. A hosted step// with no resumed provider opens on none, leaving every credential state empty.@@ -87,7 +31,8 @@ for (const [name, options] of [["a self-hosted assistant endpoint", { stepId: "byok-assistant", selfHostedRequested: true }],]) {test(`the resume draft for ${name} carries no credential`, async (t) => {- const drafts = await collectByokDrafts(t, options);+ const step = await mountByokStep(t, { ...options, secrets: SECRETS });+ const drafts = await step.unmountForDrafts();assert.ok(drafts.length > 0, "the step persists a draft so the session can restore it");for (const draft of drafts) {diff --git a/test/components/byokSavedConfig.test.js b/test/components/byokSavedConfig.test.jsnew file mode 100644index 000000000..8e12da597--- /dev/null+++ b/test/components/byokSavedConfig.test.js@@ -0,0 +1,644 @@+const assert = require("node:assert/strict");+const test = require("node:test");+const React = require("react");+const { managedPolicy } = require("../helpers/harness/policyFixtures");+const { mountByokStep } = require("../lib/byokStepHarness");++// Restarting onboarding (#2128) drops the session draft, so these steps mount with no+// resumeState and have to reopen on what the user already saved.++const PLACEHOLDER = {+ endpoint: "onboarding.rehaul.provider.endpointPlaceholder",+ selfHostedKey: "onboarding.rehaul.provider.optional",+ modelId: "onboarding.rehaul.provider.modelIdPlaceholder",+ hostedKey: "onboarding.rehaul.provider.apiKeyPlaceholder",+};+const HOSTED_GROQ = {+ useLocalWhisper: "false",+ transcriptionMode: "providers",+ cloudTranscriptionMode: "byok",+ cloudTranscriptionProvider: "groq",+ cloudTranscriptionModel: "whisper-large-v3-turbo",+};+const CUSTOM_ENDPOINT = {+ useLocalWhisper: "false",+ transcriptionMode: "self-hosted",+ cloudTranscriptionMode: "byok",+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionBaseUrl: "https://stt.example.com/v1",+ cloudTranscriptionModel: "parasail-whisper",+};+const SETTINGS_SELF_HOSTED = {+ useLocalWhisper: "false",+ transcriptionMode: "self-hosted",+ cloudTranscriptionMode: "byok",+ cloudTranscriptionProvider: "openai",+ remoteTranscriptionUrl: "http://192.168.1.5:8178",+ remoteTranscriptionModel: "large-v3",+};++// The route helper is pure, so it loads straight through tsx like its own tests do.+const loadTranscriptionRoute = () => import("../../src/helpers/transcriptionRoute.ts");++async function routeAfterOnboardingSave(step) {+ // OnboardingFlow's byok-dictation continue runs this fan-out after the step saves.+ await React.act(async () =>+ step.state().setCloudTranscriptionForAllScopes({+ useLocalWhisper: false,+ cloudTranscriptionMode: "byok",+ })+ );+ const { resolveTranscriptionRoute } = await loadTranscriptionRoute();+ return resolveTranscriptionRoute({ settings: step.state() });+}++// As UploadAudioView hands it to resolveFileTranscriptionRoute: the upload scope plus+// the shared self-hosted fields.+async function uploadRoute(step) {+ const { selectResolvedUploadTranscription } = await step.vite.ssrLoadModule(+ "/stores/settingsStore.ts"+ );+ const state = step.state();+ const { resolveTranscriptionRoute } = await loadTranscriptionRoute();+ return resolveTranscriptionRoute({+ settings: {+ ...selectResolvedUploadTranscription(state),+ remoteTranscriptionUrl: state.remoteTranscriptionUrl,+ remoteTranscriptionModel: state.remoteTranscriptionModel,+ },+ });+}++// A workspace policy arriving while the card is open, as policyStore applies it.+async function applyTranscriptionPolicy(step, transcription) {+ const { usePolicyStore } = await step.vite.ssrLoadModule("/stores/policyStore.ts");+ await React.act(async () =>+ usePolicyStore.setState({+ status: "managed",+ appVersion: "1.10.0",+ policy: managedPolicy({ transcription }),+ })+ );+}++test("a first run opens blank", async (t) => {+ await t.test("hosted", async (t) => {+ const step = await mountByokStep(t, {});+ assert.deepEqual(step.selectValues(), [undefined, undefined]);+ assert.equal(step.value(PLACEHOLDER.hostedKey), "");+ });++ await t.test("self-hosted", async (t) => {+ const step = await mountByokStep(t, { selfHostedRequested: true });+ assert.equal(step.value(PLACEHOLDER.endpoint), "");+ assert.equal(step.value(PLACEHOLDER.modelId), "");+ });+});++test("a saved hosted provider reopens with its model and key, and the draft stays key-free", async (t) => {+ const step = await mountByokStep(t, {+ settings: HOSTED_GROQ,+ secrets: { groqApiKey: "gsk-saved-key" },+ });++ assert.deepEqual(step.selectValues(), ["groq", "whisper-large-v3-turbo"]);+ assert.equal(step.value(PLACEHOLDER.hostedKey), "gsk-saved-key");++ const drafts = await step.unmountForDrafts();+ assert.deepEqual(drafts.at(-1), {+ selectedProvider: "groq",+ selectedModel: "whisper-large-v3-turbo",+ baseUrl: "",+ customModel: "",+ });+ assert.doesNotMatch(JSON.stringify(drafts), /gsk-saved-key/);+});++test("a saved custom endpoint reopens in the self-hosted card with its key", async (t) => {+ const step = await mountByokStep(t, {+ selfHostedRequested: true,+ settings: CUSTOM_ENDPOINT,+ secrets: { customTranscriptionApiKey: "sk-custom-key" },+ });++ assert.equal(step.value(PLACEHOLDER.endpoint), "https://stt.example.com/v1");+ assert.equal(step.value(PLACEHOLDER.modelId), "parasail-whisper");+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "sk-custom-key");+});++test("the Settings self-hosted server reopens without a leftover custom key", async (t) => {+ const step = await mountByokStep(t, {+ selfHostedRequested: true,+ settings: SETTINGS_SELF_HOSTED,+ secrets: { customTranscriptionApiKey: "sk-stale-custom-key" },+ });++ assert.equal(step.value(PLACEHOLDER.endpoint), "http://192.168.1.5:8178");+ assert.equal(step.value(PLACEHOLDER.modelId), "large-v3");+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "");+});++test("a first setup ignores a leftover custom key and saves a key-less server", async (t) => {+ const step = await mountByokStep(t, {+ // Local dictation: nothing to reopen on, but an abandoned Custom setup left its key+ // behind. Offering it would send it to the endpoint the user is about to type.+ settings: { useLocalWhisper: "true", transcriptionMode: "local" },+ secrets: { customTranscriptionApiKey: "sk-abandoned-key" },+ selfHostedRequested: true,+ });+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "");++ await step.type(PLACEHOLDER.endpoint, "https://typed.example.com/v1");+ await step.type(PLACEHOLDER.modelId, "whisper-proxy-test");+ await step.passConnectionTest();+ await step.proceed();++ const state = step.state();+ assert.equal(state.remoteTranscriptionUrl, "https://typed.example.com/v1");+ assert.equal(state.customTranscriptionApiKey, "sk-abandoned-key", "the stored key is unused");++ const route = await routeAfterOnboardingSave(step);+ assert.equal(route.provider, "self-hosted");+ assert.equal(route.endpoint, "https://typed.example.com/v1/audio/transcriptions");+ assert.deepEqual(route.auth, { scheme: "none", keyRef: null });+});++test("a remount from the saved draft keeps a Settings self-hosted server key-less", async (t) => {+ const mountSettingsServer = (t, resumeState) =>+ mountByokStep(t, {+ selfHostedRequested: true,+ settings: SETTINGS_SELF_HOSTED,+ secrets: { customTranscriptionApiKey: "sk-stale-custom-key" },+ resumeState,+ });+ let draft;++ await t.test("the first visit writes the draft", async (t) => {+ const step = await mountSettingsServer(t);+ draft = (await step.unmountForDrafts()).at(-1);+ assert.equal(draft.baseUrl, "http://192.168.1.5:8178");+ });++ // Back from the next step, or a reload, reopens the step from that draft.+ await t.test("the remount stays key-less and saves back to the same server", async (t) => {+ assert.ok(draft, "the first visit has to write the draft this remount reopens");+ const step = await mountSettingsServer(t, draft);+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "");+ // Every other place the key is chosen keeps it empty too: a mode round trip and a+ // key that arrives late.+ await step.toggleSelfHosted();+ await step.toggleSelfHosted();+ await step.setStore({ customTranscriptionApiKey: "sk-late-stale-key" });+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "");++ await step.passConnectionTest();+ await step.proceed();+ assert.equal(step.state().remoteTranscriptionUrl, "http://192.168.1.5:8178");+ assert.equal((await routeAfterOnboardingSave(step)).provider, "self-hosted");+ });+});++test("a saved assistant endpoint reopens with its key", async (t) => {+ const step = await mountByokStep(t, {+ stepId: "byok-assistant",+ selfHostedRequested: true,+ settings: {+ chatAgentMode: "self-hosted",+ chatAgentRemoteUrl: "http://127.0.0.1:1234/v1",+ chatAgentModel: "llm-proxy-test",+ },+ secrets: { chatAgentCustomApiKey: "sk-agent-key" },+ });++ assert.equal(step.value(PLACEHOLDER.endpoint), "http://127.0.0.1:1234/v1");+ assert.equal(step.value(PLACEHOLDER.modelId), "llm-proxy-test");+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "sk-agent-key");+});++test("a saved hosted assistant provider reopens with its model and key", async (t) => {+ const step = await mountByokStep(t, {+ stepId: "byok-assistant",+ settings: {+ chatAgentMode: "providers",+ chatAgentProvider: "anthropic",+ chatAgentModel: "claude-sonnet-5",+ },+ secrets: { anthropicApiKey: "sk-ant-saved-key" },+ });++ assert.deepEqual(step.selectValues(), ["anthropic", "claude-sonnet-5"]);+ assert.equal(step.value(PLACEHOLDER.hostedKey), "sk-ant-saved-key");+});++test("a self-hosted assistant setup ignores a leftover agent key", async (t) => {+ const step = await mountByokStep(t, {+ stepId: "byok-assistant",+ // Saved as a hosted provider, so the abandoned self-hosted key is not this+ // endpoint's: offering it would send it to the server the user is about to type.+ settings: {+ chatAgentMode: "providers",+ chatAgentProvider: "anthropic",+ chatAgentModel: "claude-sonnet-5",+ },+ secrets: { chatAgentCustomApiKey: "sk-abandoned-agent-key" },+ });+ await step.toggleSelfHosted();+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "");++ // Secrets hydrate over IPC, so a key arriving after mount must stay out too.+ await step.setStore({ chatAgentCustomApiKey: "sk-late-agent-key" });+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "");+});++test("the prefilled key follows the endpoint it was saved under", async (t) => {+ const mountSavedEndpoint = (t) =>+ mountByokStep(t, {+ selfHostedRequested: true,+ settings: CUSTOM_ENDPOINT,+ secrets: { customTranscriptionApiKey: "sk-custom-key" },+ });++ await t.test("retyping the endpoint takes the prefilled key back out", async (t) => {+ const step = await mountSavedEndpoint(t);+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "sk-custom-key");++ await step.type(PLACEHOLDER.endpoint, "https://rented.example.com/v1");+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "");++ // The same server written another way is still that server.+ await step.type(PLACEHOLDER.endpoint, "stt.example.com/v1/");+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "sk-custom-key");+ });++ await t.test("a key the user typed survives the endpoint change", async (t) => {+ const step = await mountSavedEndpoint(t);+ await step.type(PLACEHOLDER.selfHostedKey, "sk-typed-key");+ await step.type(PLACEHOLDER.endpoint, "https://rented.example.com/v1");+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "sk-typed-key");+ });++ await t.test("re-typing the saved key for the saved endpoint keeps it", async (t) => {+ const step = await mountSavedEndpoint(t);+ await step.type(PLACEHOLDER.selfHostedKey, "");+ await step.type(PLACEHOLDER.selfHostedKey, "sk-custom-key");+ await step.setStore({ cortiTenant: "unrelated-change" });+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "sk-custom-key");+ });+});++test("a draft that names another server reopens key-less and saves it key-less", async (t) => {+ const step = await mountByokStep(t, {+ selfHostedRequested: true,+ settings: CUSTOM_ENDPOINT,+ secrets: { customTranscriptionApiKey: "sk-custom-key" },+ // Edited earlier this session and never committed, so the stored key still belongs to+ // the saved server, not to the one the card now shows.+ resumeState: {+ selectedProvider: "",+ selectedModel: "",+ baseUrl: "https://draft.example.com/v1",+ customModel: "draft-model",+ },+ });+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "");++ await step.passConnectionTest();+ await step.proceed();++ assert.equal(step.state().customTranscriptionApiKey, "sk-custom-key", "the stored key is unused");+ const route = await routeAfterOnboardingSave(step);+ assert.equal(route.endpoint, "https://draft.example.com/v1/audio/transcriptions");+ assert.deepEqual(route.auth, { scheme: "none", keyRef: null });+});++test("an assistant endpoint the user retyped never takes the saved agent key", async (t) => {+ const step = await mountByokStep(t, {+ stepId: "byok-assistant",+ selfHostedRequested: true,+ settings: {+ chatAgentMode: "self-hosted",+ chatAgentRemoteUrl: "http://127.0.0.1:1234/v1",+ chatAgentModel: "llm-proxy-test",+ },+ });++ await step.type(PLACEHOLDER.endpoint, "https://rented.example.com/v1");+ // Secrets hydrate over IPC, so the saved key can land after the endpoint was retyped.+ await step.setStore({ chatAgentCustomApiKey: "sk-agent-key" });+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "");+});++test("an in-progress draft wins over saved settings, and a blank one falls back to them", async (t) => {+ await t.test("draft", async (t) => {+ const step = await mountByokStep(t, {+ selfHostedRequested: true,+ settings: CUSTOM_ENDPOINT,+ resumeState: {+ selectedProvider: "",+ selectedModel: "",+ baseUrl: "https://draft.example.com/v1",+ customModel: "draft-model",+ },+ });+ assert.equal(step.value(PLACEHOLDER.endpoint), "https://draft.example.com/v1");+ assert.equal(step.value(PLACEHOLDER.modelId), "draft-model");+ });++ await t.test("blank draft", async (t) => {+ const step = await mountByokStep(t, {+ selfHostedRequested: true,+ settings: CUSTOM_ENDPOINT,+ resumeState: { selectedProvider: "", selectedModel: "", baseUrl: "", customModel: "" },+ });+ assert.equal(step.value(PLACEHOLDER.endpoint), "https://stt.example.com/v1");+ });+});++test("with no draft, the saved setup picks the card, whichever tile was clicked", async (t) => {+ // Restarting onboarding wipes the session, so the tile clicked on setup-choice is the+ // only mode on record; a reverse-proxy user who clicks "Bring your own key" must still+ // land on their endpoint (#2128).+ await t.test("a saved custom endpoint opens self-hosted from the BYOK tile", async (t) => {+ const step = await mountByokStep(t, {+ selfHostedRequested: false,+ settings: CUSTOM_ENDPOINT,+ secrets: { customTranscriptionApiKey: "sk-custom-key" },+ });+ assert.equal(step.value(PLACEHOLDER.endpoint), "https://stt.example.com/v1");+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "sk-custom-key");+ assert.deepEqual(step.selfHostedChanges, [true], "the session follows the card");+ });++ await t.test("a saved hosted provider opens hosted from the Self-hosted tile", async (t) => {+ const step = await mountByokStep(t, { selfHostedRequested: true, settings: HOSTED_GROQ });+ assert.deepEqual(step.selectValues(), ["groq", "whisper-large-v3-turbo"]);+ assert.deepEqual(step.selfHostedChanges, [false]);+ });++ await t.test("a self-hosted assistant opens self-hosted behind a hosted dictation", async (t) => {+ const step = await mountByokStep(t, {+ stepId: "byok-assistant",+ selfHostedRequested: false,+ settings: {+ ...HOSTED_GROQ,+ chatAgentMode: "self-hosted",+ chatAgentProvider: "custom",+ chatAgentRemoteUrl: "http://10.0.0.7:8080/v1",+ chatAgentModel: "qwen3-8b",+ },+ });+ assert.equal(step.value(PLACEHOLDER.endpoint), "http://10.0.0.7:8080/v1");+ assert.equal(step.value(PLACEHOLDER.modelId), "qwen3-8b");+ assert.deepEqual(step.selfHostedChanges, [true]);+ });++ await t.test("a draft keeps the card the session recorded", async (t) => {+ const step = await mountByokStep(t, {+ selfHostedRequested: false,+ settings: CUSTOM_ENDPOINT,+ resumeState: {+ selectedProvider: "groq",+ selectedModel: "whisper-large-v3-turbo",+ baseUrl: "https://stt.example.com/v1",+ customModel: "parasail-whisper",+ },+ });+ assert.deepEqual(step.selectValues(), ["groq", "whisper-large-v3-turbo"]);+ assert.deepEqual(step.selfHostedChanges, []);+ });+});++test("the saved key still matches an endpoint typed with a differently cased host", async (t) => {+ const step = await mountByokStep(t, {+ selfHostedRequested: true,+ settings: CUSTOM_ENDPOINT,+ secrets: { customTranscriptionApiKey: "sk-custom-key" },+ resumeState: {+ selectedProvider: "",+ selectedModel: "",+ baseUrl: "HTTPS://STT.Example.com/v1/",+ customModel: "parasail-whisper",+ },+ });+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "sk-custom-key");+});++test("a hosted save keeps the Settings self-hosted server for the Upload tab", async (t) => {+ const step = await mountByokStep(t, {+ selfHostedRequested: true,+ settings: SETTINGS_SELF_HOSTED,+ secrets: { groqApiKey: "gsk-saved-key" },+ });+ await step.toggleSelfHosted();+ await step.chooseProvider("groq");+ await step.passConnectionTest();+ await step.proceed();++ assert.equal(step.state().cloudTranscriptionProvider, "groq");+ // remoteTranscriptionUrl is shared with Upload's Self-hosted panel; the mode the+ // fan-out derives is what keeps the server out of dictation's route and out of+ // the card a later restart reopens on.+ assert.equal(step.state().remoteTranscriptionUrl, "http://192.168.1.5:8178");++ const route = await routeAfterOnboardingSave(step);+ assert.equal(route.provider, "groq");+ const { resolveSavedByokConfig } =+ await import("../../src/components/onboarding/savedByokConfig.ts");+ assert.equal(resolveSavedByokConfig("byok-dictation", step.state()).draft.baseUrl, "");+});++test("switching modes keeps both halves of the form and swaps only the key", async (t) => {+ const step = await mountByokStep(t, {+ settings: HOSTED_GROQ,+ secrets: { groqApiKey: "gsk-saved-key", customTranscriptionApiKey: "sk-custom-key" },+ });+ assert.equal(step.value(PLACEHOLDER.hostedKey), "gsk-saved-key");++ await step.toggleSelfHosted();+ // What is saved is a hosted provider, so the stored custom key is not this endpoint's.+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "");+ await step.type(PLACEHOLDER.endpoint, "https://typed.example.com/v1");++ await step.toggleSelfHosted();+ assert.deepEqual(step.selectValues(), ["groq", "whisper-large-v3-turbo"]);+ assert.equal(step.value(PLACEHOLDER.hostedKey), "gsk-saved-key");++ await step.toggleSelfHosted();+ assert.equal(step.value(PLACEHOLDER.endpoint), "https://typed.example.com/v1");+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "");+});++test("a key that loads after mount fills an empty field but never replaces typed input", async (t) => {+ const mountSavedEndpoint = (t) =>+ mountByokStep(t, { selfHostedRequested: true, settings: CUSTOM_ENDPOINT });++ await t.test("empty field", async (t) => {+ const step = await mountSavedEndpoint(t);+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "");+ await step.setStore({ customTranscriptionApiKey: "sk-late-key" });+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "sk-late-key");+ });++ await t.test("typed field", async (t) => {+ const step = await mountSavedEndpoint(t);+ await step.type(PLACEHOLDER.selfHostedKey, "sk-typed-key");+ await step.setStore({ customTranscriptionApiKey: "sk-late-key" });+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "sk-typed-key");+ });+});++test("policy removing self-hosting mid-step keeps the hosted half and loads its key", async (t) => {+ const step = await mountByokStep(t, {+ settings: HOSTED_GROQ,+ secrets: { groqApiKey: "gsk-saved-key", customTranscriptionApiKey: "sk-custom-key" },+ });+ await step.toggleSelfHosted();+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "");++ await applyTranscriptionPolicy(step, {+ allowedModes: ["providers"],+ allowedByokProviders: ["groq"],+ });+ assert.deepEqual(step.selectValues(), ["groq", "whisper-large-v3-turbo"]);+ assert.equal(step.value(PLACEHOLDER.hostedKey), "gsk-saved-key");+});++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" }],+ [+ "Corti",+ {+ ...HOSTED_GROQ,+ cloudTranscriptionProvider: "corti",+ cloudTranscriptionModel: "corti-transcribe",+ },+ { cortiClientId: "corti-client-id", cortiClientSecret: "corti-client-secret" },+ ],+ ]) {+ await t.test(name, async (t) => {+ const step = await mountByokStep(t, { settings, secrets });+ await step.passConnectionTest();+ assert.equal(step.proceedDisabled(), false);++ await applyTranscriptionPolicy(step, {+ allowedModes: ["providers"],+ allowedByokProviders: ["openai"],+ });+ assert.equal(step.proceedDisabled(), true);+ });+ }+});++test("a key-less endpoint saved over a hosted setup keeps its model and routes to it", async (t) => {+ const step = await mountByokStep(t, {+ settings: {+ ...HOSTED_GROQ,+ cloudTranscriptionProvider: "openai",+ cloudTranscriptionModel: "gpt-4o-mini-transcribe",+ },+ });+ await step.toggleSelfHosted();+ const customBaseUrl = step.state().cloudTranscriptionBaseUrl;+ await step.type(PLACEHOLDER.endpoint, "http://127.0.0.1:8791/v1");+ await step.type(PLACEHOLDER.modelId, "whisper-proxy-test");+ await step.passConnectionTest();+ await step.proceed();++ const state = step.state();+ assert.equal(state.cloudTranscriptionProvider, "custom");+ assert.equal(state.cloudTranscriptionBaseUrl, customBaseUrl, "the Custom slot is left alone");+ assert.equal(+ state.transcriptionModelByProvider["dictation:openai"],+ "gpt-4o-mini-transcribe",+ "the hosted model stays filed under its provider"+ );+ assert.equal(state.remoteTranscriptionUrl, "http://127.0.0.1:8791/v1");+ assert.equal(state.remoteTranscriptionModel, "whisper-proxy-test");+ assert.equal(state.remoteTranscriptionType, "openai-compatible");++ const route = await routeAfterOnboardingSave(step);+ assert.equal(route.provider, "self-hosted");+ assert.equal(route.endpoint, "http://127.0.0.1:8791/v1/audio/transcriptions");+ assert.equal(route.model, "whisper-proxy-test");+ assert.deepEqual(route.auth, { scheme: "none", keyRef: null });++ const upload = await uploadRoute(step);+ assert.equal(upload.provider, "self-hosted");+ assert.equal(upload.model, "whisper-proxy-test");+ assert.deepEqual(upload.auth, { scheme: "none", keyRef: null });+});++test("re-confirming the Settings self-hosted server keeps an unused custom endpoint and its key", async (t) => {+ const step = await mountByokStep(t, {+ selfHostedRequested: true,+ settings: {+ ...CUSTOM_ENDPOINT,+ remoteTranscriptionUrl: SETTINGS_SELF_HOSTED.remoteTranscriptionUrl,+ remoteTranscriptionModel: SETTINGS_SELF_HOSTED.remoteTranscriptionModel,+ },+ secrets: { customTranscriptionApiKey: "sk-unused-custom-key" },+ });+ assert.equal(step.value(PLACEHOLDER.endpoint), "http://192.168.1.5:8178");+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "");+ await step.passConnectionTest();+ await step.proceed();++ const state = step.state();+ assert.equal(state.cloudTranscriptionBaseUrl, "https://stt.example.com/v1");+ assert.equal(state.customTranscriptionApiKey, "sk-unused-custom-key");+ assert.equal(state.cloudTranscriptionModel, "parasail-whisper");+ assert.equal(state.remoteTranscriptionUrl, "http://192.168.1.5:8178");++ const route = await routeAfterOnboardingSave(step);+ assert.equal(route.provider, "self-hosted");+ assert.equal(route.model, "large-v3");+ assert.deepEqual(route.auth, { scheme: "none", keyRef: null });+});++test("clearing a reopened custom key saves a key-less server and leaves the stored key unused", async (t) => {+ for (const cleared of ["", " "]) {+ await t.test(JSON.stringify(cleared), async (t) => {+ const step = await mountByokStep(t, {+ selfHostedRequested: true,+ settings: CUSTOM_ENDPOINT,+ secrets: { customTranscriptionApiKey: "sk-saved-custom-key" },+ });+ assert.equal(step.value(PLACEHOLDER.selfHostedKey), "sk-saved-custom-key");+ await step.type(PLACEHOLDER.selfHostedKey, cleared);+ await step.passConnectionTest();+ await step.proceed();++ const state = step.state();+ assert.equal(state.customTranscriptionApiKey, "sk-saved-custom-key");+ assert.equal(state.remoteTranscriptionUrl, "https://stt.example.com/v1");+ const route = await routeAfterOnboardingSave(step);+ assert.equal(route.provider, "self-hosted");+ assert.equal(route.model, "parasail-whisper");+ assert.deepEqual(route.auth, { scheme: "none", keyRef: null });+ });+ }+});++test("an endpoint saved with a key replaces a Settings self-hosted server and authenticates", async (t) => {+ const step = await mountByokStep(t, {+ selfHostedRequested: true,+ settings: SETTINGS_SELF_HOSTED,+ });+ await step.type(PLACEHOLDER.endpoint, "https://proxy.example.com/v1");+ await step.type(PLACEHOLDER.selfHostedKey, "sk-proxy-key");+ await step.type(PLACEHOLDER.modelId, "proxy-whisper");+ await step.passConnectionTest();+ await step.proceed();++ const state = step.state();+ assert.equal(state.remoteTranscriptionUrl, "");+ assert.equal(state.cloudTranscriptionBaseUrl, "https://proxy.example.com/v1");+ assert.equal(state.customTranscriptionApiKey, "sk-proxy-key");+ assert.equal(state.cloudTranscriptionModel, "proxy-whisper");++ const route = await routeAfterOnboardingSave(step);+ assert.equal(route.provider, "custom");+ assert.equal(route.endpoint, "https://proxy.example.com/v1/audio/transcriptions");+ assert.deepEqual(route.auth, { scheme: "bearer", keyRef: "custom" });+});diff --git a/test/components/onboardingFlow.test.js b/test/components/onboardingFlow.test.jsindex 1b1e7ecc9..319ad0802 100644--- a/test/components/onboardingFlow.test.js+++ b/test/components/onboardingFlow.test.js@@ -286,6 +286,7 @@ test("an explicit restart clears every persisted route choice and returns to aut["skipAuth", "true"],["localSetupPending", "true"],["pendingLocalModelSelectionsV1", '{"assistant":{"provider":"qwen","modelId":"qwen-9b"}}'],+ ["signInPromptedAt", "1700000000000"],]);const storage = {setItem: (key, value) => values.set(key, value),@@ -301,6 +302,7 @@ test("an explicit restart clears every persisted route choice and returns to autassert.equal(values.has("skipAuth"), false);assert.equal(values.has("localSetupPending"), false);assert.equal(values.has("pendingLocalModelSelectionsV1"), false);+ assert.equal(values.has("signInPromptedAt"), false, "a restart is not a sign-in");});test("legacy numeric steps migrate conservatively", async () => {diff --git a/test/components/savedByokConfig.test.js b/test/components/savedByokConfig.test.jsnew file mode 100644index 000000000..ccb302768--- /dev/null+++ b/test/components/savedByokConfig.test.js@@ -0,0 +1,244 @@+const assert = require("node:assert/strict");+const test = require("node:test");++const load = () => import("../../src/components/onboarding/savedByokConfig.ts");+const loadDefaultTranscriptionBase = async () =>+ (await import("../../src/config/constants.ts")).API_ENDPOINTS.TRANSCRIPTION_BASE;++const DRAFT_KEYS = ["baseUrl", "customModel", "selectedModel", "selectedProvider"];++// A fresh install: only store defaults, nothing the user configured.+const firstRun = async () => ({+ useLocalWhisper: false,+ transcriptionMode: "openwhispr",+ cloudTranscriptionProvider: "openai",+ cloudTranscriptionModel: "gpt-4o-mini-transcribe",+ cloudTranscriptionBaseUrl: await loadDefaultTranscriptionBase(),+ remoteTranscriptionUrl: "",+ remoteTranscriptionModel: "",+ chatAgentMode: "openwhispr",+ chatAgentProvider: "groq",+ chatAgentModel: "openai/gpt-oss-120b",+ chatAgentRemoteUrl: "",+});++const CUSTOM_ENDPOINT = {+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionBaseUrl: "https://stt.example.com/v1",+ cloudTranscriptionModel: "parasail-whisper",+};++test("a first run has nothing to reopen", async () => {+ const { resolveSavedByokConfig } = await load();+ const settings = await firstRun();+ assert.equal(resolveSavedByokConfig("byok-dictation", settings), null);+ assert.equal(resolveSavedByokConfig("byok-assistant", settings), null);+});++test("local, OpenWhispr Cloud and enterprise dictation reopen nothing", async () => {+ const { resolveSavedByokConfig } = await load();+ const base = await firstRun();+ for (const settings of [+ // Settings writes cloudTranscriptionMode "byok" for Local too, so the provider+ // fields of a local user can look like a hosted setup.+ {+ ...base,+ transcriptionMode: "local",+ useLocalWhisper: true,+ cloudTranscriptionProvider: "groq",+ },+ { ...base, transcriptionMode: "providers", useLocalWhisper: true },+ { ...base, transcriptionMode: "openwhispr", ...CUSTOM_ENDPOINT },+ { ...base, transcriptionMode: "enterprise", ...CUSTOM_ENDPOINT },+ ]) {+ assert.equal(+ resolveSavedByokConfig("byok-dictation", settings),+ null,+ settings.transcriptionMode+ );+ }+});++test("a hosted dictation provider reopens with its model", async () => {+ const { resolveSavedByokConfig } = await load();+ const saved = resolveSavedByokConfig("byok-dictation", {+ ...(await firstRun()),+ transcriptionMode: "providers",+ cloudTranscriptionProvider: "groq",+ cloudTranscriptionModel: "whisper-large-v3-turbo",+ });+ assert.deepEqual(saved, {+ draft: {+ selectedProvider: "groq",+ selectedModel: "whisper-large-v3-turbo",+ baseUrl: "",+ customModel: "",+ },+ usesCustomKey: false,+ });+});++test("the Settings self-hosted server reopens as a key-less endpoint and wins over custom fields", async () => {+ const { resolveSavedByokConfig } = await load();+ const saved = resolveSavedByokConfig("byok-dictation", {+ ...(await firstRun()),+ ...CUSTOM_ENDPOINT,+ transcriptionMode: "self-hosted",+ remoteTranscriptionUrl: " http://192.168.1.5:8178 ",+ remoteTranscriptionModel: "large-v3",+ });+ assert.deepEqual(saved, {+ draft: {+ selectedProvider: "",+ selectedModel: "",+ baseUrl: "http://192.168.1.5:8178",+ customModel: "large-v3",+ },+ usesCustomKey: false,+ });+});++test("the Settings self-hosted server wins over a stale local flag, as in the router", async () => {+ const { resolveSavedByokConfig } = await load();+ const saved = resolveSavedByokConfig("byok-dictation", {+ ...(await firstRun()),+ transcriptionMode: "self-hosted",+ useLocalWhisper: true,+ remoteTranscriptionUrl: "http://192.168.1.5:8178",+ remoteTranscriptionModel: "large-v3",+ });+ assert.equal(saved?.draft.baseUrl, "http://192.168.1.5:8178");+ assert.equal(saved?.usesCustomKey, false);+});++test("a custom endpoint reopens under either mode it is filed under", async () => {+ const { resolveSavedByokConfig } = await load();+ for (const transcriptionMode of ["providers", "self-hosted"]) {+ const saved = resolveSavedByokConfig("byok-dictation", {+ ...(await firstRun()),+ ...CUSTOM_ENDPOINT,+ transcriptionMode,+ });+ assert.deepEqual(+ saved,+ {+ draft: {+ selectedProvider: "",+ selectedModel: "",+ baseUrl: "https://stt.example.com/v1",+ customModel: "parasail-whisper",+ },+ usesCustomKey: true,+ },+ transcriptionMode+ );+ }+});++test("an unconfigured custom endpoint reopens nothing", async () => {+ const { resolveSavedByokConfig } = await load();+ const base = await firstRun();+ for (const cloudTranscriptionBaseUrl of ["", " ", base.cloudTranscriptionBaseUrl]) {+ const saved = resolveSavedByokConfig("byok-dictation", {+ ...base,+ transcriptionMode: "providers",+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionBaseUrl,+ });+ assert.equal(saved, null, JSON.stringify(cloudTranscriptionBaseUrl));+ }+});++test("self-hosted mode without a URL or custom provider reopens nothing", async () => {+ const { resolveSavedByokConfig } = await load();+ const saved = resolveSavedByokConfig("byok-dictation", {+ ...(await firstRun()),+ transcriptionMode: "self-hosted",+ cloudTranscriptionProvider: "groq",+ });+ assert.equal(saved, null);+});++test("the assistant reopens its self-hosted endpoint or hosted provider", async () => {+ const { resolveSavedByokConfig } = await load();+ const base = await firstRun();++ assert.deepEqual(+ resolveSavedByokConfig("byok-assistant", {+ ...base,+ chatAgentMode: "self-hosted",+ chatAgentRemoteUrl: " http://127.0.0.1:1234/v1 ",+ chatAgentModel: "llm-proxy-test",+ }),+ {+ draft: {+ selectedProvider: "",+ selectedModel: "",+ baseUrl: "http://127.0.0.1:1234/v1",+ customModel: "llm-proxy-test",+ },+ // The assistant's only self-hosted route sends chatAgentCustomApiKey.+ usesCustomKey: true,+ }+ );+ assert.deepEqual(+ resolveSavedByokConfig("byok-assistant", {+ ...base,+ chatAgentMode: "providers",+ chatAgentProvider: "anthropic",+ chatAgentModel: "claude-sonnet-5",+ }),+ {+ draft: {+ selectedProvider: "anthropic",+ selectedModel: "claude-sonnet-5",+ baseUrl: "",+ customModel: "",+ },+ usesCustomKey: false,+ }+ );+});++test("the assistant reopens nothing it could not save back", async () => {+ const { resolveSavedByokConfig } = await load();+ const base = await firstRun();+ for (const settings of [+ { ...base, chatAgentMode: "self-hosted", chatAgentRemoteUrl: "" },+ { ...base, chatAgentMode: "providers", chatAgentProvider: "custom" },+ { ...base, chatAgentMode: "openwhispr" },+ { ...base, chatAgentMode: "local", chatAgentProvider: "qwen" },+ ]) {+ assert.equal(resolveSavedByokConfig("byok-assistant", settings), null, settings.chatAgentMode);+ }+});++test("a reopened draft only carries the four session fields", async () => {+ const { resolveSavedByokConfig } = await load();+ const base = await firstRun();+ for (const [stepId, settings] of [+ [+ "byok-dictation",+ { ...base, transcriptionMode: "providers", cloudTranscriptionProvider: "groq" },+ ],+ ["byok-dictation", { ...base, ...CUSTOM_ENDPOINT, transcriptionMode: "providers" }],+ [+ "byok-assistant",+ { ...base, chatAgentMode: "self-hosted", chatAgentRemoteUrl: "http://x/v1" },+ ],+ ]) {+ assert.deepEqual(+ Object.keys(resolveSavedByokConfig(stepId, settings).draft).sort(),+ DRAFT_KEYS+ );+ }+});++test("a draft is blank only when every field is empty", async () => {+ const { isBlankByokDraft } = await load();+ const blank = { selectedProvider: "", selectedModel: "", baseUrl: "", customModel: "" };+ assert.equal(isBlankByokDraft(blank), true);+ for (const field of DRAFT_KEYS) {+ assert.equal(isBlankByokDraft({ ...blank, [field]: "x" }), false, field);+ }+});diff --git a/test/helpers/harness/policyFixtures.js b/test/helpers/harness/policyFixtures.jsnew file mode 100644index 000000000..6da2813c6--- /dev/null+++ b/test/helpers/harness/policyFixtures.js@@ -0,0 +1,24 @@+// A managed workspace policy in the shape policyStore applies, with every section+// closed off unless the test opens it.+function managedPolicy({ transcription = {}, llm = {} } = {}) {+ return {+ version: 1,+ transcription: {+ allowedModes: [],+ allowedByokProviders: [],+ allowedEnterpriseProviders: [],+ ...transcription,+ },+ llm: { allowedModes: [], allowedByokProviders: [], allowedEnterpriseProviders: [], ...llm },+ features: { agentEnabled: false, webSearchEnabled: false },+ sharing: { externalLinkSharing: "disabled" },+ dataRetention: {+ audioRetentionMaxDays: null,+ localHistoryMode: "user_choice",+ cloudBackupAllowed: false,+ },+ minAppVersion: null,+ };+}++module.exports = { managedPolicy };diff --git a/test/hooks/signInCloudNudge.test.js b/test/hooks/signInCloudNudge.test.jsnew file mode 100644index 000000000..ce31add4c--- /dev/null+++ b/test/hooks/signInCloudNudge.test.js@@ -0,0 +1,182 @@+const assert = require("node:assert/strict");+const test = require("node:test");+const React = require("react");+const { createRoot } = require("react-dom/client");+const {+ createRendererServer,+ installBrowserGlobals,+ installHookDom,+} = require("../lib/rendererTestHarness");+const { managedPolicy } = require("../helpers/harness/policyFixtures");++// Signing in never switches a setting — a post-sign-in cloud switch is what overrode Local+// for #2086 — so a user who signed in from one of the Cloud entry points (#2128) is only+// told Cloud is there. requestSignIn leaves the marker this reads behind, because the+// sign-in it starts always crosses a reload.++const PROMPTED_AT_KEY = "signInPromptedAt";+const GUEST_ON_OWN_SETUP = {+ onboardingCompleted: "true",+ transcriptionMode: "providers",+ useLocalWhisper: "false",+ cloudTranscriptionMode: "byok",+ cloudTranscriptionProvider: "groq",+};++async function mountNudge(t, { settings = {}, prompted = true } = {}) {+ let unmount = async () => {};+ t.after(() => unmount());+ const { storage } = installBrowserGlobals(t, {+ initialStorage: {+ ...(prompted ? { [PROMPTED_AT_KEY]: String(Date.now()) } : {}),+ ...GUEST_ON_OWN_SETUP,+ ...settings,+ },+ });+ const container = installHookDom(t);+ const toasts = [];+ const dismissed = [];+ globalThis.__cloudNudgeToasts = { toasts, dismissed };+ t.after(() => delete globalThis.__cloudNudgeToasts);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-cloud-nudge-",+ noExternal: ["react-i18next"],+ mockModules: {+ "react-i18next": `+ const t = (key) => key;+ export function useTranslation() { return { t }; }+ export const initReactI18next = { type: "3rdParty", init() {} };+ `,+ "/ui/useToast": `+ function toast(props) {+ const { toasts } = globalThis.__cloudNudgeToasts;+ toasts.push(props);+ return "toast-" + toasts.length;+ }+ function dismiss(id) { globalThis.__cloudNudgeToasts.dismissed.push(id); }+ export function useToast() { return { toast, dismiss }; }+ `,+ },+ });+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");+ const { useSignInCloudNudge } = await vite.ssrLoadModule("/hooks/useSignInCloudNudge.tsx");++ let isSignedIn = false;+ let settingsOpened = 0;+ const openTranscriptionSettings = () => {+ settingsOpened += 1;+ };+ function Harness() {+ useSignInCloudNudge(isSignedIn, openTranscriptionSettings);+ return null;+ }+ const root = createRoot(container);+ const render = () => React.act(async () => root.render(React.createElement(Harness)));+ await render();+ let mounted = true;+ unmount = async () => {+ if (!mounted) return;+ mounted = false;+ await React.act(async () => root.unmount());+ };++ return {+ storage,+ toasts,+ dismissed,+ rerender: render,+ settingsOpened: () => settingsOpened,+ signIn: async () => {+ isSignedIn = true;+ await render();+ },+ settlePolicy: (status = "unmanaged", policy = null) =>+ React.act(async () => usePolicyStore.setState({ status, policy, appVersion: "1.10.0" })),+ };+}++test("a sign-in nudges towards Cloud once the account's policy settles", async (t) => {+ const nudge = await mountNudge(t);+ await nudge.settlePolicy("loading");+ await nudge.signIn();+ assert.deepEqual(nudge.toasts, [], "no nudge before the policy can allow Cloud");+ assert.notEqual(nudge.storage.getItem(PROMPTED_AT_KEY), null);++ await nudge.settlePolicy();++ assert.equal(nudge.toasts.length, 1);+ assert.equal(nudge.toasts[0].title, "controlPanel.cloudNudge.title");+ assert.equal(nudge.toasts[0].description, "controlPanel.cloudNudge.description");+ assert.equal(nudge.storage.getItem(PROMPTED_AT_KEY), null);+ assert.equal(nudge.storage.getItem("transcriptionMode"), "providers");+ assert.equal(nudge.storage.getItem("cloudTranscriptionMode"), "byok");++ nudge.toasts[0].action.props.onClick();+ assert.deepEqual(nudge.dismissed, ["toast-1"]);+ assert.equal(nudge.settingsOpened(), 1);++ await nudge.rerender();+ assert.equal(nudge.toasts.length, 1, "the nudge shows once");+});++test("abandoning the sign-in never nudges", async (t) => {+ const nudge = await mountNudge(t);+ await nudge.settlePolicy();+ await nudge.rerender();++ assert.deepEqual(nudge.toasts, []);+ assert.notEqual(nudge.storage.getItem(PROMPTED_AT_KEY), null, "still waiting on a sign-in");+});++test("an ordinary launch by a signed-in user never nudges", async (t) => {+ const nudge = await mountNudge(t, { prompted: false });+ await nudge.signIn();+ await nudge.settlePolicy();++ assert.deepEqual(nudge.toasts, []);+});++test("dictation already on Cloud, or a policy that forbids it, gets no nudge", async (t) => {+ await t.test("already on Cloud", async (t) => {+ const nudge = await mountNudge(t, {+ settings: {+ transcriptionMode: "openwhispr",+ cloudTranscriptionMode: "openwhispr",+ cloudTranscriptionProvider: "openwhispr",+ },+ });+ await nudge.settlePolicy();+ await nudge.signIn();++ assert.deepEqual(nudge.toasts, []);+ assert.equal(nudge.storage.getItem(PROMPTED_AT_KEY), null);+ });++ await t.test("policy forbids Cloud", async (t) => {+ const nudge = await mountNudge(t);+ await nudge.signIn();+ await nudge.settlePolicy(+ "managed",+ managedPolicy({+ transcription: { allowedModes: ["providers"], allowedByokProviders: ["groq"] },+ })+ );++ assert.deepEqual(nudge.toasts, []);+ assert.equal(nudge.storage.getItem(PROMPTED_AT_KEY), null);+ });++ // The stored preference still reads "providers", but the policy clamps dictation onto+ // Cloud, which is where the settings pane shows it — so there is nothing to switch.+ await t.test("policy already puts dictation on Cloud", async (t) => {+ const nudge = await mountNudge(t);+ await nudge.signIn();+ await nudge.settlePolicy(+ "managed",+ managedPolicy({ transcription: { allowedModes: ["openwhispr"] } })+ );++ assert.deepEqual(nudge.toasts, []);+ assert.equal(nudge.storage.getItem(PROMPTED_AT_KEY), null);+ });+});diff --git a/test/hooks/useStartOnboarding.test.js b/test/hooks/useStartOnboarding.test.jsdeleted file mode 100644index 28449a9ec..000000000--- a/test/hooks/useStartOnboarding.test.js+++ /dev/null@@ -1,60 +0,0 @@-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");--// Restarting onboarding used to arm `pendingCloudMigration`, which a ControlPanel-// effect consumed after sign-in to force cloud routing regardless of the setup-// the user then chose in onboarding (#2086). The hook must only reset onboarding-// progress and reload; the routing pair is onboarding's to decide.-test("restarting onboarding resets progress without arming a cloud switch", async (t) => {- let root = null;- t.after(async () => {- if (root) await React.act(async () => root.unmount());- });- let reloads = 0;- const { storage } = installBrowserGlobals(t, {- initialStorage: {- onboardingCompleted: "true",- transcriptionMode: "local",- useLocalWhisper: "true",- },- window: {- location: {- reload() {- reloads += 1;- },- },- },- });- const container = installHookDom(t);- const vite = await createRendererServer(t, {- cachePrefix: "openwhispr-use-start-onboarding-test-",- });- const { useStartOnboarding } = await vite.ssrLoadModule("/hooks/useStartOnboarding.ts");- const { LEGACY_ONBOARDING_STEP_KEY } = await vite.ssrLoadModule("/components/onboarding/flow.ts");-- let startOnboarding;- function Harness() {- startOnboarding = useStartOnboarding();- return null;- }- root = createRoot(container);- await React.act(async () => {- root.render(React.createElement(Harness));- });-- startOnboarding();-- assert.equal(reloads, 1);- assert.equal(storage.getItem("pendingCloudMigration"), null);- assert.equal(storage.getItem("onboardingCompleted"), null);- assert.equal(storage.getItem(LEGACY_ONBOARDING_STEP_KEY), "0");- assert.equal(storage.getItem("transcriptionMode"), "local");- assert.equal(storage.getItem("useLocalWhisper"), "true");-});diff --git a/test/lib/byokStepHarness.js b/test/lib/byokStepHarness.jsnew file mode 100644index 000000000..3f3cf8338--- /dev/null+++ b/test/lib/byokStepHarness.js@@ -0,0 +1,152 @@+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;+}++/**+ * Mounts the onboarding BYOK step with the real component and hooks under React's+ * lifecycle, leaving native controls unmounted: the returned element tree, the+ * settings store and the persisted draft are the test boundary.+ */+async function mountByokStep(+ t,+ {+ stepId = "byok-dictation",+ selfHostedRequested = false,+ resumeState,+ settings = {},+ 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;+ });+ installBrowserGlobals(t, {+ initialStorage: { ...MIGRATED, ...settings },+ window: { electronAPI: { getPlatform: () => "linux" }, dispatchEvent: () => true },+ });+ const container = installHookDom(t);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-byok-step-",+ noExternal: ["react-i18next"],+ mockModules: {+ "react-i18next": `+ const t = (key) => key;+ 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.+ "/services/ReasoningService": `export default { clearApiKeyCache() {} };`,+ },+ });+ const { useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");+ useSettingsStore.setState(secrets);+ const { ByokProviderStep } = await vite.ssrLoadModule(+ "/components/onboarding/ProviderSetupStep.tsx"+ );++ let tree;+ const drafts = [];+ const selfHostedChanges = [];+ function Harness() {+ tree = ByokProviderStep({+ stepId,+ selfHostedRequested,+ resumeState,+ onSelfHostedChange: (requested) => selfHostedChanges.push(requested),+ onConnectionChange() {},+ onProceed() {},+ onResumeStateChange: (draft) => drafts.push(draft),+ });+ return null;+ }+ const root = createRoot(container);+ await React.act(async () => root.render(React.createElement(Harness)));+ let mounted = true;+ unmount = async () => {+ if (!mounted) return;+ mounted = false;+ await React.act(async () => root.unmount());+ };++ const find = (predicate) => findAll(tree, predicate);+ const input = (placeholder) => find((node) => node.props?.placeholder === placeholder)[0];+ const act = (fn) => React.act(async () => fn());+ const proceedButton = () =>+ find((node) => node.props?.children === "onboarding.rehaul.provider.proceed")[0];+ return {+ vite,+ selfHostedChanges,+ state: () => useSettingsStore.getState(),+ setStore: (patch) => act(() => useSettingsStore.setState(patch)),+ value: (placeholder) => input(placeholder)?.props.value,+ type: (placeholder, value) =>+ act(() => input(placeholder).props.onChange({ target: { value } })),+ // [provider, model] in the hosted half; absent while the card is self-hosted.+ selectValues: () =>+ find((node) => typeof node.props?.onValueChange === "function").map(+ (node) => node.props.value+ ),+ toggleSelfHosted: () =>+ act(() => find((node) => node.props?.role === "checkbox")[0].props.onClick()),+ chooseProvider: (providerId) =>+ act(() =>+ find((node) => typeof node.props?.onValueChange === "function")[0].props.onValueChange(+ providerId+ )+ ),+ passConnectionTest: () =>+ act(() =>+ find((node) => typeof node.props?.onSuccessChange === "function")[0].props.onSuccessChange(+ true+ )+ ),+ proceedDisabled: () => proceedButton().props.disabled,+ proceed: () => act(() => proceedButton().props.onClick()),+ // Unmounting flushes the debounced draft write, as advancing past the step does.+ unmountForDrafts: async () => {+ await unmount();+ return drafts;+ },+ };+}++module.exports = { mountByokStep };diff --git a/test/utils/requestSignIn.test.js b/test/utils/requestSignIn.test.jsnew file mode 100644index 000000000..491f803f6--- /dev/null+++ b/test/utils/requestSignIn.test.js@@ -0,0 +1,75 @@+const assert = require("node:assert/strict");+const test = require("node:test");+const { installBrowserGlobals } = require("../lib/rendererTestHarness");++// Every signed-out "sign in" entry point used to reset onboarding progress (#2128), and+// re-walking the wizard rewrote the provider setup the user had configured. Signing in now+// only drops the guest flag, which is what sends AppRouter to the reauthentication screen+// instead of the wizard.++const PROMPTED_AT_KEY = "signInPromptedAt";+const GUEST_ON_OWN_SETUP = {+ onboardingCompleted: "true",+ authenticationSkipped: "true",+ skipAuth: "true",+ transcriptionMode: "local",+ useLocalWhisper: "true",+ cloudTranscriptionMode: "byok",+ cloudTranscriptionProvider: "groq",+ cloudTranscriptionModel: "whisper-large-v3-turbo",+ remoteTranscriptionUrl: "http://192.168.1.4:8000/v1",+ whisperModel: "base",+};++async function signIn(t, settings = {}) {+ let reloads = 0;+ const { storage } = installBrowserGlobals(t, {+ initialStorage: { ...GUEST_ON_OWN_SETUP, ...settings },+ window: {+ location: {+ reload() {+ reloads += 1;+ },+ },+ },+ });+ const { requestSignIn } = await import("../../src/utils/requestSignIn.ts");+ requestSignIn();+ return { storage, reloads: () => reloads };+}++test("signing in logs the guest out instead of restarting onboarding", async (t) => {+ const { storage, reloads } = await signIn(t);++ // Onboarding stays finished and no wizard state is written, so the reload lands on+ // AppRouter's reauthentication branch: completed, signed out, no guest flag.+ assert.equal(storage.getItem("authenticationSkipped"), null);+ assert.equal(storage.getItem("skipAuth"), null);+ assert.equal(storage.getItem("onboardingCompleted"), "true");+ assert.equal(storage.getItem("onboardingSessionV2"), null);+ assert.equal(storage.getItem("onboardingCurrentStep"), null);+ assert.equal(storage.getItem("localSetupPending"), null);+ assert.equal(reloads(), 1);+});++test("signing in switches nothing the user configured", async (t) => {+ const { storage } = await signIn(t);++ // A post-sign-in cloud switch is what overrode Local for #2086.+ assert.equal(storage.getItem("transcriptionMode"), "local");+ assert.equal(storage.getItem("useLocalWhisper"), "true");+ assert.equal(storage.getItem("cloudTranscriptionMode"), "byok");+ assert.equal(storage.getItem("cloudTranscriptionProvider"), "groq");+ assert.equal(storage.getItem("cloudTranscriptionModel"), "whisper-large-v3-turbo");+ assert.equal(storage.getItem("remoteTranscriptionUrl"), "http://192.168.1.4:8000/v1");+ assert.equal(storage.getItem("whisperModel"), "base");+ assert.equal(storage.getItem("pendingCloudMigration"), null);+});++test("the Cloud nudge marker survives the reload the sign-in goes through", async (t) => {+ const before = Date.now();+ const { storage } = await signIn(t);++ const promptedAt = Number(storage.getItem(PROMPTED_AT_KEY));+ assert.ok(promptedAt >= before && promptedAt <= Date.now());+});diff --git a/test/utils/signInCloudNudge.test.js b/test/utils/signInCloudNudge.test.jsnew file mode 100644index 000000000..e5c1a436a--- /dev/null+++ b/test/utils/signInCloudNudge.test.js@@ -0,0 +1,58 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { managedPolicy } = require("../helpers/harness/policyFixtures");++const load = () => import("../../src/utils/signInCloudNudge.ts");++const NOW = 1_700_000_000_000;+const UNMANAGED = { status: "unmanaged", policy: null, appVersion: null };++const decide = async (overrides) => {+ const { decideSignInCloudNudge } = await load();+ return decideSignInCloudNudge({+ promptedAt: NOW - 60_000,+ now: NOW,+ isSignedIn: true,+ policy: UNMANAGED,+ transcriptionMode: "providers",+ ...overrides,+ });+};++const managedSnapshot = (allowedModes) => ({+ status: "managed",+ appVersion: "1.10.0",+ policy: managedPolicy({ transcription: { allowedModes } }),+});++test("a signed-in user on their own dictation setup is nudged towards Cloud", async () => {+ for (const transcriptionMode of ["local", "providers", "self-hosted"]) {+ assert.equal(await decide({ transcriptionMode }), "nudge", transcriptionMode);+ }+});++test("dictation already on Cloud needs no nudge", async () => {+ assert.equal(await decide({ transcriptionMode: "openwhispr" }), "skip");+});++test("it waits for the sign-in and for the account's policy to settle", async () => {+ assert.equal(await decide({ isSignedIn: false }), "wait");+ // A failed load is retried on the next identity refresh, and the prompt window+ // absorbs that; dropping the marker here would lose the nudge to a flaky connection.+ for (const status of ["idle", "loading", "error"]) {+ assert.equal(await decide({ policy: { ...UNMANAGED, status } }), "wait", status);+ }+});++test("a policy that forbids Cloud gets no nudge", async () => {+ assert.equal(await decide({ policy: managedSnapshot(["local", "providers"]) }), "skip");+ assert.equal(await decide({ policy: managedSnapshot(["openwhispr", "providers"]) }), "nudge");+});++test("a prompt that is too old or unreadable is dropped", async () => {+ const { SIGN_IN_CLOUD_NUDGE_WINDOW_MS } = await load();+ assert.equal(await decide({ promptedAt: NOW - SIGN_IN_CLOUD_NUDGE_WINDOW_MS }), "nudge");+ assert.equal(await decide({ promptedAt: NOW - SIGN_IN_CLOUD_NUDGE_WINDOW_MS - 1 }), "skip");+ assert.equal(await decide({ promptedAt: Number.NaN }), "skip");+ assert.equal(await decide({ promptedAt: Number.NaN, isSignedIn: false }), "skip");+});diff --git a/test/utils/withHttpsScheme.test.js b/test/utils/withHttpsScheme.test.jsnew file mode 100644index 000000000..7d5398ac6--- /dev/null+++ b/test/utils/withHttpsScheme.test.js@@ -0,0 +1,11 @@+const assert = require("node:assert/strict");+const test = require("node:test");++const load = () => import("../../src/utils/urlUtils.ts");++test("a scheme-less endpoint is read as https, as the connection test does", async () => {+ const { withHttpsScheme } = await load();+ assert.equal(withHttpsScheme("stt.example.com/v1"), "https://stt.example.com/v1");+ assert.equal(withHttpsScheme(" http://127.0.0.1:8178 "), "http://127.0.0.1:8178");+ assert.equal(withHttpsScheme(" "), "");+});