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(i18n): Simplified vs Traditional Chinese script for zh STT (#1226)
Po-Han Shih44fc210055b6
diff --git a/package-lock.json b/package-lock.jsonindex 143dfa536..1f6b85b72 100644--- a/package-lock.json+++ b/package-lock.json@@ -54,6 +54,7 @@"lucide-react": "^1.7.0","object-assign": "^4.1.1","onnxruntime-node": "^1.21.0",+ "opencc-js": "^1.4.1","ps-list": "^9.0.0","react": "^19.1.0","react-dom": "^19.1.0",@@ -10434,6 +10435,12 @@}}},+ "node_modules/opencc-js": {+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/opencc-js/-/opencc-js-1.4.1.tgz",+ "integrity": "sha512-2lPLcrg7cnh1ATSduOxhnk/jq6KlR6w+5Ihl4wF7Z5e5Rva4vxTyugV5rZ7EiUCOZl+EDOLetIix+BhgYDCC+A==",+ "license": "MIT AND Apache-2.0"+ },"node_modules/optionator": {"version": "0.9.4","resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",diff --git a/package.json b/package.jsonindex 6aa0dd335..7e9b44b01 100644--- a/package.json+++ b/package.json@@ -161,6 +161,7 @@"lucide-react": "^1.7.0","object-assign": "^4.1.1","onnxruntime-node": "^1.21.0",+ "opencc-js": "^1.4.1","ps-list": "^9.0.0","react": "^19.1.0","react-dom": "^19.1.0",diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsxindex 815f73056..5aa281065 100644--- a/src/components/ControlPanel.tsx+++ b/src/components/ControlPanel.tsx@@ -52,6 +52,7 @@ import {} from "../stores/noteStore";import { fetchProviders as fetchStreamingProviders } from "../stores/streamingProvidersStore";import { executeTranslationChain, shouldRunTranslateStep } from "../helpers/translationChain";+import { applyChineseScript, resolveChineseScriptTarget } from "../utils/chineseScript";import HistoryView from "./HistoryView";import BackgroundActionToastListener from "./notes/BackgroundActionToastListener";import SpaceSyncToastListener from "./notes/SpaceSyncToastListener";@@ -588,6 +589,7 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro// A translation dictation must re-run cleanup-then-translate on retry, not plain cleanup.let handledTranslation = false;+ let translationApplied = false;if (result.transcription.route_kind === "translation") {handledTranslation = true;try {@@ -604,7 +606,7 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelProconst agentName = localStorage.getItem("agentName") || null;const route = resolveReasoningRoute(rawText, settings, agentName, false, true);if (route.kind === "translation") {- const { text } = await executeTranslationChain({+ const { text, translated } = await executeTranslationChain({text: rawText,cleanupReachable: route.cleanupReachable,runCleanup: (currentText: string) =>@@ -632,7 +634,14 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro{},"transcription"),+ onUnchangedTranslate: () =>+ logger.warn(+ "Translation step returned unchanged text, keeping source text",+ {},+ "transcription"+ ),});+ translationApplied = translated;if (text !== rawText) {const updated = await window.electronAPI.updateTranscriptionText(id,@@ -685,6 +694,40 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro}}+ // Deterministic Chinese script pass, mirroring dictation (#975). Runs last so+ // it covers the cleaned/translated text, or the raw transcript when neither ran.+ // Same rule as audioManager.getEffectiveOutputLanguage: only a completed+ // translate step moves the text into the target language, so anything else+ // still has to be scripted as the language that was dictated.+ try {+ const outputLanguage =+ result.transcription.route_kind === "translation"+ ? (translationApplied+ ? s.translationTargetLanguage+ : s.translationSourceLanguage) || "auto"+ : s.preferredLanguage;+ const scripted = await applyChineseScript(+ finalTranscription.text,+ resolveChineseScriptTarget(+ outputLanguage,+ s.chineseScriptPreference,+ finalTranscription.text+ )+ );+ if (scripted !== finalTranscription.text) {+ const updated = await window.electronAPI.updateTranscriptionText(+ id,+ scripted,+ rawText+ );+ if (updated.success && updated.transcription) {+ finalTranscription = updated.transcription;+ }+ }+ } catch {+ // Conversion failed — keep the text as transcribed+ }+updateInStore(finalTranscription);toast({title: t(diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 40639b979..be79ab462 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -89,7 +89,12 @@ import { Skeleton } from "./ui/skeleton";import { Progress } from "./ui/progress";import { useToast } from "./ui/useToast";import { useTheme } from "../hooks/useTheme";-import type { GpuDevice, LocalTranscriptionProvider, InferenceMode } from "../types/electron";+import type {+ ChineseScriptPreference,+ GpuDevice,+ LocalTranscriptionProvider,+ InferenceMode,+} from "../types/electron";import logger from "../utils/logger";import { SettingsRow, InferenceModeSelector } from "./ui/SettingsSection";import type { InferenceModeOption } from "./ui/SettingsSection";@@ -738,6 +743,7 @@ export default function SettingsPage({parakeetModel,uiLanguage,preferredLanguage,+ chineseScriptPreference,cloudTranscriptionProvider,cloudTranscriptionModel,cloudTranscriptionBaseUrl,@@ -2718,6 +2724,36 @@ export default function SettingsPage({/></SettingsRow></SettingsPanelRow>+ {preferredLanguage === "auto" && (+ <SettingsPanelRow>+ <SettingsRow+ label={t("settings.language.chineseScriptLabel")}+ description={t("settings.language.chineseScriptDescription")}+ >+ <Select+ value={chineseScriptPreference}+ onValueChange={(value: ChineseScriptPreference) =>+ updateTranscriptionSettings({ chineseScriptPreference: value })+ }+ >+ <SelectTrigger className="h-7 w-44 text-xs rounded-lg px-2.5 [&>svg]:h-3 [&>svg]:w-3">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="as-transcribed">+ {t("settings.language.chineseScriptAsTranscribed")}+ </SelectItem>+ <SelectItem value="simplified">+ {t("settings.language.chineseScriptSimplified")}+ </SelectItem>+ <SelectItem value="traditional">+ {t("settings.language.chineseScriptTraditional")}+ </SelectItem>+ </SelectContent>+ </Select>+ </SettingsRow>+ </SettingsPanelRow>+ )}</SettingsPanel></div>diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex 0515a9e8e..efef900cc 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -9,6 +9,12 @@ import {} from "../utils/urlUtils";import { withSessionRefresh } from "../lib/auth";import { getBaseLanguageCode, getLanguageLabel } from "../utils/languageSupport";+import {+ applyChineseScript,+ mergeWhisperPrompt,+ resolveChineseScriptTarget,+ resolveCleanupLanguage,+} from "../utils/chineseScript";import {createLocalSpeechGateState,getLocalSpeechGateDecision,@@ -315,6 +321,7 @@ class AudioManager {this.skipReasoning = false;this.voiceAgentRequested = false;this.translationRequested = false;+ this.translationApplied = false;this.context = "dictation";this.sttConfig = null;this.lastAudioBlob = null;@@ -400,8 +407,58 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);return words.length > 0 ? words.join(", ") : null;}+ // Script conversion targets whatever the user ends up pasting: the translation+ // target when translating, otherwise the dictation language. Using the STT+ // language here would force zh-TW source audio back to Traditional even when+ // the user asked to translate into Simplified.+ //+ // Only a completed translate step actually moves text into the target language.+ // When translation is unreachable, skipped or fails, the source transcript is+ // what gets pasted, so it must be scripted as the STT language — otherwise a+ // failed ja → zh-CN run would run Japanese through OpenCC (会議の資料 → 会议の数据).+ getEffectiveOutputLanguage(settings) {+ if (this.translationRequested && this.translationApplied) {+ return settings.translationTargetLanguage || "auto";+ }+ return this.getEffectiveSttLanguage(settings);+ }++ // Whisper only accepts language "zh"; script (简体/繁體) is applied here. See #975.+ // No transcript exists yet, so only an explicit zh-CN/zh-TW may bias the prompt.+ getWhisperPrompt(settings = getSettings()) {+ return mergeWhisperPrompt(+ this.getCustomDictionaryPrompt(),+ resolveChineseScriptTarget(+ this.getEffectiveSttLanguage(settings),+ settings.chineseScriptPreference+ )+ );+ }++ // Cleanup runs before the translate step, so it still works in the STT language.+ getCleanupLanguage(settings) {+ return resolveCleanupLanguage(this.getEffectiveSttLanguage(settings));+ }++ finalizeChineseScript(text, settings = getSettings()) {+ return applyChineseScript(+ text,+ resolveChineseScriptTarget(+ this.getEffectiveOutputLanguage(settings),+ settings.chineseScriptPreference,+ text+ )+ );+ }++ // Check the dictionary on its own as well as the full prompt: the echo filter needs+ // 70% of the prompt's words to appear, and a Chinese script bias counts as one more+ // word, which alone pushes a one- or two-term dictionary under the threshold.isDictionaryEcho(text) {- return matchesDictionaryPrompt(text, this.getCustomDictionaryPrompt());+ return (+ matchesDictionaryPrompt(text, this.getCustomDictionaryPrompt()) ||+ matchesDictionaryPrompt(text, this.getWhisperPrompt())+ );}setCallbacks({@@ -489,6 +546,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);setTranslationRequested(requested) {this.translationRequested = requested;+ this.translationApplied = false;}// In translation mode the STT hint is the configured source language, not@@ -1343,7 +1401,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}// Add custom dictionary as initial prompt to help Whisper recognize specific words- const dictionaryPrompt = this.getCustomDictionaryPrompt();+ const dictionaryPrompt = this.getWhisperPrompt();if (dictionaryPrompt) {options.initialPrompt = dictionaryPrompt;}@@ -1754,7 +1812,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);promptMode: "cleanup",customDictionary: getDictionaryHintWords(settings),customPrompt: this.getCustomPrompt(),- language: this.getEffectiveSttLanguage(settings) || "auto",+ language: this.getCleanupLanguage(settings),locale: settings.uiLanguage || "en",...(cleanup.meta || {}),});@@ -1783,7 +1841,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);this.processWithReasoningModel(currentText, route.model, agentName, route.config);try {- return await executeTranslationChain({+ const chainResult = await executeTranslationChain({text,cleanupReachable: route.cleanupReachable,cleanupIsCloud: cleanup.mode === "cloudReason",@@ -1807,7 +1865,15 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);logger.warn("Translation step returned empty text, keeping previous text", {}, channel);this.notifyTranslationFallback("failed");},+ // No fallback toast here: an echoed translation usually means the dictation was+ // already in the target language, which the current app treats as silent success.+ onUnchangedTranslate: () => {+ const { channel } = cleanup.log || {};+ logger.warn("Translation step returned unchanged text, keeping source text", {}, channel);+ },});+ this.translationApplied = chainResult.translated;+ return chainResult;} catch (translateError) {// Translate step threw: raw text is still pasted by the caller. Surface the failure.this.notifyTranslationFallback("failed");@@ -1816,6 +1882,11 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}async processTranscription(text, source) {+ const result = await this.processTranscriptionCore(text, source);+ return this.finalizeChineseScript(result);+ }++ async processTranscriptionCore(text, source) {const normalizedText = typeof text === "string" ? text.trim() : "";if (!normalizedText) {@@ -2135,7 +2206,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);opts.sendLogs = "false";}- const dictionaryPrompt = this.getCustomDictionaryPrompt();+ const dictionaryPrompt = this.getWhisperPrompt(settings);if (dictionaryPrompt) opts.prompt = dictionaryPrompt;// Use withSessionRefresh to handle AUTH_EXPIRED automatically@@ -2187,7 +2258,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);promptMode: "cleanup",customDictionary: getDictionaryHintWords(settings),customPrompt: this.getCustomPrompt(),- language: this.getEffectiveSttLanguage(settings) || "auto",+ language: this.getCleanupLanguage(settings),locale: settings.uiLanguage || "en",sttProvider: result.sttProvider,sttModel: result.sttModel,@@ -2264,7 +2335,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);return {success: true,- text: processedText,+ text: await this.finalizeChineseScript(processedText, settings),rawText,source: "openwhispr",timings,@@ -2322,7 +2393,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);if (!window.electronAPI?.proxyTinfoilTranscription) {throw new Error("Tinfoil transcription is unavailable in this window");}- const dictionaryPrompt = this.getCustomDictionaryPrompt();+ const dictionaryPrompt = this.getWhisperPrompt(apiSettings);const apiCallStart = performance.now();const result = await window.electronAPI.proxyTinfoilTranscription({audioBuffer: await optimizedAudio.arrayBuffer(),@@ -2390,7 +2461,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);// 890 leaves margin for UTF-16 vs codepoint counting drift.const isGroqEndpoint = provider === "groq" || endpoint.includes("api.groq.com");const MAX_PROMPT_CHARS = isGroqEndpoint ? 890 : 900;- let dictionaryPrompt = this.getCustomDictionaryPrompt();+ let dictionaryPrompt = this.getWhisperPrompt(apiSettings);if (dictionaryPrompt) {if (dictionaryPrompt.length > MAX_PROMPT_CHARS) {const originalLength = dictionaryPrompt.length;@@ -3782,7 +3853,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);promptMode: "cleanup",customDictionary: getDictionaryHintWords(stSettings),customPrompt: this.getCustomPrompt(),- language: this.getEffectiveSttLanguage(stSettings) || "auto",+ language: this.getCleanupLanguage(stSettings),locale: stSettings.uiLanguage || "en",sttProvider: this.getStreamingProviderName(),sttModel: streamingSttModel,@@ -3910,6 +3981,11 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}if (finalText) {+ // The batch fallback routes through processTranscription, which already+ // applied the script; only streamed text still needs it.+ if (!usedBatchFallback) {+ finalText = await this.finalizeChineseScript(finalText, stSettings);+ }const tBeforePaste = performance.now();const clientTotalMs = Math.round(tBeforePaste - t0);this.lastAudioMetadata = {diff --git a/src/helpers/translationChain.js b/src/helpers/translationChain.jsindex bf9d48d8b..1739632a9 100644--- a/src/helpers/translationChain.js+++ b/src/helpers/translationChain.js@@ -1,6 +1,11 @@// Pure orchestration for the cleanup-then-translate chain. No imports: callers// inject the actual cleanup/translate calls and logging so this stays node-testable.+function normalizeComparableText(value) {+ if (typeof value !== "string") return value;+ return value.trim().replace(/\s+/g, " ");+}+// Whether the translate step should run: skip only when an explicit source language// equals the target. "auto" (or empty, treated as auto) always translates.export function shouldRunTranslateStep(sourceLanguage, targetLanguage) {@@ -8,7 +13,8 @@ export function shouldRunTranslateStep(sourceLanguage, targetLanguage) {}// Step 1 (optional cleanup) soft-fails to the input text; Step 2 translates unless-// shouldTranslate is false. usedCloudReasoning tracks whether a cloud step actually ran.+// shouldTranslate is false. usedCloudReasoning tracks whether a cloud step actually ran;+// translated tracks whether the output really reached the target language.export async function executeTranslationChain({text,cleanupReachable,@@ -19,9 +25,11 @@ export async function executeTranslationChain({translateIsCloud = false,onCleanupError,onEmptyTranslate,+ onUnchangedTranslate,}) {let out = text;let usedCloudReasoning = false;+ let translated = false;if (cleanupReachable) {try {@@ -36,16 +44,21 @@ export async function executeTranslationChain({}if (shouldTranslate) {- const translated = await runTranslate(out);- if (translated) {- out = translated;+ const translateResult = await runTranslate(out);+ const normalizedResult = normalizeComparableText(translateResult);+ const translationChanged = normalizedResult !== normalizeComparableText(out);+ if (normalizedResult && translationChanged) {+ out = translateResult;+ translated = true;+ } else if (normalizedResult) {+ if (onUnchangedTranslate) onUnchangedTranslate();} else if (onEmptyTranslate) {onEmptyTranslate();}if (translateIsCloud) usedCloudReasoning = true;}- return { text: out, usedCloudReasoning };+ return { text: out, usedCloudReasoning, translated };}// Keep the chain result only when it produced text; an empty/missing resultdiff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.tsindex 28146ff37..67254a14a 100644--- a/src/hooks/useSettings.ts+++ b/src/hooks/useSettings.ts@@ -2,7 +2,12 @@ import React, { createContext, useCallback, useContext, useEffect, useRef } fromimport { useSettingsStore, initializeSettings } from "../stores/settingsStore";import logger from "../utils/logger";import { useLocalStorage } from "./useLocalStorage";-import type { LocalTranscriptionProvider, InferenceMode, SelfHostedType } from "../types/electron";+import type {+ ChineseScriptPreference,+ LocalTranscriptionProvider,+ InferenceMode,+ SelfHostedType,+} from "../types/electron";import type { Snippet } from "../utils/snippets";export interface TranscriptionSettings {@@ -15,6 +20,8 @@ export interface TranscriptionSettings {allowLocalFallback: boolean;fallbackWhisperModel: string;preferredLanguage: string;+ /** When transcription language is Auto, force Chinese output script. See #975. */+ chineseScriptPreference: ChineseScriptPreference;cloudTranscriptionProvider: string;cloudTranscriptionModel: string;cloudTranscriptionBaseUrl?: string;@@ -235,6 +242,7 @@ function useSettingsInternal() {allowLocalFallback: store.allowLocalFallback,fallbackWhisperModel: store.fallbackWhisperModel,preferredLanguage: store.preferredLanguage,+ chineseScriptPreference: store.chineseScriptPreference,cloudTranscriptionProvider: store.cloudTranscriptionProvider,cloudTranscriptionModel: store.cloudTranscriptionModel,cloudTranscriptionBaseUrl: store.cloudTranscriptionBaseUrl,@@ -281,6 +289,7 @@ function useSettingsInternal() {setAllowLocalFallback: store.setAllowLocalFallback,setFallbackWhisperModel: store.setFallbackWhisperModel,setPreferredLanguage: store.setPreferredLanguage,+ setChineseScriptPreference: store.setChineseScriptPreference,setCloudTranscriptionProvider: store.setCloudTranscriptionProvider,setCloudTranscriptionModel: store.setCloudTranscriptionModel,setCloudTranscriptionBaseUrl: store.setCloudTranscriptionBaseUrl,diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex e477f3c83..52da2425d 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -6,7 +6,12 @@"uiLabel": "Sprache der Oberfläche","uiDescription": "Wählen Sie die Sprache für die OpenWhispr-Oberfläche","transcriptionLabel": "Transkriptionssprache",- "transcriptionDescription": "Wählen Sie die Sprache, die Sie sprechen, für genauere Transkription"+ "transcriptionDescription": "Wählen Sie die Sprache, die Sie sprechen, für genauere Transkription",+ "chineseScriptLabel": "Chinesische Schrift (Diktat)",+ "chineseScriptDescription": "Wenn Chinesisch erkannt wird, diktierte Transkripte in vereinfachte oder traditionelle Zeichen umwandeln. Gesprochenes Chinesisch klingt gleich; Whisper liefert nur eine Schrift.",+ "chineseScriptAsTranscribed": "Wie transkribiert belassen",+ "chineseScriptSimplified": "Vereinfacht (简体)",+ "chineseScriptTraditional": "Traditionell (繁體)"},"noteFiles": {"title": "Notizen als Dateien speichern",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 37d5b15b2..811dacfef 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -6,7 +6,12 @@"uiLabel": "Interface language","uiDescription": "Choose the language used throughout OpenWhispr's interface","transcriptionLabel": "Transcription language",- "transcriptionDescription": "Choose the language you speak for more accurate transcription"+ "transcriptionDescription": "Choose the language you speak for more accurate transcription",+ "chineseScriptLabel": "Chinese script (dictation)",+ "chineseScriptDescription": "When Chinese is detected, convert dictated transcripts to Simplified or Traditional characters. Spoken Chinese is the same either way; Whisper only returns one script.",+ "chineseScriptAsTranscribed": "Keep as transcribed",+ "chineseScriptSimplified": "Simplified (简体)",+ "chineseScriptTraditional": "Traditional (繁體)"},"noteFiles": {"title": "Save notes as files",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 34144fa43..ef94b86f3 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -6,7 +6,12 @@"uiLabel": "Idioma de la interfaz","uiDescription": "Elige el idioma usado en la interfaz de OpenWhispr","transcriptionLabel": "Idioma de transcripción",- "transcriptionDescription": "Elige el idioma que hablas para mejorar la precisión"+ "transcriptionDescription": "Elige el idioma que hablas para mejorar la precisión",+ "chineseScriptLabel": "Escritura china (dictado)",+ "chineseScriptDescription": "Cuando se detecte chino, convierte las transcripciones dictadas a caracteres simplificados o tradicionales. El chino hablado suena igual; Whisper solo devuelve una escritura.",+ "chineseScriptAsTranscribed": "Mantener como se transcribió",+ "chineseScriptSimplified": "Simplificado (简体)",+ "chineseScriptTraditional": "Tradicional (繁體)"},"noteFiles": {"title": "Guardar notas como archivos",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex c278b65be..cfe19c4ad 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -6,7 +6,12 @@"uiLabel": "Langue de l'interface","uiDescription": "Choisissez la langue utilisée dans l'interface OpenWhispr","transcriptionLabel": "Langue de transcription",- "transcriptionDescription": "Choisissez la langue que vous parlez pour une transcription plus précise"+ "transcriptionDescription": "Choisissez la langue que vous parlez pour une transcription plus précise",+ "chineseScriptLabel": "Écriture chinoise (dictée)",+ "chineseScriptDescription": "Lorsque le chinois est détecté, convertir les transcriptions dictées en caractères simplifiés ou traditionnels. Le chinois parlé sonne pareil ; Whisper ne renvoie qu'une écriture.",+ "chineseScriptAsTranscribed": "Garder tel que transcrit",+ "chineseScriptSimplified": "Simplifié (简体)",+ "chineseScriptTraditional": "Traditionnel (繁體)"},"noteFiles": {"title": "Enregistrer les notes en fichiers",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex d0538d61f..a68aca523 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -6,7 +6,12 @@"uiLabel": "Lingua dell'interfaccia","uiDescription": "Scegli la lingua usata nell'interfaccia di OpenWhispr","transcriptionLabel": "Lingua di trascrizione",- "transcriptionDescription": "Scegli la lingua che parli per una trascrizione più accurata"+ "transcriptionDescription": "Scegli la lingua che parli per una trascrizione più accurata",+ "chineseScriptLabel": "Scrittura cinese (dettatura)",+ "chineseScriptDescription": "Quando viene rilevato il cinese, converte le trascrizioni dettate in caratteri semplificati o tradizionali. Il cinese parlato suona uguale; Whisper restituisce una sola scrittura.",+ "chineseScriptAsTranscribed": "Mantieni come trascritto",+ "chineseScriptSimplified": "Semplificato (简体)",+ "chineseScriptTraditional": "Tradizionale (繁體)"},"noteFiles": {"title": "Salva note come file",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex f7ae81ff7..24e7ed5ca 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -6,7 +6,12 @@"uiLabel": "インターフェース言語","uiDescription": "OpenWhispr のインターフェースで使用する言語を選択","transcriptionLabel": "文字起こし言語",- "transcriptionDescription": "より正確な文字起こしのために話す言語を選択"+ "transcriptionDescription": "より正確な文字起こしのために話す言語を選択",+ "chineseScriptLabel": "中国語の字体(ディクテーション)",+ "chineseScriptDescription": "中国語が検出されたとき、ディクテーションの文字起こしを簡体字または繁体字に変換します。話し言葉は同じでも、Whisperはどちらか一方の字体だけを返します。",+ "chineseScriptAsTranscribed": "文字起こしのまま",+ "chineseScriptSimplified": "簡体字 (简体)",+ "chineseScriptTraditional": "繁体字 (繁體)"},"noteFiles": {"title": "ノートをファイルとして保存",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex 0edf01369..4b79b1486 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -6,7 +6,12 @@"uiLabel": "Idioma da interface","uiDescription": "Escolha o idioma usado na interface do OpenWhispr","transcriptionLabel": "Idioma de transcrição",- "transcriptionDescription": "Escolha o idioma que você fala para maior precisão"+ "transcriptionDescription": "Escolha o idioma que você fala para maior precisão",+ "chineseScriptLabel": "Escrita chinesa (ditado)",+ "chineseScriptDescription": "Quando o chinês for detectado, converter as transcrições ditadas para caracteres simplificados ou tradicionais. O chinês falado soa igual; o Whisper só retorna uma escrita.",+ "chineseScriptAsTranscribed": "Manter como transcrito",+ "chineseScriptSimplified": "Simplificado (简体)",+ "chineseScriptTraditional": "Tradicional (繁體)"},"noteFiles": {"title": "Salvar notas como arquivos",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 44a9a6865..934e706d1 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -6,7 +6,12 @@"uiLabel": "Язык интерфейса","uiDescription": "Выберите язык интерфейса OpenWhispr","transcriptionLabel": "Язык транскрипции",- "transcriptionDescription": "Выберите язык, на котором вы говорите, для более точной транскрипции"+ "transcriptionDescription": "Выберите язык, на котором вы говорите, для более точной транскрипции",+ "chineseScriptLabel": "Китайская письменность (диктовка)",+ "chineseScriptDescription": "Когда обнаружен китайский, преобразовать надиктованные транскрипты в упрощенные или традиционные иероглифы. На слух китайский одинаков; Whisper возвращает только одну письменность.",+ "chineseScriptAsTranscribed": "Оставить как распознано",+ "chineseScriptSimplified": "Упрощенный (简体)",+ "chineseScriptTraditional": "Традиционный (繁體)"},"noteFiles": {"title": "Сохранять заметки как файлы",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex fc402b4df..eb732ee1b4 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -6,7 +6,12 @@"uiLabel": "界面语言","uiDescription": "选择 OpenWhispr 界面使用的语言","transcriptionLabel": "转录语言",- "transcriptionDescription": "选择你说话的语言,以提高转录准确率"+ "transcriptionDescription": "选择你说话的语言,以提高转录准确率",+ "chineseScriptLabel": "中文书写(听写)",+ "chineseScriptDescription": "检测到中文时,将听写的转录结果转换为简体或繁体。口语听起来一样;Whisper 只会输出一种字形。",+ "chineseScriptAsTranscribed": "保持转录原样",+ "chineseScriptSimplified": "简体",+ "chineseScriptTraditional": "繁体"},"noteFiles": {"title": "将笔记保存为文件",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex cc1d1c81c..0ea32af26 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -6,7 +6,12 @@"uiLabel": "介面語言","uiDescription": "選擇 OpenWhispr 介面使用的語言","transcriptionLabel": "轉錄語言",- "transcriptionDescription": "選擇你說話的語言,以提高轉錄準確度"+ "transcriptionDescription": "選擇你說話的語言,以提高轉錄準確度",+ "chineseScriptLabel": "中文書寫(語音輸入)",+ "chineseScriptDescription": "偵測到中文時,將語音輸入的轉錄結果轉換為簡體或繁體。口語聽起來一樣;Whisper 只會輸出一種字形。",+ "chineseScriptAsTranscribed": "保持轉錄原樣",+ "chineseScriptSimplified": "簡體",+ "chineseScriptTraditional": "繁體"},"noteFiles": {"title": "將筆記儲存為檔案",diff --git a/src/services/BaseReasoningService.ts b/src/services/BaseReasoningService.tsindex 5d9a0f99b..c9a069966 100644--- a/src/services/BaseReasoningService.ts+++ b/src/services/BaseReasoningService.ts@@ -1,5 +1,6 @@import { getCleanupSystemPrompt } from "../config/prompts";import { getSettings } from "../stores/settingsStore";+import { resolveCleanupLanguage } from "../utils/chineseScript";import { getDictionaryHintWords } from "../utils/snippets";export interface ReasoningConfig {@@ -22,8 +23,11 @@ export abstract class BaseReasoningService {return getDictionaryHintWords(getSettings());}+ // Auto must remain auto here: zh-CN/zh-TW instructions make cleanup write its+ // entire response in Chinese before the transcription language is known. The+ // final deterministic script pass handles likely-Chinese output instead. See #975.protected getPreferredLanguage(): string {- return getSettings().preferredLanguage || "auto";+ return resolveCleanupLanguage(getSettings().preferredLanguage);}protected getUiLanguage(): string {diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex 8b14a7a95..beb2f36d1 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -6,7 +6,12 @@ import { chooseDictionaryStartupAction } from "../helpers/dictionaryStartup";import { useStreamingProvidersStore } from "./streamingProvidersStore";import logger from "../utils/logger";import whisperVadConstants from "../constants/whisperVad.json";-import type { LocalTranscriptionProvider, InferenceMode, SelfHostedType } from "../types/electron";+import type {+ ChineseScriptPreference,+ LocalTranscriptionProvider,+ InferenceMode,+ SelfHostedType,+} from "../types/electron";import type { GoogleCalendarAccount } from "../types/calendar";import { PROMPT_KIND_LIST, type PromptKind } from "../config/prompts/registry";import {@@ -21,6 +26,7 @@ import {type InferenceScopeDefinition,type InferenceScopeStoreKeys,} from "../config/inferenceScopes";+import { normalizeChineseScriptPreference } from "../utils/chineseScript";import type {TranscriptionSettings,CleanupSettings,@@ -590,6 +596,7 @@ export interface SettingsStatesetAllowLocalFallback: (value: boolean) => void;setFallbackWhisperModel: (value: string) => void;setPreferredLanguage: (value: string) => void;+ setChineseScriptPreference: (value: ChineseScriptPreference) => void;setCloudTranscriptionProvider: (value: string) => void;setCloudTranscriptionModel: (value: string) => void;setCloudTranscriptionBaseUrl: (value: string) => void;@@ -944,6 +951,9 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({allowLocalFallback: readBoolean("allowLocalFallback", false),fallbackWhisperModel: readString("fallbackWhisperModel", "base"),preferredLanguage: readString("preferredLanguage", "auto"),+ chineseScriptPreference: normalizeChineseScriptPreference(+ readString("chineseScriptPreference", "as-transcribed")+ ),cloudTranscriptionProvider: readString("cloudTranscriptionProvider", "openai"),cloudTranscriptionModel: readString("cloudTranscriptionModel", "gpt-4o-mini-transcribe"),cloudTranscriptionBaseUrl: readString(@@ -1354,6 +1364,8 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({setAllowLocalFallback: createBooleanSetter("allowLocalFallback"),setFallbackWhisperModel: createStringSetter("fallbackWhisperModel"),setPreferredLanguage: createStringSetter("preferredLanguage"),+ setChineseScriptPreference: (value: ChineseScriptPreference) =>+ createStringSetter("chineseScriptPreference")(normalizeChineseScriptPreference(value)),setCloudTranscriptionProvider: createStringSetter("cloudTranscriptionProvider"),setCloudTranscriptionModel: createStringSetter("cloudTranscriptionModel"),setCloudTranscriptionBaseUrl: createStringSetter("cloudTranscriptionBaseUrl"),@@ -1815,6 +1827,8 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({s.setFallbackWhisperModel(settings.fallbackWhisperModel);if (settings.preferredLanguage !== undefined)s.setPreferredLanguage(settings.preferredLanguage);+ if (settings.chineseScriptPreference !== undefined)+ s.setChineseScriptPreference(settings.chineseScriptPreference);if (settings.cloudTranscriptionProvider !== undefined)s.setCloudTranscriptionProvider(settings.cloudTranscriptionProvider);if (settings.cloudTranscriptionModel !== undefined)diff --git a/src/types/electron.ts b/src/types/electron.tsindex d0330c747..589056768 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -3,6 +3,8 @@ import type { TinfoilCatalogModel } from "../models/tinfoilModels";export type LocalTranscriptionProvider = "whisper" | "nvidia";+export type ChineseScriptPreference = "simplified" | "traditional" | "as-transcribed";+export type InferenceMode = "openwhispr" | "providers" | "local" | "self-hosted" | "enterprise";export type SelfHostedType = "openai-compatible" | "lan";diff --git a/src/utils/chineseScript.js b/src/utils/chineseScript.jsnew file mode 100644index 000000000..4ef408347--- /dev/null+++ b/src/utils/chineseScript.js@@ -0,0 +1,161 @@+/**+ * Chinese script preference helpers for Whisper-family STT.+ *+ * Whisper language codes only expose "zh", so zh-CN / zh-TW / auto all share the+ * same STT language hint. Script choice is applied after transcription so+ * Simplified vs Traditional is deterministic. An explicit zh-CN / zh-TW also+ * biases the Whisper prompt; auto never does, because the bias would skew the+ * language detection it depends on.+ *+ * Scope: dictation (audioManager) and history retry (ControlPanel). Meeting+ * transcription and uploaded audio strip zh-CN / zh-TW to "zh" and store the+ * response unconverted; the setting's copy is worded to match. Widening it means+ * converting at those sinks too, before the transcript is persisted.+ *+ * See #975.+ */++const HAN_RE = /\p{Script=Han}/u;+// Kana and Hangul never appear in Chinese, so either one rules the text out.+const KANA_RE = /[\u3040-\u30ff\u31f0-\u31ff\uff66-\uff9f]/;+const HANGUL_RE = /[\u1100-\u11ff\u3130-\u318f\uac00-\ud7af]/;++// Auto mode must be conservative: Han is shared by Chinese and Japanese. These+// signals use forms that differ from modern Japanese. Shared forms and phrases+// such as 開, 電, 設定 and 資料 are deliberately absent: without a distinct+// character there is no reliable way to distinguish kanji-only Japanese.+const SIMPLIFIED_CHINESE_VARIANT_RE =+ /[这们吗简软网语汉习说发东车门问间书见长爱据实认让给还过边达选进运远违连迟适应际标亲亿优仅从众气请谢听读卖产业电备复历压类总处线证验权转导报记试计机传云丰动务场图库录页价关规办觉坏变删乐广设]/;+const TRADITIONAL_CHINESE_VARIANT_RE =+ /[這們嗎體說發據實讓邊遲應氣條聽讀寫賣兒經廣樂觀號國學會產歷壓總處證驗權轉傳豐圖錄價關辦覺壞變刪]/;++/** @typedef {"simplified" | "traditional" | "as-transcribed"} ChineseScriptPreference */+/** @typedef {"simplified" | "traditional"} ChineseScriptTarget */++const VALID_PREFERENCES = new Set(["simplified", "traditional", "as-transcribed"]);++let convertersPromise = null;++// opencc-js ships ~1.2 MB of dictionaries. Import it on first conversion rather+// than at module load, so the renderer bundle stays lean for everyone who never+// dictates Chinese.+function getConverters() {+ if (!convertersPromise) {+ convertersPromise = import("opencc-js").then((OpenCC) => ({+ // twp includes Taiwan phrase variants (軟體) that plain tw misses.+ toSimplified: OpenCC.Converter({ from: "twp", to: "cn" }),+ toTraditional: OpenCC.Converter({ from: "cn", to: "twp" }),+ }));+ }+ return convertersPromise;+}++/**+ * @param {string | null | undefined} value+ * @returns {ChineseScriptPreference}+ */+export function normalizeChineseScriptPreference(value) {+ if (VALID_PREFERENCES.has(value)) return value;+ return "as-transcribed";+}++/**+ * Whether text has positive evidence of being Chinese rather than merely+ * containing Han. Kana/Hangul rule it out, while short or mixed-script text with+ * no Chinese-specific variants/phrases stays ambiguous and is left untouched.+ *+ * @param {string | null | undefined} text+ * @returns {boolean}+ */+export function isChineseText(text) {+ if (!text) return false;+ if (KANA_RE.test(text) || HANGUL_RE.test(text)) return false;+ return SIMPLIFIED_CHINESE_VARIANT_RE.test(text) || TRADITIONAL_CHINESE_VARIANT_RE.test(text);+}++/**+ * Resolve the script target from preferred language + auto-detect preference.+ *+ * zh-CN / zh-TW are an explicit user assertion and always win. On auto the+ * preference applies only to text that actually looks Chinese — otherwise+ * Japanese and Korean dictation gets rewritten (会議の資料 → 会议の数据).+ *+ * Omit `text` when no transcript exists yet (Whisper prompt building): without+ * it only an explicit language can be trusted, since biasing the prompt toward+ * Chinese would corrupt the very auto-detection it is scoped to.+ *+ * @param {string | null | undefined} preferredLanguage+ * @param {string | null | undefined} chineseScriptPreference+ * @param {string | null | undefined} [text]+ * @returns {ChineseScriptTarget | null}+ */+export function resolveChineseScriptTarget(preferredLanguage, chineseScriptPreference, text) {+ if (preferredLanguage === "zh-CN") return "simplified";+ if (preferredLanguage === "zh-TW") return "traditional";++ if ((!preferredLanguage || preferredLanguage === "auto") && isChineseText(text)) {+ const preference = normalizeChineseScriptPreference(chineseScriptPreference);+ if (preference === "simplified") return "simplified";+ if (preference === "traditional") return "traditional";+ }++ return null;+}++/**+ * Language code passed to cleanup/reasoning prompts. Auto stays auto: specifying+ * zh-CN / zh-TW tells cleanup to write its entire response in Chinese, which is+ * unsafe before the transcription language is known. The deterministic final+ * conversion still applies the selected script to likely-Chinese output.+ *+ * @param {string | null | undefined} preferredLanguage+ * @returns {string}+ */+export function resolveCleanupLanguage(preferredLanguage) {+ if (preferredLanguage && preferredLanguage !== "auto") return preferredLanguage;+ return "auto";+}++/**+ * Short Whisper prompt bias so the model prefers the target character set.+ *+ * @param {ChineseScriptTarget | null} target+ * @returns {string | null}+ */+export function getChineseScriptPromptBias(target) {+ if (target === "simplified") {+ return "以下是简体中文。语言、学习、软件、网络。";+ }+ if (target === "traditional") {+ return "以下是繁體中文。語言、學習、軟體、網路。";+ }+ return null;+}++/**+ * @param {string | null | undefined} text+ * @param {ChineseScriptTarget | null} target+ * @returns {Promise<string>}+ */+export async function applyChineseScript(text, target) {+ if (!text || !target) return text || "";+ if (!HAN_RE.test(text)) return text;++ const { toSimplified, toTraditional } = await getConverters();+ return target === "simplified" ? toSimplified(text) : toTraditional(text);+}++/**+ * Merge dictionary words with an optional Chinese script bias for Whisper prompts.+ *+ * @param {string | null | undefined} dictionaryPrompt+ * @param {ChineseScriptTarget | null} target+ * @returns {string | null}+ */+export function mergeWhisperPrompt(dictionaryPrompt, target) {+ const bias = getChineseScriptPromptBias(target);+ const dict = typeof dictionaryPrompt === "string" ? dictionaryPrompt.trim() : "";+ if (bias && dict) return `${bias} ${dict}`;+ if (bias) return bias;+ return dict || null;+}diff --git a/test/helpers/chineseScript.test.js b/test/helpers/chineseScript.test.jsnew file mode 100644index 000000000..e324dc5b7--- /dev/null+++ b/test/helpers/chineseScript.test.js@@ -0,0 +1,147 @@+const test = require("node:test");+const assert = require("node:assert/strict");++async function load() {+ return import("../../src/utils/chineseScript.js");+}++test("normalizeChineseScriptPreference defaults unknown values", async () => {+ const { normalizeChineseScriptPreference } = await load();+ assert.equal(normalizeChineseScriptPreference("simplified"), "simplified");+ assert.equal(normalizeChineseScriptPreference("traditional"), "traditional");+ assert.equal(normalizeChineseScriptPreference("as-transcribed"), "as-transcribed");+ assert.equal(normalizeChineseScriptPreference("nope"), "as-transcribed");+ assert.equal(normalizeChineseScriptPreference(undefined), "as-transcribed");+});++test("resolveChineseScriptTarget: zh-CN / zh-TW override auto preference", async () => {+ const { resolveChineseScriptTarget } = await load();+ assert.equal(resolveChineseScriptTarget("zh-CN", "traditional"), "simplified");+ assert.equal(resolveChineseScriptTarget("zh-TW", "simplified"), "traditional");+ assert.equal(resolveChineseScriptTarget("en", "simplified"), null);+});++test("isChineseText distinguishes Chinese from Japanese and Korean", async () => {+ const { isChineseText } = await load();+ assert.equal(isChineseText("这是简体中文"), true);+ assert.equal(isChineseText("這是繁體中文"), true);+ assert.equal(isChineseText("这是 OpenAI 的 API"), true);+ assert.equal(isChineseText("今天天气很好"), true);+ assert.equal(isChineseText("今天天氣很好"), true);+ assert.equal(isChineseText("Hello 世界"), false);+ assert.equal(isChineseText("Meet at 東京駅"), false);+ assert.equal(isChineseText("東京駅"), false);+ assert.equal(isChineseText("会議資料"), false);+ assert.equal(isChineseText("開発資料"), false);+ assert.equal(isChineseText("設定変更"), false);+ assert.equal(isChineseText("電気"), false);+ assert.equal(isChineseText("資料確認"), false);+ assert.equal(isChineseText("導入試験"), false);+ assert.equal(isChineseText("会議の資料を確認してください"), false);+ assert.equal(isChineseText("今日は時間がありますか"), false);+ assert.equal(isChineseText("한국어 漢字 텍스트"), false);+ assert.equal(isChineseText("hello world"), false);+ assert.equal(isChineseText(""), false);+ assert.equal(isChineseText(undefined), false);+});++test("resolveChineseScriptTarget: auto applies preference only to Chinese text", async () => {+ const { resolveChineseScriptTarget } = await load();+ assert.equal(resolveChineseScriptTarget("auto", "simplified", "這是中文"), "simplified");+ assert.equal(resolveChineseScriptTarget("auto", "traditional", "这是中文"), "traditional");+ assert.equal(resolveChineseScriptTarget("auto", "as-transcribed", "这是中文"), null);+ assert.equal(resolveChineseScriptTarget(undefined, "simplified", "这是中文"), "simplified");+ // Japanese, Korean and non-CJK must never be rewritten. See #975.+ assert.equal(resolveChineseScriptTarget("auto", "simplified", "会議の資料"), null);+ assert.equal(resolveChineseScriptTarget("auto", "simplified", "会議資料"), null);+ assert.equal(resolveChineseScriptTarget("auto", "simplified", "Meet at 東京駅"), null);+ assert.equal(resolveChineseScriptTarget("auto", "simplified", "한국어 漢字"), null);+ assert.equal(resolveChineseScriptTarget("auto", "simplified", "hello world"), null);+});++test("resolveChineseScriptTarget: without text only explicit zh-CN / zh-TW apply", async () => {+ const { resolveChineseScriptTarget } = await load();+ assert.equal(resolveChineseScriptTarget("zh-CN", "as-transcribed"), "simplified");+ assert.equal(resolveChineseScriptTarget("zh-TW", "as-transcribed"), "traditional");+ assert.equal(resolveChineseScriptTarget("auto", "simplified"), null);+ assert.equal(resolveChineseScriptTarget("auto", "traditional"), null);+});++test("resolveCleanupLanguage keeps auto until the transcription language is known", async () => {+ const { resolveCleanupLanguage } = await load();+ // Cleanup must never be told to answer in Chinese before the language is known,+ // so the script preference is deliberately not an input here.+ assert.equal(resolveCleanupLanguage("auto"), "auto");+ assert.equal(resolveCleanupLanguage(""), "auto");+ assert.equal(resolveCleanupLanguage(undefined), "auto");+ assert.equal(resolveCleanupLanguage("zh-CN"), "zh-CN");+ assert.equal(resolveCleanupLanguage("zh-TW"), "zh-TW");+ assert.equal(resolveCleanupLanguage("ja"), "ja");+});++test("applyChineseScript converts traditional to simplified", async () => {+ const { applyChineseScript } = await load();+ assert.equal(await applyChineseScript("這是繁體中文軟體", "simplified"), "这是繁体中文软件");+});++test("applyChineseScript converts simplified to traditional Taiwan phrases", async () => {+ const { applyChineseScript } = await load();+ assert.equal(await applyChineseScript("这是简体中文软件", "traditional"), "這是簡體中文軟體");+});++test("applyChineseScript leaves non-CJK and empty text alone", async () => {+ const { applyChineseScript } = await load();+ assert.equal(await applyChineseScript("hello world", "simplified"), "hello world");+ assert.equal(await applyChineseScript("", "simplified"), "");+ assert.equal(await applyChineseScript("mixed 軟體 ok", null), "mixed 軟體 ok");+});++test("applyChineseScript is idempotent for the same target", async () => {+ const { applyChineseScript } = await load();+ // Text that is already in the target script must survive untouched, so a+ // transcript never shifts characters just by passing through twice.+ const toSimplified = await applyChineseScript("這是繁體中文軟體", "simplified");+ assert.equal(await applyChineseScript(toSimplified, "simplified"), toSimplified);++ // Ambiguous simplified chars (干/后/面) pick one traditional form; re-running+ // must not pick a different one.+ for (const input of ["干净的头发", "他很干练", "面条和方便面", "皇后在后面"]) {+ const once = await applyChineseScript(input, "traditional");+ assert.equal(await applyChineseScript(once, "traditional"), once, `not idempotent: ${input}`);+ }+});++test("applyChineseScript is a no-op for Japanese and Korean when target is null", async () => {+ const { applyChineseScript, resolveChineseScriptTarget } = await load();+ for (const text of ["会議の資料を確認してください", "한국어 漢字 텍스트"]) {+ const target = resolveChineseScriptTarget("auto", "simplified", text);+ assert.equal(target, null);+ assert.equal(await applyChineseScript(text, target), text);+ }+});++test("Whisper prompt bias and merge", async () => {+ const { getChineseScriptPromptBias, mergeWhisperPrompt } = await load();+ assert.match(getChineseScriptPromptBias("simplified"), /简体/);+ assert.match(getChineseScriptPromptBias("traditional"), /繁體/);+ assert.equal(getChineseScriptPromptBias(null), null);+ assert.equal(mergeWhisperPrompt("foo, bar", "simplified").includes("foo, bar"), true);+ assert.match(mergeWhisperPrompt(null, "simplified"), /简体/);+ assert.equal(mergeWhisperPrompt("foo", null), "foo");+ assert.equal(mergeWhisperPrompt(" ", null), null);+});++test("mergeWhisperPrompt puts the bias first so prompt truncation keeps it", async () => {+ const { mergeWhisperPrompt, getChineseScriptPromptBias } = await load();+ const bias = getChineseScriptPromptBias("simplified");+ const dictionary = Array.from({ length: 400 }, (_, i) => `term${i}`).join(", ");+ const prompt = mergeWhisperPrompt(dictionary, "simplified");+ assert.equal(prompt.startsWith(bias), true);++ // audioManager truncates to MAX_PROMPT_CHARS then back to the last comma;+ // the bias sits ahead of every dictionary word, so it always survives.+ const MAX_PROMPT_CHARS = 890;+ assert.equal(prompt.length > MAX_PROMPT_CHARS, true);+ const truncated = prompt.slice(0, MAX_PROMPT_CHARS);+ assert.equal(truncated.slice(0, truncated.lastIndexOf(",")).startsWith(bias), true);+});diff --git a/test/helpers/translationChain.test.js b/test/helpers/translationChain.test.jsindex 78943d487..e8b6295e0 100644--- a/test/helpers/translationChain.test.js+++ b/test/helpers/translationChain.test.js@@ -15,6 +15,7 @@ function makeOpts(overrides = {}) {runTranslate: async () => null,onCleanupError: () => {},onEmptyTranslate: () => {},+ onUnchangedTranslate: () => {},...overrides,};}@@ -111,6 +112,25 @@ test("translate returns empty: onEmptyTranslate fires, cleaned text kept", asyncassert.equal(result.text, "cleaned");});+test("translate echoes its input: onUnchangedTranslate fires, source text kept", async () => {+ const { executeTranslationChain } = await load();+ let unchangedCalled = false;++ const result = await executeTranslationChain(+ makeOpts({+ runCleanup: async () => "cleaned source",+ runTranslate: async () => " cleaned source ",+ onUnchangedTranslate: () => {+ unchangedCalled = true;+ },+ })+ );++ assert.equal(unchangedCalled, true);+ assert.equal(result.text, "cleaned source");+ assert.equal(result.translated, false);+});+test("shouldTranslate false: translate never called, cleaned text returned", async () => {const { executeTranslationChain } = await load();let translateCalled = false;@@ -303,3 +323,44 @@ test("resolveTranslatedText: non-empty chain result replaces finalText", async (assert.equal(resolveTranslatedText("streamed text", { text: "traducido" }), "traducido");});++// `translated` tells the caller whether the output is really in the target language.+// audioManager keys Chinese script conversion off it: scripting a failed translation's+// source-language fallback as the target corrupts it (ja 会議の資料 → 会议の数据).+test("translated: true only when the translate step produced changed text", async () => {+ const { executeTranslationChain } = await load();++ const ok = await executeTranslationChain(makeOpts({ runTranslate: async () => "translated" }));+ assert.equal(ok.translated, true);+ assert.equal(ok.text, "translated");+});++test("translated: false when the translate step returns empty", async () => {+ const { executeTranslationChain } = await load();++ const result = await executeTranslationChain(+ makeOpts({ runCleanup: async () => "cleaned", runTranslate: async () => "" })+ );+ assert.equal(result.translated, false);+ assert.equal(result.text, "cleaned");+});++test("translated: false when the translate step echoes the source", async () => {+ const { executeTranslationChain } = await load();++ const result = await executeTranslationChain(+ makeOpts({ runCleanup: async () => "会議の資料", runTranslate: async (text) => text })+ );+ assert.equal(result.translated, false);+ assert.equal(result.text, "会議の資料");+});++test("translated: false when the translate step is skipped", async () => {+ const { executeTranslationChain } = await load();++ const result = await executeTranslationChain(+ makeOpts({ shouldTranslate: false, runTranslate: async () => "translated" })+ );+ assert.equal(result.translated, false);+ assert.equal(result.text, "raw");+});