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(billing): keep BYOK streams out of Cloud usage metering (#2559)
Benyamin JafariMoghaddamFardbcd5ba61d054
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 2a3527672..cba6ded1b 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -2487,6 +2487,9 @@ export default function SettingsPage({<span>{t("settingsPage.account.rollingWeeklyLimit")}</span>)}</div>+ <p className="text-xs text-muted-foreground">+ {t("settingsPage.account.planDescriptions.byokUnlimited")}+ </p></div></SettingsPanelRow>)}diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex a6e8726df..74641c762 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -166,6 +166,7 @@ import {resolveManagedOrukeetRoute,resolveStreamingProviderName,buildStreamingSessionOptions,+ isCloudMeteredStream,evaluateOrukeetLanguageRouting,hasOrukeetExperiment,ORUKEET_EXPERIMENT_CONFIG_TTL_MS,@@ -703,6 +704,7 @@ class AudioManager {this._streamingCancellationGeneration = 0;this._activeTranscriptionAbortController = null;this._activeStreamingSessionId = null;+ this._streamingMeteredByCloud = false;this._activeStreamingProviderName = null;this._activeStreamingConfig = null;this._activePipelineOptions = undefined;@@ -5264,16 +5266,18 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);const result = await withSessionRefresh(async () => {const streamingSettings = getSettings();const { useLocalWhisper } = streamingSettings;- const res = await provider.start(- buildStreamingSessionOptions({- providerName,- settings: streamingSettings,- language: this.getEffectiveSttLanguage(streamingSettings),- keyterms: this.getKeyterms(),- voiceAgentRequested: this.voiceAgentRequested,- pipelineOptions: this._activePipelineOptions,- })- );+ const sessionOptions = buildStreamingSessionOptions({+ providerName,+ settings: streamingSettings,+ language: this.getEffectiveSttLanguage(streamingSettings),+ keyterms: this.getKeyterms(),+ voiceAgentRequested: this.voiceAgentRequested,+ pipelineOptions: this._activePipelineOptions,+ });+ // Decided from the credentials this session opens with, so a mode+ // switch before stop cannot move its words in or out of Cloud usage.+ this._streamingMeteredByCloud = isCloudMeteredStream(sessionOptions);+ const res = await provider.start(sessionOptions);return this.classifyStreamingStartResult(res, { useLocalWhisper });});@@ -5764,6 +5768,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor););const stSettings = getSettings();+ const meteredByCloud = this._streamingMeteredByCloud;const streamingSttModel = stopResult?.model || "nova-3";const streamingSttProcessingMs = Number.isFinite(orukeetFinal?.asrFinalMs)? Math.round(orukeetFinal.asrFinalMs)@@ -6202,7 +6207,10 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);...(batchWarning ? { warning: batchWarning } : {}),});- if (!usedBatchFallback) {+ // Only a stream on OpenWhispr Cloud credentials draws on the account's+ // word allowance; opted-in history and insights sync push the local row+ // of every other stream themselves.+ if (!usedBatchFallback && meteredByCloud) {(async () => {try {await withSessionRefresh(async () => {@@ -6224,14 +6232,6 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);// makes the row the server writes and the local one the same// event. Held back until opt-in, a later sync would push the// local copy under a second id and double every total.- // Cosmetic caveat: the server labels its row mode- // "openwhispr_cloud" whatever actually transcribed the audio,- // and BYOK streaming reaches here too (tinfoil-realtime,- // corti, openai-realtime — see resolveStreamingProviderName).- // That row only exists when localDate rides along, which is- // exactly when this device also pushes its own copy under the- // same id, and last-write-wins replaces the label with the- // real mode. Neither summary renders mode either way.clientTranscriptionId,...(analyticsSyncEnabled()? {@@ -6254,7 +6254,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}window.dispatchEvent(new Event("usage-changed"));})();- } else {+ } else if (batchFallbackResult?.source === "openwhispr") {+ // /api/transcribe recorded the Cloud upload's words.window.dispatchEvent(new Event("usage-changed"));}diff --git a/src/helpers/dictationStreamingRouting.js b/src/helpers/dictationStreamingRouting.jsindex 9889380ac..6c7d11d4a 100644--- a/src/helpers/dictationStreamingRouting.js+++ b/src/helpers/dictationStreamingRouting.js@@ -189,6 +189,15 @@ export function resolveStreamingProviderName({ settings, context, sttConfig, lanreturn sttConfig?.streamingProvider || defaultStreamingProviderName(context);}+// Tinfoil and Corti stream on the user's own credentials in either mode (see+// realtimeTokenProviders.js), so only the other providers' managed sessions+// draw on the OpenWhispr Cloud word allowance.+const OWN_CREDENTIAL_STREAMING_PROVIDERS = new Set(["tinfoil-realtime", "corti"]);++export function isCloudMeteredStream({ provider, mode }) {+ return mode === "openwhispr" && !OWN_CREDENTIAL_STREAMING_PROVIDERS.has(provider);+}+export function buildStreamingSessionOptions({providerName,settings,diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex d0a35c91b..8ae5a26a4 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -415,7 +415,7 @@ function interpretTranscribeResponse(data) {throw Object.assign(new Error("Request timed out"), { code: "SERVER_ERROR" });}if (data.statusCode === 429) {- throw Object.assign(new Error("Daily word limit reached"), {+ throw Object.assign(new Error("Weekly Cloud word limit reached"), {code: "LIMIT_REACHED",...data.data,});diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.jsonindex c4a76320f..83c893639 100644--- a/src/locales/ar/translation.json+++ b/src/locales/ar/translation.json@@ -8,7 +8,7 @@"offline": "أنت غير متصل بالإنترنت","agentUnavailable": "المساعد غير متاح","screenContextSkipped": "تم تخطي سياق الشاشة",- "dailyLimitReached": "تم الوصول إلى الحد اليومي",+ "cloudLimitReached": "تم بلوغ الحد السحابي الأسبوعي","providerRateLimited": "تم تقييد المعدل من قبل المزود"},"fallback": {@@ -538,7 +538,7 @@"availableButton": "التحديث متاح"},"limit": {- "weeklyTitle": "تم الوصول إلى الحد الأسبوعي",+ "weeklyTitle": "تم بلوغ الحد السحابي الأسبوعي","weeklyDescription": "تتم إعادة تعيين الحد الخاص بك على أساس متجدد. قم بالترقية إلى Pro أو استخدم مفتاح API الخاص بك للاستخدام غير المحدود."},"accessibilityMissing": {@@ -3243,7 +3243,7 @@"account": {"badges": {"free": "مجاني",- "limitReached": "تم بلوغ الحد الأقصى",+ "limitReached": "تم بلوغ الحد السحابي","pastDue": "متأخر الدفع","pro": "Pro","business": "Business",@@ -3279,9 +3279,10 @@"title": "لم نتمكن من معالجة دفعتك"},"planDescriptions": {- "freeUsage": "{{used}} من {{limit}} كلمة هذا الأسبوع",+ "freeUsage": "{{used}} من {{limit}} كلمة في OpenWhispr Cloud هذا الأسبوع",+ "byokUnlimited": "يبقى استخدام مفاتيح API الخاصة بك والنماذج المحلية غير محدود.","nextBilling": "الفوترة القادمة: {{date}}",- "pastDue": "{{used}} من {{limit}} كلمة مجانية هذا الأسبوع - قم بتحديث الدفع لاستعادة Pro",+ "pastDue": "{{used}} من {{limit}} كلمة في OpenWhispr Cloud هذا الأسبوع - قم بتحديث الدفع لاستعادة Pro","trial": "عدد الأيام المتبقية: {{days}} - تفريغ غير محدود","unlimited": "غير محدود","accessUntil": "الوصول حتى {{date}}",@@ -3399,8 +3400,8 @@"title": "الحساب","toasts": {"approachingLimit": {- "description": "لقد استخدمت {{used}} من أصل {{limit}} كلمة مجانية هذا الأسبوع. قم بالترقية إلى Pro للاستخدام غير المحدود.",- "title": "الاقتراب من الحد الأسبوعي"+ "description": "استخدمت {{used}} من {{limit}} كلمة في OpenWhispr Cloud هذا الأسبوع. قم بالترقية إلى Pro للاستخدام غير المحدود.",+ "title": "الاقتراب من الحد السحابي للكلمات"}},"trialCta": {@@ -4236,7 +4237,7 @@},"upgradePrompt": {"paymentFailed": "لم نتمكن من معالجة دفعتك",- "weeklyLimit": "لقد وصلت إلى حدك الأسبوعي",+ "weeklyLimit": "لقد وصلت إلى حدك السحابي الأسبوعي","pastDueDescription": "أنت الآن على الخطة المجانية — لا تقلق، ما زلت تحصل على {{limit}} كلمة في الأسبوع.\nقم بتحديث طريقة الدفع للعودة إلى خطة Pro غير المحدودة.","limitDescription": "تم استخدام {{used}} من {{limit}} كلمة.\nتم حفظ نصك المفرَّغ ولصقه.","updatePayment": "تحديث طريقة الدفع",@@ -4580,8 +4581,8 @@"inviteTeam": "ادعُ فريقك","settings": "الإعدادات","support": "الدعم",- "limitReached": "تم الوصول إلى الحد الأسبوعي",- "limitReachedDescription": "قم بالترقية إلى Pro للحصول على تفريغ صوتي غير محدود.",+ "limitReached": "تم بلوغ الحد السحابي الأسبوعي",+ "limitReachedDescription": "قم بالترقية إلى Pro أو استخدم مفتاح API الخاص بك للاستخدام غير المحدود.","viewPlans": "عرض الخطط","upgradeTitle": "الترقية إلى Pro","upgradeDescription": "تفريغ صوتي غير محدود، أكثر دقة، وأسرع.",diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 9782dd2e3..00b99bb8c 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -142,7 +142,7 @@},"upgradePrompt": {"paymentFailed": "Ihre Zahlung konnte nicht verarbeitet werden",- "weeklyLimit": "Sie haben Ihr Wochenlimit erreicht",+ "weeklyLimit": "Sie haben Ihr wöchentliches Cloud-Limit erreicht","pastDueDescription": "Sie sind vorerst im kostenlosen Tarif – keine Sorge, Sie haben weiterhin {{limit}} Wörter pro Woche.\nAktualisieren Sie Ihre Zahlungsmethode, um wieder unbegrenztes Pro zu erhalten.","limitDescription": "{{used}} von {{limit}} Wörtern verwendet.\nIhre Transkription wurde gespeichert und eingefügt.","updatePayment": "Zahlungsmethode aktualisieren",@@ -631,7 +631,7 @@"availableButton": "Update verfügbar"},"limit": {- "weeklyTitle": "Wochenlimit erreicht",+ "weeklyTitle": "Wöchentliches Cloud-Limit erreicht","weeklyDescription": "Ihr Limit setzt sich rollierend zurück. Upgraden Sie auf Pro oder nutzen Sie Ihren eigenen API-Schlüssel für unbegrenzte Nutzung."},"accessibilityMissing": {@@ -925,7 +925,7 @@"offline": "Sie sind offline","agentUnavailable": "Assistent nicht verfügbar","screenContextSkipped": "Bildschirmkontext übersprungen",- "dailyLimitReached": "Tägliches Limit erreicht",+ "cloudLimitReached": "Wöchentliches Cloud-Limit erreicht","providerRateLimited": "Anbieter-Ratenlimit erreicht"},"fallback": {@@ -1891,7 +1891,7 @@"account": {"badges": {"free": "Kostenlos",- "limitReached": "Limit erreicht",+ "limitReached": "Cloud-Limit erreicht","pastDue": "Überfällig","pro": "Pro","business": "Business",@@ -1927,9 +1927,10 @@"title": "Ihre Zahlung konnte nicht verarbeitet werden"},"planDescriptions": {- "freeUsage": "{{used}} / {{limit}} Wörter diese Woche",+ "freeUsage": "{{used}} / {{limit}} Wörter in OpenWhispr Cloud diese Woche",+ "byokUnlimited": "Eigene API-Schlüssel und lokale Modelle bleiben unbegrenzt nutzbar.","nextBilling": "Nächste Abrechnung: {{date}}",- "pastDue": "{{used}} / {{limit}} kostenlose Wörter diese Woche – Zahlung aktualisieren, um Pro wiederherzustellen",+ "pastDue": "{{used}} / {{limit}} Wörter in OpenWhispr Cloud diese Woche – Zahlung aktualisieren, um Pro wiederherzustellen","trial": "Noch {{days}} Tage – unbegrenzte Transkriptionen","unlimited": "Unbegrenzt","accessUntil": "Zugang bis {{date}}",@@ -2047,8 +2048,8 @@"title": "Konto","toasts": {"approachingLimit": {- "description": "Sie haben diese Woche {{used}} von {{limit}} kostenlosen Wörtern verwendet. Upgraden Sie auf Pro für unbegrenzte Nutzung.",- "title": "Wochenlimit fast erreicht"+ "description": "Sie haben diese Woche {{used}} von {{limit}} Wörtern in OpenWhispr Cloud genutzt. Upgraden Sie auf Pro für unbegrenzte Nutzung.",+ "title": "Cloud-Wortlimit fast erreicht"}},"trialCta": {@@ -2995,8 +2996,8 @@"inviteTeam": "Team einladen","settings": "Einstellungen","support": "Support",- "limitReached": "Wochenlimit erreicht",- "limitReachedDescription": "Upgraden Sie auf Pro für unbegrenzte Transkriptionen.",+ "limitReached": "Wöchentliches Cloud-Limit erreicht",+ "limitReachedDescription": "Upgraden Sie auf Pro oder nutzen Sie Ihren eigenen API-Schlüssel für unbegrenzte Nutzung.","viewPlans": "Tarife ansehen","upgradeTitle": "Auf Pro upgraden","upgradeDescription": "Unbegrenzte, genauere und schnellere Transkription.",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 7b3d321dd..087fec25b 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -142,7 +142,7 @@},"upgradePrompt": {"paymentFailed": "We couldn't process your payment",- "weeklyLimit": "You've reached your weekly limit",+ "weeklyLimit": "You've reached your weekly Cloud limit","pastDueDescription": "You're on the free plan for now — don't worry, you still get {{limit}} words per week.\nUpdate your payment method to get back to unlimited Pro.","limitDescription": "{{used}} of {{limit}} words used.\nYour transcription was saved and pasted.","updatePayment": "Update payment method",@@ -631,7 +631,7 @@"availableButton": "Update Available"},"limit": {- "weeklyTitle": "Weekly limit reached",+ "weeklyTitle": "Weekly Cloud limit reached","weeklyDescription": "Your limit resets on a rolling basis. Upgrade to Pro or use your own API key for unlimited use."},"accessibilityMissing": {@@ -925,7 +925,7 @@"offline": "You're Offline","agentUnavailable": "Assistant Unavailable","screenContextSkipped": "Screen Context Skipped",- "dailyLimitReached": "Daily Limit Reached",+ "cloudLimitReached": "Weekly Cloud Limit Reached","providerRateLimited": "Provider Rate Limited"},"fallback": {@@ -1891,7 +1891,7 @@"account": {"badges": {"free": "Free",- "limitReached": "Limit reached",+ "limitReached": "Cloud limit reached","pastDue": "Past due","pro": "Pro","business": "Business",@@ -1927,9 +1927,10 @@"title": "We couldn't process your payment"},"planDescriptions": {- "freeUsage": "{{used}} / {{limit}} words this week",+ "freeUsage": "{{used}} / {{limit}} OpenWhispr Cloud words this week",+ "byokUnlimited": "Your own API keys and local models remain unlimited.","nextBilling": "Next billing: {{date}}",- "pastDue": "{{used}} / {{limit}} free words this week - update payment to restore Pro",+ "pastDue": "{{used}} / {{limit}} OpenWhispr Cloud words this week - update payment to restore Pro","trial": "{{days}} days remaining - unlimited transcriptions","unlimited": "Unlimited","accessUntil": "Access until {{date}}",@@ -2047,8 +2048,8 @@"title": "Account","toasts": {"approachingLimit": {- "description": "You've used {{used}} of {{limit}} free words this week. Upgrade to Pro for unlimited use.",- "title": "Approaching weekly limit"+ "description": "You've used {{used}} of {{limit}} OpenWhispr Cloud words this week. Upgrade to Pro for unlimited use.",+ "title": "Approaching Cloud word limit"}},"trialCta": {@@ -2869,8 +2870,8 @@"inviteTeam": "Invite your team","settings": "Settings","support": "Support",- "limitReached": "Weekly limit reached",- "limitReachedDescription": "Upgrade to Pro for unlimited transcriptions.",+ "limitReached": "Weekly Cloud limit reached",+ "limitReachedDescription": "Upgrade to Pro or use your own API key for unlimited use.","viewPlans": "View Plans","upgradeTitle": "Upgrade to Pro","upgradeDescription": "Unlimited, more accurate, faster transcription.",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 163890de6..2784544cb 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -142,7 +142,7 @@},"upgradePrompt": {"paymentFailed": "No pudimos procesar tu pago",- "weeklyLimit": "Has alcanzado tu límite semanal",+ "weeklyLimit": "Has alcanzado tu límite semanal de la nube","pastDueDescription": "Estás en el plan gratuito por ahora, pero no te preocupes: aún tienes {{limit}} palabras por semana.\nActualiza tu método de pago para volver a Pro ilimitado.","limitDescription": "{{used}} de {{limit}} palabras usadas.\nTu transcripción fue guardada y pegada.","updatePayment": "Actualizar método de pago",@@ -631,7 +631,7 @@"availableButton": "Actualización disponible"},"limit": {- "weeklyTitle": "Límite semanal alcanzado",+ "weeklyTitle": "Límite semanal de la nube alcanzado","weeklyDescription": "Tu límite se restablece de forma continua. Mejora a Pro o usa tu propia clave API para uso ilimitado."},"accessibilityMissing": {@@ -925,7 +925,7 @@"offline": "Sin conexión","agentUnavailable": "Asistente no disponible","screenContextSkipped": "Contexto de pantalla omitido",- "dailyLimitReached": "Límite diario alcanzado",+ "cloudLimitReached": "Límite semanal de la nube alcanzado","providerRateLimited": "Límite de tasa del proveedor"},"fallback": {@@ -1649,7 +1649,7 @@"account": {"badges": {"free": "Gratis",- "limitReached": "Límite alcanzado",+ "limitReached": "Límite de la nube alcanzado","pastDue": "Pago vencido","pro": "Pro","business": "Business",@@ -1685,9 +1685,10 @@"title": "No pudimos procesar tu pago"},"planDescriptions": {- "freeUsage": "{{used}} / {{limit}} palabras esta semana",+ "freeUsage": "{{used}} / {{limit}} palabras de OpenWhispr Cloud esta semana",+ "byokUnlimited": "Tus propias claves API y los modelos locales siguen sin límite.","nextBilling": "Próxima facturación: {{date}}",- "pastDue": "{{used}} / {{limit}} palabras gratis esta semana: actualiza el pago para restaurar Pro",+ "pastDue": "{{used}} / {{limit}} palabras de OpenWhispr Cloud esta semana: actualiza el pago para restaurar Pro","trial": "{{days}} días restantes: transcripciones ilimitadas","unlimited": "Ilimitado","accessUntil": "Acceso hasta el {{date}}",@@ -1808,8 +1809,8 @@"title": "Cuenta","toasts": {"approachingLimit": {- "description": "Has usado {{used}} de {{limit}} palabras gratis esta semana. Mejora a Pro para uso ilimitado.",- "title": "Cerca del límite semanal"+ "description": "Has usado {{used}} de {{limit}} palabras de OpenWhispr Cloud esta semana. Mejora a Pro para uso ilimitado.",+ "title": "Cerca del límite de palabras de la nube"}},"trialCta": {@@ -3706,8 +3707,8 @@"inviteTeam": "Invita a tu equipo","settings": "Configuración","support": "Soporte",- "limitReached": "Límite semanal alcanzado",- "limitReachedDescription": "Mejora a Pro para transcripciones ilimitadas.",+ "limitReached": "Límite semanal de la nube alcanzado",+ "limitReachedDescription": "Mejora a Pro o usa tu propia clave API para uso ilimitado.","viewPlans": "Ver planes","upgradeTitle": "Mejorar a Pro","upgradeDescription": "Transcripción ilimitada, más precisa y más rápida.",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 8fd20867a..8fbe481ca 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -142,7 +142,7 @@},"upgradePrompt": {"paymentFailed": "Nous n'avons pas pu traiter votre paiement",- "weeklyLimit": "Vous avez atteint votre limite hebdomadaire",+ "weeklyLimit": "Vous avez atteint votre limite cloud hebdomadaire","pastDueDescription": "Vous êtes temporairement sur le plan gratuit — pas de souci, vous avez encore {{limit}} mots par semaine.\nMettez à jour votre moyen de paiement pour revenir à Pro illimité.","limitDescription": "{{used}} de {{limit}} mots utilisés.\nVotre transcription a été sauvegardée et collée.","updatePayment": "Mettre à jour le moyen de paiement",@@ -631,7 +631,7 @@"availableButton": "Mise à jour disponible"},"limit": {- "weeklyTitle": "Limite hebdomadaire atteinte",+ "weeklyTitle": "Limite cloud hebdomadaire atteinte","weeklyDescription": "Votre limite se renouvelle de manière glissante. Passez à Pro ou utilisez votre propre clé API pour un usage illimité."},"accessibilityMissing": {@@ -925,7 +925,7 @@"offline": "Vous êtes hors ligne","agentUnavailable": "Assistant indisponible","screenContextSkipped": "Contexte d'écran ignoré",- "dailyLimitReached": "Limite quotidienne atteinte",+ "cloudLimitReached": "Limite cloud hebdomadaire atteinte","providerRateLimited": "Limite de débit du fournisseur"},"fallback": {@@ -1891,7 +1891,7 @@"account": {"badges": {"free": "Gratuit",- "limitReached": "Limite atteinte",+ "limitReached": "Limite cloud atteinte","pastDue": "Paiement en retard","pro": "Pro","business": "Business",@@ -1927,9 +1927,10 @@"title": "Nous n'avons pas pu traiter votre paiement"},"planDescriptions": {- "freeUsage": "{{used}} / {{limit}} mots cette semaine",+ "freeUsage": "{{used}} / {{limit}} mots sur OpenWhispr Cloud cette semaine",+ "byokUnlimited": "Vos propres clés API et les modèles locaux restent utilisables sans limite.","nextBilling": "Prochaine facturation : {{date}}",- "pastDue": "{{used}} / {{limit}} mots gratuits cette semaine - mettez à jour le paiement pour restaurer Pro",+ "pastDue": "{{used}} / {{limit}} mots sur OpenWhispr Cloud cette semaine - mettez à jour le paiement pour restaurer Pro","trial": "{{days}} jours restants - transcriptions illimitées","unlimited": "Illimité","accessUntil": "Accès jusqu'au {{date}}",@@ -2047,8 +2048,8 @@"title": "Compte","toasts": {"approachingLimit": {- "description": "Vous avez utilisé {{used}} de {{limit}} mots gratuits cette semaine. Passez à Pro pour une utilisation illimitée.",- "title": "Limite hebdomadaire bientôt atteinte"+ "description": "Vous avez utilisé {{used}} mots sur {{limit}} dans OpenWhispr Cloud cette semaine. Passez à Pro pour une utilisation illimitée.",+ "title": "Limite de mots cloud bientôt atteinte"}},"trialCta": {@@ -2995,8 +2996,8 @@"inviteTeam": "Invitez votre équipe","settings": "Paramètres","support": "Assistance",- "limitReached": "Limite hebdomadaire atteinte",- "limitReachedDescription": "Passez à Pro pour des transcriptions illimitées.",+ "limitReached": "Limite cloud hebdomadaire atteinte",+ "limitReachedDescription": "Passez à Pro ou utilisez votre propre clé API pour un usage illimité.","viewPlans": "Voir les forfaits","upgradeTitle": "Passer à Pro","upgradeDescription": "Transcription illimitée, plus précise et plus rapide.",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 12998cfd6..01862e5ce 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -142,7 +142,7 @@},"upgradePrompt": {"paymentFailed": "Non siamo riusciti a elaborare il pagamento",- "weeklyLimit": "Hai raggiunto il limite settimanale",+ "weeklyLimit": "Hai raggiunto il limite cloud settimanale","pastDueDescription": "Sei nel piano gratuito per ora — nessun problema, hai ancora {{limit}} parole a settimana.\nAggiorna il metodo di pagamento per tornare a Pro illimitato.","limitDescription": "{{used}} di {{limit}} parole utilizzate.\nLa trascrizione è stata salvata e incollata.","updatePayment": "Aggiorna metodo di pagamento",@@ -631,7 +631,7 @@"availableButton": "Aggiornamento disponibile"},"limit": {- "weeklyTitle": "Limite settimanale raggiunto",+ "weeklyTitle": "Limite cloud settimanale raggiunto","weeklyDescription": "Il limite si rinnova in modo progressivo. Passa a Pro o usa la tua chiave API per un uso illimitato."},"accessibilityMissing": {@@ -925,7 +925,7 @@"offline": "Sei offline","agentUnavailable": "Assistente non disponibile","screenContextSkipped": "Contesto dello schermo ignorato",- "dailyLimitReached": "Limite giornaliero raggiunto",+ "cloudLimitReached": "Limite cloud settimanale raggiunto","providerRateLimited": "Limite di velocità del provider"},"fallback": {@@ -1597,7 +1597,7 @@"account": {"badges": {"free": "Gratuito",- "limitReached": "Limite raggiunto",+ "limitReached": "Limite cloud raggiunto","pastDue": "Scaduto","pro": "Pro","business": "Business",@@ -1633,9 +1633,10 @@"title": "Non siamo riusciti a elaborare il pagamento"},"planDescriptions": {- "freeUsage": "{{used}} / {{limit}} parole questa settimana",+ "freeUsage": "{{used}} / {{limit}} parole di OpenWhispr Cloud questa settimana",+ "byokUnlimited": "Le tue chiavi API e i modelli locali restano utilizzabili senza limiti.","nextBilling": "Prossima fatturazione: {{date}}",- "pastDue": "{{used}} / {{limit}} parole gratuite questa settimana — aggiorna il pagamento per ripristinare Pro",+ "pastDue": "{{used}} / {{limit}} parole di OpenWhispr Cloud questa settimana — aggiorna il pagamento per ripristinare Pro","trial": "{{days}} giorni rimanenti — trascrizioni illimitate","unlimited": "Illimitato","accessUntil": "Accesso fino al {{date}}",@@ -1657,8 +1658,8 @@"title": "Account","toasts": {"approachingLimit": {- "description": "Hai usato {{used}} di {{limit}} parole gratuite questa settimana. Passa a Pro per un uso illimitato.",- "title": "Prossimo al limite settimanale"+ "description": "Hai usato {{used}} di {{limit}} parole di OpenWhispr Cloud questa settimana. Passa a Pro per un uso illimitato.",+ "title": "Limite di parole cloud quasi raggiunto"}},"trialCta": {@@ -3654,8 +3655,8 @@"inviteTeam": "Invita il tuo team","settings": "Impostazioni","support": "Assistenza",- "limitReached": "Limite settimanale raggiunto",- "limitReachedDescription": "Passa a Pro per trascrizioni illimitate.",+ "limitReached": "Limite cloud settimanale raggiunto",+ "limitReachedDescription": "Passa a Pro o usa la tua chiave API per un uso illimitato.","viewPlans": "Vedi i piani","upgradeTitle": "Passa a Pro","upgradeDescription": "Trascrizione illimitata, più precisa e più veloce.",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex 55908555d..9d7eb89fb 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -142,7 +142,7 @@},"upgradePrompt": {"paymentFailed": "お支払いを処理できませんでした",- "weeklyLimit": "週間の利用上限に達しました",+ "weeklyLimit": "週間のクラウド上限に達しました","pastDueDescription": "現在は無料プランをご利用中です。ご安心ください、週 {{limit}} ワードまで引き続きご利用いただけます。\nお支払い方法を更新して、無制限の Pro に戻しましょう。","limitDescription": "{{used}} / {{limit}} ワード使用済み。\n文字起こしは保存・貼り付けされました。","updatePayment": "お支払い方法を更新",@@ -631,7 +631,7 @@"availableButton": "アップデートあり"},"limit": {- "weeklyTitle": "週間の利用上限に達しました",+ "weeklyTitle": "週間のクラウド上限に達しました","weeklyDescription": "利用上限はローリング方式でリセットされます。Pro にアップグレードするか、自分の API キーを使用して無制限にご利用ください。"},"accessibilityMissing": {@@ -925,7 +925,7 @@"offline": "オフラインです","agentUnavailable": "アシスタントを利用できません","screenContextSkipped": "画面コンテキストをスキップしました",- "dailyLimitReached": "1 日の上限に達しました",+ "cloudLimitReached": "週間のクラウド上限に達しました","providerRateLimited": "プロバイダーのレート制限"},"fallback": {@@ -1597,7 +1597,7 @@"account": {"badges": {"free": "無料",- "limitReached": "上限到達",+ "limitReached": "クラウド上限到達","pastDue": "支払い遅延","pro": "Pro","business": "Business",@@ -1633,9 +1633,10 @@"title": "お支払いを処理できませんでした"},"planDescriptions": {- "freeUsage": "今週 {{used}} / {{limit}} ワード使用済み",+ "freeUsage": "今週の OpenWhispr Cloud 使用量:{{used}} / {{limit}} ワード",+ "byokUnlimited": "独自の API キーとローカルモデルは引き続き無制限で利用できます。","nextBilling": "次の請求日: {{date}}",- "pastDue": "今週 {{used}} / {{limit}} 無料ワード使用済み - お支払い方法を更新して Pro を復元",+ "pastDue": "今週の OpenWhispr Cloud 使用量:{{used}} / {{limit}} ワード - お支払い方法を更新して Pro を復元","trial": "残り {{days}} 日 - 無制限の文字起こし","unlimited": "無制限","accessUntil": "{{date}} まで利用可能",@@ -1756,8 +1757,8 @@"title": "アカウント","toasts": {"approachingLimit": {- "description": "今週 {{used}} / {{limit}} 無料ワードを使用しました。Pro にアップグレードして無制限にご利用ください。",- "title": "週間利用上限に近づいています"+ "description": "今週、OpenWhispr Cloud で {{limit}} ワード中 {{used}} ワードを使用しました。Pro にアップグレードして無制限にご利用ください。",+ "title": "クラウドのワード上限に近づいています"}},"trialCta": {@@ -3654,8 +3655,8 @@"inviteTeam": "チームを招待","settings": "設定","support": "サポート",- "limitReached": "週間の利用上限に達しました",- "limitReachedDescription": "Pro にアップグレードして無制限の文字起こしをご利用ください。",+ "limitReached": "週間のクラウド上限に達しました",+ "limitReachedDescription": "Pro にアップグレードするか、自分の API キーを使用して無制限にご利用ください。","viewPlans": "プランを見る","upgradeTitle": "Pro にアップグレード","upgradeDescription": "無制限・高精度・高速の文字起こし。",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex 9bcb2f064..c44b74e31 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -610,7 +610,7 @@"availableButton": "Atualização disponível"},"limit": {- "weeklyTitle": "Limite semanal atingido",+ "weeklyTitle": "Limite semanal da nuvem atingido","weeklyDescription": "Seu limite é redefinido continuamente. Faça upgrade para Pro ou use sua própria chave API para uso ilimitado."},"accessibilityMissing": {@@ -904,7 +904,7 @@"offline": "Sem conexão","agentUnavailable": "Assistente indisponível","screenContextSkipped": "Contexto de tela ignorado",- "dailyLimitReached": "Limite diário atingido",+ "cloudLimitReached": "Limite semanal da nuvem atingido","providerRateLimited": "Limite de taxa do provedor"},"fallback": {@@ -1576,7 +1576,7 @@"account": {"badges": {"free": "Gratuito",- "limitReached": "Limite atingido",+ "limitReached": "Limite da nuvem atingido","pastDue": "Em atraso","pro": "Pro","business": "Business",@@ -1612,9 +1612,10 @@"title": "Não foi possível processar seu pagamento"},"planDescriptions": {- "freeUsage": "{{used}} / {{limit}} palavras esta semana",+ "freeUsage": "{{used}} / {{limit}} palavras do OpenWhispr Cloud esta semana",+ "byokUnlimited": "Suas próprias chaves de API e os modelos locais continuam sem limite.","nextBilling": "Próxima cobrança: {{date}}",- "pastDue": "{{used}} / {{limit}} palavras gratuitas esta semana — atualize o pagamento para restaurar o Pro",+ "pastDue": "{{used}} / {{limit}} palavras do OpenWhispr Cloud esta semana — atualize o pagamento para restaurar o Pro","trial": "{{days}} dias restantes — transcrições ilimitadas","unlimited": "Ilimitado","accessUntil": "Acesso até {{date}}",@@ -1636,8 +1637,8 @@"title": "Conta","toasts": {"approachingLimit": {- "description": "Você usou {{used}} de {{limit}} palavras gratuitas esta semana. Faça upgrade para Pro para uso ilimitado.",- "title": "Aproximando-se do limite semanal"+ "description": "Você usou {{used}} de {{limit}} palavras do OpenWhispr Cloud esta semana. Faça upgrade para Pro para uso ilimitado.",+ "title": "Aproximando-se do limite de palavras da nuvem"}},"trialCta": {@@ -2746,7 +2747,7 @@},"upgradePrompt": {"paymentFailed": "Não foi possível processar seu pagamento",- "weeklyLimit": "Você atingiu seu limite semanal",+ "weeklyLimit": "Você atingiu seu limite semanal da nuvem","pastDueDescription": "Você está no plano gratuito por enquanto — sem problemas, você ainda tem {{limit}} palavras por semana.\nAtualize sua forma de pagamento para voltar ao Pro ilimitado.","limitDescription": "{{used}} de {{limit}} palavras usadas.\nSua transcrição foi salva e colada.","updatePayment": "Atualizar forma de pagamento",@@ -3654,8 +3655,8 @@"inviteTeam": "Convide sua equipe","settings": "Configurações","support": "Suporte",- "limitReached": "Limite semanal atingido",- "limitReachedDescription": "Faça upgrade para Pro para transcrições ilimitadas.",+ "limitReached": "Limite semanal da nuvem atingido",+ "limitReachedDescription": "Faça upgrade para Pro ou use sua própria chave API para uso ilimitado.","viewPlans": "Ver planos","upgradeTitle": "Fazer upgrade para Pro","upgradeDescription": "Transcrição ilimitada, mais precisa e mais rápida.",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 76fc112ab..316c1a7fe 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -142,7 +142,7 @@},"upgradePrompt": {"paymentFailed": "Не удалось обработать платёж",- "weeklyLimit": "Вы достигли недельного лимита",+ "weeklyLimit": "Вы достигли недельного облачного лимита","pastDueDescription": "Сейчас вы на бесплатном плане — не волнуйтесь, у вас есть {{limit}} слов в неделю.\nОбновите способ оплаты, чтобы вернуться к безлимитному Pro.","limitDescription": "Использовано {{used}} из {{limit}} слов.\nВаша транскрипция сохранена и вставлена.","updatePayment": "Обновить способ оплаты",@@ -631,7 +631,7 @@"availableButton": "Доступно обновление"},"limit": {- "weeklyTitle": "Недельный лимит достигнут",+ "weeklyTitle": "Недельный облачный лимит достигнут","weeklyDescription": "Ваш лимит обновляется на скользящей основе. Перейдите на Pro или используйте свой API-ключ для безлимитного использования."},"accessibilityMissing": {@@ -925,7 +925,7 @@"offline": "Нет подключения к интернету","agentUnavailable": "Помощник недоступен","screenContextSkipped": "Контекст экрана пропущен",- "dailyLimitReached": "Дневной лимит достигнут",+ "cloudLimitReached": "Недельный облачный лимит достигнут","providerRateLimited": "Ограничение провайдера"},"fallback": {@@ -1601,7 +1601,7 @@"account": {"badges": {"free": "Бесплатный",- "limitReached": "Лимит достигнут",+ "limitReached": "Облачный лимит достигнут","pastDue": "Просрочен","pro": "Pro","business": "Business",@@ -1637,9 +1637,10 @@"title": "Не удалось обработать платёж"},"planDescriptions": {- "freeUsage": "{{used}} / {{limit}} слов на этой неделе",+ "freeUsage": "{{used}} / {{limit}} слов в OpenWhispr Cloud на этой неделе",+ "byokUnlimited": "Собственные API-ключи и локальные модели по-прежнему доступны без ограничений.","nextBilling": "Следующее списание: {{date}}",- "pastDue": "{{used}} / {{limit}} бесплатных слов на этой неделе — обновите платёж для восстановления Pro",+ "pastDue": "{{used}} / {{limit}} слов в OpenWhispr Cloud на этой неделе — обновите платёж для восстановления Pro","trial": "Осталось {{days}} дней — безлимитные транскрипции","unlimited": "Без ограничений","accessUntil": "Доступ до {{date}}",@@ -1661,8 +1662,8 @@"title": "Аккаунт","toasts": {"approachingLimit": {- "description": "Вы использовали {{used}} из {{limit}} бесплатных слов на этой неделе. Перейдите на Pro для безлимитного использования.",- "title": "Приближение к недельному лимиту"+ "description": "На этой неделе вы использовали {{used}} из {{limit}} слов в OpenWhispr Cloud. Перейдите на Pro для безлимитного использования.",+ "title": "Приближение к облачному лимиту слов"}},"trialCta": {@@ -3698,8 +3699,8 @@"inviteTeam": "Пригласите команду","settings": "Настройки","support": "Поддержка",- "limitReached": "Недельный лимит достигнут",- "limitReachedDescription": "Перейдите на Pro для безлимитных транскрипций.",+ "limitReached": "Недельный облачный лимит достигнут",+ "limitReachedDescription": "Перейдите на Pro или используйте свой API-ключ для безлимитного использования.","viewPlans": "Посмотреть тарифы","upgradeTitle": "Перейдите на Pro","upgradeDescription": "Безлимитная, более точная и быстрая транскрипция.",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 4e26dd7d0..11b7971be 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -142,7 +142,7 @@},"upgradePrompt": {"paymentFailed": "我们无法处理你的付款",- "weeklyLimit": "你已达到本周的使用上限",+ "weeklyLimit": "你已达到本周的云端使用上限","pastDueDescription": "你目前使用的是免费版——别担心,每周仍有 {{limit}} 个词的额度。\n更新支付方式即可恢复无限制的 Pro 版。","limitDescription": "已使用 {{used}} / {{limit}} 个词。\n你的转录已保存并粘贴。","updatePayment": "更新支付方式",@@ -631,7 +631,7 @@"availableButton": "有可用更新"},"limit": {- "weeklyTitle": "已达到周限额",+ "weeklyTitle": "已达本周云端上限","weeklyDescription": "你的额度按滚动方式重置。升级到 Pro 或使用自己的 API Key 可不受限制。"},"accessibilityMissing": {@@ -925,7 +925,7 @@"offline": "你已离线","agentUnavailable": "助手不可用","screenContextSkipped": "已跳过屏幕上下文",- "dailyLimitReached": "已达到每日上限",+ "cloudLimitReached": "已达本周云端上限","providerRateLimited": "服务商速率限制"},"fallback": {@@ -1597,7 +1597,7 @@"account": {"badges": {"free": "免费版",- "limitReached": "已达上限",+ "limitReached": "已达云端上限","pastDue": "逾期未付","pro": "Pro","business": "Business",@@ -1633,9 +1633,10 @@"title": "我们无法处理你的付款"},"planDescriptions": {- "freeUsage": "本周已使用 {{used}} / {{limit}} 个词",+ "freeUsage": "本周 OpenWhispr Cloud 已使用 {{used}} / {{limit}} 个词",+ "byokUnlimited": "使用自己的 API 密钥和本地模型仍不受此限制。","nextBilling": "下次扣费:{{date}}",- "pastDue": "本周 {{used}} / {{limit}} 免费词数——更新支付方式以恢复 Pro",+ "pastDue": "本周 OpenWhispr Cloud 已使用 {{used}} / {{limit}} 个词——更新支付方式以恢复 Pro","trial": "剩余 {{days}} 天——无限转录","unlimited": "无限制","accessUntil": "可使用至 {{date}}",@@ -1657,8 +1658,8 @@"title": "账户","toasts": {"approachingLimit": {- "description": "本周已使用 {{used}} / {{limit}} 个免费词数。升级到 Pro 可享受无限使用。",- "title": "即将达到周限额"+ "description": "本周已使用 {{used}} / {{limit}} 个 OpenWhispr Cloud 词。升级到 Pro 可享受无限使用。",+ "title": "即将达到云端字数上限"}},"trialCta": {@@ -3654,8 +3655,8 @@"inviteTeam": "邀请你的团队","settings": "设置","support": "支持",- "limitReached": "已达每周上限",- "limitReachedDescription": "升级到 Pro 即可无限转录。",+ "limitReached": "已达本周云端上限",+ "limitReachedDescription": "升级到 Pro 或使用自己的 API Key 可不受限制。","viewPlans": "查看套餐","upgradeTitle": "升级到 Pro","upgradeDescription": "无限量、更准确、更快速的转录。",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 96e7a46e9..980e1cc3c 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -142,7 +142,7 @@},"upgradePrompt": {"paymentFailed": "我們無法處理你的付款",- "weeklyLimit": "你已達到每週使用上限",+ "weeklyLimit": "你已達到每週雲端使用上限","pastDueDescription": "你目前使用的是免費方案,別擔心,每週仍有 {{limit}} 字的額度。\n更新付款方式即可恢復無限制的 Pro 方案。","limitDescription": "已使用 {{used}} / {{limit}} 字。\n你的轉錄已儲存並貼上。","updatePayment": "更新付款方式",@@ -631,7 +631,7 @@"availableButton": "有可用更新"},"limit": {- "weeklyTitle": "已達每週使用上限",+ "weeklyTitle": "已達本週雲端上限","weeklyDescription": "你的額度為滾動式重置。升級至 Pro 或使用自己的 API Key 即可無限使用。"},"accessibilityMissing": {@@ -925,7 +925,7 @@"offline": "你目前離線","agentUnavailable": "助理無法使用","screenContextSkipped": "已略過螢幕內容",- "dailyLimitReached": "已達每日上限",+ "cloudLimitReached": "已達本週雲端上限","providerRateLimited": "服務商速率限制"},"fallback": {@@ -1597,7 +1597,7 @@"account": {"badges": {"free": "免費",- "limitReached": "已達上限",+ "limitReached": "已達雲端上限","pastDue": "款項逾期","pro": "Pro","business": "Business",@@ -1633,9 +1633,10 @@"title": "我們無法處理你的付款"},"planDescriptions": {- "freeUsage": "本週已使用 {{used}} / {{limit}} 字",+ "freeUsage": "本週 OpenWhispr Cloud 已使用 {{used}} / {{limit}} 字",+ "byokUnlimited": "使用自己的 API 金鑰和本機模型仍不受此限制。","nextBilling": "下次扣款日:{{date}}",- "pastDue": "本週 {{used}} / {{limit}} 免費字數——更新付款方式以恢復 Pro",+ "pastDue": "本週 OpenWhispr Cloud 已使用 {{used}} / {{limit}} 字——更新付款方式以恢復 Pro","trial": "剩餘 {{days}} 天——無限轉錄","unlimited": "無限","accessUntil": "可使用至 {{date}}",@@ -1657,8 +1658,8 @@"title": "帳號","toasts": {"approachingLimit": {- "description": "你本週已使用 {{used}} / {{limit}} 免費字數。升級至 Pro 即可無限使用。",- "title": "即將達到每週上限"+ "description": "本週已使用 {{used}} / {{limit}} 個 OpenWhispr Cloud 字。升級至 Pro 即可無限使用。",+ "title": "即將達到雲端字數上限"}},"trialCta": {@@ -3654,8 +3655,8 @@"inviteTeam": "邀請你的團隊","settings": "設定","support": "支援",- "limitReached": "已達每週上限",- "limitReachedDescription": "升級至 Pro 即可無限轉錄。",+ "limitReached": "已達本週雲端上限",+ "limitReachedDescription": "升級至 Pro 或使用自己的 API Key 即可無限使用。","viewPlans": "查看方案","upgradeTitle": "升級至 Pro","upgradeDescription": "無限量、更準確、更快速的轉錄。",diff --git a/src/utils/recordingErrors.ts b/src/utils/recordingErrors.tsindex a497fa194..063d253b3 100644--- a/src/utils/recordingErrors.ts+++ b/src/utils/recordingErrors.ts@@ -33,7 +33,7 @@ export function getRecordingErrorTitle(error: RecordingError, t: TFunction): strreturn t("hooks.audioRecording.errorTitles.screenContextSkipped");}if (error.code === "LIMIT_REACHED")- return t("hooks.audioRecording.errorTitles.dailyLimitReached");+ return t("hooks.audioRecording.errorTitles.cloudLimitReached");if (error.code === "PROVIDER_RATE_LIMITED")return t("hooks.audioRecording.errorTitles.providerRateLimited");if (error.code?.startsWith("PROVIDER_")) {diff --git a/test/helpers/audioManagerCleanupOutput.test.js b/test/helpers/audioManagerCleanupOutput.test.jsindex 72626b5f3..020bf549d 100644--- a/test/helpers/audioManagerCleanupOutput.test.js+++ b/test/helpers/audioManagerCleanupOutput.test.js@@ -48,7 +48,7 @@ test("invalid completed cleanup keeps raw text across dictation routes", async (finalizeChineseScript: async (text) => text,});- for (const route of ["batch", "streaming", "translation"]) {+ for (const route of ["batch", "streaming", "byok-streaming", "translation"]) {await t.test(`${route} Cloud cleanup snapshots its custom prompt and rejects duplicated output`,async () => {@@ -69,8 +69,9 @@ test("invalid completed cleanup keeps raw text across dictation routes", async (result = await manager.processWithOpenWhisprCloud(new Blob(["synthetic audio"]));result = { ...result, ...manager._takePendingResultExtras() };assert.equal(result.rawText, RAW);- } else if (route === "streaming") {+ } else if (route === "streaming" || route === "byok-streaming") {Object.assign(manager, {+ _streamingMeteredByCloud: route === "streaming",streamingFinalText: RAW,streamingCleanupFns: [],micRecovery: { stop() {} },@@ -88,15 +89,30 @@ test("invalid completed cleanup keeps raw text across dictation routes", async (},});let usageOptions;+ const usageEvents = [];window.electronAPI.cloudStreamingUsage = async (text, seconds, options) => {usageOptions = options;return { success: true };};- await manager._finalizeStreamingRecording(null);+ const dispatchEvent = window.dispatchEvent;+ window.dispatchEvent = (event) => usageEvents.push(event.type);+ try {+ await manager._finalizeStreamingRecording(null);+ await new Promise(setImmediate);+ } finally {+ window.dispatchEvent = dispatchEvent;+ }assert.equal(result.rawText, RAW);- await new Promise(setImmediate);- // The successful /api/reason call already logged this dictation.- assert.equal(usageOptions?.sendLogs, false);+ if (route === "streaming") {+ // The successful /api/reason call already logged this dictation.+ assert.equal(usageOptions?.sendLogs, false);+ assert.deepEqual(usageEvents, ["usage-changed"]);+ } else {+ // Cloud cleanup records no words, so an own-key stream has no+ // usage to report or refresh.+ assert.equal(usageOptions, undefined);+ assert.deepEqual(usageEvents, []);+ }} else {let translationInput;manager.processWithReasoningModel = async (text) => {diff --git a/test/helpers/audioManagerStreamingFinalization.test.js b/test/helpers/audioManagerStreamingFinalization.test.jsindex 27d2569e6..1b4a3b000 100644--- a/test/helpers/audioManagerStreamingFinalization.test.js+++ b/test/helpers/audioManagerStreamingFinalization.test.js@@ -184,6 +184,84 @@ test("streaming completion keeps the recording occurrence time", async (t) => {assert.equal(completion.analyticsOccurredAt, new Date(recordingStartedAt).toISOString());});+// Starts a stream on `providerName` under `startMode`, switches the saved mode to+// `stopMode` mid-recording, and stops with a streamed transcript.+async function streamAcrossModeSwitch(t, AudioManager, { providerName, startMode, stopMode }) {+ globalThis.__streamingFinalizationSettings = {+ ...globalThis.__streamingFinalizationSettings,+ cloudTranscriptionMode: startMode,+ isSignedIn: true,+ insightsSyncEnabled: true,+ };+ installCapture(t);+ const provider = startingOrukeetProvider({+ finalizeAcknowledged: false,+ awaitsFinalTranscript: false,+ finalize() {},+ });+ const { manager, completions } = createStartingManager(AudioManager, { providerName, provider });+ manager.finalizeChineseScript = async (text) => text;+ const usageCalls = [];+ globalThis.window.electronAPI.cloudStreamingUsage = async (...args) => {+ usageCalls.push(args);+ return { success: true };+ };+ const events = [];+ globalThis.window.dispatchEvent = (event) => events.push(event.type);++ assert.equal(await manager.startStreamingRecording(), true);+ globalThis.__streamingFinalizationSettings = {+ ...globalThis.__streamingFinalizationSettings,+ cloudTranscriptionMode: stopMode,+ };+ manager.streamingFinalText = "Words from this stream.";+ await manager.stopStreamingRecording();+ await new Promise(setImmediate);+ return { completion: completions[0], usageCalls, events };+}++test("a stream counts toward Cloud usage by the credentials it started on", async (t) => {+ const AudioManager = await loadManagerClass(t);++ await t.test("a Cloud stream switched to own keys mid-recording is still counted", async (t) => {+ const { usageCalls, events } = await streamAcrossModeSwitch(t, AudioManager, {+ providerName: "gemini",+ startMode: "openwhispr",+ stopMode: "byok",+ });+ assert.equal(usageCalls.length, 1);+ assert.equal(usageCalls[0][0], "Words from this stream.");+ assert.equal(usageCalls[0][2].sttProvider, "gemini");+ assert.equal(usageCalls[0][2].sendLogs, true);+ assert.deepEqual(events, ["usage-changed"]);+ });++ // #2558: a Free user's own Gemini key filled the Cloud word allowance.+ await t.test("an own-key stream switched to Cloud mid-recording is not counted", async (t) => {+ const { completion, usageCalls, events } = await streamAcrossModeSwitch(t, AudioManager, {+ providerName: "gemini",+ startMode: "byok",+ stopMode: "openwhispr",+ });+ assert.equal(completion.text, "Words from this stream.");+ // The opted-in insights sync pushes the local row under these.+ assert.ok(completion.clientTranscriptionId);+ assert.ok(completion.analyticsOccurredAt);+ assert.deepEqual(usageCalls, []);+ assert.deepEqual(events, []);+ });++ await t.test("tinfoil in Cloud mode streams on the user's key and is not counted", async (t) => {+ const { usageCalls, events } = await streamAcrossModeSwitch(t, AudioManager, {+ providerName: "tinfoil-realtime",+ startMode: "openwhispr",+ stopMode: "openwhispr",+ });+ assert.deepEqual(usageCalls, []);+ assert.deepEqual(events, []);+ });+});+test("only a provider that prefers its stop transcript pastes it over the streamed finals", async (t) => {const AudioManager = await loadManagerClass(t);globalThis.window.dispatchEvent = () => true;@@ -728,21 +806,15 @@ test("a no-final stream whose upload transcribed but failed its selection edit ktest("Orukeet uses the acknowledged final even if the transcript event is delayed", async (t) => {const AudioManager = await loadManagerClass(t);const { manager } = createFinalizingManager(AudioManager);+ manager.getStreamingProviderName = () => "orukeet";manager.getStreamingProvider = () => ({finalizeAcknowledged: true,finalize: async () => ({ success: true, text: "Acknowledged final" }),stop: async () => ({ success: true, text: "" }),});- let usageReported;- const usage = new Promise((resolve) => {- usageReported = resolve;- });- globalThis.window.electronAPI.cloudStreamingUsage = async () => ({ success: true });- globalThis.window.dispatchEvent = () => usageReported();const results = [];manager.onTranscriptionComplete = (result) => results.push(result);await manager.stopStreamingRecording();- await usage;assert.equal(results[0].text, "Acknowledged final");});@@ -1498,6 +1570,8 @@ async function stopManagedDictation(...settings,};const { manager } = createFinalizingManager(AudioManager);+ manager._streamingMeteredByCloud =+ globalThis.__streamingFinalizationSettings.cloudTranscriptionMode === "openwhispr";manager.recordingStartTime = Date.now() - 8000;manager.mergeRecordedSegments = async () => new Blob([new Uint8Array(100)]);manager.getStreamingProvider = () => orukeetProvider(final);@@ -1521,18 +1595,14 @@ async function stopManagedDictation(usage.push({ ...opts, text, seconds });return { success: true };};- let usageSettled;- const settled = new Promise((resolve) => {- usageSettled = resolve;- });- globalThis.window.dispatchEvent = () => usageSettled();+ globalThis.window.dispatchEvent = () => true;const published = [];manager.onTranscriptionComplete = (result) => published.push(result);const errors = [];manager.onError = (error) => errors.push(error);const stopResult = await manager.stopStreamingRecording();- // Usage settles only after a non-empty transcript is published.- if (published.some((result) => result.text)) await settled;+ // Usage is reported in the background after the transcript is published.+ await new Promise(setImmediate);return { manager, uploads, reasonCalls, usage, published, errors, stopResult };}@@ -1971,10 +2041,9 @@ test("language-score routing uses analyzed time and preserves explicit language,...overrides,});assert.equal(r.uploads.length, 0, JSON.stringify(overrides));- if (- overrides.settings?.cloudTranscriptionMode === "byok" ||- overrides.providerName === "deepgram"- )+ // An own-key stream reports no Cloud usage (#2558).+ if (overrides.settings?.cloudTranscriptionMode === "byok") assert.deepEqual(r.usage, []);+ if (overrides.providerName === "deepgram")assert.equal(r.usage[0].orukeetLanguageRouting, undefined);}});@@ -2108,7 +2177,7 @@ test("combined text never replaces an unsupported-language fallback", async (t)assert.equal(published[0].text, "明日の会議");});-test("ordinary Orukeet and BYOK streams continue metering processed text", async (t) => {+test("ordinary Orukeet streams meter processed text and BYOK streams meter nothing", async (t) => {const AudioManager = await loadManagerClass(t, {"/stores/settingsStore": `export const getSettings = () => globalThis.__streamingFinalizationSettings;@@ -2129,8 +2198,13 @@ test("ordinary Orukeet and BYOK streams continue metering processed text", asynccustomPrompts: { cleanup: "Keep text." },},});+ assert.equal(result.published[0].text, "um please send invoice 128。");+ if (cloudTranscriptionMode === "byok") {+ // An own-key stream reports no Cloud usage (#2558).+ assert.deepEqual(result.usage, []);+ continue;+ }assert.equal(result.usage[0].text, result.published[0].text);- assert.equal(result.usage[0].text, "um please send invoice 128。");assert.equal(result.usage[0].sendLogs, false);}});diff --git a/test/helpers/dictationStreamingMatrix.test.js b/test/helpers/dictationStreamingMatrix.test.jsindex 866e4735c..fe510ad49 100644--- a/test/helpers/dictationStreamingMatrix.test.js+++ b/test/helpers/dictationStreamingMatrix.test.js@@ -170,6 +170,97 @@ test("resolution: every matrix outcome is a renderer channel binding", async ()}});+const GEMINI_LIVE = {+ cloudTranscriptionProvider: "gemini",+ cloudTranscriptionModel: "gemini-3.5-transcribe-live",+};++// [description, { settings, sttConfig }, resolved provider, counts toward Cloud usage]+const METERING_MATRIX = [+ ["managed openai-realtime", {}, "openai-realtime", true],+ [+ "openai-realtime on the user's key",+ { settings: settingsWith({ cloudTranscriptionMode: "byok" }) },+ "openai-realtime",+ false,+ ],+ ["managed gemini live", { settings: settingsWith(GEMINI_LIVE) }, "gemini", true],+ [+ "gemini live on the user's key (#2558)",+ { settings: settingsWith({ ...GEMINI_LIVE, cloudTranscriptionMode: "byok" }) },+ "gemini",+ false,+ ],+ [+ "tinfoil left selected in Cloud mode still streams on the user's key",+ { settings: settingsWith({ cloudTranscriptionProvider: "tinfoil" }) },+ "tinfoil-realtime",+ false,+ ],+ [+ "corti on the user's credentials",+ {+ settings: settingsWith({+ cloudTranscriptionProvider: "corti",+ cloudTranscriptionMode: "byok",+ }),+ },+ "corti",+ false,+ ],+ [+ "deepgram on the user's key",+ {+ settings: settingsWith({+ cloudTranscriptionProvider: "deepgram",+ cloudTranscriptionModel: "nova-3",+ cloudTranscriptionMode: "byok",+ }),+ },+ "deepgram",+ false,+ ],+ [+ "managed orukeet",+ { sttConfig: { dictation: { mode: "streaming" }, streamingProvider: "orukeet" } },+ "orukeet",+ true,+ ],+ [+ "self-hosted orukeet",+ {+ settings: settingsWith({+ cloudTranscriptionMode: "byok",+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionModel: "orukeet-v0.1.0",+ cloudTranscriptionBaseUrl: "http://localhost:9000",+ }),+ },+ "orukeet",+ false,+ ],+];++for (const [+ name,+ { settings = settingsWith({}), sttConfig = null },+ provider,+ metered,+] of METERING_MATRIX) {+ test(`metering: ${name}`, async () => {+ const { resolveStreamingProviderName, buildStreamingSessionOptions, isCloudMeteredStream } =+ await loadRouting();+ const providerName = resolveStreamingProviderName({+ settings,+ context: "dictation",+ sttConfig,+ });+ assert.equal(providerName, provider);+ const options = buildStreamingSessionOptions({ providerName, settings, language: "auto" });+ assert.equal(isCloudMeteredStream(options), metered);+ });+}+test("options: openai-realtime sends provider explicitly and no preview (#1624)", async () => {const { buildStreamingSessionOptions } = await loadRouting();const options = buildStreamingSessionOptions({