Skip to content

Doubao-powered voice input for Linux, Wayland and Omarchy

release: 1.7.0 个人语音评测与输入稳定性修复 (#78)

Leyang8842fded9259
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index b9f87c4..ae3d1a8 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -58,7 +58,7 @@ jobs:
run: |
python -m unittest -v \
tests.unit.test_delivery tests.unit.test_gesture tests.unit.test_input_worker \
- tests.unit.test_manual_safety tests.unit.test_plugin_launch tests.unit.test_polish \
+ tests.unit.test_manual_safety tests.unit.test_plugin_launch tests.unit.test_polish tests.unit.test_polish_transport \
tests.unit.test_polish_preview tests.unit.test_reasoning tests.unit.test_settings \
tests.unit.test_updates tests.unit.test_update_install tests.unit.test_personal tests.unit.test_personal_corrections tests.unit.test_speech_eval tests.contracts.test_version_check tests.unit.test_voice_motion
python -m compileall -q src/doubao_input packaging
@@ -99,6 +99,24 @@ jobs:
path: artifacts/verification/personal-ui
if-no-files-found: warn
retention-days: 14
+ - name: Check credential ownership through real GTK controls
+ env:
+ GTK_A11Y: none
+ PYTHONPATH: src:.
+ ASR_UI_SCREENSHOTS: artifacts/verification/asr-key-ui
+ run: |
+ for language in en zh_CN; do
+ ASR_UI_LANGUAGE="$language" timeout --signal=TERM --kill-after=5s 35s xvfb-run -a dbus-run-session -- .venv/bin/python tests/manual/asr_key_ui.py
+ done
+ timeout --signal=TERM --kill-after=5s 35s xvfb-run -a dbus-run-session -- .venv/bin/python tests/manual/refactor_smoke.py
+ - name: Upload synthetic GTK credential UI captures
+ if: always()
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: asr-key-ui-captures
+ path: artifacts/verification/asr-key-ui
+ if-no-files-found: warn
+ retention-days: 14
- name: Upload coverage report
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index eca1223..a670b51 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,15 @@
- macOS: expose English, Simplified Chinese and system language selection in General settings with immediate switching and persistent preferences.
+## 1.7.0
+
+- Add native Mac/Linux personal speech evaluation with local recordings, reviewed references, same-audio ASR/hotword/polishing comparisons and protected-term scoring.
+- Carry selected words and exact occurrence positions into explicitly confirmed corrections.
+- Record stop-to-recognition, polishing and delivery timings; compute Mac evaluation statistics in the background.
+- Persist API-key drafts across onboarding/settings provider changes and verify credential ownership.
+- Cancel interrupted polishing HTTP/TLS requests, reject redirects and incomplete results, and recover the final request worker.
+- Keep recording, retry delivery, microphone checks, evaluations and updates mutually exclusive; mark synthetic Mac paste events.
+
## 1.6.0
- Send a conservatively bounded personal hotword subset to official Volcengine streaming ASR on Mac and Linux, prioritize confirmed spellings, and show the exact preview.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 980279c..f206cb8 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -79,9 +79,9 @@ For marketplace preparation, use `make marketplace-check` with Gitleaks on PATH
and follow [the publishing checklist](packaging/MARKETPLACE.md). Reports and local
review drafts belong in ignored `artifacts/` and `docs/`, not in release payloads.
-The current public version is `1.6.0`. Keep `pyproject.toml`, `manifest.json` and
+The current public version is `1.7.0`. Keep `pyproject.toml`, `manifest.json` and
`src/doubao_input/product.py` aligned; `python packaging/version_check.py` verifies
-them. A pushed tag such as `v1.6.0` runs all checks and secret scanning, builds app
+them. A pushed tag such as `v1.7.0` runs all checks and secret scanning, builds app
and plugin archives for every supported Python version, creates `SHA256SUMS`, and
publishes the GitHub Release. `workflow_dispatch` performs a non-publishing build.
# Bounded desktop tests
diff --git a/README.md b/README.md
index 636ab05..0b08ff4 100644
--- a/README.md
+++ b/README.md
@@ -268,6 +268,9 @@ as HTML; images and URI lists retain their existing priority. This is best-effor
restoration of one payload, not all original clipboard formats.
A copy made by the user during delivery is never overwritten.
Cancellation stops remaining input and cannot undo text already delivered.
+Standalone Enter does not change the previous dictation's history or word counts.
+On macOS, retries, new dictation and standalone Enter are disabled during a retry
+countdown or pending delivery. Use Escape or **Cancel input** to cancel it.
Failed recognition can preserve partial text; failed paste preserves the result.
The editable recent-text slot is memory-only. Completed dictation attempts are
stored separately in a local 30-day history, with recognition original, final
@@ -278,8 +281,8 @@ up to 200 terms of 80 characters). Official Volcengine ASR sends a length-limite
subset as session hotwords, prioritizing spellings you explicitly confirmed.
The vocabulary page previews the actual subset. Doubao Web and other engines use
this list only as context during AI polishing. This does not retrain the model.
-From an input-history entry, choose **Correct & remember…**, enter the recognized
-term and correct spelling, review the preview, then confirm. Only that explicit
+From an input-history entry, select the wrong term and choose **Correct & remember…**,
+or select it in the dialog to fill it in. Enter the correct spelling, review the preview, then confirm. Only that explicit
action creates memory. Original recognition and polishing output are preserved.
Future polishing receives relevant correction pairs and example contexts as
reference data, never global replacements. You can forget pairs individually;
@@ -309,6 +312,13 @@ Key recording accepts ordinary keyboard keys and modifier combinations. The left
and right variants of Ctrl, Shift, Alt and Meta are treated as the same key.
Automatic detection of every desktop shortcut conflict is not supported.
+The **Speech evaluation** page in Mac Settings and Linux Vocabulary & history
+records local samples and compares the same audio with raw ASR, hotwords, and
+optional polishing. References are only used for scoring. Comparison explicitly
+uploads audio to your paid official ASR; drafts save automatically and recordings
+remain until deleted. Input history also shows stop-to-ASR, polishing, input and
+total waiting times, separately from recording duration and replay timing.
+
## Privacy and limitations
After a recording gesture is confirmed, the default unofficial backend sends the
@@ -512,7 +522,7 @@ validate package metadata and scan for secrets. The current whole-package branch
coverage floor is 55%; desktop UI, WebKit and real-device paths remain included
in the denominator.
-The current release version is **1.6.0**. A `v1.6.0` tag must match every embedded
+The current release version is **1.7.0**. A `v1.7.0` tag must match every embedded
version before CI can publish. Tag releases rebuild both offline app and Omarchy
plugin archives for Python 3.11–3.14 and attach SHA-256 checksums. A manually started
release workflow builds artifacts for inspection but does not publish them. Real
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 418e8e3..0e00285 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -199,15 +199,19 @@ MIME 内容;仅当剪贴板仍是本次识别文字时,才按原始字节恢
两者同时存在时会丢失富文本格式。只有 HTML 时仍按 HTML 恢复,图片和 URI 列表的优先级不变。
恢复只针对选中的一份内容,无法完整还原所有剪贴板格式。用户在输入期间复制的新内容
不会被旧内容覆盖。取消会停止后续输入,但无法撤回已经发送的文字。
+单独发送回车不会改变上一条听写的历史状态或词频。Mac 在重试倒计时和输入完成前,
+会禁用重复重试、新听写和独立回车;可按 Esc 或从菜单选择「取消输入」。
识别失败时可能保留已收到的部分文字,粘贴失败时会保留结果。
可编辑的最近文字仍是内存中的单条结果;完成的听写另外保存到本机 30 天历史,记录识别原文、最终文字、润色与输入状态。历史不设条数上限,可在「个人词汇与历史」暂停记录或清空;不记录试说测试、取消的识别、音频或其他应用的键盘输入。
个人词汇每行一个,自动保存,最多 200 个,每个最多 80 个字符。官方火山引擎 ASR 会把部分词汇作为热词随本次请求发送,优先使用你确认过的词;受接口长度限制,无法一次传入全部词库,页面会显示实际发送的热词预览。豆包 Web 和其他引擎仅在 AI 润色时参考词库,不会训练识别模型。
-在输入历史中点击「纠正并记住…」,填写误识别的词和正确写法,检查预览,再点击「确认并记住」。只有这一步才保存纠错记忆,识别原文和原来的润色结果都会保留。后续润色遇到同一个错词时,会参考纠错对和当时的语境,不做全局强制替换。可以逐条「忘记」;清空历史或历史过期时,个人词汇和纠错记忆仍会保留。
+在输入历史中点击「纠正并记住…」,选中错词后自动带入(也可手动填写),填写正确写法,检查预览,再点击「确认并记住」。只有这一步才保存纠错记忆,识别原文和原来的润色结果都会保留。后续润色遇到同一个错词时,会参考纠错对和当时的语境,不做全局强制替换。可以逐条「忘记」;清空历史或历史过期时,个人词汇和纠错记忆仍会保留。
本地词频统计已发送的润色结果和你确认过的纠正;「AI 整理高频词」仅把候选词和次数发送至已配置的润色服务,不发送完整历史或纠错语境。候选需选择后才添加。数据各自保存在本机,暂不跨设备同步。
+Mac 设置和 Linux「个人词汇与历史」新增「语音评测」页面:添加样本、本地录音、核对参考文字,再对比原始识别、热词识别和润色结果。草稿自动保存,录音保留到手动删除;点击「开始对比」才会上传录音到已配置的官方 ASR,并产生接口费用。参考文字仅用于评分,不发送给识别或润色服务。输入历史同时显示结束录音后的识别、润色、输入和总等待时间,与录音时长、评测回放时间分开。
+
同一批录音的对照测试可使用[个人语音评测工具](packaging/SPEECH_EVAL.md),分别统计原始 ASR、热词 ASR 和润色后的结果,同时检查本来正确的 Midjourney 是否被误改。也支持离线评分,比较手动收集的其他输入法结果。尚未用个人真实录音测量时,不宣称口音识别率已经提升。
自动粘贴要求能确认 Hyprland 或原生 X11 的目标窗口未变化。
@@ -371,7 +375,7 @@ timeout --kill-after=5s 50s env PYTHONPATH=src python3 tests/manual/x11.py --run
GTK 测试、代码检查、编译、包元数据校验和密钥扫描。覆盖率按整个源码包的分支覆盖率
计算,当前真实门槛为 55%;GTK 界面、WebKit 和实体设备路径没有从分母中排除。
-当前发布版本为 **1.6.0**。只有 `v1.6.0` 标签与所有内置版本完全一致时,CI 才能发布。
+当前发布版本为 **1.7.0**。只有 `v1.7.0` 标签与所有内置版本完全一致时,CI 才能发布。
标签发布会为 Python 3.11–3.14 分别构建独立应用与 Omarchy 插件离线包,并附带 SHA-256
校验文件。手动启动发布工作流只构建供检查的产物,不会公开发布。真实登录、麦克风、
全局按键及桌面行为仍需按人工验收清单检查。
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index 4acd081..1ce7c4b 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -1,47 +1,21 @@
-# Doubao Say 1.6.0
-
-## Personal vocabulary and confirmed corrections
-
-Mac and Linux now send a length-limited subset of personal vocabulary to the
-existing official Volcengine streaming ASR endpoint as session hotwords. Spellings
-you confirmed have priority, and the vocabulary page previews the actual subset.
-Doubao Web and other engines continue using vocabulary during polishing only.
-This does not train a personal recognition model.
-
-Choose Correct & remember from an input-history entry, enter the misrecognized
-term and correct spelling, review the preview, then confirm. Original recognition
-and polishing output remain available. Future polishing uses relevant confirmed
-corrections and example contexts as reference data, with instructions to preserve
-legitimate words in unrelated contexts. It never performs global replacements.
-Forget individual corrections in Personal vocabulary; clearing or expiring
-history retains vocabulary and correction memory. Local frequencies now include
-corrections you explicitly confirmed. AI frequency organization still sends only
-candidate terms and counts, without full transcripts or correction contexts.
-
-## Repeatable speech evaluation
-
-The opt-in Python evaluation CLI compares raw official ASR, hotword ASR and
-optional polishing using identical WAV recordings. It reports character error
-rate, target-term accuracy, protected-term loss, failures and latency P50/P95.
-Offline scoring supports manually collected outputs from other input methods.
-Reference transcripts never enter ASR requests or automatically become vocabulary.
-Reports are local and owner-only; credentials are never included. See the
-[usage guide](https://github.com/quanru/doubao-say/blob/v1.6.0/packaging/SPEECH_EVAL.md).
-The Mac DMG does not bundle the Python evaluation tool or interpreter.
-
-## Download and verification
-
-Choose the Developer ID signed, Apple-notarized arm64 or x86_64 Mac DMG. Linux
-app/plugin archives remain available for Python 3.11–3.14. Settings and login data
-are retained. SHA256SUMS covers both platforms; update.json remains the public
-update source.
-
-Verification covers hotword protocol framing, explicit confirmation, rollback,
-retention, forgetting, context boundaries, scoring failures and negative cases,
-Mac streaming network fixtures, and native personal-data UI checks in both
-supported languages. Linux CI exercises the actual GTK confirmation flow.
-Synthetic fixtures do not prove real microphone accuracy, personal-accent
-improvement, competitor parity or behavior on Intel hardware. Actual personal
-recordings have not been benchmarked.
-
-[Full changes](https://github.com/quanru/doubao-say/compare/v1.5.3...v1.6.0)
+# Doubao Say 1.7.0
+
+## Personal speech evaluation
+
+Mac and Linux now provide an in-app speech evaluation page. Record locally, review what you actually said, then compare the same recording with raw official ASR, personal hotwords and optional polishing. Review character errors, target terms, protected-term loss, failed samples and replay timings. Starting comparison explicitly uploads recordings to your configured paid official ASR. Reference text is only used for scoring and never becomes vocabulary or enters recognition requests. Drafts save automatically; recordings remain until deleted.
+
+## Selected corrections and input timings
+
+Select a wrong term to fill the correction form, review the exact occurrence replacement and confirm before it becomes memory. Original recognition and polishing output remain available. Future polishing uses confirmed corrections as contextual references. Input history shows recognition, remaining polishing, delivery and total waiting time after recording stops. Mac computes evaluation statistics in the background and reads timings in batches.
+
+## Input reliability
+
+API-key drafts survive saves and provider changes across onboarding and settings. Polishing requests support cancellation during connection, TLS and response reads, reject redirects and incomplete output, and free the final request worker after timeout. Recording, retry delivery, microphone checks, evaluation and updates are coordinated. Mac synthetic paste shortcuts carry an event marker to prevent feedback into voice triggers.
+
+## Downloads and verification
+
+Developer ID signed, Apple-notarized Mac DMGs are available for Apple Silicon and Intel. Linux app/plugin archives support Python 3.11–3.14. Settings, login data, vocabulary and history are retained. SHA256SUMS covers all packages; update.json is the public update source.
+
+Automated verification uses synthetic credentials, recordings and loopback network services. It covers protocol framing, selected corrections, scoring, credential persistence, cancellation, input state transitions and native interfaces. Actual personal-accent accuracy, competitor parity, physical microphones, cross-application input and Intel hardware behavior have not been established by these checks.
+
+[Full changes](https://github.com/quanru/doubao-say/compare/v1.6.0...v1.7.0)
diff --git a/SECURITY.md b/SECURITY.md
index 0a9f1bd..5f355bb 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -9,7 +9,7 @@ group membership and `/dev/uinput` permissions before installation.
Recordings are sent to the selected provider for recognition; the microphone-only
check stays local. Volcengine API usage and data handling follow the user's
-account and provider terms. The application does not retain recordings on disk. Optional local input history
+account and provider terms. Daily dictation does not retain recordings on disk. The opt-in speech evaluation page stores local recordings until you delete the samples; starting comparison explicitly uploads them to official ASR. Reference transcripts and labels are used only for scoring. Optional local input history
retains original and final text for a rolling 30 days; it can be disabled or cleared. The clipboard and target application may retain text. Older development
logs can contain transcript excerpts: never attach them without review.
diff --git a/debian/changelog b/debian/changelog
index 7166488..9e43f86 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,10 @@
+doubao-say (1.7.0-1) noble; urgency=medium
+
+ * Add personal speech evaluation, selected corrections and input timings.
+ * Improve API-key persistence, polishing cancellation and input reliability.
+
+ -- doubao-say contributors <[email protected]> Tue, 13 Oct 2026 12:00:00 +0800
+
doubao-say (1.3.1-1) noble; urgency=medium
* Prefer plain text over HTML when restoring the clipboard after dictation.
diff --git a/macos/Package.swift b/macos/Package.swift
index 2c73415..a336fde 100644
--- a/macos/Package.swift
+++ b/macos/Package.swift
@@ -1,6 +1,6 @@
// swift-tools-version: 5.9
import PackageDescription
let package = Package(name: "DoubaoSayCore", platforms: [.macOS(.v13)], targets: [
- .target(name: "DoubaoSayCore", path: "Sources", exclude: ["APIASRClient.swift", "ASRParamsStore.swift", "AppState.swift", "AudioCaptureManager.swift", "AudioDevices.swift", "DoubaoASRClient.swift", "DoubaoSayApp.swift", "HotkeyManager.swift", "OverlayPanel.swift", "OverlayView.swift", "ListeningWaveform.swift", "PasteHelper.swift", "SecretStore.swift", "SettingsWindow.swift", "StartupService.swift", "TranscriptionManager.swift", "UpdateInstaller.swift", "VibekeyReceiver.swift", "WebViewManager.swift", "WindowCapture.swift", "PersonalViews.swift"], sources: ["VoiceMotion.swift", "HotkeyGesture.swift", "ASRResponse.swift", "FinalResultGate.swift", "ShortcutGesture.swift", "MacSettings.swift", "Strings.swift", "PolishDefaults.swift", "PolishClient.swift", "PolishCoordinator.swift", "SeedProtocol.swift", "VibekeyProtocol.swift", "UpdateRelease.swift", "UpdateChecker.swift", "PersonalData.swift", "PersonalCorrections.swift"]),
- .testTarget(name: "DoubaoSayCoreTests", dependencies: ["DoubaoSayCore"], path: "Tests", exclude: ["Transport", "Live", "Network", "Settings"])
+ .target(name: "DoubaoSayCore", path: "Sources", exclude: ["APIASRClient.swift", "ASRParamsStore.swift", "AppState.swift", "AudioCaptureManager.swift", "AudioDevices.swift", "DoubaoASRClient.swift", "DoubaoSayApp.swift", "HotkeyManager.swift", "OverlayPanel.swift", "OverlayView.swift", "ListeningWaveform.swift", "PasteHelper.swift", "SecretStore.swift", "SettingsWindow.swift", "StartupService.swift", "TranscriptionManager.swift", "UpdateInstaller.swift", "VibekeyReceiver.swift", "WebViewManager.swift", "WindowCapture.swift", "PersonalViews.swift", "SpeechEvaluationView.swift", "SpeechEvaluationModel.swift"], sources: ["InputLatency.swift", "SpeechEvaluation.swift", "VoiceMotion.swift", "HotkeyGesture.swift", "ASRResponse.swift", "FinalResultGate.swift", "ShortcutGesture.swift", "MacSettings.swift", "Strings.swift", "PolishDefaults.swift", "PolishClient.swift", "PolishCoordinator.swift", "SeedProtocol.swift", "VibekeyProtocol.swift", "UpdateRelease.swift", "UpdateChecker.swift", "PersonalData.swift", "PersonalCorrections.swift"]),
+ .testTarget(name: "DoubaoSayCoreTests", dependencies: ["DoubaoSayCore"], path: "Tests", exclude: ["Transport", "Live", "Network", "Settings", "Input"])
])
diff --git a/macos/README.zh-CN.md b/macos/README.zh-CN.md
index 0126252..0b9ec1f 100644
--- a/macos/README.zh-CN.md
+++ b/macos/README.zh-CN.md
@@ -16,20 +16,20 @@ open 'build/macos/arm64/Doubao Say.app'
## 首次使用与设置
1. 首次启动会打开“设置”,也可从菜单栏波形图标打开。在“识别服务”中选择豆包账号、火山引擎官方 API 或 Deepgram Nova-3(英语)。豆包使用登录窗口;官方服务填写自己的 API Key,可先测试连接。火山资源 `volc.seedasr.sauc.duration` 已内置,不需要 App ID。Deepgram 使用美式英语、标点和智能格式化。
-2. 保存设置。允许麦克风访问,并从“启用全局快捷键”授予辅助功能权限。系统要求本人输入密码时在系统弹窗完成,不向应用填写系统密码。
+2. 设置会自动保存,无需点击保存按钮。允许麦克风访问,并从“启用全局快捷键”授予辅助功能权限。系统要求本人输入密码时在系统弹窗完成,不向应用填写系统密码。
3. 在“使用准备”中选择麦克风,先进行三秒本地检查,再进行五秒语音测试。语音测试会向已保存的识别服务发送音频,结果只显示在软件内,不粘贴,也不发送回车。全部检查完成后点击“完成设置”,后续启动不再自动打开使用准备。
4. 在目标应用的普通文本输入框中放好光标。默认 `Control+Option+空格`,可在“快捷键”中录制其他组合或单独修饰键;选键不使用麦克风。
5. 短按切换录音;按住达到默认 350 毫秒后说话,松开结束。开启“双击发送回车”时,短按需等待默认 300 毫秒确认,双击结束录音并在输入后发送回车,空闲时双击发送回车。可调整两项阈值或关闭双击。Fn 作为触发键时,其他按键也可结束当前录音。`Esc` 取消,单次最多 60 秒。
-按下触发键后,先在内存保存最多三秒本地预录音,确认单击或长按后再发送到识别服务。双击或取消会丢弃尚未确认的音频。设置更改使用“保存设置”明确提交,录音和检查期间不能提交;已有网页登录、语言和自动粘贴选择保留。
+按下触发键后,先在内存保存最多三秒本地预录音,确认单击或长按后再发送到识别服务。双击或取消会丢弃尚未确认的音频。设置修改后自动保存,录音和检查期间暂缓生效,结束后自动应用;已有网页登录、语言和自动粘贴选择保留。
“通用”中可选择麦克风、剪贴板或辅助功能直接输入、登录时启动、减少动态效果和四种波纹样式。“快捷键”还支持 Vibekey AU05 接收器的三键、两种旋转方向和旋钮按下映射;接收器支持默认关闭。登录时启动通过 macOS 登录项管理,可能需要在系统设置允许;注册失败会明确报错并回滚,不将失败显示为已保存。
## 语音润色
-打开“语音润色”,填写 OpenAI 兼容的 Base URL、API Key 和模型,使用“测试接口”验证,再保存设置。默认关闭。建议使用低延迟小模型,服务商思考开关策略与 Linux 版一致;没有通用的跨服务商关闭思考参数。
+打开“语音润色”,填写 OpenAI 兼容的 Base URL、API Key 和模型,等待自动保存后使用“测试接口”验证。默认关闭。建议使用低延迟小模型,服务商思考开关策略与 Linux 版一致;没有通用的跨服务商关闭思考参数。
-中文、英文提示词分别编辑,可恢复 Linux 版相同的默认值。按转写文字的主要语言选择提示词,与界面语言无关。默认提示词修正明确口误、重复、无意义语气词和有充分上下文的近音错误,整理必要标点、段落与明确列举的列表;不回答转写中的问题,不添加事实。不额外注入 Midscene 等产品示例,也没有个人纠错记忆。
+中文、英文提示词分别编辑,可恢复 Linux 版相同的默认值。按转写文字的主要语言选择提示词,与界面语言无关。默认提示词修正明确口误、重复、无意义语气词和有充分上下文的近音错误,整理必要标点、段落与明确列举的列表;不回答转写中的问题,不添加事实。个人词汇和你明确确认过的纠错会作为上下文参考,不做全局替换,也不额外注入固定产品示例。
转写稳定、低于语音阈值并静音 1.2 秒后启动预润色。音量变化只暂停计时,文字变化才使旧请求失效,避免背景噪声反复发请求。结束录音后可复用同一段文字的预润色结果或仍在运行的请求;不同文字重新请求,旧返回不能上屏。
@@ -37,13 +37,13 @@ open 'build/macos/arm64/Doubao Say.app'
## 文字恢复与隐私
-“最近文字”只保留一条内存文字,可编辑、复制、清除,或点击“三秒后重试”并切换到目标输入框;重试不发送回车。关闭“自动粘贴”后每次手动复制。识别或音频中断时保留部分文字,不自动输入。
+“最近文字”只保留一条内存文字,可编辑、复制、清除,或点击“三秒后重试”并切换到目标输入框。倒计时和输入完成前不能重复重试,也不响应新的听写或独立回车;可按 `Esc` 或从菜单选择“取消输入”。重试不发送回车。关闭“自动粘贴”后每次手动复制。识别或音频中断时保留部分文字,不自动输入。
输入前核对前台进程和原辅助功能输入元素,并等待快捷键修饰键松开。密码框不自动输入。输入目标变化或直接输入不可用时,文字保留在软件内。剪贴板在粘贴后延迟恢复,期间有新复制内容时不恢复;部分应用异步读取剪贴板可能晚于恢复时间。输入和回车前分别检查目标,但系统事件仍存在短暂竞争窗口,需要完全手动控制时关闭自动粘贴。
-录音发送到所选识别服务,不保存本地录音文件。润色启用后,整段文字及停顿预览会发送到配置的接口;识别和模型用量由相应服务商向你的账号计费。会话和 API Key 分别保存在应用专属 macOS 钥匙串条目,登录 WebView 使用临时网站数据存储。偏好不包含凭证;可编辑的单条最近文字退出后消失,但完成的听写另存本机 30 天历史,可暂停或清空。诊断复制不包含转写、Cookie、账号或设备标识。
+普通听写的音频发送到所选识别服务,不保存本地录音文件。“语音评测”中主动录制的样本会保存到本机,直到手动删除;点击“开始对比”后才上传样本。润色启用后,整段文字及停顿预览会发送到配置的接口;识别和模型用量由相应服务商向你的账号计费。会话和 API Key 分别保存在应用专属 macOS 钥匙串条目,登录 WebView 使用临时网站数据存储。偏好不包含凭证;可编辑的单条最近文字退出后消失,但完成的听写另存本机 30 天历史,可暂停或清空。诊断复制不包含转写、Cookie、账号或设备标识。
-更新检查查询项目 GitHub 最新稳定发行版,间隔 24 小时;可手动检查并打开项目发行页,不自动下载安装,不假定 Linux 发行包包含 Mac 安装包。
+更新检查查询项目 GitHub 最新稳定发行版,间隔 24 小时,也可手动检查。在“设置 → 更新”中点击下载并安装后,应用会下载适配当前架构的 Mac 更新包,核对哈希、开发者签名、公证和应用标识,再安装并重启。下载期间可以取消;检查更新本身不会静默安装。没有合格的 Mac 更新包时,可打开发行页查看,不会把 Linux 归档当成 Mac 安装包。
## 验证与分发
@@ -72,7 +72,7 @@ open 'build/macos/arm64/Doubao Say.app'
## 个人词汇与 30 天历史
-「个人词汇」每行输入一个词,自动保存,最多 200 个词,每个不超过 80 个字符。词汇会作为 AI 润色的参考;须配置并启用润色,不会训练 ASR,也不会全局替换近音词。
+「个人词汇」每行输入一个词,自动保存,最多 200 个词,每个不超过 80 个字符。火山引擎官方 ASR 会把符合长度限制的词汇作为本次识别的热词,无需开启润色;豆包 Web 和其他引擎仅在 AI 润色时参考词库。词汇不会训练 ASR,也不会全局替换近音词。
「输入历史」记录本应用的识别原文、最终文字、润色和输入状态。数据仅存本机,超过 30 天自动清理,不记录音频、试说测试或其他应用的键盘输入。可以暂停记录、查看原文、放回最近文字编辑,以及清空历史。
diff --git a/macos/Sources/APIASRClient.swift b/macos/Sources/APIASRClient.swift
index bdecccd..4629a5e 100644
--- a/macos/Sources/APIASRClient.swift
+++ b/macos/Sources/APIASRClient.swift
@@ -17,6 +17,7 @@ extension DoubaoASRClient: ASRTransport {}
final class APIASRClient: ASRTransport {
let provider: RecognitionProvider
private let endpoint: URL?
+ private let hotwords: [String]?
private let queue = DispatchQueue(label: "md.lifeos.doubao-say.api-asr")
private var session: URLSession?
private var socket: URLSessionWebSocketTask?
@@ -36,7 +37,7 @@ final class APIASRClient: ASRTransport {
var onAudioDrained: (() -> Void)?
var onError: (() -> Void)?
var onAuthError: (() -> Void)?
- init(provider: RecognitionProvider, endpoint: URL? = nil) { self.provider = provider; self.endpoint = endpoint }
+ init(provider: RecognitionProvider, endpoint: URL? = nil, hotwords: [String]? = nil) { self.provider = provider; self.endpoint = endpoint; self.hotwords = hotwords }
func connect(apiKey: String) {
let url = endpoint ?? URL(string: provider == .volcengine ? "wss://openspeech.bytedance.com/api/v3/sauc/bigmodel" : "wss://api.deepgram.com/v1/listen?model=nova-3&language=en-US&encoding=linear16&sample_rate=16000&channels=1&interim_results=true&punctuate=true&smart_format=true")!
var request = URLRequest(url: url, timeoutInterval: 5)
@@ -57,7 +58,7 @@ final class APIASRClient: ASRTransport {
self.queue.asyncAfter(deadline: .now() + 5, execute: deadline)
if self.provider == .volcengine {
do {
- let frame = try SeedProtocol.initial(hotwords: (try? PersonalDataStore.shared.recognitionWords()) ?? [])
+ let frame = try SeedProtocol.initial(hotwords: self.hotwords ?? (try? PersonalDataStore.shared.recognitionWords()) ?? [])
task.send(.data(frame)) { error in self.queue.async {
if error != nil { self.fail() } else { self.receive(acknowledgement: true) }
} }
diff --git a/macos/Sources/AppState.swift b/macos/Sources/AppState.swift
index 365333c..83465d9 100644
--- a/macos/Sources/AppState.swift
+++ b/macos/Sources/AppState.swift
@@ -19,6 +19,8 @@ enum RecordingState {
class AppState: ObservableObject {
static let shared = AppState()
+ @Published var evaluationBusy = false
+ @Published var inputPending = false
@Published var updateVersion = ""
@Published var updateStatus = ""
@Published var updateBusy = false
@@ -45,6 +47,7 @@ class AppState: ObservableObject {
func reset() {
recordingState = .idle
+ inputPending = false
transcriptionText = ""
showOverlay = false
errorMessage = nil
diff --git a/macos/Sources/DoubaoASRClient.swift b/macos/Sources/DoubaoASRClient.swift
index ad1f303..9569490 100644
--- a/macos/Sources/DoubaoASRClient.swift
+++ b/macos/Sources/DoubaoASRClient.swift
@@ -122,7 +122,10 @@ final class DoubaoASRClient {
}
private func fail() {
guard !closed else { return }
- close(); onError?()
+ let status = (socket?.response as? HTTPURLResponse)?.statusCode
+ close()
+ if status == 401 || status == 403 { onAuthError?() }
+ else { onError?() }
}
private func pump() {
guard connected, !closed, !sending, let socket = socket else { return }
diff --git a/macos/Sources/DoubaoSayApp.swift b/macos/Sources/DoubaoSayApp.swift
index 861c78f..fef03e4 100644
--- a/macos/Sources/DoubaoSayApp.swift
+++ b/macos/Sources/DoubaoSayApp.swift
@@ -105,9 +105,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
if SettingsStore.shared.value.provider == .doubao { add(L("Sign in to Doubao…", "登录豆包…"), #selector(showLogin)) }
if state.loginStatus == .loggedIn { add(L("Sign out", "退出登录"), #selector(logout)) }
add(L("Copy last result", "复制最近结果"), #selector(copyLast)).isEnabled = !state.lastTranscript.isEmpty
- add(L("Retry input in 3 seconds", "三秒后重试输入"), #selector(retryLast)).isEnabled = !state.lastTranscript.isEmpty && state.recordingState == .idle
+ add(L("Retry input in 3 seconds", "三秒后重试输入"), #selector(retryLast)).isEnabled = !state.lastTranscript.isEmpty && state.recordingState == .idle && !state.inputPending && !state.evaluationBusy
add(L("Clear recent text", "清除最近文字"), #selector(clearLast)).isEnabled = !state.lastTranscript.isEmpty
- add(L("Cancel recording", "取消录音"), #selector(cancelRecording)).isEnabled = state.recordingState != .idle
+ add(L("Cancel input", "取消输入"), #selector(cancelRecording)).isEnabled = state.recordingState != .idle || state.inputPending
let paste = add(L("Automatically paste", "自动粘贴"), #selector(togglePaste))
paste.state = (UserDefaults.standard.object(forKey: "autoPaste") as? Bool ?? true) ? .on : .off
menu.addItem(.separator())
@@ -196,6 +196,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
self?.settingsWindow.updateTitle()
self?.rebuildMenu()
}
+ model.canEvaluate = { [weak self] in self?.transcription.canInstallUpdate ?? false }
transcription.canRecord = { [weak model] in !(model?.testing ?? false) && !(model?.capturing ?? false) }
model.cancelCapture = { [weak self] in self?.hotkey.cancelCapture() }
model.apply = { [weak self] settings, recognitionKey, polishKey in
@@ -282,21 +283,23 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
let alert = NSAlert()
alert.messageText = "Doubao Say · macOS"
alert.informativeText = L("""
- Sign in to Doubao, then enable the microphone and global shortcut.
+ Configure your recognition service, then enable the microphone and global shortcut.
Focus an input field before recording.
Your configured shortcut: tap to toggle, hold to talk; double-tap sends Enter.
Escape: cancel. Maximum recording: 60 seconds.
If the input target changes, use Copy last result from this menu.
- Audio is sent to Doubao for recognition. No local audio files are saved.
+ Dictation audio is sent to your selected service without saving local audio files.
+ Speech evaluation recordings are saved locally until you delete them; running a comparison uploads them.
Settings includes recognition services, polishing, microphones, shortcuts and input recovery.
Polishing sends text to your configured endpoint, with a five-second limit.
""", """
- 登录豆包,并启用麦克风和全局快捷键权限。
+ 配置识别服务,并启用麦克风和全局快捷键权限。
录音前将光标放到输入框。
使用你配置的快捷键:短按切换录音,长按说话;双击发送回车。
Esc 取消。单次最多录音 60 秒。
输入目标变化时,请从菜单复制最近结果。
- 音频发送至豆包识别,不保存本地录音文件。
+ 普通听写音频发送至所选识别服务,不保存本地录音文件。
+ 语音评测录音会保存在本机,直到手动删除;开始对比时才上传。
可在设置中配置识别服务、润色、麦克风、快捷键和输入恢复。
润色将文字发送至你配置的接口,最多等待五秒。
""")
diff --git a/macos/Sources/HotkeyManager.swift b/macos/Sources/HotkeyManager.swift
index d9bac09..6eb1705 100644
--- a/macos/Sources/HotkeyManager.swift
+++ b/macos/Sources/HotkeyManager.swift
@@ -100,7 +100,7 @@ final class HotkeyManager {
}
}
}
- private func handle(_ type: CGEventType, _ event: CGEvent) -> Unmanaged<CGEvent>? {
+ func handle(_ type: CGEventType, _ event: CGEvent) -> Unmanaged<CGEvent>? {
if event.getIntegerValueField(.eventSourceUserData) == Self.syntheticMarker { return Unmanaged.passUnretained(event) }
if type == .tapDisabledByTimeout || type == .tapDisabledByUserInput {
if let tap = eventTap { CGEvent.tapEnable(tap: tap, enable: true) }
diff --git a/macos/Sources/InputLatency.swift b/macos/Sources/InputLatency.swift
new file mode 100644
index 0000000..584c331
--- /dev/null
+++ b/macos/Sources/InputLatency.swift
@@ -0,0 +1,17 @@
+import Foundation
+
+struct InputLatency {
+ private var stopped: TimeInterval?
+ private var last: TimeInterval?
+ private(set) var values: [String: Double] = [:]
+ mutating func stop(at now: TimeInterval) {
+ guard stopped == nil else { return }
+ stopped = now; last = now
+ }
+ mutating func mark(_ stage: String, at now: TimeInterval) {
+ guard let stopped = stopped, let last = last, values[stage] == nil else { return }
+ values[stage] = max(0, now - last) * 1000
+ values["total"] = max(0, now - stopped) * 1000
+ self.last = now
+ }
+}
diff --git a/macos/Sources/PasteHelper.swift b/macos/Sources/PasteHelper.swift
index 372051d..4ff3d6e 100644
--- a/macos/Sources/PasteHelper.swift
+++ b/macos/Sources/PasteHelper.swift
@@ -44,9 +44,7 @@ final class PasteHelper {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { attempt() }
return
}
- guard let source = CGEventSource(stateID: .hidSystemState),
- let down = CGEvent(keyboardEventSource: source, virtualKey: 9, keyDown: true),
- let up = CGEvent(keyboardEventSource: source, virtualKey: 9, keyDown: false) else {
+ guard let (down, up) = Self.shortcutEvents(Shortcut(keyCode: 9, modifiers: 4)) else {
completion(false); return
}
if method == "direct" {
@@ -66,7 +64,6 @@ final class PasteHelper {
pasteboard.clearContents()
guard pasteboard.setString(text, forType: .string) else { completion(false); return }
let changeCount = pasteboard.changeCount
- down.flags = .maskCommand; up.flags = .maskCommand
down.post(tap: .cghidEventTap); up.post(tap: .cghidEventTap)
// Best effort: leave newer clipboard content untouched. Applications can
// consume paste asynchronously; users can disable automatic paste.
@@ -92,14 +89,18 @@ final class PasteHelper {
}
}
static func sendShortcut(_ shortcut: Shortcut) {
- guard AXIsProcessTrusted(), let source = CGEventSource(stateID: .hidSystemState),
+ guard AXIsProcessTrusted(), let (down, up) = shortcutEvents(shortcut) else { return }
+ down.post(tap: .cghidEventTap); up.post(tap: .cghidEventTap)
+ }
+ static func shortcutEvents(_ shortcut: Shortcut) -> (CGEvent, CGEvent)? {
+ guard let source = CGEventSource(stateID: .hidSystemState),
let down = CGEvent(keyboardEventSource: source, virtualKey: shortcut.keyCode, keyDown: true),
- let up = CGEvent(keyboardEventSource: source, virtualKey: shortcut.keyCode, keyDown: false) else { return }
+ let up = CGEvent(keyboardEventSource: source, virtualKey: shortcut.keyCode, keyDown: false) else { return nil }
let flags = HotkeyManager.flags(shortcut.modifiers)
down.flags = flags; up.flags = flags
down.setIntegerValueField(.eventSourceUserData, value: HotkeyManager.syntheticMarker)
up.setIntegerValueField(.eventSourceUserData, value: HotkeyManager.syntheticMarker)
- down.post(tap: .cghidEventTap); up.post(tap: .cghidEventTap)
+ return (down, up)
}
static func copyOnly(_ text: String) {
guard !text.isEmpty else { return }
diff --git a/macos/Sources/PersonalCorrections.swift b/macos/Sources/PersonalCorrections.swift
index b2120c4..3a5eb8f 100644
--- a/macos/Sources/PersonalCorrections.swift
+++ b/macos/Sources/PersonalCorrections.swift
@@ -16,12 +16,17 @@ enum PersonalCorrections {
let expression = try? NSRegularExpression(pattern: left + NSRegularExpression.escapedPattern(for: term) + right, options: .caseInsensitive)
return expression?.firstMatch(in: text, range: NSRange(location: 0, length: (text as NSString).length))?.range
}
- static func confirmation(original: String, output: String, recognized: String, corrected: String) throws -> (String, String, String, String) {
+ static func confirmation(original: String, output: String, recognized: String, corrected: String, selection: NSRange? = nil) throws -> (String, String, String, String) {
let sources = try PersonalVocabulary.normalize(recognized), targets = try PersonalVocabulary.normalize(corrected)
guard sources.count == 1, targets.count == 1, sources[0] != targets[0] else { throw PersonalDataStore.Failure.invalid }
let source = sources[0], target = targets[0]
guard match(source, in: original) != nil || match(source, in: output) != nil else { throw PersonalDataStore.Failure.invalid }
- let range = match(source, in: output)
+ var range = match(source, in: output)
+ if let selection = selection {
+ guard selection.location >= 0, selection.length > 0, selection.location + selection.length <= (output as NSString).length,
+ (output as NSString).substring(with: selection).caseInsensitiveCompare(source) == .orderedSame else { throw PersonalDataStore.Failure.invalid }
+ range = selection
+ }
let text = range.map { (output as NSString).replacingCharacters(in: $0, with: target) } ?? output
guard let occurrence = range.map({ NSRange(location: $0.location, length: (target as NSString).length) }) ?? match(target, in: text) else { throw PersonalDataStore.Failure.invalid }
guard let indices = Range(occurrence, in: text) else { throw PersonalDataStore.Failure.invalid }
diff --git a/macos/Sources/PersonalData.swift b/macos/Sources/PersonalData.swift
index b633baf..e900baa 100644
--- a/macos/Sources/PersonalData.swift
+++ b/macos/Sources/PersonalData.swift
@@ -87,9 +87,10 @@ final class PersonalDataStore {
defer { sqlite3_close(db) }
sqlite3_busy_timeout(db, 5000)
guard sqlite3_exec(db, "PRAGMA secure_delete=ON; CREATE TABLE IF NOT EXISTS words (term TEXT PRIMARY KEY); CREATE TABLE IF NOT EXISTS history (id TEXT PRIMARY KEY, created REAL, original TEXT, output TEXT, polished INTEGER, status TEXT); CREATE INDEX IF NOT EXISTS history_created ON history(created); CREATE TABLE IF NOT EXISTS preferences (key TEXT PRIMARY KEY, value TEXT);", nil, nil, nil) == SQLITE_OK else { throw Failure.storage }
- guard sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS corrections (key TEXT PRIMARY KEY, recognized TEXT, corrected TEXT, context TEXT, created REAL); CREATE TABLE IF NOT EXISTS confirmed_history (history_id TEXT PRIMARY KEY, text TEXT);", nil, nil, nil) == SQLITE_OK else { throw Failure.storage }
+ guard sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS input_timings (history_id TEXT PRIMARY KEY, data TEXT); CREATE TABLE IF NOT EXISTS corrections (key TEXT PRIMARY KEY, recognized TEXT, corrected TEXT, context TEXT, created REAL); CREATE TABLE IF NOT EXISTS confirmed_history (history_id TEXT PRIMARY KEY, text TEXT);", nil, nil, nil) == SQLITE_OK else { throw Failure.storage }
_ = try query(db, "DELETE FROM history WHERE created < ?", [clock().timeIntervalSince1970 - 30 * 86400])
_ = try query(db, "DELETE FROM confirmed_history WHERE history_id NOT IN (SELECT id FROM history)")
+ _ = try query(db, "DELETE FROM input_timings WHERE history_id NOT IN (SELECT id FROM history)")
return try body(db)
}
private func query(_ db: OpaquePointer, _ sql: String, _ values: [Any] = []) throws -> [[String]] {
@@ -143,19 +144,40 @@ final class PersonalDataStore {
} }
}
func clearHistory() throws { try database { db in
- _ = try query(db, "DELETE FROM history"); _ = try query(db, "DELETE FROM confirmed_history")
+ _ = try query(db, "DELETE FROM input_timings"); _ = try query(db, "DELETE FROM history"); _ = try query(db, "DELETE FROM confirmed_history")
} }
+ func saveTimings(_ id: String?, values: [String: Double]) throws {
+ guard let id = id else { return }
+ let data = try JSONSerialization.data(withJSONObject: values)
+ guard let text = String(data: data, encoding: .utf8) else { throw Failure.invalid }
+ try database { _ = try query($0, "INSERT OR REPLACE INTO input_timings SELECT ?,? WHERE EXISTS (SELECT 1 FROM history WHERE id=?)", [id, text, id]) }
+ }
+ func allTimings(limit: Int = 100) throws -> [String: [String: Double]] {
+ try database { db in
+ var result: [String: [String: Double]] = [:]
+ for row in try query(db, "SELECT history_id,data FROM input_timings JOIN history ON history_id=history.id ORDER BY history.created DESC,history.rowid DESC LIMIT ?", [limit]) {
+ result[row[0]] = (try? JSONSerialization.jsonObject(with: Data(row[1].utf8)) as? [String: Double]) ?? [:]
+ }
+ return result
+ }
+ }
+ func timings(_ id: String) throws -> [String: Double] {
+ try database { db in
+ guard let text = try query(db, "SELECT data FROM input_timings WHERE history_id=?", [id]).first?.first else { return [:] }
+ return (try JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Double]) ?? [:]
+ }
+ }
func corrections() throws -> [ConfirmedCorrection] {
try database { try query($0, "SELECT key,recognized,corrected,context FROM corrections ORDER BY created DESC,rowid DESC").map {
ConfirmedCorrection(id: $0[0], recognized: $0[1], corrected: $0[2], context: $0[3])
} }
}
- @discardableResult func confirmCorrection(_ id: String, recognized: String, corrected: String) throws -> String {
+ @discardableResult func confirmCorrection(_ id: String, recognized: String, corrected: String, selection: NSRange? = nil) throws -> String {
try database { db in
_ = try query(db, "BEGIN IMMEDIATE")
do {
guard let row = try query(db, "SELECT original,COALESCE(confirmed_history.text,history.output) FROM history LEFT JOIN confirmed_history ON history.id=confirmed_history.history_id WHERE history.id=?", [id]).first else { throw Failure.invalid }
- let (source, target, text, context) = try PersonalCorrections.confirmation(original: row[0], output: row[1], recognized: recognized, corrected: corrected)
+ let (source, target, text, context) = try PersonalCorrections.confirmation(original: row[0], output: row[1], recognized: recognized, corrected: corrected, selection: selection)
let key = source.lowercased() + "\n" + target.lowercased()
let exists = try query(db, "SELECT 1 FROM corrections WHERE key=?", [key]).first != nil
let count = Int(try query(db, "SELECT COUNT(*) FROM corrections")[0][0]) ?? 0
diff --git a/macos/Sources/PersonalViews.swift b/macos/Sources/PersonalViews.swift
index fe178d4..51070e8 100644
--- a/macos/Sources/PersonalViews.swift
+++ b/macos/Sources/PersonalViews.swift
@@ -14,6 +14,7 @@ final class PersonalModel: ObservableObject {
let store: PersonalDataStore
@Published var words = "" { didSet { if !loading && words != oldValue { scheduleSave() } } }
@Published var history: [InputHistory] = []
+ @Published var timings: [String: [String: Double]] = [:]
@Published var enabled = true { didSet { if !loading { do { try store.setEnabled(enabled) } catch { feedback = L("Could not save history preference.", "历史记录设置保存失败。") } } } }
@Published var candidates: [VocabularyCandidate] = []
@Published var selected = Set<String>()
@@ -22,8 +23,10 @@ final class PersonalModel: ObservableObject {
@Published var corrections: [ConfirmedCorrection] = []
@Published var hotwords = ""
@Published var correctionTarget: InputHistory?
- @Published var recognizedTerm = ""
+ var correctionSelection: NSRange?
+ @Published var recognizedTerm = "" { didSet { if recognizedTerm != oldValue { correctionSelection = nil } } }
@Published var correctedTerm = ""
+ var selectedHistory: (String, String, NSRange)?
private var loading = false
private var limit = 100
private var saveTimer: DispatchWorkItem?
@@ -33,6 +36,7 @@ final class PersonalModel: ObservableObject {
loading = true; defer { loading = false }
do {
if saveTimer == nil { words = try store.words().joined(separator: "\n") }
+ timings = try store.allTimings(limit: limit)
enabled = try store.enabled(); history = try store.history(limit: limit); corrections = try store.corrections()
refreshHotwords()
} catch { feedback = L("Could not read local vocabulary or history.", "无法读取本地词汇或历史。") }
@@ -55,17 +59,20 @@ final class PersonalModel: ObservableObject {
}
func more() { limit += 100; refresh() }
func beginCorrection(_ item: InputHistory) {
- recognizedTerm = ""; correctedTerm = ""; correctionTarget = item
+ correctionSelection = nil; recognizedTerm = ""; correctedTerm = ""; correctionTarget = item
+ if let selection = selectedHistory, selection.0 == item.id {
+ recognizedTerm = selection.1; correctionSelection = selection.2
+ }
}
var correctionPreview: String? {
guard let item = correctionTarget else { return nil }
- return try? PersonalCorrections.confirmation(original: item.original, output: item.confirmed.isEmpty ? item.output : item.confirmed, recognized: recognizedTerm, corrected: correctedTerm).2
+ return try? PersonalCorrections.confirmation(original: item.original, output: item.confirmed.isEmpty ? item.output : item.confirmed, recognized: recognizedTerm, corrected: correctedTerm, selection: correctionSelection).2
}
func confirmCorrection() {
guard let item = correctionTarget else { return }
do {
- try store.confirmCorrection(item.id, recognized: recognizedTerm, corrected: correctedTerm)
- correctionTarget = nil; refresh()
+ try store.confirmCorrection(item.id, recognized: recognizedTerm, corrected: correctedTerm, selection: correctionSelection)
+ correctionTarget = nil; selectedHistory = nil; refresh()
feedback = L("Correction remembered. Future matching contexts can use it.", "已记住这次纠正,之后遇到相似语境时参考。")
} catch { feedback = L("Could not confirm. Check both terms and refresh the history entry.", "无法确认,请检查两个词,并确认这条历史仍然存在。") }
}
@@ -177,7 +184,12 @@ struct InputHistoryView: View {
Text(item.polished ? L("Polished", "已润色") : L("Original", "原文"))
Text(["sent", "attempted"].contains(item.status) ? L("Input sent", "已发送输入操作") : L("Kept / not confirmed", "已保留/未确认输入"))
}.font(.caption).foregroundColor(.secondary)
- Text(item.confirmed.isEmpty ? item.output : item.confirmed).textSelection(.enabled)
+ CorrectionSelectionText(text: item.confirmed.isEmpty ? item.output : item.confirmed) { term, range in
+ model.selectedHistory = (item.id, term, range)
+ }.frame(height: 65)
+ if let timing = model.timings[item.id], !timing.isEmpty {
+ Text(String(format: L("After stop: ASR %.0f ms · Polish %.0f ms · Input %.0f ms · Total %.0f ms", "结束录音后:识别 %.0f 毫秒 · 润色 %.0f 毫秒 · 输入 %.0f 毫秒 · 共 %.0f 毫秒"), timing["asr"] ?? 0, timing["polish"] ?? 0, timing["delivery"] ?? 0, timing["total"] ?? 0)).font(.caption).foregroundColor(.secondary)
+ }
if !item.confirmed.isEmpty {
Text(L("Correction confirmed by you", "你已确认纠正")).font(.caption).foregroundColor(.secondary)
DisclosureGroup(L("Before your correction", "确认前的文字")) { Text(item.output).textSelection(.enabled) }
@@ -205,17 +217,21 @@ struct InputHistoryView: View {
}
struct ConfirmCorrectionView: View {
+ @FocusState private var correctedFocus: Bool
@ObservedObject var model: PersonalModel
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text(L("Confirm & remember a correction", "确认并记住这次纠正")).font(.headline)
if let item = model.correctionTarget {
- ScrollView { Text(item.confirmed.isEmpty ? item.output : item.confirmed).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading) }.frame(maxHeight: 120)
+ Text(L("Select the wrong word below to fill it in, then enter the correct spelling.", "在下方选中错词即可带入,再填写正确写法。")).font(.caption)
+ CorrectionSelectionText(text: item.confirmed.isEmpty ? item.output : item.confirmed) { term, range in
+ model.recognizedTerm = term; model.correctionSelection = range; correctedFocus = true
+ }.frame(height: 85)
}
Text(L("Misrecognized word or phrase", "误识别的词或短语"))
TextField(L("For example: Midjourney", "例如:Midjourney"), text: $model.recognizedTerm)
Text(L("Correct spelling", "正确写法"))
- TextField(L("For example: Midscene", "例如:Midscene"), text: $model.correctedTerm)
+ TextField(L("For example: Midscene", "例如:Midscene"), text: $model.correctedTerm).focused($correctedFocus)
if let preview = model.correctionPreview {
Text(L("After confirmation", "确认后的文字")).font(.headline)
ScrollView { Text(preview).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading) }.frame(maxHeight: 120)
@@ -233,5 +249,38 @@ struct ConfirmCorrectionView: View {
.keyboardShortcut(.defaultAction).disabled(model.correctionPreview == nil)
}
}.textFieldStyle(.roundedBorder).padding(20).frame(width: 540)
+ .onAppear { correctedFocus = true }
+ }
+}
+
+/// Read-only native text with selection callbacks; selecting a word never confirms it.
+struct CorrectionSelectionText: NSViewRepresentable {
+ let text: String
+ var selected: (String, NSRange) -> Void
+ func makeCoordinator() -> Coordinator { Coordinator(self) }
+ func makeNSView(context: Context) -> NSScrollView {
+ let scroll = NSScrollView(); scroll.hasVerticalScroller = true
+ let view = NSTextView(); view.isEditable = false; view.isSelectable = true
+ view.drawsBackground = false; view.font = .systemFont(ofSize: 13)
+ view.textContainerInset = NSSize(width: 6, height: 6)
+ view.isVerticallyResizable = true; view.isHorizontallyResizable = false
+ view.autoresizingMask = [.width]; view.textContainer?.widthTracksTextView = true
+ view.delegate = context.coordinator; scroll.documentView = view; return scroll
+ }
+ func updateNSView(_ scroll: NSScrollView, context: Context) {
+ context.coordinator.parent = self
+ if let view = scroll.documentView as? NSTextView, view.string != text { view.string = text }
+ }
+ final class Coordinator: NSObject, NSTextViewDelegate {
+ var parent: CorrectionSelectionText
+ init(_ parent: CorrectionSelectionText) { self.parent = parent }
+ func textViewDidChangeSelection(_ notification: Notification) {
+ guard let view = notification.object as? NSTextView else { return }
+ let range = view.selectedRange(), text = view.string as NSString
+ guard range.length > 0, range.location + range.length <= text.length else { return }
+ let selection = text.substring(with: range)
+ guard selection.count <= 80, !selection.contains("\n") else { return }
+ DispatchQueue.main.async { self.parent.selected(selection, range) }
+ }
}
}
diff --git a/macos/Sources/SettingsWindow.swift b/macos/Sources/SettingsWindow.swift
index ef576c8..3dc8330 100644
--- a/macos/Sources/SettingsWindow.swift
+++ b/macos/Sources/SettingsWindow.swift
@@ -43,6 +43,8 @@ final class SettingsModel: ObservableObject {
var shortcutReady: (() -> Bool)?
var onFinishSetup: (() -> Void)?
var checkUpdates: (() -> Void)?
+ var canEvaluate: (() -> Bool)?
+ var cancelEvaluation: (() -> Void)?
var cancelUpdate: (() -> Void)?
var installUpdate: (() -> Void)?
var releaseNotes: (() -> Void)?
@@ -83,7 +85,7 @@ final class SettingsModel: ObservableObject {
}
@discardableResult func saveIfNeeded() -> Bool { (!hasPendingAutosave || save()) && (flushPersonal?() ?? true) }
func closeEditor() {
- stopTests(); cancelCapture?(); capturing = false
+ cancelEvaluation?(); stopTests(); cancelCapture?(); capturing = false
if saveIfNeeded() {
suppressAutosave = true
recognitionKey = ""; polishKey = ""; savedRecognitionKey = ""; savedPolishKey = ""
@@ -194,7 +196,7 @@ final class SettingsModel: ObservableObject {
client.start(text: "周三上线,不对,周四上线。", settings: draft, apiKey: key)
}
func clearKey(_ account: String) {
- guard !testing, state.recordingState == .idle else { return }
+ guard !testing, !state.evaluationBusy, state.recordingState == .idle else { return }
do {
try SecretStore.clear(account)
if account == "polish-api-key" { savedPolishKey = ""; polishKey = ""; polishKeySaved = false }
@@ -227,7 +229,7 @@ final class SettingsModel: ObservableObject {
}
func checkMicrophone() {
guard saveIfNeeded() else { return }
- guard !testing, state.recordingState == .idle else { return }
+ guard !testing, !state.evaluationBusy, state.recordingState == .idle else { return }
guard AVCaptureDevice.authorizationStatus(for: .audio) == .authorized else {
AVCaptureDevice.requestAccess(for: .audio) { _ in }
feedback = L("Allow microphone access, then retry.", "允许麦克风访问后,请重试。"); return
@@ -272,6 +274,7 @@ struct SettingsView: View {
("result", L("Recent text", "最近文字"), "text.alignleft"),
("vocabulary", L("Personal vocabulary", "个人词汇"), "character.book.closed"),
("history", L("Input history", "输入历史"), "clock"),
+ ("speech-evaluation", L("Speech evaluation", "语音评测"), "chart.bar"),
("updates", L("Updates", "软件更新"), "arrow.triangle.2.circlepath") ] }
private var pageTitle: String { pages.first { $0.0 == model.selectedTab }?.1 ?? L("Settings", "设置") }
var body: some View {
@@ -339,6 +342,7 @@ struct SettingsView: View {
case "result": result
case "vocabulary": PersonalVocabularyView(settingsModel: model)
case "history": InputHistoryView(state: state)
+ case "speech-evaluation": SpeechEvaluationView(state: state, settingsModel: model, canStart: { !model.testing && !model.capturing && (model.canEvaluate?() ?? true) })
case "updates": updatePage
default: setup
}
@@ -560,7 +564,7 @@ struct SettingsView: View {
PaddedTextEditor(text: $state.lastTranscript)
HStack {
Button(L("Copy", "复制")) { PasteHelper.copyOnly(state.lastTranscript) }.disabled(state.lastTranscript.isEmpty)
- Button(L("Retry in 3 seconds", "三秒后重试")) { model.retry?() }.disabled(state.lastTranscript.isEmpty || state.recordingState != .idle)
+ Button(L("Retry in 3 seconds", "三秒后重试")) { model.retry?() }.disabled(state.lastTranscript.isEmpty || state.recordingState != .idle || state.inputPending || state.evaluationBusy)
Button(L("Clear", "清除")) { model.clear?() }
}
}.padding(16)
diff --git a/macos/Sources/SpeechEvaluation.swift b/macos/Sources/SpeechEvaluation.swift
new file mode 100644
index 0000000..b4240cc
--- /dev/null
+++ b/macos/Sources/SpeechEvaluation.swift
@@ -0,0 +1,93 @@
+import Foundation
+
+struct SpeechSample: Codable, Identifiable {
+ var id = UUID().uuidString
+ var reference = ""
+ var terms = ""
+ var protectedTerms = ""
+ var audioBytes = 0
+ var results: [SpeechResult] = []
+}
+struct SpeechResult: Codable, Identifiable {
+ var id: String { mode }
+ let mode: String
+ var text: String
+ var elapsedMS: Double
+ var error: Bool = false
+}
+enum SpeechScoring {
+ static func normalized(_ text: String) -> [Character] {
+ Array(text.precomposedStringWithCanonicalMapping.lowercased().filter {
+ !$0.unicodeScalars.allSatisfy { CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters).contains($0) }
+ })
+ }
+ static func edits(_ reference: String, _ text: String) -> Int {
+ let a = normalized(reference), b = normalized(text)
+ var previous = Array(0...b.count)
+ for (i, left) in a.enumerated() {
+ var current = [i + 1]
+ for (j, right) in b.enumerated() { current.append(min(current[j] + 1, previous[j + 1] + 1, previous[j] + (left == right ? 0 : 1))) }
+ previous = current
+ }
+ return previous.last ?? 0
+ }
+ static func labels(_ text: String) -> [String] { text.components(separatedBy: .newlines).map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty } }
+ static func valid(_ sample: SpeechSample) -> Bool {
+ let labels = labels(sample.terms) + labels(sample.protectedTerms)
+ return !normalized(sample.reference).isEmpty && sample.reference.count <= 4096 && labels.count <= 60 && labels.allSatisfy { $0.count <= 80 && PersonalCorrections.match($0, in: sample.reference) != nil }
+ }
+ static func summary(_ samples: [SpeechSample], mode: String) -> [String: Double] {
+ var errors = 0, characters = 0, hits = 0, targets = 0, losses = 0, protected = 0, failed = 0
+ var timings: [Double] = []
+ for sample in samples {
+ let row = sample.results.first { $0.mode == mode }
+ let success = row != nil && row?.error == false && !(row?.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?? true)
+ let text = success ? row!.text : ""
+ errors += edits(sample.reference, text); characters += normalized(sample.reference).count
+ failed += success ? 0 : 1
+ for term in labels(sample.terms) { targets += 1; hits += PersonalCorrections.match(term, in: text) != nil ? 1 : 0 }
+ for term in labels(sample.protectedTerms) { protected += 1; losses += PersonalCorrections.match(term, in: text) == nil ? 1 : 0 }
+ if success { timings.append(row!.elapsedMS) }
+ }
+ var report = ["samples": Double(samples.count), "failed": Double(failed), "cer": Double(errors) / Double(max(1, characters))]
+ if targets > 0 { report["terms"] = Double(hits) / Double(targets) }
+ if protected > 0 { report["protected"] = Double(losses) / Double(protected) }
+ if !timings.isEmpty { let sorted = timings.sorted(); report["p50"] = sorted[Int(ceil(Double(sorted.count) * 0.5)) - 1]; report["p95"] = sorted[Int(ceil(Double(sorted.count) * 0.95)) - 1] }
+ return report
+ }
+}
+
+final class SpeechSampleStore {
+ let directory: URL
+ init(directory: URL? = nil) {
+ self.directory = directory ?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent(Bundle.main.bundleIdentifier ?? "md.lifeos.doubao-say.development").appendingPathComponent("speech-evaluation")
+ }
+ private func prepare() throws { try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) }
+ func load() throws -> [SpeechSample] {
+ let path = directory.appendingPathComponent("samples.json")
+ guard FileManager.default.fileExists(atPath: path.path) else { return [] }
+ let data = try Data(contentsOf: path)
+ guard data.count <= 10_000_000 else { throw PersonalDataStore.Failure.invalid }
+ let samples = try JSONDecoder().decode([SpeechSample].self, from: data)
+ guard samples.count <= 200, samples.allSatisfy({ UUID(uuidString: $0.id) != nil }) else { throw PersonalDataStore.Failure.invalid }
+ return samples
+ }
+ func save(_ samples: [SpeechSample]) throws {
+ guard samples.count <= 200 else { throw PersonalDataStore.Failure.invalid }
+ try prepare()
+ let path = directory.appendingPathComponent("samples.json")
+ try JSONEncoder().encode(samples).write(to: path, options: .atomic)
+ try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: path.path)
+ }
+ func audio(_ id: String) throws -> URL {
+ guard UUID(uuidString: id) != nil else { throw PersonalDataStore.Failure.invalid }
+ try prepare(); return directory.appendingPathComponent(id + ".pcm")
+ }
+ func saveAudio(_ pcm: Data, id: String) throws {
+ guard !pcm.isEmpty, pcm.count <= 1_920_000, pcm.count % 2 == 0 else { throw PersonalDataStore.Failure.invalid }
+ let path = try audio(id)
+ try pcm.write(to: path, options: .atomic)
+ try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: path.path)
+ }
+ func remove(_ id: String) throws { let path = try audio(id); if FileManager.default.fileExists(atPath: path.path) { try FileManager.default.removeItem(at: path) } }
+}
diff --git a/macos/Sources/SpeechEvaluationModel.swift b/macos/Sources/SpeechEvaluationModel.swift
new file mode 100644
index 0000000..356e243
--- /dev/null
+++ b/macos/Sources/SpeechEvaluationModel.swift
@@ -0,0 +1,203 @@
+import Foundation
+import AVFoundation
+import Combine
+
+/// A replay owns its transport, timers and continuation; late callbacks are ignored.
+@MainActor final class SpeechReplay {
+ private var client: APIASRClient?
+ private var continuation: CheckedContinuation<SpeechResult, Error>?
+ private var stream: Task<Void, Never>?
+ private var deadline: Task<Void, Never>?
+ private var text = ""
+ private var started: TimeInterval = 0
+ private var mode = ""
+ func recognize(_ pcm: Data, key: String, words: [String], mode: String) async throws -> SpeechResult {
+ self.mode = mode; text = ""; started = ProcessInfo.processInfo.systemUptime
+ return try await withCheckedThrowingContinuation { continuation in
+ self.continuation = continuation
+ let client = APIASRClient(provider: .volcengine, hotwords: words); self.client = client
+ client.onOpen = { [weak self] in Task { @MainActor in
+ guard let self = self, self.continuation != nil else { return }
+ self.stream = Task { @MainActor in
+ for offset in stride(from: 0, to: pcm.count, by: 3200) {
+ guard !Task.isCancelled, self.continuation != nil else { return }
+ client.sendAudio(pcm.subdata(in: offset..<min(offset + 3200, pcm.count)))
+ try? await Task.sleep(nanoseconds: 100_000_000)
+ }
+ client.finishSending()
+ }
+ } }
+ client.onResult = { [weak self] text in Task { @MainActor in if self?.continuation != nil { self?.text = text } } }
+ client.onFinish = { [weak self] in Task { @MainActor in self?.finish() } }
+ client.onError = { [weak self] in Task { @MainActor in self?.finish(failed: true) } }
+ client.onAuthError = client.onError
+ self.deadline = Task { @MainActor in
+ try? await Task.sleep(nanoseconds: 75_000_000_000)
+ if !Task.isCancelled { self.finish(failed: true) }
+ }
+ client.connect(apiKey: key)
+ }
+ }
+ private func finish(failed: Bool = false) {
+ guard let continuation = continuation else { return }
+ let result = SpeechResult(mode: mode, text: text, elapsedMS: (ProcessInfo.processInfo.systemUptime - started) * 1000, error: failed || text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
+ cleanup(); continuation.resume(returning: result)
+ }
+ func cancel() { let pending = continuation; cleanup(); pending?.resume(throwing: CancellationError()) }
+ private func cleanup() { continuation = nil; stream?.cancel(); deadline?.cancel(); client?.disconnect(); client = nil }
+}
+
+@MainActor final class SpeechEvaluationModel: ObservableObject {
+ @Published var samples: [SpeechSample] = []
+ @Published var selected: String?
+ @Published var recording = false
+ @Published var busy = false
+ @Published var includePolish = true
+ @Published var feedback = ""
+ @Published var hotwords = ""
+ @Published var summaries: [String: [String: Double]] = [:]
+ private var summaryRevision = UUID()
+ let store: SpeechSampleStore
+ private let state: AppState
+ private let audio = AudioCaptureManager()
+ private var pcm = Data()
+ private var generation = UUID()
+ private var recordDeadline: Task<Void, Never>?
+ private let canStart: () -> Bool
+ private var task: Task<Void, Never>?
+ private var replay: SpeechReplay?
+ private var polisher: PolishClient?
+ private var polishContinuation: CheckedContinuation<String?, Never>?
+ init(state: AppState, store: SpeechSampleStore = SpeechSampleStore(), canStart: @escaping () -> Bool = { true }) {
+ self.state = state; self.store = store; self.canStart = canStart
+ do { samples = try store.load(); selected = samples.first?.id } catch { feedback = L("Could not read local speech samples.", "无法读取本地语音样本。") }
+ refreshSummary()
+ }
+ var index: Int? { samples.firstIndex { $0.id == selected } }
+ func add() {
+ guard !busy, !recording, samples.count < 200 else { return }
+ let sample = SpeechSample(); samples.append(sample); selected = sample.id; save(); refreshSummary()
+ }
+ func save() { do { try store.save(samples) } catch { feedback = L("Could not save local speech samples.", "本地语音样本保存失败。") } }
+ func edit(_ field: WritableKeyPath<SpeechSample, String>, _ text: String) {
+ guard !busy, !recording, let index = index else { return }
+ samples[index][keyPath: field] = text; samples[index].results = []; save(); refreshSummary()
+ }
+ func delete() {
+ guard !busy, !recording, let index = index else { return }
+ do { try store.remove(samples[index].id); samples.remove(at: index); selected = samples.first?.id; save(); refreshSummary() }
+ catch { feedback = L("Could not delete the local recording.", "无法删除本地录音。") }
+ }
+ func record() {
+ guard !busy, !recording, index != nil else { return }
+ guard state.recordingState == .idle, !state.evaluationBusy, canStart() else { feedback = L("Finish dictation or microphone checks first.", "请先结束日常听写或麦克风检查。"); return }
+ guard AVCaptureDevice.authorizationStatus(for: .audio) == .authorized else {
+ feedback = L("Allow microphone access in System Settings, then retry.", "请在系统设置中允许麦克风访问,再重试。")
+ if AVCaptureDevice.authorizationStatus(for: .audio) == .notDetermined { AVCaptureDevice.requestAccess(for: .audio) { _ in } }; return
+ }
+ generation = UUID(); let token = generation; pcm = Data(); recording = true; state.evaluationBusy = true
+ audio.onAudioData = { [weak self] data in Task { @MainActor in
+ guard let self = self, self.recording, self.generation == token else { return }
+ let remaining = 1_920_000 - self.pcm.count
+ self.pcm.append(data.prefix(remaining))
+ if self.pcm.count >= 1_920_000 { self.stop() }
+ } }
+ audio.onError = { [weak self] in Task { @MainActor in guard self?.generation == token else { return }; self?.cancel(); self?.feedback = L("Microphone unavailable. Recording discarded.", "麦克风不可用,本次录音已丢弃。") } }
+ do {
+ try audio.startCapture(deviceID: SettingsStore.shared.value.microphoneID)
+ recordDeadline = Task { @MainActor in
+ try? await Task.sleep(nanoseconds: 60_000_000_000)
+ if !Task.isCancelled && generation == token { stop() }
+ }
+ }
+ catch { cancel(); feedback = L("The selected microphone could not start.", "所选麦克风无法启动。") }
+ }
+ func stop() {
+ guard recording, let index = index else { return }
+ recordDeadline?.cancel(); recordDeadline = nil
+ audio.stopCapture(); audio.onAudioData = nil; audio.onError = nil; recording = false; state.evaluationBusy = false; generation = UUID()
+ do { try store.saveAudio(pcm, id: samples[index].id); samples[index].audioBytes = pcm.count; samples[index].results = []; save(); refreshSummary(); feedback = L("Recording saved locally. Review the reference before comparing.", "录音已保存在本机,请核对参考文字后再对比。") }
+ catch { feedback = L("Could not save recording. Record again.", "录音保存失败,请重新录制。") }
+ pcm = Data()
+ }
+ var ready: Bool { !samples.isEmpty && samples.allSatisfy { $0.audioBytes > 0 && SpeechScoring.valid($0) } }
+ func run() {
+ guard ready, !busy, !recording else { return }
+ guard state.recordingState == .idle, !state.evaluationBusy, canStart() else { feedback = L("Finish dictation or microphone checks first.", "请先结束日常听写或麦克风检查。"); return }
+ guard let key = SecretStore.load("volcengine-api-key"), !key.isEmpty else { feedback = L("Configure an official Volcengine ASR key first.", "请先配置官方火山引擎 ASR Key。") ; return }
+ let polishKey = includePolish ? SecretStore.load("polish-api-key") : nil
+ guard !includePolish || !(polishKey ?? "").isEmpty else { feedback = L("Configure polishing credentials or turn off polishing comparison.", "请配置润色凭证,或关闭润色对比。") ; return }
+ let words = (try? PersonalDataStore.shared.recognitionWords()) ?? []
+ let settings = SettingsStore.shared.value
+ let context = try? PersonalCorrections.hotwordContext(words)
+ hotwords = context ?? "[]"
+ let snapshot = samples; generation = UUID(); let token = generation
+ busy = true; state.evaluationBusy = true
+ samples.indices.forEach { samples[$0].results = [] }; summaries = [:]; summaryRevision = UUID(); save()
+ task = Task { @MainActor in
+ defer { if generation == token { busy = false; state.evaluationBusy = false; replay = nil; task = nil; save(); refreshSummary() } }
+ do {
+ // Validate every recording before any paid request.
+ for sample in snapshot {
+ let data = try Data(contentsOf: store.audio(sample.id))
+ guard data.count == sample.audioBytes, data.count > 0, data.count <= 1_920_000, data.count % 2 == 0 else { throw PersonalDataStore.Failure.invalid }
+ }
+ for i in snapshot.indices {
+ let pcm = try Data(contentsOf: store.audio(snapshot[i].id))
+ for mode in ["raw", "hotwords"] {
+ try Task.checkCancellation()
+ let label = mode == "raw" ? L("Original ASR", "原始识别") : L("With hotwords", "加入热词")
+ feedback = L("Comparing sample ", "正在对比第 ") + "\(i + 1)/\(snapshot.count) · " + label
+ let request = SpeechReplay(); replay = request
+ let row = try await request.recognize(pcm, key: key, words: mode == "raw" ? [] : words, mode: mode)
+ guard generation == token else { return }
+ samples[i].results.append(row); save()
+ if mode == "hotwords", let polishKey = polishKey {
+ var polished = SpeechResult(mode: "hotwords+polish", text: row.text, elapsedMS: row.elapsedMS, error: row.error)
+ if !row.error {
+ let started = ProcessInfo.processInfo.systemUptime
+ let text = await polish(row.text, settings: settings, key: polishKey)
+ try Task.checkCancellation()
+ polished.text = text ?? row.text; polished.error = text == nil
+ polished.elapsedMS += (ProcessInfo.processInfo.systemUptime - started) * 1000
+ }
+ samples[i].results.append(polished); save()
+ }
+ }
+ }
+ feedback = L("Comparison complete. Review failures and protected terms as well as accuracy.", "对比完成,请同时检查失败样本、准确率和受保护词是否被误改。")
+ } catch is CancellationError { }
+ catch { feedback = L("Comparison failed. Check recordings and credentials; completed results are retained.", "对比失败,请检查录音和凭证,已完成的结果保留。") }
+ }
+ }
+ private func polish(_ text: String, settings: MacSettings, key: String) async -> String? {
+ await withCheckedContinuation { continuation in
+ polishContinuation = continuation
+ let request = PolishClient(); polisher = request
+ request.completion = { [weak self] result, _ in self?.finishPolish(result) }
+ request.start(text: text, settings: settings, apiKey: key, timeout: 25)
+ }
+ }
+ private func finishPolish(_ text: String?) { let pending = polishContinuation; polishContinuation = nil; polisher = nil; pending?.resume(returning: text) }
+ func cancel() {
+ recordDeadline?.cancel(); recordDeadline = nil
+ generation = UUID(); audio.stopCapture(); audio.onAudioData = nil; audio.onError = nil
+ pcm = Data(); task?.cancel(); task = nil; replay?.cancel(); replay = nil
+ polisher?.cancel(); finishPolish(nil); recording = false; busy = false; state.evaluationBusy = false
+ feedback = L("Cancelled. Completed results remain available.", "已取消,已完成的结果保留。")
+ refreshSummary()
+ }
+ func refreshSummary() {
+ let snapshot = samples; summaryRevision = UUID(); let revision = summaryRevision
+ Task { @MainActor in
+ let reports = await Task.detached(priority: .utility) { () -> [String: [String: Double]] in
+ var result: [String: [String: Double]] = [:]
+ for mode in ["raw", "hotwords", "hotwords+polish"] where snapshot.contains(where: { $0.results.contains { $0.mode == mode } }) {
+ result[mode] = SpeechScoring.summary(snapshot, mode: mode)
+ }
+ return result
+ }.value
+ if summaryRevision == revision { summaries = reports }
+ }
+ }
+}
diff --git a/macos/Sources/SpeechEvaluationView.swift b/macos/Sources/SpeechEvaluationView.swift
new file mode 100644
index 0000000..90bafa9
--- /dev/null
+++ b/macos/Sources/SpeechEvaluationView.swift
@@ -0,0 +1,94 @@
+import SwiftUI
+
+struct SpeechEvaluationView: View {
+ private var settingsModel: SettingsModel?
+ @StateObject private var model: SpeechEvaluationModel
+ init(state: AppState, model: SpeechEvaluationModel? = nil, settingsModel: SettingsModel? = nil, canStart: @escaping () -> Bool = { true }) { self.settingsModel = settingsModel; _model = StateObject(wrappedValue: model ?? SpeechEvaluationModel(state: state, canStart: canStart)) }
+ private func field(_ key: WritableKeyPath<SpeechSample, String>) -> Binding<String> {
+ Binding(get: { model.index.map { model.samples[$0][keyPath: key] } ?? "" }, set: { model.edit(key, $0) })
+ }
+ private func title(_ mode: String) -> String {
+ switch mode {
+ case "raw": return L("Original ASR", "原始识别")
+ case "hotwords": return L("With hotwords", "加入热词")
+ default: return L("Hotwords + polishing", "热词+润色")
+ }
+ }
+ var body: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 12) {
+ Text(L("1. Record · 2. Review reference · 3. Compare", "1. 录音 · 2. 核对参考文字 · 3. 对比结果")).font(.headline)
+ Text(L("Record 30–50 short clips in your normal accent. Include jargon, mixed languages, names, numbers and cases where Midjourney is correct. Recordings stay locally until you start comparison.", "建议用日常口音录制 30–50 条短句,包括专业词、中英混说、人名、数字,以及确实应该是 Midjourney 的句子。开始对比前,录音仅保存在本机。"))
+ .fixedSize(horizontal: false, vertical: true)
+ HStack {
+ Picker(L("Sample", "样本"), selection: $model.selected) {
+ ForEach(Array(model.samples.enumerated()), id: \.element.id) { i, sample in Text("\(i + 1). " + (sample.reference.isEmpty ? L("New sample", "新样本") : String(sample.reference.prefix(25)))).tag(Optional(sample.id)) }
+ }.disabled(model.busy || model.recording)
+ Button(L("Add sample", "添加样本")) { model.add() }.disabled(model.busy || model.recording || model.samples.count >= 200)
+ }
+ if let index = model.index {
+ HStack {
+ if model.recording {
+ ProgressView().controlSize(.small)
+ Button(L("Stop & keep recording", "结束并保留录音")) { model.stop() }
+ Button(L("Discard", "丢弃")) { model.cancel() }
+ } else {
+ Button(model.samples[index].audioBytes == 0 ? L("Record", "录音") : L("Record again", "重新录音")) { model.record() }.disabled(model.busy)
+ Text(String(format: L("Local audio: %.1f s", "本地录音:%.1f 秒"), Double(model.samples[index].audioBytes) / 32000)).font(.caption)
+ Spacer()
+ Button(L("Delete sample", "删除样本"), role: .destructive) { model.delete() }.disabled(model.busy)
+ }
+ }
+ Text(L("Reference text — what you actually said", "参考文字——你实际说的内容")).font(.headline)
+ PaddedTextEditor(text: field(\.reference)).frame(height: 85).disabled(model.busy || model.recording)
+ HStack(alignment: .top, spacing: 12) {
+ VStack(alignment: .leading) {
+ Text(L("Target terms (one per line)", "目标词(每行一个)"))
+ PaddedTextEditor(text: field(\.terms)).frame(height: 65)
+ }
+ VStack(alignment: .leading) {
+ Text(L("Protected terms (one per line)", "受保护词(每行一个)"))
+ PaddedTextEditor(text: field(\.protectedTerms)).frame(height: 65)
+ }
+ }.disabled(model.busy || model.recording)
+ Text(L("Labels must occur in the reference. References are used only for scoring and never sent to ASR or polishing. Editing a sample clears its old results.", "标注的词必须出现在参考文字中。参考文字仅用于评分,不会发送给识别或润色服务;修改样本会清除该样本的旧结果。"))
+ .font(.caption).foregroundColor(.secondary).fixedSize(horizontal: false, vertical: true)
+ Toggle(L("Compare AI polishing too", "同时对比 AI 润色"), isOn: $model.includePolish).disabled(model.busy || model.recording)
+ if !model.ready { Text(L("Every sample needs a recording, reference text and valid term labels.", "每条样本都需要录音、参考文字和有效词汇标注。")) .font(.caption).foregroundColor(.secondary) }
+ Text(L("Start comparison uploads each recording twice to your paid official Volcengine ASR. Polishing also sends recognized text to your configured service. No text is pasted and no reference is learned.", "开始对比会将每段录音发送两次给你配置的官方火山引擎 ASR,并产生接口费用;润色对比还会发送识别文字给润色服务。不会粘贴文字,也不会学习参考答案。"))
+ .font(.caption).foregroundColor(.secondary).fixedSize(horizontal: false, vertical: true)
+ HStack {
+ if model.busy { ProgressView().controlSize(.small); Button(L("Cancel comparison", "取消对比")) { model.cancel() } }
+ else { Button(L("Start comparison", "开始对比")) { model.run() }.disabled(!model.ready || model.recording) }
+ }
+ Text(model.feedback).font(.callout).fixedSize(horizontal: false, vertical: true)
+ if !model.hotwords.isEmpty { Text(L("Actual hotword request: ", "实际热词请求:") + model.hotwords).font(.caption).textSelection(.enabled) }
+ if model.samples.contains(where: { !$0.results.isEmpty }) {
+ Divider()
+ Text(L("Comparison summary", "对比汇总")).font(.headline)
+ Text(L("Lower character errors and protected-term loss are better. Higher target-term accuracy is better. Missing/failed samples count as failures. Timing includes connection and recording playback; it is separate from daily input delay.", "字错率和受保护词丢失率越低越好,目标词准确率越高越好。缺失或失败样本按失败计分。此处耗时包含连接和录音回放,与日常输入等待时间分开。"))
+ .font(.caption).foregroundColor(.secondary).fixedSize(horizontal: false, vertical: true)
+ ForEach(["raw", "hotwords", "hotwords+polish"].filter { model.summaries[$0] != nil }, id: \.self) { mode in
+ let report = model.summaries[mode] ?? [:]
+ VStack(alignment: .leading, spacing: 4) {
+ Text(title(mode)).font(.headline)
+ Text(String(format: L("Character error rate %.1f%% · Failed %.0f/%.0f", "字错率 %.1f%% · 失败 %.0f/%.0f"), (report["cer"] ?? 0) * 100, report["failed"] ?? 0, report["samples"] ?? 0))
+ if let rate = report["terms"] { Text(String(format: L("Target-term accuracy %.1f%%", "目标词准确率 %.1f%%"), rate * 100)) }
+ if let rate = report["protected"] { Text(String(format: L("Protected-term loss %.1f%%", "受保护词丢失率 %.1f%%"), rate * 100)) }
+ if let p50 = report["p50"], let p95 = report["p95"] { Text(String(format: "P50 %.0f ms · P95 %.0f ms", p50, p95)) }
+ }.font(.callout)
+ }
+ Text(L("Selected sample results", "当前样本结果")).font(.headline)
+ ForEach(model.samples[index].results) { row in
+ VStack(alignment: .leading) {
+ Text(title(row.mode) + (row.error ? L(" · Failed", " · 失败") : "")).font(.headline)
+ Text(row.text.isEmpty ? L("No result", "无结果") : row.text).textSelection(.enabled)
+ }
+ }
+ }
+ } else { Text(L("Add your first sample to begin.", "添加第一条样本开始评测。")) }
+ }.padding(16)
+ }.onAppear { settingsModel?.cancelEvaluation = { [weak evaluation = model] in evaluation?.cancel() } }
+ .onDisappear { model.cancel(); model.save(); settingsModel?.cancelEvaluation = nil }
+ }
+}
diff --git a/macos/Sources/TranscriptionManager.swift b/macos/Sources/TranscriptionManager.swift
index 2888344..469747b 100644
--- a/macos/Sources/TranscriptionManager.swift
+++ b/macos/Sources/TranscriptionManager.swift
@@ -11,6 +11,7 @@ final class TranscriptionManager {
private var client: ASRTransport?
private let polisher = PolishCoordinator()
private var polishAvailable = false
+ private var latency = InputLatency()
private var rawText = ""
private var speaking = false
private var sendEnter = false
@@ -21,10 +22,11 @@ final class TranscriptionManager {
private var session = UUID()
private var target: InputTarget?
private var updateSafeAfter: TimeInterval = 0
- var canInstallUpdate: Bool { state.recordingState == .idle && !primed && ProcessInfo.processInfo.systemUptime >= updateSafeAfter }
+ var canInstallUpdate: Bool { state.recordingState == .idle && !state.inputPending && !state.evaluationBusy && !primed && ProcessInfo.processInfo.systemUptime >= updateSafeAfter }
private var finalGate = FinalResultGate()
private var quietTimer: DispatchWorkItem?
private var timeout: DispatchWorkItem?
+ private var retryTimeout: DispatchWorkItem?
var canRecord: (() -> Bool)?
var onLoginNeeded: (() -> Void)?
@@ -57,9 +59,9 @@ final class TranscriptionManager {
hotkey.start()
}
func startRecording() {
- defer { hotkey.setEscapeHandlingEnabled(state.recordingState != .idle || overlay.isVisible, recording: state.isRecording) }
+ defer { hotkey.setEscapeHandlingEnabled(state.recordingState != .idle || state.inputPending || overlay.isVisible, recording: state.isRecording) }
if state.recordingState == .polishing { polisher.useOriginal(); return }
- guard state.recordingState == .idle, canRecord?() ?? true else { return }
+ guard state.recordingState == .idle, !state.inputPending, !state.evaluationBusy, canRecord?() ?? true else { return }
settings = SettingsStore.shared.value
delivery.cancel()
let params = settings.provider == .doubao ? ASRParamsStore.load() : nil
@@ -77,6 +79,7 @@ final class TranscriptionManager {
let token = session
let transport: ASRTransport = settings.provider == .doubao ? DoubaoASRClient() : APIASRClient(provider: settings.provider)
client = transport
+ latency = InputLatency()
rawText = ""; speaking = false; finalGate = FinalResultGate()
state.transcriptionText = ""; state.errorMessage = nil; state.overlayStatus = ""
let polishKey = settings.polishEnabled ? (SecretStore.load("polish-api-key") ?? "") : ""
@@ -145,6 +148,7 @@ final class TranscriptionManager {
}
func stopRecording() {
guard state.recordingState == .starting || state.recordingState == .recording else { return }
+ latency.stop(at: ProcessInfo.processInfo.systemUptime)
setState(.stopping); audio.stopCapture(); client?.finishSending()
// Bound slow handshakes without authorizing delivery of incomplete text.
scheduleTimeout(seconds: 8, token: session) { [weak self] in
@@ -177,6 +181,8 @@ final class TranscriptionManager {
}
private func complete() {
guard state.recordingState == .starting || state.recordingState == .recording || state.recordingState == .stopping else { return }
+ latency.stop(at: ProcessInfo.processInfo.systemUptime)
+ latency.mark("asr", at: ProcessInfo.processInfo.systemUptime)
let text = rawText.trimmingCharacters(in: .whitespacesAndNewlines)
timeout?.cancel(); quietTimer?.cancel(); quietTimer = nil; audio.stopCapture(); audio.onAudioData = nil; audio.onRMS = nil; audio.onError = nil
client?.disconnect(); client = nil
@@ -194,6 +200,8 @@ final class TranscriptionManager {
}
}
private func submit(_ text: String, polished: Bool) {
+ latency.mark("polish", at: ProcessInfo.processInfo.systemUptime)
+ var timing = latency
let captured = target
let enter = sendEnter
let original = rawText
@@ -208,25 +216,32 @@ final class TranscriptionManager {
state.feedback = polishAvailable ? L("Polishing unavailable or skipped; original text used.", "润色未完成或已跳过,本次使用原文。") : L("Polishing is enabled but no API key is saved; original text used.", "润色已开启但未保存 API Key,本次使用原文。")
} else { state.feedback = L("Original text", "原文") }
if historyFailed { state.feedback += L(" Local history could not be saved.", " 本地历史保存失败。") }
- guard UserDefaults.standard.object(forKey: "autoPaste") as? Bool ?? true else { return }
+ guard UserDefaults.standard.object(forKey: "autoPaste") as? Bool ?? true else {
+ try? PersonalDataStore.shared.saveTimings(historyID, values: timing.values); return
+ }
let token = session
hotkey.setEscapeHandlingEnabled(true)
+ state.inputPending = true
updateSafeAfter = ProcessInfo.processInfo.systemUptime + 1.2
delivery.deliver(text, target: captured, method: settings.inputMethod, sendEnter: enter) { [weak self] sent in
+ timing.mark("delivery", at: ProcessInfo.processInfo.systemUptime)
+ try? PersonalDataStore.shared.saveTimings(historyID, values: timing.values)
try? PersonalDataStore.shared.status(historyID, sent ? "sent" : "failed")
guard self?.session == token else { return }
+ self?.state.inputPending = false
self?.hotkey.setEscapeHandlingEnabled(false)
if !sent { self?.state.errorMessage = L("Target changed or input failed. Text kept in the app.", "目标已变化或输入失败,文字已保留在应用中。") }
}
}
func finishWithEnter() {
+ guard !state.evaluationBusy, !state.inputPending else { return }
if state.recordingState == .polishing { sendEnter = true; polisher.useOriginal() }
else if state.isRecording { sendEnter = true; stopRecording() }
else if state.recordingState == .stopping { sendEnter = true }
else { PasteHelper.sendShortcut(Shortcut(keyCode: 36, modifiers: 0)) }
}
func voiceTest() {
- guard state.recordingState == .idle else { return }
+ guard state.recordingState == .idle, !state.inputPending else { return }
testMode = true; startRecording()
let token = session
DispatchQueue.main.asyncAfter(deadline: .now() + 5) { [weak self] in
@@ -235,21 +250,26 @@ final class TranscriptionManager {
if state.recordingState == .idle { testMode = false }
}
func retryLast() {
+ guard state.recordingState == .idle, !state.inputPending, !state.evaluationBusy, !state.lastTranscript.isEmpty else { return }
updateSafeAfter = ProcessInfo.processInfo.systemUptime + 4.5
- guard state.recordingState == .idle, !state.lastTranscript.isEmpty else { return }
let token = session, text = state.lastTranscript
+ state.inputPending = true
hotkey.setEscapeHandlingEnabled(true)
state.feedback = L("Choose a text field within 3 seconds. No Enter will be sent.", "请在三秒内点击目标输入框,本次不发送回车。")
- DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self] in
+ let item = DispatchWorkItem { [weak self] in
guard let self = self, self.session == token, self.state.recordingState == .idle else { return }
+ self.retryTimeout = nil
let historyID = try? PersonalDataStore.shared.record(original: text, output: text, polished: false)
self.delivery.deliver(text, target: InputTarget.capture(), method: SettingsStore.shared.value.inputMethod) { sent in
try? PersonalDataStore.shared.status(historyID, sent ? "sent" : "failed")
guard self.session == token else { return }
+ self.state.inputPending = false
self.hotkey.setEscapeHandlingEnabled(false)
self.state.feedback = sent ? L("Input attempted", "已发送输入操作") : L("Target unavailable; text kept", "目标不可用,文字已保留")
}
}
+ retryTimeout = item
+ DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: item)
}
private func configureAudioCallbacks() {
let audioToken = session
@@ -278,7 +298,7 @@ final class TranscriptionManager {
try audio.startCapture(deviceID: SettingsStore.shared.value.microphoneID)
}
private func prime() {
- guard state.recordingState == .idle, !primed, canRecord?() ?? true,
+ guard state.recordingState == .idle, !state.inputPending, !state.evaluationBusy, !primed, canRecord?() ?? true,
AVCaptureDevice.authorizationStatus(for: .audio) == .authorized else { return }
delivery.cancel(); session = UUID()
target = InputTarget.capture(); primedAudio.removeAll(); primed = true
@@ -304,6 +324,7 @@ final class TranscriptionManager {
}
func cancel() {
session = UUID(); timeout?.cancel(); timeout = nil; quietTimer?.cancel(); quietTimer = nil; finalGate = FinalResultGate()
+ retryTimeout?.cancel(); retryTimeout = nil; state.inputPending = false
polisher.cancel(); primed = false; primedAudio.removeAll(); testMode = false; sendEnter = false
delivery.cancel(); audio.stopCapture(); audio.onAudioData = nil; audio.onRMS = nil; audio.onError = nil
client?.disconnect(); client = nil; target = nil
diff --git a/macos/Tests/Input/RetryCheck.swift b/macos/Tests/Input/RetryCheck.swift
new file mode 100644
index 0000000..c3a89e8
--- /dev/null
+++ b/macos/Tests/Input/RetryCheck.swift
@@ -0,0 +1,98 @@
+import AppKit
+import AVFoundation
+
+// Dependencies are inert: no microphone, permissions, credentials or real input.
+enum RecognitionProvider { case doubao, volcengine, deepgram; var rawValue: String { "synthetic" } }
+struct MacSettings { var provider: RecognitionProvider = .doubao; var polishEnabled = false; var inputMethod = "clipboard"; var microphoneID = "" }
+@MainActor final class SettingsStore { static let shared = SettingsStore(); var value = MacSettings() }
+enum SecretStore { static func load(_ key: String) -> String? { nil } }
+enum ASRParamsStore { static func load() -> Int? { nil }; static func clear() {} }
+func L(_ english: String, _ chinese: String) -> String { english }
+struct Shortcut { var keyCode: UInt16; var modifiers: Int }
+struct InputTarget { static func capture() -> InputTarget? { InputTarget() } }
+@MainActor final class PasteHelper {
+ static var events: [String] = []
+ static var pending: ((Bool) -> Void)?
+ func cancel() {}
+ func deliver(_ text: String, target: InputTarget?, method: String, sendEnter: Bool = false, completion: @escaping (Bool) -> Void) {
+ Self.events.append("paste"); Self.pending = completion
+ }
+ static func sendShortcut(_ shortcut: Shortcut) { events.append("enter") }
+}
+final class AudioCaptureManager {
+ var onAudioData: ((Data) -> Void)?; var onRMS: ((Double) -> Void)?; var onError: (() -> Void)?
+ func startCapture(deviceID: String) throws { fatalError("Audio must not be used") }
+ func stopCapture() {}
+}
+@MainActor final class OverlayPanel { var isVisible = false; func showOverlay() { isVisible = true }; func hideOverlay() { isVisible = false } }
+final class HotkeyManager {
+ enum HotkeyEvent { case start, stop, cancel, enter, prime, discard }
+ var onHotkeyEvent: ((HotkeyEvent) -> Void)?
+ func setEscapeHandlingEnabled(_ enabled: Bool, recording: Bool = false) {}
+ func start() {}
+}
+@MainActor final class PolishCoordinator {
+ var onPreview: ((String, Bool) -> Void)?; var onProgress: ((String) -> Void)?
+ func begin(settings: MacSettings, key: String) {}
+ func update(text: String, speaking: Bool) {}
+ func useOriginal() {}
+ func cancel() {}
+ func finish(text: String, completion: @escaping (String, Bool) -> Void) { completion(text, false) }
+}
+protocol ASRTransport: AnyObject {
+ var onOpen: (() -> Void)? { get set }; var onResult: ((String) -> Void)? { get set }
+ var onFinish: (() -> Void)? { get set }; var onAudioDrained: (() -> Void)? { get set }
+ var onError: (() -> Void)? { get set }; var onAuthError: (() -> Void)? { get set }
+ func sendAudio(_ data: Data); func finishSending(); func disconnect()
+}
+class DoubaoASRClient: ASRTransport {
+ var onOpen: (() -> Void)?; var onResult: ((String) -> Void)?; var onFinish: (() -> Void)?
+ var onAudioDrained: (() -> Void)?; var onError: (() -> Void)?; var onAuthError: (() -> Void)?
+ func sendAudio(_ data: Data) {}; func finishSending() {}; func disconnect() {}
+ func connect(params: Int) { fatalError("Network must not be used") }
+}
+final class APIASRClient: DoubaoASRClient {
+ init(provider: RecognitionProvider) {}
+ func connect(apiKey: String) { fatalError("Network must not be used") }
+}
+final class PersonalDataStore {
+ static let shared = PersonalDataStore()
+ func record(original: String, output: String, polished: Bool) throws -> String? { UUID().uuidString }
+ func saveTimings(_ id: String?, values: [String: Double]) throws {}
+ func status(_ id: String?, _ value: String) throws {}
+}
+
+@main struct RetryCheck {
+ @MainActor static func main() {
+ func wait() { RunLoop.current.run(until: Date().addingTimeInterval(3.2)) }
+ let state = AppState(); state.lastTranscript = "synthetic"
+ let manager = TranscriptionManager(appState: state, overlayPanel: OverlayPanel(), hotkeyManager: HotkeyManager())
+ manager.retryLast(); manager.retryLast(); manager.finishWithEnter()
+ precondition(state.inputPending && !manager.canInstallUpdate)
+ precondition(PasteHelper.events.isEmpty, "No Enter during countdown")
+ wait()
+ precondition(PasteHelper.events == ["paste"], "Repeated clicks must deliver once")
+ precondition(state.inputPending, "Keep ownership until delivery completes")
+ manager.retryLast(); manager.finishWithEnter(); manager.startRecording()
+ precondition(PasteHelper.events == ["paste"])
+ PasteHelper.pending?(true)
+ precondition(!state.inputPending)
+ manager.finishWithEnter()
+ precondition(PasteHelper.events == ["paste", "enter"], "Standalone Enter works after delivery")
+
+ manager.retryLast(); manager.cancel()
+ precondition(!state.inputPending)
+ PasteHelper.events = []
+ manager.retryLast()
+ wait()
+ precondition(PasteHelper.events == ["paste"], "Cancelled countdown must not fire in a new retry")
+ let oldCompletion = PasteHelper.pending
+ manager.cancel(); manager.retryLast()
+ oldCompletion?(false)
+ precondition(state.inputPending, "Old completion must not release the new retry")
+ manager.cancel()
+ wait()
+ precondition(PasteHelper.events == ["paste"])
+ print("PASS: retry single delivery, pending Enter suppression, cancellation and stale completion isolation; no real input")
+ }
+}
diff --git a/macos/Tests/Network/APIASRCheck.swift b/macos/Tests/Network/APIASRCheck.swift
index cfa9463..6a03f7f 100644
--- a/macos/Tests/Network/APIASRCheck.swift
+++ b/macos/Tests/Network/APIASRCheck.swift
@@ -3,10 +3,11 @@ import Foundation
@main
struct APIASRCheck {
static func main() {
- guard CommandLine.arguments.count == 3, let endpoint = URL(string: CommandLine.arguments[1]) else { exit(1) }
+ guard (3...4).contains(CommandLine.arguments.count), let endpoint = URL(string: CommandLine.arguments[1]) else { exit(1) }
let provider: RecognitionProvider = CommandLine.arguments[2] == "volcengine" ? .volcengine : .deepgram
try! PersonalDataStore.shared.saveWords("Midscene\nVibelet")
- let client = APIASRClient(provider: provider, endpoint: endpoint)
+ let raw = CommandLine.arguments.last == "raw"
+ let client = APIASRClient(provider: provider, endpoint: endpoint, hotwords: raw ? [] : nil)
var finished = false, opened = false, drained = false, text = "", failed = false
client.onOpen = { DispatchQueue.main.async { opened = true } }
client.onAudioDrained = { DispatchQueue.main.async { drained = true } }
diff --git a/macos/Tests/Network/api_check.py b/macos/Tests/Network/api_check.py
index 59ccfcf..fc9e6f6 100644
--- a/macos/Tests/Network/api_check.py
+++ b/macos/Tests/Network/api_check.py
@@ -10,7 +10,7 @@ import sys
import threading
-def check(provider):
+def check(provider, raw=False):
errors = []
listener = socket.socket()
listener.bind(('127.0.0.1', 0))
@@ -68,7 +68,10 @@ def check(provider):
assert opcode == 2 and data[:4] == bytes([0x11, 0x11, 0x11, 0])
body = json.loads(gzip.decompress(data[12:]))
assert body['audio']['rate'] == 16000 and body['request']['enable_punc'] is True
- assert json.loads(body['request']['corpus']['context']) == {'hotwords': [{'word': 'Midscene'}, {'word': 'Vibelet'}]}
+ if raw:
+ assert 'corpus' not in body['request']
+ else:
+ assert json.loads(body['request']['corpus']['context']) == {'hotwords': [{'word': 'Midscene'}, {'word': 'Vibelet'}]}
payload = gzip.compress(b'{}')
send(2, bytes([0x11, 0x91, 0x11, 0]) + struct.pack('!iI', 1, len(payload)) + payload)
opcode, data = receive()
@@ -91,7 +94,7 @@ def check(provider):
thread = threading.Thread(target=serve, daemon=True)
thread.start()
- result = subprocess.run([sys.argv[1], f'ws://127.0.0.1:{port}/asr', provider], timeout=12)
+ result = subprocess.run([sys.argv[1], f'ws://127.0.0.1:{port}/asr', provider] + (['raw'] if raw else []), timeout=12)
thread.join(timeout=10)
if errors or thread.is_alive():
raise SystemExit('FAIL: ' + repr(errors or ['fixture did not exit']))
@@ -101,3 +104,5 @@ def check(provider):
for provider in ['volcengine', 'deepgram']:
check(provider)
+
+check('volcengine', raw=True)
diff --git a/macos/Tests/Settings/AutoSaveCheck.swift b/macos/Tests/Settings/AutoSaveCheck.swift
index 70a455a..9950845 100644
--- a/macos/Tests/Settings/AutoSaveCheck.swift
+++ b/macos/Tests/Settings/AutoSaveCheck.swift
@@ -1,8 +1,21 @@
-import Foundation
+import AppKit
@main
struct AutoSaveCheck {
@MainActor static func main() {
+ let hotkey = HotkeyManager()
+ for shortcut in [Shortcut(keyCode: 9, modifiers: 4), Shortcut(keyCode: 49, modifiers: 3), Shortcut(keyCode: 58, modifiers: 0)] {
+ var settings = MacSettings(); settings.shortcut = shortcut
+ hotkey.configure(settings)
+ var actions = 0
+ hotkey.onHotkeyEvent = { _ in actions += 1 }
+ let (down, up) = PasteHelper.shortcutEvents(Shortcut(keyCode: 9, modifiers: 4))!
+ precondition(down.getIntegerValueField(.eventSourceUserData) == HotkeyManager.syntheticMarker)
+ precondition(up.getIntegerValueField(.eventSourceUserData) == HotkeyManager.syntheticMarker)
+ precondition(hotkey.handle(.keyDown, down) != nil && hotkey.handle(.keyUp, up) != nil)
+ precondition(actions == 0, "Synthetic paste must not trigger dictation")
+ }
+ print("PASS: synthetic paste bypasses configurable hotkeys; no event tap or posted key events")
func wait(_ seconds: Double) { RunLoop.current.run(until: Date().addingTimeInterval(seconds)) }
let state = AppState()
let model = SettingsModel(state: state)
diff --git a/macos/Tests/Settings/PersonalUICheck.swift b/macos/Tests/Settings/PersonalUICheck.swift
index 70fc331..d6a607f 100644
--- a/macos/Tests/Settings/PersonalUICheck.swift
+++ b/macos/Tests/Settings/PersonalUICheck.swift
@@ -11,6 +11,9 @@ import SwiftUI
var settings: SettingsWindow?
var parent: NSWindow?
var model: PersonalModel?
+ var evaluation: SpeechEvaluationModel?
+ var sourceText = "用 Midjourney 编写自动化测试"
+ var expectedText = "用 Midscene 编写自动化测试"
func applicationDidFinishLaunching(_ notification: Notification) {
guard Bundle.main.bundleIdentifier?.hasPrefix("md.lifeos.doubao-say.update-verify.") == true else { exit(2) }
NSApp.setActivationPolicy(.regular)
@@ -19,17 +22,48 @@ import SwiftUI
try store.clearHistory()
for memory in try store.corrections() { try store.forgetCorrection(memory.id) }
try store.saveWords("Midscene\nVibelet")
- let id = try store.record(original: "用 Midjourney 编写自动化测试", output: "用 Midjourney 编写自动化测试", polished: true, status: "sent")!
let page = ProcessInfo.processInfo.environment["PERSONAL_PAGE"] ?? "history"
+ if page == "selection" { sourceText = "用 Midjourney 画图,用 Midjourney 写测试"; expectedText = "用 Midjourney 画图,用 Midscene 写测试" }
+ let id = try store.record(original: sourceText, output: sourceText, polished: true, status: "sent")!
+ try store.saveTimings(id, values: ["asr": 320, "polish": 180, "delivery": 90, "total": 590])
if page == "confirmed" || page == "memory" { try store.confirmCorrection(id, recognized: "Midjourney", corrected: "Midscene") }
- if page == "editor" || page == "cancel" {
+ if page == "evaluation" || page == "evaluation-results" {
+ let state = AppState()
+ try SpeechSampleStore().save([])
+ let model = SpeechEvaluationModel(state: state); evaluation = model
+ model.add()
+ model.edit(\.reference, "用 Midscene 编写自动化测试")
+ model.edit(\.terms, "Midscene")
+ if let index = model.index {
+ try model.store.saveAudio(Data(repeating: 0, count: 32000), id: model.samples[index].id)
+ model.samples[index].audioBytes = 32000
+ if page == "evaluation-results" {
+ model.samples[index].results = [SpeechResult(mode: "raw", text: "用 Midjourney 编写自动化测试", elapsedMS: 1800), SpeechResult(mode: "hotwords", text: "用 Midscene 编写自动化测试", elapsedMS: 1700), SpeechResult(mode: "hotwords+polish", text: "用 Midscene 编写自动化测试。", elapsedMS: 1900)]
+ }
+ model.save(); model.refreshSummary()
+ }
+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 700, height: 640), styleMask: [.titled, .closable], backing: .buffered, defer: false)
+ window.title = "Speech evaluation verification"; window.center(); parent = window
+ window.contentView = NSHostingView(rootView: SpeechEvaluationView(state: state, model: model))
+ window.makeKeyAndOrderFront(nil)
+ } else if page == "editor" || page == "cancel" || page == "selection" {
let model = PersonalModel(store: store); self.model = model
let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 660, height: 540), styleMask: [.titled, .closable], backing: .buffered, defer: false)
window.title = "Personal learning verification"; window.center(); parent = window
window.contentView = NSHostingView(rootView: InputHistoryView(state: AppState(), model: model))
window.makeKeyAndOrderFront(nil)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
- model.beginCorrection(model.history[0]); model.recognizedTerm = "Midjourney"; model.correctedTerm = "Midscene"
+ if page == "selection" {
+ guard let view = self.findTextView(window.contentView!, text: self.sourceText) else { print("FAIL: native selectable history"); exit(1) }
+ view.setSelectedRange((self.sourceText as NSString).range(of: "Midjourney", options: .backwards))
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {
+ model.beginCorrection(model.history[0])
+ guard model.recognizedTerm == "Midjourney", model.correctionSelection != nil else { print("FAIL: selected term not carried"); exit(1) }
+ model.correctedTerm = "Midscene"
+ }
+ } else {
+ model.beginCorrection(model.history[0]); model.recognizedTerm = "Midjourney"; model.correctedTerm = "Midscene"
+ }
}
} else {
let window = SettingsWindow(state: AppState()); settings = window
@@ -38,7 +72,11 @@ import SwiftUI
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {
NSApp.activate(ignoringOtherApps: true)
- if let parent = self.parent {
+ if page.hasPrefix("evaluation"), let parent = self.parent {
+ guard self.evaluation?.ready == true, self.evaluation?.busy == false else { print("FAIL: evaluation drafts"); exit(1) }
+ print("CAPTURE_WINDOW:\(parent.windowNumber)"); fflush(stdout)
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.7) { self.finish() }
+ } else if let parent = self.parent {
guard let sheet = parent.attachedSheet else { print("FAIL: correction sheet missing"); exit(1) }
sheet.makeKeyAndOrderFront(nil)
print("CAPTURE_WINDOW:\(sheet.windowNumber)"); fflush(stdout)
@@ -50,6 +88,11 @@ import SwiftUI
}
} catch { print("FAIL: synthetic fixture setup"); exit(1) }
}
+ func findTextView(_ root: NSView, text: String) -> NSTextView? {
+ if let view = root as? NSTextView, view.string == text { return view }
+ for child in root.subviews { if let found = findTextView(child, text: text) { return found } }
+ return nil
+ }
func activateDefault(cancel: Bool) {
guard let sheet = parent?.attachedSheet else { exit(1) }
let code: UInt16 = cancel ? 53 : 36
@@ -64,8 +107,8 @@ import SwiftUI
let row = try PersonalDataStore.shared.history()[0]
guard self.parent?.attachedSheet == nil,
memories.count == (cancel ? 0 : 1),
- row.confirmed == (cancel ? "" : "用 Midscene 编写自动化测试"),
- row.output == "用 Midjourney 编写自动化测试" else { print("FAIL: native confirmation/cancel"); exit(1) }
+ row.confirmed == (cancel ? "" : self.expectedText),
+ row.output == self.sourceText else { print("FAIL: native confirmation/cancel"); exit(1) }
print("PASS: native \(cancel ? "cancel" : "confirm"), explicit memory, immutable ASR and output")
self.finish()
} catch { exit(1) }
diff --git a/macos/Tests/SpeechWorkbenchTests.swift b/macos/Tests/SpeechWorkbenchTests.swift
new file mode 100644
index 0000000..345d3c9
--- /dev/null
+++ b/macos/Tests/SpeechWorkbenchTests.swift
@@ -0,0 +1,39 @@
+import XCTest
+@testable import DoubaoSayCore
+
+final class SpeechWorkbenchTests: XCTestCase {
+ func testSelectedRepeatedTermPreservesFirstAndUnicode() throws {
+ let text = "用 Midjourney 画图,用 Midjourney 写测试"
+ let range = (text as NSString).range(of: "Midjourney", options: .backwards)
+ let result = try PersonalCorrections.confirmation(original: text, output: text, recognized: "Midjourney", corrected: "Midscene", selection: range)
+ XCTAssertEqual(result.2, "用 Midjourney 画图,用 Midscene 写测试")
+ XCTAssertThrowsError(try PersonalCorrections.confirmation(original: text, output: text, recognized: "Midjourney", corrected: "Midscene", selection: NSRange(location: 0, length: 3)))
+ }
+ func testLatencyExcludesRecordingAndDuplicateStages() {
+ var timing = InputLatency(); timing.mark("asr", at: 100); XCTAssertTrue(timing.values.isEmpty)
+ timing.stop(at: 130); timing.stop(at: 131); timing.mark("asr", at: 130.25); timing.mark("polish", at: 131); timing.mark("delivery", at: 131.1)
+ XCTAssertEqual(timing.values["asr"]!, 250, accuracy: 0.01)
+ XCTAssertEqual(timing.values["total"]!, 1100, accuracy: 0.01)
+ }
+ func testNegativeCaseAndFailureScoring() {
+ var sample = SpeechSample(reference: "Use Midjourney for art", protectedTerms: "Midjourney")
+ XCTAssertTrue(SpeechScoring.valid(sample))
+ sample.results = [SpeechResult(mode: "raw", text: sample.reference, elapsedMS: 100), SpeechResult(mode: "hotwords", text: "Use Midscene for art", elapsedMS: 200)]
+ XCTAssertEqual(SpeechScoring.summary([sample], mode: "raw")["cer"], 0)
+ XCTAssertEqual(SpeechScoring.summary([sample], mode: "hotwords")["protected"], 1)
+ XCTAssertEqual(SpeechScoring.summary([sample], mode: "missing")["failed"], 1)
+ sample.terms = "Unrelated"; XCTAssertFalse(SpeechScoring.valid(sample))
+ }
+ func testLocalDraftAndAudioPersistence() throws {
+ let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: folder) }
+ let store = SpeechSampleStore(directory: folder); let sample = SpeechSample()
+ try store.save([sample]); XCTAssertEqual(try store.load().first?.id, sample.id)
+ XCTAssertThrowsError(try store.audio("../escape"))
+ XCTAssertThrowsError(try store.saveAudio(Data([0]), id: sample.id))
+ try store.saveAudio(Data([0, 0]), id: sample.id)
+ let attributes = try FileManager.default.attributesOfItem(atPath: store.audio(sample.id).path)
+ XCTAssertEqual(attributes[.posixPermissions] as? Int, 0o600)
+ try store.remove(sample.id)
+ }
+}
diff --git a/macos/Tests/Transport/TransportCheck.swift b/macos/Tests/Transport/TransportCheck.swift
index 7976cdc..7c9b8e5 100644
--- a/macos/Tests/Transport/TransportCheck.swift
+++ b/macos/Tests/Transport/TransportCheck.swift
@@ -6,10 +6,11 @@ struct TransportCheck {
let client = DoubaoASRClient(endpoint: CommandLine.arguments[1])
let semaphore = DispatchSemaphore(value: 0)
var ok = false
+ let expectedError = CommandLine.arguments.count > 2 ? CommandLine.arguments[2] : ""
client.onResult = { text in ok = text == "synthetic result" }
client.onFinish = { semaphore.signal() }
- client.onError = { semaphore.signal() }
- client.onAuthError = { semaphore.signal() }
+ client.onError = { ok = expectedError == "generic"; semaphore.signal() }
+ client.onAuthError = { ok = expectedError == "auth"; semaphore.signal() }
// Exercise stopping before connect: all captured bytes must precede silence.
client.sendAudio(Data([1, 2, 3, 4]))
client.finishSending()
@@ -17,6 +18,6 @@ struct TransportCheck {
client.connect(params: DoubaoASRParams(cookies: ["fake": "test"], deviceId: "test", webId: "test"))
guard semaphore.wait(timeout: .now() + 8) == .success, ok else { exit(1) }
client.disconnect()
- print("PASS: queued audio before connect, ordered silence, rejected post-stop audio, result and finish")
+ print(expectedError.isEmpty ? "PASS: queued audio before connect, ordered silence, rejected post-stop audio, result and finish" : "PASS: handshake failure classified as \(expectedError)")
}
}
diff --git a/macos/Tests/Transport/check.py b/macos/Tests/Transport/check.py
index 7adc782..a7267ca 100644
--- a/macos/Tests/Transport/check.py
+++ b/macos/Tests/Transport/check.py
@@ -7,6 +7,7 @@ import struct
import subprocess
import sys
import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
errors = []
listener = socket.socket()
@@ -76,4 +77,24 @@ result = subprocess.run([sys.argv[1], f'ws://127.0.0.1:{port}/asr'], timeout=12)
thread.join(timeout=10)
if errors or thread.is_alive():
raise SystemExit(f'FAIL: {errors or "fixture did not exit"}')
-raise SystemExit(result.returncode)
+if result.returncode:
+ raise SystemExit(result.returncode)
+
+for status in (401, 403, 500):
+ class Rejection(BaseHTTPRequestHandler):
+ def log_message(self, *_):
+ pass
+
+ def do_GET(self):
+ self.send_response(status)
+ self.send_header('Content-Length', '0')
+ self.end_headers()
+
+ server = ThreadingHTTPServer(('127.0.0.1', 0), Rejection)
+ worker = threading.Thread(target=server.serve_forever, daemon=True)
+ worker.start()
+ try:
+ subprocess.run([sys.argv[1], f'ws://127.0.0.1:{server.server_port}/asr',
+ 'auth' if status in (401, 403) else 'generic'], timeout=12, check=True)
+ finally:
+ server.shutdown(); server.server_close(); worker.join(timeout=2)
diff --git a/macos/check.sh b/macos/check.sh
index 0da1920..97401d3 100755
--- a/macos/check.sh
+++ b/macos/check.sh
@@ -25,3 +25,10 @@ xcrun swiftc -swift-version 5 -target "$(uname -m)-apple-macos13.0" \
python3 macos/Tests/Network/api_check.py build/macos/tests/api-asr-check
bash macos/Tests/Settings/check.sh
+
+xcrun swiftc -swift-version 5 -target "$(uname -m)-apple-macos13.0" \
+ -module-cache-path build/macos/module-cache \
+ macos/Sources/AppState.swift macos/Sources/InputLatency.swift macos/Sources/FinalResultGate.swift \
+ macos/Sources/TranscriptionManager.swift macos/Tests/Input/RetryCheck.swift \
+ -o build/macos/tests/retry-check
+build/macos/tests/retry-check
diff --git a/manifest.json b/manifest.json
index c95863d..b152078 100644
--- a/manifest.json
+++ b/manifest.json
@@ -2,7 +2,7 @@
"schemaVersion": 1,
"id": "md.lifeos.doubao-say",
"name": "Doubao Say",
- "version": "1.6.0",
+ "version": "1.7.0",
"author": "quanru and contributors",
"description": "Doubao Say turns speech into polished text with live captions and configurable tap or hold triggers on Wayland.",
"kinds": [
diff --git a/packaging/INSTALL.md b/packaging/INSTALL.md
index 80df5e9..4205760 100644
--- a/packaging/INSTALL.md
+++ b/packaging/INSTALL.md
@@ -1,4 +1,4 @@
-# Doubao Say 1.6.0
+# Doubao Say 1.7.0
[Website](https://doubao-say.lifeos.md/) · [简体中文安装指南](https://doubao-say.lifeos.md/zh/guide/install)
diff --git a/packaging/SPEECH_EVAL.md b/packaging/SPEECH_EVAL.md
index 570a886..76e6b65 100644
--- a/packaging/SPEECH_EVAL.md
+++ b/packaging/SPEECH_EVAL.md
@@ -101,3 +101,33 @@ accuracy. Repeat the complete test under the same conditions, check per-sample
failures, and inspect negative cases. A hotword improving Midscene while corrupting
legitimate Midjourney is a regression. The tool makes no claim of measurable
personal-accent improvement until actual recordings have been evaluated.
+
+## In-app evaluation (Mac and Linux)
+
+Open **Speech evaluation** in Mac Settings, or in Linux **Vocabulary & history**.
+Add a sample, record locally (maximum 60 seconds), and enter the reference you
+actually spoke. Target and protected terms use one term per line and must occur
+in that reference. Drafts save automatically; deleting a sample removes its local
+recording. Evaluation recordings remain until you delete them, separately from
+the 30-day dictation history.
+
+**Start comparison** explicitly uploads each recording twice to the official
+Volcengine ASR using the saved key, with and without the current bounded personal
+hotword list. Optional polishing uses the configured polishing credentials.
+References and scoring labels never enter requests or personal vocabulary.
+The view shows per-sample texts, character errors, term accuracy, protected-term
+loss, failed samples and P50/P95 replay time. Cancel stops subsequent requests;
+completed results remain available. Linux may wait for an in-flight polishing
+request to time out before finishing cancellation. Closing the page/window stops
+recording and comparison. Evaluation cannot run alongside dictation or mic checks.
+
+Reference/label edits and recording again clear that sample's old results.
+Repeating comparison clears previous results for the whole set to avoid mixing
+runs. Scores include missing/failed samples. Replay times include connection and
+recording playback; they are not daily input latency.
+
+Input history now shows daily **stop-to-ASR / polishing / input / total** timings.
+The clock starts when dictation stops, excluding recording duration. Polishing
+measures remaining work after ASR (a speculative cached result can be nearly
+instant). Input measures the attempt to deliver text, and its status still needs
+to be checked separately. Old entries without timing metadata remain readable.
diff --git a/pyproject.toml b/pyproject.toml
index eb17b22..658c8a2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "doubao-say"
-version = "1.6.0"
+version = "1.7.0"
description = "Global push-to-hold voice input for Linux/Wayland, backed by Doubao ASR"
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/doubao_input/app.py b/src/doubao_input/app.py
index 8679ad0..44a3a39 100644
--- a/src/doubao_input/app.py
+++ b/src/doubao_input/app.py
@@ -107,6 +107,8 @@ class DoubaoInputApp(Gtk.Application):
self._rms_speaking = False
self._asr_probe = None
self._diagnostics = DiagnosticTrace()
+ from doubao_input.input_latency import InputLatency
+ self._input_latency = InputLatency()
self.app_state.connect("transcription-text-changed", self._prepolish_text_changed)
try:
self.settings = Settings.load()
@@ -219,7 +221,7 @@ class DoubaoInputApp(Gtk.Application):
tm.on_cancel_enabled_changed = lambda enabled: None
tm.on_auth_expired = self._on_auth_expired
tm.on_params_needed = self._provide_params
- tm.on_diagnostic = self._diagnostics.add
+ tm.on_diagnostic = self._trace_input
self._tm = tm
# ---- Control window ----
@@ -389,10 +391,15 @@ class DoubaoInputApp(Gtk.Application):
self._history_id = None
self._control.set_feedback(tr("Could not save local input history. Input is still available.", "本地输入历史保存失败,文字仍可输入。"))
+ def _can_evaluate_speech(self):
+ audio = getattr(self, "_audio_capture", None)
+ # A held gesture may be buffering audio while the visible state is idle.
+ return not self._busy() and not (audio and audio.is_capturing)
+
def _show_personal(self):
from doubao_input.ui.personal_window import PersonalWindow
if self._personal_window is None:
- self._personal_window = PersonalWindow(self._personal_store, lambda: self.settings, self._polish_key, self.recent, self._retry_recent)
+ self._personal_window = PersonalWindow(self._personal_store, lambda: self.settings, self._polish_key, self.recent, self._retry_recent, self._can_evaluate_speech)
self._personal_window.show()
def _check_updates(self):
@@ -430,8 +437,16 @@ class DoubaoInputApp(Gtk.Application):
raise ValueError(tr("This installation is started by Omarchy. Disable plugin startup before using a standalone autostart installation.",
"当前安装由 Omarchy 插件启动。请勿同时启用独立应用自启动。"))
if self._busy() or self._triggers.busy:
- raise ValueError(tr("Finish recording and release the trigger before saving", "请先结束录音并松开触发键,再保存设置"))
+ raise ValueError(tr("Finish the current operation and release the trigger before saving", "请先结束当前操作并松开触发键,再保存设置"))
previous = self.settings
+ if previous.asr_provider != settings.asr_provider:
+ # A modal Settings window can open while onboarding's debounce is
+ # pending. Both drafts still belong to the provider being left.
+ for view in (self._control, self._settings_window):
+ if view and not view._flush_asr_key():
+ raise ValueError(tr(
+ "Save the current API key before switching services.",
+ "请先保存当前 API Key,再切换识别服务。"))
def apply_runtime(value, strict):
self._triggers.configure(value, strict=strict)
@@ -451,6 +466,13 @@ class DoubaoInputApp(Gtk.Application):
self._setup_session.microphone_ok = self._setup_session.voice_ok = False
self._control.refresh()
+ def _trace_input(self, stage):
+ self._diagnostics.add(stage)
+ if stage == "gesture_confirmed":
+ self._input_latency.reset()
+ elif stage == "stop_requested":
+ self._input_latency.stop()
+
def _new_transcription_manager(self):
provider = recognition_provider(self.settings.asr_provider)
return TranscriptionManager(
@@ -462,6 +484,9 @@ class DoubaoInputApp(Gtk.Application):
)
def _configure_recognition_backend(self):
+ if self._asr_probe:
+ self._asr_probe.disconnect()
+ self._asr_probe = None
provider = recognition_provider(self.settings.asr_provider)
self._tm.configure_backend(
provider.new_client(),
@@ -488,6 +513,8 @@ class DoubaoInputApp(Gtk.Application):
if getattr(self, "_polish_mode", None) == "final" and self._polisher.busy:
self._cancel_polish(use_original=True)
return
+ if getattr(self, "_personal_window", None) and self._personal_window.evaluation and self._personal_window.evaluation.active:
+ return
if self._mic_test_running or self._triggers.capturing or self._recovery_timer:
return
if self.app_state.recording_state == RecordingState.IDLE and not self._paste_pending:
@@ -501,7 +528,8 @@ class DoubaoInputApp(Gtk.Application):
def _voice_prime(self):
if (not self._mic_test_running and not self._triggers.capturing
and not self._recovery_timer and not self._paste_pending
- and getattr(self, "_polish_mode", None) != "final"):
+ and getattr(self, "_polish_mode", None) != "final"
+ and not (getattr(self, "_personal_window", None) and self._personal_window.evaluation and self._personal_window.evaluation.active)):
self._tm.prime_recording()
def _voice_stop(self):
@@ -512,6 +540,8 @@ class DoubaoInputApp(Gtk.Application):
self._tm.handle_toggle()
def _voice_toggle(self):
+ if getattr(self, "_personal_window", None) and self._personal_window.evaluation and self._personal_window.evaluation.active:
+ return
if getattr(self, "_polish_mode", None) == "final" and self._polisher.busy:
self._cancel_polish(use_original=True)
return
@@ -529,6 +559,8 @@ class DoubaoInputApp(Gtk.Application):
self._voice_stop()
def _voice_enter(self):
+ if getattr(self, "_personal_window", None) and self._personal_window.evaluation and self._personal_window.evaluation.active:
+ return
if self._mic_test_running or self._triggers.capturing or self._recovery_timer:
return
if self._preview_testing:
@@ -546,9 +578,18 @@ class DoubaoInputApp(Gtk.Application):
self._voice_stop()
def _send_enter(self):
- self._delivery.submit_enter(focused_target())
+ self._delivery.submit_enter(focused_target(), changed=self._enter_changed)
return GLib.SOURCE_REMOVE
+ def _enter_changed(self, status):
+ messages = {
+ "pending": tr("Sending Enter…", "正在发送回车…"),
+ "attempted": tr("Enter sent.", "已发送回车。"),
+ "cancelled": tr("Enter cancelled.", "已取消回车。"),
+ }
+ self._control.set_feedback(messages.get(status, tr(
+ "Enter not sent; check the target field.", "未发送回车,请检查目标输入框。")))
+
def _empty_complete(self):
if self._preview_testing:
self._setup_session.complete_voice("")
@@ -570,6 +611,9 @@ class DoubaoInputApp(Gtk.Application):
if self._setup_session.complete_voice(text):
self._control.refresh()
return
+ latency = getattr(self, "_input_latency", None)
+ if latency:
+ latency.mark("asr")
text = DoubaoInputApp._uncommitted_text(self, text)
if not text:
return
@@ -606,6 +650,9 @@ class DoubaoInputApp(Gtk.Application):
self._submit_transcript(text, self._target, send_enter)
def _submit_transcript(self, text, target, send_enter=False, *, original=None):
+ latency = getattr(self, "_input_latency", None)
+ if latency:
+ latency.mark("polish")
self._remember_input(original if original is not None else text, text, original is not None)
self.recent.keep(text)
self._control.set_result(self.recent.text, tr("Ready to input", "准备输入"))
@@ -670,6 +717,10 @@ class DoubaoInputApp(Gtk.Application):
if store:
try:
store.status(self._history_id, status)
+ latency = getattr(self, "_input_latency", None)
+ if latency and status != "pending":
+ latency.mark("delivery")
+ store.save_timings(self._history_id, latency.values)
except Exception:
logger.warning("Could not update local input history")
diagnostics = getattr(self, "_diagnostics", None)
@@ -733,6 +784,8 @@ class DoubaoInputApp(Gtk.Application):
self._recovery_timer = GLib.timeout_add(3000, retry)
def _cancel_input(self):
+ if getattr(self, "_personal_window", None) and self._personal_window.evaluation:
+ self._personal_window.evaluation.cancel()
self._enter_after_paste = False
if self._triggers:
self._triggers.cancel_gesture()
@@ -749,7 +802,7 @@ class DoubaoInputApp(Gtk.Application):
self._tm.handle_cancel()
def _busy(self):
- return (self.app_state.recording_state != RecordingState.IDLE or self._mic_test_running
+ return (bool(getattr(self, "_asr_probe", None)) or bool(getattr(self, "_personal_window", None) and self._personal_window.evaluation and self._personal_window.evaluation.active) or self.app_state.recording_state != RecordingState.IDLE or self._mic_test_running
or self._paste_pending or (self._triggers is not None and self._triggers.capturing)
or self._recovery_timer is not None
or bool(self._polisher and self._polisher.busy))
@@ -1088,14 +1141,12 @@ class DoubaoInputApp(Gtk.Application):
if credentials is None:
raise ValueError(tr("Enter an API key first.", "请先填写 API Key。"))
credentials.validate()
- if self._asr_probe:
- self._asr_probe.disconnect()
probe = self._asr_probe = provider.new_client()
finished = False
- def deliver(result, error):
+ def complete(result, error):
nonlocal finished
if finished or self._asr_probe is not probe:
- return
+ return GLib.SOURCE_REMOVE
finished = True
probe.disconnect()
self._asr_probe = None
@@ -1103,7 +1154,10 @@ class DoubaoInputApp(Gtk.Application):
self._sync_recognition_status()
if self._control:
self._control.refresh()
- GLib.idle_add(completed, result, error)
+ completed(result, error)
+ return GLib.SOURCE_REMOVE
+ def deliver(result, error):
+ GLib.idle_add(complete, result, error)
# A successful WebSocket handshake validates the provider credential.
# No microphone data is needed for this settings test.
probe.on_open = lambda: deliver(tr("API key accepted", "API Key 可用"), "")
@@ -1113,8 +1167,13 @@ class DoubaoInputApp(Gtk.Application):
probe.on_error = lambda _error: deliver(None, tr(
"Connection failed; check the network and service status",
"连接失败,请检查网络和服务状态"))
- probe.prepare()
- probe.connect(credentials)
+ try:
+ probe.prepare()
+ probe.connect(credentials)
+ except Exception:
+ self._asr_probe = None
+ probe.disconnect()
+ raise
def _cancel_login_attempt(self):
self._login_attempt = None
diff --git a/src/doubao_input/diagnostics.py b/src/doubao_input/diagnostics.py
index 635a688..01bda28 100644
--- a/src/doubao_input/diagnostics.py
+++ b/src/doubao_input/diagnostics.py
@@ -11,10 +11,10 @@ from doubao_input.product import VERSION
DIAGNOSTIC_STAGES = frozenset({
- "audio_buffering", "gesture_confirmed", "connection_requested", "connected",
+ "stop_requested", "audio_buffering", "gesture_confirmed", "connection_requested", "connected",
"first_result", "audio_drained", "server_finished", "quiet_finished",
"empty_result", "delivery_pending", "delivery_finished", "cancelled",
- "failed", "timed_out",
+ "failed", "timed_out", "audio_failed",
})
diff --git a/src/doubao_input/doubao/transcription.py b/src/doubao_input/doubao/transcription.py
index d74247a..24f1378 100644
--- a/src/doubao_input/doubao/transcription.py
+++ b/src/doubao_input/doubao/transcription.py
@@ -170,7 +170,11 @@ class TranscriptionManager:
def _trace(self, stage):
if self.on_diagnostic:
- self.on_diagnostic(stage)
+ try:
+ self.on_diagnostic(stage)
+ except Exception:
+ # Support metadata must never prevent audio cleanup or recovery.
+ logger.warning("Could not record diagnostic stage")
def _commit_primed_audio(self) -> None:
with self._prime_lock:
@@ -276,6 +280,7 @@ class TranscriptionManager:
def _stop_recording(self) -> None:
logger.info("Stopping recording...")
self._stopped_at = time.monotonic()
+ self._trace("stop_requested")
self._set_state(RecordingState.STOPPING)
try:
self.audio_capture.finish()
diff --git a/src/doubao_input/inject/delivery.py b/src/doubao_input/inject/delivery.py
index fc25497..55efd6d 100644
--- a/src/doubao_input/inject/delivery.py
+++ b/src/doubao_input/inject/delivery.py
@@ -11,14 +11,16 @@ class Delivery:
self.want_enter = False
self._token = Event()
self._closed = False
+ self._changed = changed
- def _begin(self):
+ def _begin(self, changed=None):
if self.busy or self._closed:
return None
self._token = Event()
self.busy = True
self.want_enter = False
- self.changed("pending")
+ self._changed = changed if changed is not None else self.changed
+ self._changed("pending")
return self._token
def _current(self, token):
@@ -27,7 +29,7 @@ class Delivery:
def _finish(self, token, status):
if self._current(token):
self.busy = self.want_enter = False
- self.changed(status)
+ self._changed(status)
def _run(self, token, work, completed):
if not self._current(token):
@@ -62,8 +64,8 @@ class Delivery:
self.schedule(delay_ms, lambda: self._run(token, paste, pasted))
return True
- def submit_enter(self, target):
- token = self._begin()
+ def submit_enter(self, target, *, changed=None):
+ token = self._begin(changed)
if token is None:
return False
self._run_enter(token, target)
@@ -88,7 +90,7 @@ class Delivery:
was_busy = self.busy
self.busy = self.want_enter = False
if was_busy:
- self.changed("cancelled")
+ self._changed("cancelled")
def close(self, cleanup):
if not self._closed:
diff --git a/src/doubao_input/input_latency.py b/src/doubao_input/input_latency.py
new file mode 100644
index 0000000..696cda4
--- /dev/null
+++ b/src/doubao_input/input_latency.py
@@ -0,0 +1,25 @@
+"""Per-session monotonic timings, without transcripts or recording duration."""
+import time
+
+
+class InputLatency:
+ def __init__(self, clock=time.monotonic):
+ self.clock = clock
+ self.reset()
+
+ def reset(self):
+ self.stopped = None
+ self.values = {}
+ self.last = None
+
+ def stop(self):
+ if self.stopped is None:
+ self.stopped = self.last = self.clock()
+
+ def mark(self, stage):
+ if self.stopped is None or stage in self.values:
+ return
+ now = self.clock()
+ self.values[stage] = round(max(0, now - self.last) * 1000)
+ self.last = now
+ self.values['total'] = round(max(0, now - self.stopped) * 1000)
diff --git a/src/doubao_input/personal.py b/src/doubao_input/personal.py
index deb0163..8870aa0 100644
--- a/src/doubao_input/personal.py
+++ b/src/doubao_input/personal.py
@@ -81,9 +81,11 @@ class PersonalStore:
db.execute("CREATE INDEX IF NOT EXISTS history_created ON history(created)")
db.execute("CREATE TABLE IF NOT EXISTS preferences (key TEXT PRIMARY KEY, value TEXT)")
db.execute("CREATE TABLE IF NOT EXISTS corrections (key TEXT PRIMARY KEY, recognized TEXT, corrected TEXT, context TEXT, created REAL)")
+ db.execute("CREATE TABLE IF NOT EXISTS input_timings (history_id TEXT PRIMARY KEY, data TEXT)")
db.execute("CREATE TABLE IF NOT EXISTS confirmed_history (history_id TEXT PRIMARY KEY, text TEXT)")
db.execute("DELETE FROM history WHERE created < ?", (self.clock() - RETENTION,))
db.execute("DELETE FROM confirmed_history WHERE history_id NOT IN (SELECT id FROM history)")
+ db.execute("DELETE FROM input_timings WHERE history_id NOT IN (SELECT id FROM history)")
yield db
finally:
db.close()
@@ -127,25 +129,36 @@ class PersonalStore:
def history(self, limit=100):
with self.database() as db:
db.row_factory = sqlite3.Row
- return [dict(row) for row in db.execute("SELECT history.*, COALESCE(confirmed_history.text, '') AS confirmed FROM history LEFT JOIN confirmed_history ON history.id=confirmed_history.history_id ORDER BY created DESC, history.rowid DESC LIMIT ?", (limit,))]
+ return [dict(row) for row in db.execute("SELECT history.*, COALESCE(confirmed_history.text, '') AS confirmed, COALESCE(input_timings.data, '{}') AS timing_data FROM history LEFT JOIN confirmed_history ON history.id=confirmed_history.history_id LEFT JOIN input_timings ON history.id=input_timings.history_id ORDER BY created DESC, history.rowid DESC LIMIT ?", (limit,))]
def clear_history(self):
with self.database() as db:
db.execute("DELETE FROM history")
db.execute("DELETE FROM confirmed_history")
+ db.execute("DELETE FROM input_timings")
+
+ def save_timings(self, identifier, values):
+ if identifier:
+ with self.database() as db:
+ db.execute("INSERT OR REPLACE INTO input_timings SELECT ?,? WHERE EXISTS (SELECT 1 FROM history WHERE id=?)", (identifier, json.dumps(values), identifier))
+
+ def timings(self, identifier):
+ with self.database() as db:
+ row = db.execute("SELECT data FROM input_timings WHERE history_id=?", (identifier,)).fetchone()
+ return json.loads(row[0]) if row else {}
def corrections(self):
with self.database() as db:
db.row_factory = sqlite3.Row
return [dict(row) for row in db.execute("SELECT * FROM corrections ORDER BY created DESC, rowid DESC")]
- def confirm_correction(self, identifier, recognized, corrected):
+ def confirm_correction(self, identifier, recognized, corrected, selection=None):
from doubao_input.personal_corrections import confirmation
with self.database() as db:
row = db.execute("SELECT original, COALESCE(confirmed_history.text, history.output) FROM history LEFT JOIN confirmed_history ON history.id=confirmed_history.history_id WHERE history.id=?", (identifier,)).fetchone()
if row is None:
raise ValueError("This history entry is no longer available")
- source, target, text, context = confirmation(*row, recognized, corrected)
+ source, target, text, context = confirmation(*row, recognized, corrected, selection)
key = source.lower() + "\n" + target.lower()
if not db.execute("SELECT 1 FROM corrections WHERE key=?", (key,)).fetchone() and db.execute("SELECT COUNT(*) FROM corrections").fetchone()[0] >= 200:
raise ValueError("Correction memory supports up to 200 entries")
diff --git a/src/doubao_input/personal_corrections.py b/src/doubao_input/personal_corrections.py
index 13e49a5..845f409 100644
--- a/src/doubao_input/personal_corrections.py
+++ b/src/doubao_input/personal_corrections.py
@@ -11,7 +11,7 @@ def term_pattern(term):
return re.compile(left + re.escape(term) + right, re.IGNORECASE)
-def confirmation(original, output, recognized, corrected):
+def confirmation(original, output, recognized, corrected, selection=None):
source = normalize_words(recognized)
target = normalize_words(corrected)
if len(source) != 1 or len(target) != 1 or source[0] == target[0]:
@@ -21,8 +21,17 @@ def confirmation(original, output, recognized, corrected):
if not pattern.search(original) and not pattern.search(output):
raise ValueError("The recognized term must occur in this entry")
occurrence = pattern.search(output)
- text, count = pattern.subn(lambda _: target, output, count=1)
- match = term_pattern(target).search(text, occurrence.start() if occurrence else 0)
+ if selection is not None:
+ start, end = selection
+ if not 0 <= start < end <= len(output) or output[start:end].casefold() != source.casefold():
+ raise ValueError("Selection no longer matches")
+ occurrence = re.search(re.escape(output[start:end]), output[start:end])
+ text, count = output[:start] + target + output[end:], 1
+ target_offset = start
+ else:
+ text, count = pattern.subn(lambda _: target, output, count=1)
+ target_offset = occurrence.start() if occurrence else 0
+ match = term_pattern(target).search(text, target_offset)
if not count and not match:
raise ValueError("The correction must match the output or confirm an existing correction")
context = text[max(0, match.start() - 80):match.end() + 80] if match else text[:160]
diff --git a/src/doubao_input/polish.py b/src/doubao_input/polish.py
index c75d4d5..40bab07 100644
--- a/src/doubao_input/polish.py
+++ b/src/doubao_input/polish.py
@@ -12,6 +12,7 @@ from urllib import error, request
from doubao_input.settings import config_dir, write_atomic
from doubao_input.reasoning import reasoning_policy
+from doubao_input.polish_transport import RequestCancellation, open_request
logger = logging.getLogger(__name__)
@@ -67,7 +68,7 @@ def chat_completions_url(base_url):
class PolishClient:
def polish(self, text, *, base_url, api_key, model, prompt, timeout=25,
- on_progress=None):
+ on_progress=None, cancellation=None):
body = {"model": model, "temperature": 0.2,
"messages": [{"role": "system", "content": prompt},
{"role": "user", "content": text}],
@@ -80,7 +81,7 @@ class PolishClient:
"Content-Type": "application/json",
"Accept": "application/json"}, method="POST")
try:
- with request.urlopen(req, timeout=timeout) as response:
+ with open_request(req, timeout=timeout, cancellation=cancellation) as response:
if on_progress:
content = self._read_stream(response, on_progress)
raw = None
@@ -92,9 +93,12 @@ class PolishClient:
if len(raw) > 1_000_000:
raise ValueError("Polishing response is too large")
try:
- content = json.loads(raw)["choices"][0]["message"]["content"].strip()
+ choice = json.loads(raw)["choices"][0]
+ content = choice["message"]["content"].strip()
except (ValueError, KeyError, IndexError, TypeError, AttributeError) as exc:
raise ValueError("The endpoint returned an incompatible response") from exc
+ if choice.get("finish_reason") not in (None, "stop"):
+ raise ValueError("Polishing response ended before completion")
if not content:
raise ValueError("The endpoint returned empty text")
return content
@@ -147,13 +151,12 @@ class PolishManager:
def __init__(self, dispatch, client=None):
self._dispatch = dispatch
self._client = client or PolishClient()
- # A speculative request cannot be interrupted while urllib is waiting
- # for the server. Keep it off the final-delivery lane so resumed speech
- # never leaves the request made on release queued behind stale work.
+ # Keep preview connection setup off the final-delivery lane as well.
self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="doubao-polish-final")
self._speculative_executor = ThreadPoolExecutor(
max_workers=1, thread_name_prefix="doubao-polish-preview")
self._token = Event()
+ self._cancellation = RequestCancellation()
self._future = None
self._deadline = None
self._closed = False
@@ -164,6 +167,8 @@ class PolishManager:
self.cancel()
token = Event()
self._token = token
+ cancellation = RequestCancellation()
+ self._cancellation = cancellation
self.busy = True
started = time.monotonic()
executor = self._speculative_executor if speculative else self._executor
@@ -182,7 +187,7 @@ class PolishManager:
future = executor.submit(self._client.polish, text,
base_url=settings.polish_base_url, api_key=api_key,
model=settings.polish_model, prompt=polish_prompt_for_text(text, settings),
- timeout=timeout, on_progress=report if progress else None)
+ timeout=timeout, on_progress=report if progress else None, cancellation=cancellation)
self._future = future
def finished(future):
@@ -225,6 +230,7 @@ class PolishManager:
def cancel(self):
self._token.set()
+ self._cancellation.set()
if self._deadline is not None:
self._deadline.cancel()
if self._future is not None:
diff --git a/src/doubao_input/polish_transport.py b/src/doubao_input/polish_transport.py
new file mode 100644
index 0000000..32cae4e
--- /dev/null
+++ b/src/doubao_input/polish_transport.py
@@ -0,0 +1,130 @@
+"""Per-request cancellation and redirect policy for credentialed HTTP calls."""
+from contextlib import contextmanager
+from http.client import HTTPConnection, HTTPSConnection
+import socket
+from threading import Event, Lock, Timer
+from urllib import error, request
+
+
+class RequestCancellation:
+ def __init__(self):
+ self._event = Event()
+ self._lock = Lock()
+ self._socket = None
+
+ def is_set(self):
+ return self._event.is_set()
+
+ def check(self):
+ if self.is_set():
+ raise ValueError("Polishing cancelled or timed out")
+
+ def attach(self, connection_socket):
+ with self._lock:
+ if not self.is_set():
+ self._socket = connection_socket
+ return
+ self._interrupt(connection_socket)
+ connection_socket.close()
+ self.check()
+
+ def detach(self):
+ with self._lock:
+ self._socket = None
+
+ def set(self):
+ with self._lock:
+ self._event.set()
+ active = self._socket
+ self._socket = None
+ if active is not None:
+ self._interrupt(active)
+
+ @staticmethod
+ def _interrupt(active):
+ # Leave descriptor cleanup to the request thread. Closing it here can
+ # strand a concurrent TLS handshake in poll until its socket timeout.
+ # Bypass SSLSocket.shutdown so its SSL state stays owned by that thread.
+ try:
+ socket.socket.shutdown(active, socket.SHUT_RDWR)
+ except OSError:
+ pass
+
+
+class _TrackedConnection:
+ def __init__(self, *args, cancellation, **kwargs):
+ self._cancellation = cancellation
+ super().__init__(*args, **kwargs)
+ create_connection = self._create_connection
+
+ def connect_socket(*args, **kwargs):
+ self._cancellation.check()
+ active = create_connection(*args, **kwargs)
+ # Track TCP before http.client starts reading a proxy CONNECT reply.
+ self._cancellation.attach(active)
+ return active
+
+ self._create_connection = connect_socket
+
+ def connect(self):
+ self._cancellation.check()
+ super().connect()
+ self._cancellation.attach(self.sock)
+
+
+class _HTTPConnection(_TrackedConnection, HTTPConnection):
+ pass
+
+
+class _HTTPSConnection(_TrackedConnection, HTTPSConnection):
+ def connect(self):
+ self._cancellation.check()
+ HTTPConnection.connect(self)
+ # Register the SSL socket before its blocking handshake. wrap_socket
+ # transfers ownership of the TCP descriptor, making the old socket inert.
+ self.sock = self._context.wrap_socket(
+ self.sock, server_hostname=self._tunnel_host or self.host,
+ do_handshake_on_connect=False)
+ self._cancellation.attach(self.sock)
+ self.sock.do_handshake()
+ self._cancellation.check()
+
+
+class _NoRedirect(request.HTTPRedirectHandler):
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
+ return None
+
+
+@contextmanager
+def open_request(req, *, timeout, cancellation=None):
+ cancellation = cancellation or RequestCancellation()
+ cancellation.check()
+
+ class HTTPHandler(request.HTTPHandler):
+ def http_open(self, req):
+ return self.do_open(lambda *args, **kwargs: _HTTPConnection(
+ *args, cancellation=cancellation, **kwargs), req)
+
+ class HTTPSHandler(request.HTTPSHandler):
+ def https_open(self, req):
+ return self.do_open(lambda *args, **kwargs: _HTTPSConnection(
+ *args, cancellation=cancellation, **kwargs), req,
+ context=self._context)
+
+ # Keep urllib's proxy and certificate handling, but never forward a key to
+ # a redirect destination. The deadline covers headers and response body.
+ opener = request.build_opener(HTTPHandler(), HTTPSHandler(), _NoRedirect())
+ deadline = Timer(timeout, cancellation.set)
+ deadline.daemon = True
+ deadline.start()
+ try:
+ with opener.open(req, timeout=timeout) as response:
+ cancellation.check()
+ yield response
+ cancellation.check()
+ except error.HTTPError as exc:
+ exc.close()
+ raise
+ finally:
+ deadline.cancel()
+ cancellation.detach()
diff --git a/src/doubao_input/product.py b/src/doubao_input/product.py
index 32aa190..ba72000 100644
--- a/src/doubao_input/product.py
+++ b/src/doubao_input/product.py
@@ -1,6 +1,6 @@
"""Single runtime source for Doubao Say release identity."""
-VERSION = "1.6.0"
+VERSION = "1.7.0"
REPOSITORY_URL = "https://github.com/quanru/doubao-say"
LATEST_RELEASE_API = "https://api.github.com/repos/quanru/doubao-say/releases/latest"
LATEST_RELEASE_FEED = REPOSITORY_URL + "/releases/latest/download/update.json"
diff --git a/src/doubao_input/speech_eval.py b/src/doubao_input/speech_eval.py
index 2d382c8..1ed9c2a 100644
--- a/src/doubao_input/speech_eval.py
+++ b/src/doubao_input/speech_eval.py
@@ -125,7 +125,7 @@ def read_audio(path):
return audio.readframes(audio.getnframes())
-def recognize(pcm, credentials, words, *, client_factory=None, timeout=75):
+def recognize(pcm, credentials, words, *, client_factory=None, timeout=75, cancel=None):
from doubao_input.doubao.volcengine_asr_client import VolcengineASRClient
client = (client_factory or VolcengineASRClient)(hotwords=lambda: words)
opened, finished = threading.Event(), threading.Event()
@@ -136,19 +136,26 @@ def recognize(pcm, credentials, words, *, client_factory=None, timeout=75):
client.on_result = lambda text: result.update(text=text)
client.on_finish = finished.set
client.on_error = client.on_auth_error = failure
+ cancel = cancel or threading.Event()
+ def wait(event, seconds):
+ deadline = time.monotonic() + seconds
+ while not cancel.is_set() and time.monotonic() < deadline:
+ if event.wait(min(.1, max(0, deadline - time.monotonic()))):
+ return True
+ return False
started = time.monotonic()
try:
client.prepare(); client.connect(credentials)
- if not opened.wait(8) or finished.is_set():
+ if not wait(opened, 8) or finished.is_set():
raise TimeoutError("ASR did not open")
for offset in range(0, len(pcm), 3200):
- if finished.is_set():
+ if finished.is_set() or cancel.is_set():
break
client.send_audio(pcm[offset:offset + 3200])
- time.sleep(.1)
+ cancel.wait(.1)
client.finish_sending()
remaining = max(0, timeout - (time.monotonic() - started))
- if not finished.wait(remaining):
+ if not wait(finished, remaining):
result["error"] = "asr_timeout"
except (OSError, ValueError, TimeoutError):
result["error"] = "asr_failed"
diff --git a/src/doubao_input/speech_workbench.py b/src/doubao_input/speech_workbench.py
new file mode 100644
index 0000000..8add93e
--- /dev/null
+++ b/src/doubao_input/speech_workbench.py
@@ -0,0 +1,106 @@
+"""Local speech samples and cancellable comparison, shared by the GTK UI."""
+import json
+from pathlib import Path
+import threading
+import uuid
+import wave
+
+from doubao_input.settings import write_atomic
+from doubao_input.speech_eval import read_manifest, read_rows, read_audio, recognize, score
+
+
+class SpeechWorkbench:
+ def __init__(self, directory):
+ self.directory = Path(directory)
+ self.samples = []
+ self.cancelled = threading.Event()
+ self.completed_results = []
+ path = self.directory / 'samples.jsonl'
+ if path.exists():
+ self.samples = read_rows(path)
+ if len(self.samples) > 200 or any(not isinstance(s.get("id"), str) or str(uuid.UUID(s["id"])) != s["id"] for s in self.samples):
+ raise ValueError("Invalid samples")
+ if len({s["id"] for s in self.samples}) != len(self.samples) or any(not isinstance(s.get("reference"), str) or any(not isinstance(s.get(k, []), list) or any(not isinstance(t, str) for t in s.get(k, [])) for k in ("terms", "protected_terms")) for s in self.samples):
+ raise ValueError("Invalid drafts")
+
+ def save(self):
+ self.directory.mkdir(parents=True, exist_ok=True, mode=0o700)
+ write_atomic(self.directory / 'samples.jsonl', ('\n'.join(json.dumps(s, ensure_ascii=False) for s in self.samples) + '\n').encode())
+
+ def add(self):
+ if len(self.samples) >= 200:
+ raise ValueError('Sample limit reached')
+ row = {'id': str(uuid.uuid4()), 'reference': '', 'terms': [], 'protected_terms': []}
+ self.samples.append(row)
+ self.save()
+ return row
+
+ def record(self, row, pcm):
+ if not pcm or len(pcm) > 1_920_000 or len(pcm) % 2:
+ raise ValueError('Invalid audio')
+ path = self.directory / (str(uuid.UUID(row['id'])) + '.wav')
+ self.directory.mkdir(parents=True, exist_ok=True, mode=0o700)
+ # Build WAV in memory so no recording is ever created world-readable.
+ from io import BytesIO
+ stream = BytesIO()
+ with wave.open(stream, 'wb') as audio:
+ audio.setnchannels(1); audio.setsampwidth(2); audio.setframerate(16000)
+ audio.writeframes(pcm)
+ write_atomic(path, stream.getvalue())
+ row['audio'] = str(path)
+ row.pop('results', None)
+ self.save()
+
+ def delete(self, row):
+ # Only remove audio owned by this sample, never an imported arbitrary path.
+ (self.directory / (str(uuid.UUID(row['id'])) + '.wav')).unlink(missing_ok=True)
+ self.samples.remove(row)
+ self.save()
+
+ def validated(self):
+ # UI permits incomplete drafts; validate the full set only when running.
+ from tempfile import TemporaryDirectory
+ with TemporaryDirectory() as temp:
+ path = Path(temp) / 'manifest.jsonl'
+ write_atomic(path, ('\n'.join(json.dumps(s, ensure_ascii=False) for s in self.samples) + '\n').encode())
+ rows = read_manifest(path)
+ for row in rows:
+ read_audio(row.get('audio', ''))
+ return rows
+
+ def compare(self, credentials, words, *, polisher=None, progress=lambda *_: None, recognizer=recognize):
+ rows = self.validated()
+ results = []
+ self.completed_results = results
+ for row in rows:
+ if self.cancelled.is_set():
+ break
+ pcm = read_audio(row['audio'])
+ for mode, hints in (('raw', []), ('hotwords', words)):
+ if self.cancelled.is_set():
+ break
+ progress(row['id'], mode)
+ if self.cancelled.is_set():
+ break
+ result = {'id': row['id'], 'mode': mode, **recognizer(pcm, credentials, hints, cancel=self.cancelled)}
+ if self.cancelled.is_set():
+ break
+ results.append(result)
+ if mode == 'hotwords' and polisher:
+ if self.cancelled.is_set():
+ break
+ import time
+ polished = {**result, 'mode': 'hotwords+polish'}
+ if not result.get('error'):
+ started = time.monotonic()
+ try:
+ polished['text'] = polisher(result['text'])
+ except (OSError, ValueError, TimeoutError):
+ polished['error'] = 'polish_failed'
+ polished['latency_ms'] += round((time.monotonic() - started) * 1000)
+ if not self.cancelled.is_set():
+ results.append(polished)
+ return results
+
+ def report(self, results):
+ return score(self.samples, results)
diff --git a/src/doubao_input/ui/control_window.py b/src/doubao_input/ui/control_window.py
index 4ff2f7f..a355746 100644
--- a/src/doubao_input/ui/control_window.py
+++ b/src/doubao_input/ui/control_window.py
@@ -78,8 +78,8 @@ class ControlWindow:
if self._actions.is_preview_testing():
self._actions.cancel_preview()
flush = getattr(self, "_flush_asr_key", None)
- if flush:
- flush()
+ if flush and not flush():
+ return
if self._window:
self._window.set_visible(False)
@@ -159,6 +159,7 @@ class ControlWindow:
summary = self._actions.summary()
provider = recognition_provider(summary.get("asr_provider", "doubao"))
uses_api_key = provider.uses_api_key
+ self._sync_asr_controls()
if self._page_headings:
self._page_titles["account"] = (tr("Recognition", "语音识别")
if uses_api_key else tr("Sign in", "登录"))
@@ -530,9 +531,17 @@ class ControlWindow:
def _asr_provider_changed(self, *_):
if self._changing_asr_provider:
return
+ if self._asr_testing:
+ self._refresh()
+ return
selected = self._asr_provider.get_selected()
if selected >= len(ASR_PROVIDERS):
return
+ # Saving can refresh the dropdown, so keep the requested selection but
+ # flush the draft while callbacks still refer to its original provider.
+ if not self._flush_asr_key():
+ self._refresh()
+ return
try:
self._actions.apply_asr_provider(ASR_PROVIDERS[selected])
except (ValueError, OSError) as error:
@@ -542,8 +551,20 @@ class ControlWindow:
self.set_feedback(tr(
"Recognition service switched. Configure its credentials below to continue.",
"语音识别服务已切换,请在下方配置对应凭证后继续。"))
+ self._asr_status.set_text("")
+
+ def _sync_asr_controls(self):
+ if not self._asr_key:
+ return
+ has_key = self._actions.asr_has_key()
+ self._asr_key.set_placeholder_text(tr(
+ "Saved — leave blank to keep" if has_key else "Enter speech API key",
+ "已保存,留空则保持不变" if has_key else "填写语音 API Key"))
+ self._asr_test_button.set_sensitive(
+ not self._asr_testing and bool(has_key or self._asr_key.get_text().strip()))
def _queue_asr_key_save(self, *_):
+ self._sync_asr_controls()
if not self._asr_key or not self._asr_key.get_text().strip():
return
if self._asr_key_save_source:
@@ -557,15 +578,16 @@ class ControlWindow:
def _save_asr_key_now(self):
if not self._asr_key:
- return self._actions.asr_has_key()
+ return True
key = self._asr_key.get_text().strip()
if not key:
- return self._actions.asr_has_key()
+ return True
try:
self._actions.save_asr(key)
except (ValueError, OSError) as error:
self._asr_status.set_text(str(error))
return False
+ self._asr_key.set_text("")
self._asr_key.set_placeholder_text(tr(
"Saved — leave blank to keep", "已保存,留空则保持不变"))
self._asr_status.set_text(tr(
@@ -576,7 +598,7 @@ class ControlWindow:
if self._asr_key_save_source:
GLib.source_remove(self._asr_key_save_source)
self._asr_key_save_source = 0
- self._save_asr_key_now()
+ return self._save_asr_key_now()
def _test_asr_clicked(self, *_):
if self._asr_testing:
@@ -585,10 +607,13 @@ class ControlWindow:
GLib.source_remove(self._asr_key_save_source)
self._asr_key_save_source = 0
if not self._save_asr_key_now():
+ return
+ if not self._actions.asr_has_key():
self._asr_status.set_text(tr(
"Enter an API key first.", "请先填写 API Key。"))
return
self._asr_testing = True
+ self._asr_provider.set_sensitive(False)
self._asr_test_button.set_sensitive(False)
self._asr_test_button.set_label(tr("Testing…", "正在测试…"))
self._asr_status.set_text(tr(
@@ -601,6 +626,7 @@ class ControlWindow:
def _asr_tested(self, result, error):
self._asr_testing = False
+ self._asr_provider.set_sensitive(True)
self._asr_test_button.set_sensitive(True)
self._asr_test_button.set_label(tr("Test API key", "测试 API Key"))
self._asr_status.set_text(
diff --git a/src/doubao_input/ui/personal_window.py b/src/doubao_input/ui/personal_window.py
index 0cfd61c..ca20f3e 100644
--- a/src/doubao_input/ui/personal_window.py
+++ b/src/doubao_input/ui/personal_window.py
@@ -12,7 +12,7 @@ from doubao_input.ui.style import apply_window_style
class PersonalWindow:
- def __init__(self, store, settings, api_key, recent, retry):
+ def __init__(self, store, settings, api_key, recent, retry, can_record=lambda: True):
self.store, self.settings, self.api_key = store, settings, api_key
self.recent, self.retry = recent, retry
self.window = None
@@ -24,6 +24,8 @@ class PersonalWindow:
self.candidates = []
self.choices = []
self.correction_window = None
+ self.can_record = can_record
+ self.evaluation = None
def label(self, text):
return Gtk.Label(label=text, xalign=0, wrap=True)
@@ -120,6 +122,9 @@ class PersonalWindow:
self.history_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
scroll = Gtk.ScrolledWindow(vexpand=True); scroll.set_child(self.history_box); history.append(scroll)
self.button(history, tr("Load more", "加载更多"), self.more)
+ from doubao_input.ui.speech_evaluation import SpeechEvaluationPage
+ evaluation = self.page(notebook, tr("Speech evaluation", "语音评测"), scroll=True)
+ self.evaluation = SpeechEvaluationPage(evaluation, self.store, self.settings, self.api_key, self.can_record)
self.feedback = self.label("")
self.feedback.set_margin_start(16); self.feedback.set_margin_end(16); self.feedback.set_margin_bottom(12)
outer.append(self.feedback)
@@ -179,7 +184,10 @@ class PersonalWindow:
expander = Gtk.Expander(label=tr("Recognition original", "识别原文"))
original = self.label(item["original"]); original.set_selectable(True); expander.set_child(original); box.append(expander)
self.button(box, tr("Use in Recent text", "放入最近文字"), lambda text=text: self.recent_editor.get_buffer().set_text(text))
- self.button(box, tr("Correct & remember…", "纠正并记住…"), lambda item=item: self.edit_correction(item))
+ self.button(box, tr("Correct & remember…", "纠正并记住…"), lambda item=item, output=output: self.edit_correction(item, output))
+ timing = json.loads(item["timing_data"])
+ if timing:
+ box.append(self.label(tr("After stop: ASR / polish / input / total (ms): ", "结束录音后:识别/润色/输入/总耗时(毫秒):") + " / ".join(str(timing.get(key, 0)) for key in ("asr", "polish", "delivery", "total"))))
box.append(Gtk.Separator()); self.history_box.append(box)
if not rows:
self.history_box.append(self.label(tr("No input history yet.", "暂无输入历史。")))
@@ -219,7 +227,7 @@ class PersonalWindow:
except Exception:
self.feedback.set_text(tr("Could not remove correction memory.", "无法删除纠错记忆。"))
- def edit_correction(self, item):
+ def edit_correction(self, item, selected_label=None):
from doubao_input.personal_corrections import confirmation
if self.correction_window:
self.correction_window.present(); return
@@ -230,7 +238,11 @@ class PersonalWindow:
getattr(box, "set_margin_" + side)(20)
current = item["confirmed"] or item["output"]
sample_scroll = Gtk.ScrolledWindow(min_content_height=70, max_content_height=120)
- sample_scroll.set_child(self.label(current)); box.append(sample_scroll)
+ sample = Gtk.TextView(editable=False, wrap_mode=Gtk.WrapMode.WORD_CHAR)
+ sample.set_top_margin(10); sample.set_left_margin(10)
+ sample.get_buffer().set_text(current)
+ sample_scroll.set_child(sample); box.append(sample_scroll)
+ box.append(self.label(tr("Select the wrong word below to fill it in, then enter the correct spelling.", "选中错词即可带入,再填写正确写法。")))
box.append(self.label(tr("Misrecognized word or phrase", "误识别的词或短语")))
source = Gtk.Entry(placeholder_text=tr("For example: Midjourney", "例如:Midjourney")); box.append(source)
box.append(self.label(tr("Correct spelling", "正确写法")))
@@ -247,7 +259,7 @@ class PersonalWindow:
self.button(buttons, tr("Cancel", "取消"), close)
def confirm():
try:
- self.store.confirm_correction(item["id"], source.get_text(), target.get_text())
+ self.store.confirm_correction(item["id"], source.get_text(), target.get_text(), selection[0])
close(); self.refresh()
self.feedback.set_text(tr("Correction remembered. Future matching contexts can use it.", "已记住这次纠正,之后遇到相似语境时参考。"))
except Exception:
@@ -256,11 +268,35 @@ class PersonalWindow:
button.add_css_class("suggested-action"); button.set_sensitive(False)
def changed(*_):
try:
- value = confirmation(item["original"], current, source.get_text(), target.get_text())[2]
+ value = confirmation(item["original"], current, source.get_text(), target.get_text(), selection[0])[2]
preview.set_text(value); button.set_sensitive(True)
except ValueError:
preview.set_text(tr("Enter a term from this entry and its correct spelling. Review before confirming.", "填写这条记录中出现的词和正确写法,检查后再确认。")); button.set_sensitive(False)
- source.connect("changed", changed); target.connect("changed", changed)
+ selection = [None]
+ def source_changed(*_):
+ selection[0] = None; changed()
+ def selected(label, *_):
+ bounds = label.get_selection_bounds()
+ if len(bounds) == 3:
+ if not bounds[0]:
+ return
+ bounds = bounds[1:]
+ if bounds and len(bounds) == 2 and bounds[0] != bounds[1]:
+ start, end = sorted(bounds)
+ term = current[start:end]
+ if 0 < len(term) <= 80 and "\n" not in term:
+ source.set_text(term); selection[0] = (start, end); changed()
+ source.connect("changed", source_changed); target.connect("changed", changed)
+ def buffer_selected(buffer, *_):
+ bounds = buffer.get_selection_bounds()
+ if len(bounds) == 2:
+ start, end = sorted(iterator.get_offset() for iterator in bounds)
+ term = current[start:end]
+ if 0 < len(term) <= 80 and "\n" not in term:
+ source.set_text(term); selection[0] = (start, end); changed()
+ sample.get_buffer().connect("mark-set", buffer_selected)
+ if selected_label:
+ selected(selected_label)
changed(); dialog.set_child(box)
dialog.connect("close-request", lambda *_: (close(), True)[1])
dialog.present()
@@ -340,6 +376,8 @@ class PersonalWindow:
self.refresh(); self.render_candidates()
def close(self, *_):
+ if self.evaluation:
+ self.evaluation.cancel()
if self.correction_window:
self.correction_window.close()
self.flush(); self.generation += 1; self.busy = False; self.ai_button.set_sensitive(True)
diff --git a/src/doubao_input/ui/settings_window.py b/src/doubao_input/ui/settings_window.py
index be664eb..86bd67d 100644
--- a/src/doubao_input/ui/settings_window.py
+++ b/src/doubao_input/ui/settings_window.py
@@ -449,15 +449,27 @@ class SettingsWindow:
def _asr_provider_changed(self, *_):
if self._updating:
return
+ if self._asr_testing:
+ self._restore_controls()
+ return
+ # The application still owns the previous provider until _save_current.
+ # Flush its draft before changing the credential store used by callbacks.
+ if not self.flush_edits():
+ self._restore_controls()
+ return
self._sync_provider_details()
+ if not self._save_current():
+ return
provider = recognition_provider(
ASR_PROVIDERS[self.asr_provider.get_selected()])
- if self._save_current():
- self._asr_has_key = self._asr_has_key_func()
- if provider.uses_api_key and not self._asr_has_key:
- self.asr_status.set_text(tr(
- "Enter an API key before using this recognition service.",
- "使用当前语音识别服务前请填写 API Key。"))
+ self._asr_has_key = self._asr_has_key_func()
+ self.asr_key.set_placeholder_text(tr(
+ "Saved — leave blank to keep" if self._asr_has_key else "Enter speech API key",
+ "已保存,留空则保持不变" if self._asr_has_key else "填写语音 API Key"))
+ self.asr_status.set_text(tr(
+ "Enter an API key before using this recognition service.",
+ "使用当前语音识别服务前请填写 API Key。")
+ if provider.uses_api_key and not self._asr_has_key else "")
def _sync_provider_details(self):
provider = recognition_provider(
@@ -490,6 +502,13 @@ class SettingsWindow:
self.asr_status.set_text(str(error))
return False
self._asr_has_key = True
+ self._updating = True
+ try:
+ self.asr_key.set_text("")
+ self.asr_key.set_placeholder_text(tr(
+ "Saved — leave blank to keep", "已保存,留空则保持不变"))
+ finally:
+ self._updating = False
self.asr_status.set_text(tr("API key saved automatically.", "API Key 已自动保存。"))
return True
@@ -500,17 +519,7 @@ class SettingsWindow:
return self._save_asr_key_now()
def _flush_asr_key(self, *_):
- if self._asr_save_source:
- GLib.source_remove(self._asr_save_source)
- self._asr_save_source = 0
- if self._save_asr_key_now() and self.asr_key.get_text():
- self._updating = True
- try:
- self.asr_key.set_text("")
- self.asr_key.set_placeholder_text(tr(
- "Saved — leave blank to keep", "已保存,留空则保持不变"))
- finally:
- self._updating = False
+ return self.flush_edits()
def _clear_asr_clicked(self, *_):
try:
@@ -536,6 +545,7 @@ class SettingsWindow:
self.asr_status.set_text(tr("Enter an API key first.", "请先填写 API Key。"))
return
self._asr_testing = True
+ self.asr_provider.set_sensitive(False)
self.asr_test_button.set_sensitive(False)
self.asr_test_button.set_label(tr("Testing…", "正在测试…"))
self.asr_status.set_text(tr(
@@ -547,6 +557,7 @@ class SettingsWindow:
def _asr_tested(self, result, error):
self._asr_testing = False
+ self.asr_provider.set_sensitive(True)
self.asr_test_button.set_sensitive(True)
self.asr_test_button.set_label(tr("Test API key", "测试 API Key"))
self.asr_status.set_text((tr("Test failed: ", "测试失败:") + error)
@@ -557,8 +568,8 @@ class SettingsWindow:
for picker in (self.trigger_picker, *self.vibekey_pickers):
picker.cancel()
flush = getattr(self, "_flush_asr_key", None)
- if flush:
- flush()
+ if flush and not flush():
+ return True
return not self._save_current()
def show(self):
diff --git a/src/doubao_input/ui/speech_evaluation.py b/src/doubao_input/ui/speech_evaluation.py
new file mode 100644
index 0000000..bb0bf13
--- /dev/null
+++ b/src/doubao_input/ui/speech_evaluation.py
@@ -0,0 +1,260 @@
+"""GTK speech evaluation UI; recording is local and replay is explicitly requested."""
+import threading
+
+from gi.repository import GLib, Gtk
+
+from doubao_input.i18n import tr
+from doubao_input.speech_workbench import SpeechWorkbench
+from doubao_input.personal import vocabulary_prompt
+from doubao_input.personal_corrections import correction_prompt, hotword_context
+from doubao_input.polish import PolishClient
+
+
+class SpeechEvaluationPage:
+ def __init__(self, box, personal, settings, polish_key, can_record):
+ self.personal, self.settings, self.polish_key, self.can_record = personal, settings, polish_key, can_record
+ self.active = False
+ self.recording = False
+ self.loading = False
+ self.pcm = bytearray()
+ self.lock = threading.Lock()
+ self.audio = None
+ self.record_timer = 0
+ self.feedback = self.label(box, '')
+ try:
+ self.workbench = SpeechWorkbench(personal.path.parent / 'speech-evaluation')
+ except (OSError, ValueError, TypeError):
+ self.workbench = SpeechWorkbench(personal.path.parent / 'speech-evaluation-empty')
+ self.feedback.set_text(tr('Could not read saved speech samples.', '无法读取已保存的语音样本。'))
+ self.label(box, tr('1. Record · 2. Review reference · 3. Compare', '1. 录音 · 2. 核对参考文字 · 3. 对比结果'))
+ self.label(box, tr('Record 30–50 short clips in your normal accent, including jargon, mixed languages, names, numbers and cases where Midjourney is correct. Recordings stay local until comparison.', '建议用日常口音录制 30–50 条短句,包括专业词、中英混说、人名、数字,以及确实应该是 Midjourney 的句子。开始对比前录音仅存本机。'))
+ controls = Gtk.Box(spacing=8); box.append(controls)
+ self.picker = Gtk.ComboBoxText(hexpand=True); controls.append(self.picker)
+ self.picker.connect('changed', lambda *_: self.refresh())
+ self.add_button = self.button(controls, tr('Add sample', '添加样本'), self.add)
+ self.delete_button = self.button(controls, tr('Delete sample', '删除样本'), self.delete)
+ controls = Gtk.Box(spacing=8); box.append(controls)
+ self.record_button = self.button(controls, tr('Record / record again', '录音/重新录音'), self.record)
+ self.stop_button = self.button(controls, tr('Stop & keep recording', '结束并保留录音'), self.stop)
+ self.duration = self.label(controls, '')
+ self.reference = self.editor(box, tr('Reference text — what you actually said', '参考文字——你实际说的内容'), 90)
+ self.terms = self.editor(box, tr('Target terms (one per line)', '目标词(每行一个)'), 55)
+ self.protected = self.editor(box, tr('Protected terms (one per line)', '受保护词(每行一个)'), 55)
+ self.label(box, tr('Labels must occur in the reference. Reference text is only used for scoring and never sent to ASR or polishing. Editing clears old results.', '标注的词必须出现在参考文字中。参考文字仅用于评分,不发送给识别或润色服务;修改样本会清除旧结果。'))
+ self.polish = Gtk.CheckButton(label=tr('Compare AI polishing too', '同时对比 AI 润色')); self.polish.set_active(True); box.append(self.polish)
+ self.label(box, tr('Start comparison uploads each recording twice to paid official Volcengine ASR. Polishing also sends recognized text to your configured service. Nothing is pasted or learned from references.', '开始对比会将每段录音发送两次给你配置的官方火山引擎 ASR,并产生接口费用;润色还会将识别文字发送给润色服务。不会粘贴文字,也不学习参考答案。'))
+ controls = Gtk.Box(spacing=8); box.append(controls)
+ self.run_button = self.button(controls, tr('Start comparison', '开始对比'), self.run)
+ self.cancel_button = self.button(controls, tr('Cancel / discard', '取消/丢弃'), self.cancel)
+ self.results = self.label(box, '')
+ self.results.set_selectable(True)
+ self.rebuild()
+
+ @staticmethod
+ def label(box, text):
+ label = Gtk.Label(label=text, xalign=0, wrap=True); box.append(label); return label
+
+ @staticmethod
+ def button(box, text, callback):
+ button = Gtk.Button(label=text); button.connect('clicked', lambda *_: callback()); box.append(button); return button
+
+ def editor(self, box, caption, height):
+ self.label(box, caption)
+ editor = Gtk.TextView(wrap_mode=Gtk.WrapMode.WORD_CHAR)
+ for side in ('top', 'bottom', 'left', 'right'):
+ getattr(editor, 'set_' + side + '_margin')(10)
+ scroll = Gtk.ScrolledWindow(min_content_height=height); scroll.set_child(editor); box.append(scroll)
+ editor.get_buffer().connect('changed', lambda *_: self.edit())
+ return editor
+
+ @staticmethod
+ def text(editor):
+ buffer = editor.get_buffer()
+ return buffer.get_text(buffer.get_start_iter(), buffer.get_end_iter(), True)
+
+ def row(self):
+ index = self.picker.get_active()
+ return self.workbench.samples[index] if 0 <= index < len(self.workbench.samples) else None
+
+ def rebuild(self, index=0):
+ self.loading = True
+ self.picker.remove_all()
+ for i, row in enumerate(self.workbench.samples):
+ self.picker.append_text(f'{i + 1}. ' + (row['reference'][:25] or tr('New sample', '新样本')))
+ self.loading = False
+ self.picker.set_active(min(index, len(self.workbench.samples) - 1)); self.refresh()
+
+ def save(self):
+ try:
+ self.workbench.save()
+ return True
+ except (OSError, ValueError):
+ self.feedback.set_text(tr('Could not save local samples.', '本地样本保存失败。')); return False
+
+ def edit(self):
+ if self.loading or self.active or not self.row():
+ return
+ row = self.row()
+ row['reference'] = self.text(self.reference)
+ row['terms'] = [s.strip() for s in self.text(self.terms).splitlines() if s.strip()]
+ row['protected_terms'] = [s.strip() for s in self.text(self.protected).splitlines() if s.strip()]
+ row.pop('results', None); self.results.set_text(''); self.save()
+
+ def refresh(self):
+ if self.loading:
+ return
+ self.loading = True
+ row = self.row() or {}
+ self.reference.get_buffer().set_text(row.get('reference', ''))
+ self.terms.get_buffer().set_text('\n'.join(row.get('terms', [])))
+ self.protected.get_buffer().set_text('\n'.join(row.get('protected_terms', [])))
+ self.duration.set_text(tr('Recording saved locally', '录音已保存在本机') if row.get('audio') else tr('No recording yet', '尚未录音'))
+ self.loading = False
+ self.sensitivity(); self.render_results()
+
+ def sensitivity(self):
+ for control in (self.picker, self.add_button, self.delete_button, self.reference, self.terms, self.protected, self.polish):
+ control.set_sensitive(not self.active)
+ self.record_button.set_sensitive(not self.active and self.row() is not None)
+ self.run_button.set_sensitive(not self.active and bool(self.workbench.samples))
+ self.stop_button.set_sensitive(self.recording)
+ self.cancel_button.set_sensitive(self.active)
+
+ def add(self):
+ if self.active:
+ return
+ try:
+ self.workbench.add(); self.rebuild(len(self.workbench.samples) - 1)
+ except (OSError, ValueError):
+ self.feedback.set_text(tr('Could not add a sample (limit 200).', '无法添加样本(最多 200 条)。'))
+
+ def delete(self):
+ if not self.active and self.row():
+ try:
+ self.workbench.delete(self.row()); self.rebuild()
+ except (OSError, ValueError):
+ self.feedback.set_text(tr('Could not delete recording.', '录音删除失败。'))
+
+ def record(self):
+ if self.active or not self.row() or not self.can_record():
+ self.feedback.set_text(tr('Finish dictation first.', '请先结束日常听写。')); return
+ from doubao_input.doubao.audio_capture import AudioCapture
+ self.audio = AudioCapture(); self.audio.device = self.settings().microphone
+ self.pcm = bytearray(); self.recording = self.active = True; self.sensitivity()
+ def chunk(data):
+ with self.lock:
+ if not self.recording:
+ return
+ self.pcm.extend(data[:max(0, 1_920_000 - len(self.pcm))])
+ if len(self.pcm) >= 1_920_000:
+ GLib.idle_add(self.stop)
+ def failed(*_):
+ GLib.idle_add(self.record_failed)
+ try:
+ self.audio.start(chunk, on_error=failed)
+ self.record_timer = GLib.timeout_add(60000, self.stop)
+ self.feedback.set_text(tr('Recording locally (maximum 60 seconds)…', '正在本地录音(最多 60 秒)…'))
+ except Exception:
+ self.record_failed()
+
+ def record_failed(self):
+ self.cancel(); self.feedback.set_text(tr('Microphone unavailable. Recording discarded.', '麦克风不可用,录音已丢弃。')); return False
+
+ def stop(self):
+ if not self.recording:
+ return False
+ if self.record_timer:
+ GLib.source_remove(self.record_timer); self.record_timer = 0
+ try:
+ self.audio.finish()
+ with self.lock:
+ self.recording = False; pcm = bytes(self.pcm); self.pcm.clear()
+ self.workbench.record(self.row(), pcm)
+ self.feedback.set_text(tr('Recording saved. Review the reference before comparing.', '录音已保存,请核对参考文字后再对比。'))
+ except Exception:
+ self.feedback.set_text(tr('Could not save recording. Record again.', '录音保存失败,请重新录制。'))
+ finally:
+ self.recording = self.active = False
+ self.audio.stop(); self.audio = None; self.refresh()
+ return False
+
+ def cancel(self):
+ if self.record_timer:
+ GLib.source_remove(self.record_timer); self.record_timer = 0
+ if self.recording:
+ self.recording = False
+ self.audio.stop(); self.audio = None; self.pcm.clear(); self.active = False
+ self.workbench.cancelled.set()
+ self.feedback.set_text(tr('Cancelling; completed results will be kept.', '正在取消,已完成的结果会保留。'))
+ self.sensitivity()
+
+ def run(self):
+ if self.active or not self.can_record():
+ return
+ try:
+ from doubao_input.doubao.volcengine_credentials import VolcengineCredentialsStore
+ credentials = VolcengineCredentialsStore.load()
+ if credentials is None:
+ raise ValueError('Missing ASR key')
+ credentials.validate(); self.workbench.validated()
+ words = self.personal.recognition_words()
+ personal_words, corrections = self.personal.words(), self.personal.corrections()
+ settings = self.settings()
+ key = self.polish_key() if self.polish.get_active() else None
+ if self.polish.get_active() and not key:
+ raise ValueError('Missing polish key')
+ except Exception:
+ self.feedback.set_text(tr('Every sample needs a recording, reference and valid labels. Configure official ASR and polishing credentials, or turn off polishing comparison.', '每条样本都需要录音、参考文字和有效标注。请配置官方 ASR 和润色凭证,或关闭润色对比。')); return
+ self.active = True; self.workbench.cancelled.clear(); self.sensitivity()
+ for row in self.workbench.samples:
+ row.pop('results', None)
+ self.save(); self.results.set_text('')
+ self.feedback.set_text(tr('Comparing recordings; actual hotword request: ', '正在对比录音,实际热词请求:') + (hotword_context(words) or '[]'))
+ def polisher(text):
+ # Reference labels are never used to build the prompt.
+ import re
+ han = len(re.findall(r"[\u3400-\u4dbf\u4e00-\u9fff]", text))
+ prompt = settings.polish_prompt_zh if han > len(re.findall(r"[A-Za-z]+", text)) else settings.polish_prompt_en
+ prompt = correction_prompt(vocabulary_prompt(prompt, personal_words), text, corrections)
+ return PolishClient().polish(text, base_url=settings.polish_base_url, api_key=key, model=settings.polish_model, prompt=prompt)
+ def worker():
+ results, failed = [], False
+ try:
+ results = self.workbench.compare(credentials, words, polisher=polisher if key else None)
+ except Exception:
+ results = list(self.workbench.completed_results)
+ failed = True
+ GLib.idle_add(done, results, failed)
+ def done(results, failed):
+ for row in self.workbench.samples:
+ row['results'] = [r for r in results if r['id'] == row['id']]
+ self.active = False; self.save(); self.refresh()
+ self.feedback.set_text(tr('Comparison stopped; completed results retained.', '对比已停止,已完成结果保留。') if failed or self.workbench.cancelled.is_set() else tr('Comparison complete. Review failures and protected terms.', '对比完成,请检查失败样本和受保护词。'))
+ return False
+ threading.Thread(target=worker, name='speech-comparison', daemon=True).start()
+
+ @staticmethod
+ def mode_title(mode):
+ return {'raw': tr('Original ASR', '原始识别'),
+ 'hotwords': tr('With hotwords', '加入热词'),
+ 'hotwords+polish': tr('Hotwords + polishing', '热词+润色')}.get(mode, mode)
+
+ def render_results(self):
+ results = [result for row in self.workbench.samples for result in row.get('results', [])]
+ if not results:
+ self.results.set_text(''); return
+ try:
+ report = self.workbench.report(results)
+ lines = [tr('Summary (lower errors/loss is better). Failed or missing samples count as failures. Timing includes connection and recording playback, separate from daily input delay.', '汇总(字错率和丢失率越低越好)。失败或缺失样本按失败计分。耗时包含连接和录音回放,与日常输入等待时间分开。')]
+ for mode, values in report['modes'].items():
+ lines.append(self.mode_title(mode) + ': ' + tr('Character error rate', '字错率') + f' {values["character_error_rate"]:.1%} · ' + tr('Failed', '失败') + f' {values["failed"]}/{values["samples"]}')
+ for field, label in (('term_accuracy', tr('Target-term accuracy', '目标词准确率')), ('protected_term_loss_rate', tr('Protected-term loss', '受保护词丢失率'))):
+ if values[field] is not None:
+ lines.append(f'{label}: {values[field]:.1%}')
+ if values['latency_p50_ms'] is not None:
+ lines.append(f'P50 {values["latency_p50_ms"]:.0f} ms · P95 {values["latency_p95_ms"]:.0f} ms')
+ for result in (self.row() or {}).get('results', []):
+ lines.append(self.mode_title(result['mode']) + (' · ' + tr('Failed', '失败') if result.get('error') else '') + '\n' + result.get('text', ''))
+ self.results.set_text('\n\n'.join(lines))
+ except (ValueError, KeyError, TypeError):
+ self.results.set_text(tr('Invalid results. Run comparison again.', '结果无效,请重新对比。'))
diff --git a/tests/README.md b/tests/README.md
index f481389..1fe9192 100644
--- a/tests/README.md
+++ b/tests/README.md
@@ -112,6 +112,24 @@ real nonactivating overlay and exits; run it under a runtime slot. Live sign-in,
audio and paste acceptance remain separate checks. See
[the Mac guide](../macos/README.zh-CN.md) for scope and permissions.
+The Mac checks also cover HTTP handshake authentication failures, synthetic paste
+event markers, retry deduplication, pending Enter suppression and cancellation.
+Retry checks compile the real transcription manager with inert device adapters;
+they do not establish acceptance of paste into another application.
+
+`tests.unit.test_polish_transport` uses bounded loopback HTTP/S fixtures to check
+redirect rejection, certificate verification, heartbeat/header/proxy deadlines,
+TLS handshake cancellation and worker recovery. Its TLS fixture generates a disposable
+self-signed certificate with OpenSSL; only that TLS case skips if OpenSSL is absent.
+
+`test_asr_key_persistence` and `test_app_edges` also cover pending credential
+drafts in onboarding and Settings, save failures, provider switches across both
+windows, and ownership of an in-flight API-key test. All keys are synthetic.
+Linux CI also runs `tests/manual/asr_key_ui.py` under isolated Xvfb and D-Bus
+sessions in English and Chinese. It exercises real GTK controls, temporary
+credential stores, cross-window saves and main-loop completion, retaining
+screenshots. Audio, keyboard injection, update checks and ASR transport are inert.
+
## Personal speech and correction checks
`tests.unit.test_personal_corrections` verifies explicit confirmation, immutable
@@ -125,7 +143,10 @@ GTK preview/cancel/confirm/forget controls, and retains synthetic screenshots.
`macos/Tests/Settings/PersonalUICheck.swift` is a native fixture; compile it with all
app sources except DoubaoSayApp.swift, wrap it in a unique
`md.lifeos.doubao-say.update-verify.<uuid>` bundle, and run with a process timeout.
-PERSONAL_PAGE selects vocabulary, history, editor, cancel, confirmed or memory.
+PERSONAL_PAGE selects vocabulary, history, editor, cancel, confirmed, memory,
+selection, evaluation or evaluation-results. Selection verifies the native text
+selection callback and correction of the second occurrence; evaluation uses local
+synthetic PCM and results without microphone access or paid services.
It activates the real sheet's Return/Escape shortcuts and checks persisted state.
Live microphone/ASR quality is separate; use the opt-in
[personal speech evaluation tool](../packaging/SPEECH_EVAL.md) with real recordings.
diff --git a/tests/contracts/test_pages_report_history.mjs b/tests/contracts/test_pages_report_history.mjs
index 9d5beeb..99a3fcb 100644
--- a/tests/contracts/test_pages_report_history.mjs
+++ b/tests/contracts/test_pages_report_history.mjs
@@ -215,10 +215,7 @@ test('keeps visual E2E interactions at task level with proven tap exceptions', a
'- aiTap: Volcengine API option in the open Recognition service dropdown',
'- aiTap: Test API key button on the Recognition step',
'- aiTap: Right-arrow Next button in the fixed top navigation',
- '- aiTap: Recognition service dropdown currently showing Doubao account',
- '- aiTap: Deepgram Nova-3 (English) option in the opened dropdown',
'- computer.inputText:',
- '- aiTap: Test API key button below the API Key field',
'- aiTap: The microphone dropdown currently showing Synthetic microphone one',
'- aiTap: Synthetic microphone two option in the open microphone dropdown',
'- aiTap: Right-arrow Next button in the fixed top navigation',
diff --git a/tests/contracts/test_release.py b/tests/contracts/test_release.py
index 5b1660d..fae2a99 100644
--- a/tests/contracts/test_release.py
+++ b/tests/contracts/test_release.py
@@ -49,7 +49,7 @@ class ReleaseTest(unittest.TestCase):
notes = (ROOT / "RELEASE_NOTES.md").read_text()
self.assertIn("--notes-file RELEASE_NOTES.md", workflow)
self.assertNotIn("--generate-notes", workflow)
- for expected in ("Doubao Say 1.6.0", "hotwords", "confirmed corrections", "evaluation"):
+ for expected in ("Doubao Say 1.7.0", "hotwords", "confirmed corrections", "evaluation"):
self.assertIn(expected, " ".join(notes.split()))
def test_both_archives_exclude_ignored_source_files(self):
diff --git a/tests/contracts/test_version_check.py b/tests/contracts/test_version_check.py
index 3a14e22..3390ecf 100644
--- a/tests/contracts/test_version_check.py
+++ b/tests/contracts/test_version_check.py
@@ -11,13 +11,13 @@ SPEC.loader.exec_module(VERSION_CHECK)
class VersionCheckTests(unittest.TestCase):
def test_sources_are_aligned_at_current_release(self):
- self.assertEqual(VERSION_CHECK.validate(root=ROOT), "1.6.0")
+ self.assertEqual(VERSION_CHECK.validate(root=ROOT), "1.7.0")
def test_exact_release_tag_is_accepted(self):
- self.assertEqual(VERSION_CHECK.validate("v1.6.0", ROOT), "1.6.0")
+ self.assertEqual(VERSION_CHECK.validate("v1.7.0", ROOT), "1.7.0")
def test_wrong_release_tag_is_rejected(self):
- with self.assertRaisesRegex(ValueError, "must be 'v1.6.0'"):
+ with self.assertRaisesRegex(ValueError, "must be 'v1.7.0'"):
VERSION_CHECK.validate("v1.1.0", ROOT)
diff --git a/tests/e2e/cases/onboarding-regressions.yaml b/tests/e2e/cases/onboarding-regressions.yaml
index 3cf645a..b2d79dc 100644
--- a/tests/e2e/cases/onboarding-regressions.yaml
+++ b/tests/e2e/cases/onboarding-regressions.yaml
@@ -195,9 +195,9 @@ cases:
- aiAssert: Open Doubao sign-in is hidden, and both Test API key and right-arrow Next are disabled while the API Key is empty.
- aiAct: Enter synthetic-ci-key in the API Key field.
- aiWaitFor:
- prompt: The API Key field has a non-empty masked value and Test API key is enabled.
+ prompt: The API Key field is empty with the Saved — leave blank to keep placeholder, API key saved automatically is visible, and Test API key is enabled.
options: { timeoutMs: 30000, checkIntervalMs: 1000 }
- - aiAssert: The API Key is visibly saved as a masked non-empty value.
+ - aiAssert: The API key saved automatically message is visible and the entry no longer contains the typed key.
- aiTap: Test API key button on the Recognition step
- aiWaitFor:
prompt: The result says API key accepted by synthetic endpoint and the page reports that the official API is ready.
@@ -211,15 +211,27 @@ cases:
tags: [shard-3, provider]
steps:
- fixture.prepare: { mode: deepgram }
- - aiTap: Recognition service dropdown currently showing Doubao account
- - aiTap: Deepgram Nova-3 (English) option in the opened dropdown
+ - aiAct: Switch the Recognition service from Doubao account to Deepgram Nova-3 (English).
- aiWaitFor:
prompt: The Recognition page shows Deepgram Nova-3 English dictation, and the API Key text entry with placeholder Enter speech API key is visible.
options: { timeoutMs: 30000, checkIntervalMs: 1000 }
- computer.inputText:
target: The empty masked text entry to the right of API Key, with placeholder Enter speech API key
value: synthetic-deepgram-key
- - aiTap: Test API key button below the API Key field
+ - aiAct: Test the saved Deepgram API key. Scroll within the page if the Test API key button is below the visible area.
+ - aiWaitFor:
+ prompt: The API key is accepted by the synthetic endpoint and the speech API is ready.
+ options: { timeoutMs: 30000, checkIntervalMs: 1000 }
+ - aiAct: Switch the Recognition service to Volcengine API.
+ - aiWaitFor:
+ prompt: Volcengine is selected, the empty API Key entry says Enter speech API key, and Test API key is disabled.
+ options: { timeoutMs: 30000, checkIntervalMs: 1000 }
+ - aiAssert: The page says no API key is saved for this service and does not show the previous accepted result.
+ - aiAct: Switch the Recognition service back to Deepgram Nova-3 (English).
+ - aiWaitFor:
+ prompt: Deepgram is selected, the empty API Key entry says Saved — leave blank to keep, and Test API key is enabled.
+ options: { timeoutMs: 30000, checkIntervalMs: 1000 }
+ - aiAct: Test the saved Deepgram API key.
- aiWaitFor:
prompt: The API key is accepted by the synthetic endpoint and the speech API is ready.
options: { timeoutMs: 30000, checkIntervalMs: 1000 }
diff --git a/tests/e2e/gtk_onboarding_fixture.py b/tests/e2e/gtk_onboarding_fixture.py
index 13b493b..ff79532 100644
--- a/tests/e2e/gtk_onboarding_fixture.py
+++ b/tests/e2e/gtk_onboarding_fixture.py
@@ -56,7 +56,7 @@ def build_onboarding_fixture(mode):
"asr_provider_name": "Doubao",
}
holder = {
- "asr_key": False,
+ "asr_keys": {},
"capture_sources": [],
"login": None,
"preview": False,
@@ -247,7 +247,7 @@ def build_onboarding_fixture(mode):
)
state.login_status = (
LoginStatus.LOGGED_IN
- if provider != "doubao" and holder["asr_key"]
+ if provider != "doubao" and holder["asr_keys"].get(provider)
else LoginStatus.NOT_LOGGED_IN
)
GLib.idle_add(refresh)
@@ -255,7 +255,9 @@ def build_onboarding_fixture(mode):
def save_asr(key):
if not key.strip():
raise ValueError("Enter an API key first.")
- holder["asr_key"] = True
+ holder["asr_keys"][summary["asr_provider"]] = key.strip()
+ state.login_status = LoginStatus.LOGGED_IN
+ refresh()
def test_asr(_key, done):
def finish():
@@ -290,7 +292,7 @@ def build_onboarding_fixture(mode):
test_polish=test_endpoint,
apply_microphone=apply_microphone,
apply_asr_provider=apply_asr_provider,
- asr_has_key=lambda: holder["asr_key"],
+ asr_has_key=lambda: bool(holder["asr_keys"].get(summary["asr_provider"])),
save_asr=save_asr,
test_asr=test_asr,
)
diff --git a/tests/e2e/run-omarchy-midscene.sh b/tests/e2e/run-omarchy-midscene.sh
index 3debb3e..329e4b5 100755
--- a/tests/e2e/run-omarchy-midscene.sh
+++ b/tests/e2e/run-omarchy-midscene.sh
@@ -3,6 +3,13 @@ set -euo pipefail
readonly ROOT_DIR="$PWD"
readonly MIDSCENE_PROJECT="${1:?Usage: run-omarchy-midscene.sh PROJECT}"
+case "$MIDSCENE_PROJECT" in
+ omarchy-shard-[1-4]|omarchy-shell|omarchy-providers) ;;
+ *)
+ echo "Unsupported Omarchy Midscene project: $MIDSCENE_PROJECT" >&2
+ exit 2
+ ;;
+esac
readonly WORK_DIR="$ROOT_DIR/.midscene-omarchy"
readonly HARNESS_DIR="$WORK_DIR/omarchy-iso"
# shellcheck source=omarchy-vm.env
@@ -219,15 +226,4 @@ for _gate_attempt in {1..100}; do
sleep 0.2
done
-case "$MIDSCENE_PROJECT" in
- omarchy-shard-[1-4])
- npm --prefix tests/e2e test -- --project "$MIDSCENE_PROJECT"
- ;;
- omarchy-shell)
- npm --prefix tests/e2e test -- --project "$MIDSCENE_PROJECT"
- ;;
- *)
- echo "Unsupported Omarchy Midscene project: $MIDSCENE_PROJECT" >&2
- exit 2
- ;;
-esac
+npm --prefix tests/e2e test -- --project "$MIDSCENE_PROJECT"
diff --git a/tests/manual/asr_key_ui.py b/tests/manual/asr_key_ui.py
new file mode 100644
index 0000000..928321a
--- /dev/null
+++ b/tests/manual/asr_key_ui.py
@@ -0,0 +1,139 @@
+"""Real GTK credential ownership checks; isolated config, synthetic keys only."""
+from contextlib import ExitStack
+from dataclasses import replace
+import os
+from pathlib import Path
+import tempfile
+from threading import Thread
+import time
+from unittest.mock import patch
+
+import gi
+gi.require_version("Gtk", "4.0")
+from gi.repository import GLib, Gtk
+
+from safety import hard_deadline
+from doubao_input.app import DoubaoInputApp
+from doubao_input.deepgram.credentials import DeepgramCredentialsStore
+from doubao_input.doubao.volcengine_credentials import VolcengineCredentialsStore
+from doubao_input.i18n import set_language, tr
+
+
+def drain(seconds=0.2):
+ deadline = time.monotonic() + seconds
+ context = GLib.MainContext.default()
+ while time.monotonic() < deadline:
+ for _ in range(50):
+ if not context.pending():
+ break
+ context.iteration(False)
+ time.sleep(0.005)
+
+
+def capture(name):
+ drain()
+ folder = os.environ.get("ASR_UI_SCREENSHOTS")
+ if folder:
+ from PIL import ImageGrab
+ destination = Path(folder) / os.environ.get("ASR_UI_LANGUAGE", "en")
+ destination.mkdir(parents=True, exist_ok=True)
+ ImageGrab.grab(xdisplay=os.environ["DISPLAY"]).save(destination / (name + ".png"))
+
+
+def main():
+ Gtk.init()
+ with tempfile.TemporaryDirectory(prefix="doubao-asr-ui-") as directory, \
+ ExitStack() as cleanup, \
+ patch.dict(os.environ, {"XDG_CONFIG_HOME": directory + "/config", "XDG_DATA_HOME": directory + "/data"}), \
+ patch("doubao_input.app.Overlay"), patch("doubao_input.app.AudioCapture"), \
+ patch("doubao_input.app.EscapeGuard"), patch("doubao_input.app.UpdateChecker"), \
+ patch("doubao_input.doubao.transcription.AudioCapture"), \
+ patch("doubao_input.app.TriggerReader") as reader, \
+ patch("doubao_input.app.Injector"), patch("doubao_input.ui.tray.Tray"), \
+ patch("doubao_input.app.ParamsStore.has_saved", return_value=False), \
+ patch("doubao_input.ui.control_window.microphones", return_value=[]), \
+ patch("doubao_input.ui.settings_window.microphones", return_value=[]):
+ reader.return_value.start.return_value = True
+ app = DoubaoInputApp(background=True)
+ cleanup.callback(app._on_shutdown, app)
+ cleanup.callback(app._quit)
+ app.register(None)
+ assert not app.get_is_remote(), "Run in an isolated dbus-run-session"
+ language = os.environ.get("ASR_UI_LANGUAGE", "en")
+ app.settings = replace(app.settings, language=language)
+ set_language(language)
+ app._build()
+ control = app._control
+ cleanup.callback(control.destroy)
+ control.show()
+ control.window.set_default_size(760, 980)
+ drain()
+
+ # Switch before the debounce fires, including the nested GTK refresh
+ # caused by persisting the old provider's credential.
+ control._asr_provider.set_selected(1)
+ control._asr_key.set_text("synthetic-volcengine-original")
+ control._asr_provider.set_selected(2)
+ drain()
+ assert app.settings.asr_provider == "deepgram"
+ assert VolcengineCredentialsStore.load().api_key == "synthetic-volcengine-original"
+ assert DeepgramCredentialsStore.load() is None
+ assert control._asr_key.get_text() == ""
+ assert not control._asr_test_button.get_sensitive()
+ capture("onboarding-new-provider")
+
+ control._asr_key.set_text("synthetic-deepgram-original")
+ assert control._flush_asr_key()
+ control._asr_provider.set_selected(1)
+ assert control._asr_test_button.get_sensitive()
+ capture("onboarding-saved-provider")
+
+ app._show_settings()
+ window = app._settings_window
+ window.window.set_default_size(660, 980)
+ cleanup.callback(window.window.destroy)
+ drain()
+ control._asr_key.set_text("synthetic-volcengine-replacement")
+ window.asr_provider.set_selected(2)
+ assert app.settings.asr_provider == "deepgram"
+ assert VolcengineCredentialsStore.load().api_key == "synthetic-volcengine-replacement"
+ assert DeepgramCredentialsStore.load().api_key == "synthetic-deepgram-original"
+ assert window.asr_key.get_placeholder_text() == tr(
+ "Saved — leave blank to keep", "已保存,留空则保持不变")
+ assert window.asr_status.get_text() == ""
+ capture("settings-saved-provider")
+
+ with patch.object(window, "_save_asr", side_effect=OSError("Synthetic save failure")):
+ window.asr_key.set_text("synthetic-deepgram-replacement")
+ window.asr_provider.set_selected(1)
+ window.window.close()
+ drain()
+ assert app.settings.asr_provider == "deepgram"
+ assert window.window.get_visible()
+ assert window.asr_key.get_text() == "synthetic-deepgram-replacement"
+ assert DeepgramCredentialsStore.load().api_key == "synthetic-deepgram-original"
+ capture("settings-save-failure")
+ assert window.flush_edits()
+ assert DeepgramCredentialsStore.load().api_key == "synthetic-deepgram-replacement"
+
+ window.asr_provider.set_selected(1)
+ with patch("doubao_input.doubao.volcengine_asr_client.VolcengineASRClient") as factory:
+ window.asr_test_button.emit("clicked")
+ assert app._asr_probe is factory.return_value and window._asr_testing
+ control._test_asr_clicked()
+ assert app._asr_probe is factory.return_value and not control._asr_testing
+ factory.return_value.disconnect.assert_not_called()
+ worker = Thread(target=factory.return_value.on_open)
+ worker.start(); worker.join(timeout=2)
+ assert not worker.is_alive() and window._asr_testing
+ drain()
+ assert not window._asr_testing and app._asr_probe is None
+ assert window.asr_provider.get_sensitive()
+ factory.return_value.disconnect.assert_called_once()
+ capture("settings-key-test-complete")
+ print("PASS: real GTK debounce, cross-window ownership, save failure and worker completion")
+
+
+if __name__ == "__main__":
+ with hard_deadline():
+ main()
diff --git a/tests/manual/personal_ui.py b/tests/manual/personal_ui.py
index 128d725..b80ab7b 100644
--- a/tests/manual/personal_ui.py
+++ b/tests/manual/personal_ui.py
@@ -126,5 +126,33 @@ with tempfile.TemporaryDirectory() as temp:
assert "Midscene" in window.hotword_preview.get_text()
click(window.memory_box, tr("Forget", "忘记"))
assert store.corrections() == [] and store.history()[0]["confirmed"] == confirmed["confirmed"]
+ # Selecting the second occurrence must not change the first.
+ repeated = "用 Midjourney 画图,用 Midjourney 写测试"
+ store.record(repeated, repeated, status="sent"); window.refresh()
+ row = store.history()[0]; window.edit_correction(row); drain()
+ sample = [widget for widget in widgets(window.correction_window) if isinstance(widget, Gtk.TextView) and window.text(widget) == repeated][0]
+ start = repeated.rindex("Midjourney"); sample.get_buffer().select_range(sample.get_buffer().get_iter_at_offset(start), sample.get_buffer().get_iter_at_offset(start + 10)); drain()
+ entries = [widget for widget in widgets(window.correction_window) if isinstance(widget, Gtk.Entry)]
+ assert entries[0].get_text() == "Midjourney"
+ entries[1].set_text("Midscene"); drain(); capture("selected-correction")
+ click(window.correction_window, tr("Confirm & remember", "确认并记住"))
+ assert store.history()[0]["confirmed"] == "用 Midjourney 画图,用 Midscene 写测试"
+ # Evaluation renders real GTK controls; all audio/network are synthetic.
+ notebook.set_current_page(3); drain()
+ evaluation = window.evaluation
+ evaluation.add()
+ evaluation.reference.get_buffer().set_text("Use Midjourney for art")
+ evaluation.protected.get_buffer().set_text("Midjourney")
+ evaluation.workbench.record(evaluation.row(), b"\x00\x00" * 160)
+ evaluation.refresh(); drain(); capture("speech-evaluation")
+ assert evaluation.workbench.validated()[0]["protected_terms"] == ["Midjourney"]
+ row = evaluation.row()
+ row["results"] = [{"id": row["id"], "mode": "raw", "text": row["reference"], "latency_ms": 100}, {"id": row["id"], "mode": "hotwords", "text": "Use Midscene for art", "latency_ms": 120}]
+ evaluation.save(); evaluation.render_results(); drain()
+ adjustment = notebook.get_nth_page(3).get_vadjustment()
+ adjustment.set_value(adjustment.get_upper() - adjustment.get_page_size()); drain(); capture("speech-results")
+ assert "100.0%" in evaluation.results.get_text()
+ evaluation.reference.get_buffer().set_text("Changed reference")
+ assert "results" not in evaluation.row()
window.close(); assert not window.window.get_visible()
print("PASS: real GTK window, padded editors, debounce, recording toggle, history, counts-only AI, reviewed vocabulary, correction preview/cancel/confirm, immutable originals, hotword preview, forget and close flush")
diff --git a/tests/manual/refactor_smoke.py b/tests/manual/refactor_smoke.py
index 13685f4..0a0dc1e 100644
--- a/tests/manual/refactor_smoke.py
+++ b/tests/manual/refactor_smoke.py
@@ -28,7 +28,7 @@ def main():
patch("doubao_input.app.Overlay"), patch("doubao_input.app.AudioCapture"), \
patch("doubao_input.app.EscapeGuard"), patch("doubao_input.app.UpdateChecker"), \
patch("doubao_input.doubao.transcription.AudioCapture"), \
- patch("doubao_input.app.EvdevPtt") as reader, \
+ patch("doubao_input.app.TriggerReader") as reader, \
patch("doubao_input.app.Injector") as injector, \
patch("doubao_input.ui.tray.Tray"), \
patch("doubao_input.app.ParamsStore.has_saved", return_value=False), \
@@ -114,17 +114,18 @@ def main():
app._do_paste("Synthetic rehearsal result")
assert app._setup_session.voice_ok and not app._delivery.busy
injector.return_value.inject.assert_not_called()
- app._target = "fake-target"
- app._do_paste("Synthetic delivery result")
- assert app._delivery.busy
loop = GLib.MainLoop()
statuses = []
changed = app._delivery.changed
def completed(status):
changed(status)
- statuses.append(status)
- loop.quit()
+ if status != "pending":
+ statuses.append(status)
+ loop.quit()
app._delivery.changed = completed
+ app._target = "fake-target"
+ app._do_paste("Synthetic delivery result")
+ assert app._delivery.busy
timeout = GLib.timeout_add(2000, lambda: loop.quit() or False)
loop.run()
if statuses:
diff --git a/tests/unit/test_app_edges.py b/tests/unit/test_app_edges.py
index eacfeaf..2c7bff5 100644
--- a/tests/unit/test_app_edges.py
+++ b/tests/unit/test_app_edges.py
@@ -3,6 +3,7 @@ from pathlib import Path
import tempfile
from unittest import TestCase
from unittest.mock import Mock, patch
+from threading import Thread, get_ident
from doubao_input.app import DoubaoInputApp
from doubao_input.doubao.app_state import AppState, LoginStatus, RecordingState
@@ -13,6 +14,7 @@ from doubao_input.deepgram.credentials import DeepgramCredentialsStore
from doubao_input.result import RecentResult
from doubao_input.personal import PersonalStore
from doubao_input.settings import Settings
+from doubao_input.inject.delivery import Delivery
class AppLifecycleEdgesTest(TestCase):
@@ -148,6 +150,15 @@ class AppDeliveryEdgesTest(TestCase):
self.assertEqual((normal.recent.text, normal.recent.status), ("partial", "partial"))
normal._notify_recovery.assert_called_once()
+ def test_speech_evaluation_waits_for_prerolled_microphone(self):
+ app = SimpleNamespace(_busy=lambda: False,
+ _audio_capture=SimpleNamespace(is_capturing=True))
+ self.assertFalse(DoubaoInputApp._can_evaluate_speech(app))
+ app._audio_capture.is_capturing = False
+ self.assertTrue(DoubaoInputApp._can_evaluate_speech(app))
+ app._busy = lambda: True
+ self.assertFalse(DoubaoInputApp._can_evaluate_speech(app))
+
def test_cancel_input_clears_every_pending_owner(self):
app = SimpleNamespace(_enter_after_paste=True, _triggers=Mock(), _setup_session=Mock(),
_recovery_timer=9, _delivery=Mock(), _polisher=Mock(),
@@ -176,18 +187,92 @@ class AppSetupEdgesTest(TestCase):
def test_successful_official_key_probe_restores_readiness(self):
completed = Mock()
+ main_thread = get_ident()
+ threads = []
app = SimpleNamespace(_busy=lambda: False, _asr_probe=None,
- _sync_recognition_status=Mock(), _control=Mock())
+ _sync_recognition_status=Mock(side_effect=lambda: threads.append(get_ident())),
+ _control=Mock())
app.settings = Settings(asr_provider="volcengine")
with patch("doubao_input.doubao.volcengine_asr_client.VolcengineASRClient") as client_type, \
patch("doubao_input.app.GLib.idle_add") as idle_add:
probe = client_type.return_value
DoubaoInputApp._test_asr_key(app, "test-key", completed)
- probe.on_open()
+ worker = Thread(target=probe.on_open)
+ worker.start(); worker.join(timeout=2)
+ self.assertFalse(worker.is_alive())
+ app._sync_recognition_status.assert_not_called()
+ app._control.refresh.assert_not_called()
+ completed.assert_not_called()
+ callback, *args = idle_add.call_args.args
+ callback(*args)
+ callback(*args)
probe.disconnect.assert_called_once_with()
app._sync_recognition_status.assert_called_once_with()
app._control.refresh.assert_called_once_with()
- idle_add.assert_called_once_with(completed, "API key accepted", "")
+ self.assertEqual(threads, [main_thread])
+ completed.assert_called_once_with("API key accepted", "")
+
+ def test_old_key_probe_completion_cannot_update_new_provider(self):
+ app = SimpleNamespace(_busy=lambda: False, _asr_probe=None,
+ _sync_recognition_status=Mock(), _control=Mock(),
+ settings=Settings(asr_provider="volcengine"))
+ completed = Mock()
+ with patch("doubao_input.doubao.volcengine_asr_client.VolcengineASRClient"), \
+ patch("doubao_input.app.GLib.idle_add") as idle:
+ DoubaoInputApp._test_asr_key(app, "synthetic-key", completed)
+ app._asr_probe.on_open()
+ app._asr_probe = None
+ callback, *args = idle.call_args.args
+ callback(*args)
+ completed.assert_not_called()
+ app._control.refresh.assert_not_called()
+
+ def test_running_probe_blocks_second_window_without_cancelling_first(self):
+ probe = Mock()
+ app = SimpleNamespace(_asr_probe=probe)
+ app._busy = lambda: DoubaoInputApp._busy(app)
+ with self.assertRaises(ValueError):
+ DoubaoInputApp._test_asr_key(app, "synthetic-key", Mock())
+ self.assertIs(app._asr_probe, probe)
+ probe.disconnect.assert_not_called()
+
+ def test_probe_start_failure_releases_busy_state(self):
+ app = SimpleNamespace(_busy=lambda: False, _asr_probe=None,
+ settings=Settings(asr_provider="volcengine"))
+ with patch("doubao_input.doubao.volcengine_asr_client.VolcengineASRClient") as client_type:
+ probe = client_type.return_value
+ probe.connect.side_effect = OSError("synthetic connection failure")
+ with self.assertRaises(OSError):
+ DoubaoInputApp._test_asr_key(app, "synthetic-key", Mock())
+ self.assertIsNone(app._asr_probe)
+ probe.disconnect.assert_called_once_with()
+
+ def test_provider_change_flushes_both_windows_before_changing_owner(self):
+ for saved in (False, True):
+ with self.subTest(saved=saved):
+ previous = Settings(asr_provider="volcengine")
+ app = SimpleNamespace(settings=previous, _busy=lambda: False,
+ _triggers=SimpleNamespace(busy=False),
+ _control=Mock(), _settings_window=Mock(),
+ _configure_recognition_backend=Mock(),
+ _sync_recognition_status=Mock(), _setup_session=Mock())
+ owners = []
+ def flush():
+ owners.append(app.settings.asr_provider)
+ return saved
+ app._control._flush_asr_key.side_effect = flush
+ app._settings_window._flush_asr_key.side_effect = flush
+ with patch("doubao_input.app.apply_preferences") as apply:
+ if saved:
+ DoubaoInputApp.apply_settings(app, Settings(asr_provider="deepgram"))
+ self.assertEqual(owners, ["volcengine", "volcengine"])
+ self.assertEqual(app.settings.asr_provider, "deepgram")
+ apply.assert_called_once()
+ else:
+ with self.assertRaises(ValueError):
+ DoubaoInputApp.apply_settings(app, Settings(asr_provider="deepgram"))
+ self.assertIs(app.settings, previous)
+ apply.assert_not_called()
def test_deepgram_provider_builds_api_key_backend(self):
app = SimpleNamespace(settings=Settings(asr_provider="deepgram"),
@@ -274,6 +359,25 @@ class AppSetupEdgesTest(TestCase):
class PersonalHistoryDeliveryTest(TestCase):
+ def test_standalone_enter_preserves_failed_history_and_word_counts(self):
+ with tempfile.TemporaryDirectory() as temp:
+ store = PersonalStore(Path(temp) / "personal.sqlite3")
+ identifier = store.record("Synthetic synthetic", "Synthetic synthetic", True, "target_changed")
+ app = SimpleNamespace(_personal_store=store, _history_id=identifier,
+ recent=RecentResult(text="Synthetic synthetic", status="target_changed"),
+ _control=Mock(), _overlay=Mock())
+ app._enter_changed = lambda status: DoubaoInputApp._enter_changed(app, status)
+ app._delivery = Delivery(lambda ms, cb: cb(), lambda: "target", Mock(return_value=True),
+ Mock(return_value=True),
+ lambda status: DoubaoInputApp._delivery_changed(app, status),
+ SimpleNamespace(submit=lambda work, done: done(work())))
+ with patch("doubao_input.app.focused_target", return_value="target"):
+ DoubaoInputApp._send_enter(app)
+ self.assertEqual(store.history()[0]["status"], "target_changed")
+ self.assertEqual(app.recent.status, "target_changed")
+ self.assertEqual(store.candidates(), [])
+ app._control.set_result.assert_not_called()
+
def test_delivery_attempt_records_once_then_updates_status_without_duplicate_rows(self):
with tempfile.TemporaryDirectory() as temp:
store = PersonalStore(Path(temp) / "personal.sqlite3")
diff --git a/tests/unit/test_asr_key_persistence.py b/tests/unit/test_asr_key_persistence.py
new file mode 100644
index 0000000..bfbe372
--- /dev/null
+++ b/tests/unit/test_asr_key_persistence.py
@@ -0,0 +1,168 @@
+"""Provider switches must not change the owner of a pending credential draft."""
+from types import MethodType, SimpleNamespace
+from unittest import TestCase
+from unittest.mock import Mock, patch
+
+from doubao_input.ui.settings_window import ASR_PROVIDERS, SettingsWindow
+from doubao_input.ui.control_window import ControlWindow
+
+
+class ASRKeyPersistenceTest(TestCase):
+ def view(self):
+ self.saved = {"deepgram": "synthetic-deepgram"}
+ self.provider = "volcengine"
+ self.draft = "synthetic-volcengine"
+ entry = Mock()
+ entry.get_text.side_effect = lambda: self.draft
+ entry.set_text.side_effect = lambda text: setattr(self, "draft", text)
+ view = SimpleNamespace(
+ _updating=False, _asr_save_source=0, _asr_has_key=False, _asr_testing=False,
+ asr_key=entry, asr_status=Mock(), asr_provider=Mock(),
+ _sync_provider_details=Mock(), _restore_controls=Mock(),
+ _save_asr=lambda key: self.saved.__setitem__(self.provider, key),
+ _asr_has_key_func=lambda: self.provider in self.saved,
+ )
+ view.asr_provider.get_selected.return_value = ASR_PROVIDERS.index("deepgram")
+ def apply():
+ self.provider = "deepgram"
+ return True
+ view._save_current = Mock(side_effect=apply)
+ for name in ("_asr_provider_changed", "_save_asr_key_now", "flush_edits", "_flush_asr_key"):
+ setattr(view, name, MethodType(getattr(SettingsWindow, name), view))
+ return view
+
+ def test_saved_and_pending_drafts_never_overwrite_other_provider(self):
+ for already_saved in (False, True):
+ with self.subTest(already_saved=already_saved):
+ view = self.view()
+ if already_saved:
+ self.assertTrue(view._save_asr_key_now())
+ else:
+ view._asr_save_source = 42
+ with patch("doubao_input.ui.settings_window.GLib.source_remove") as remove:
+ view._asr_provider_changed()
+ view._flush_asr_key()
+ self.assertEqual(remove.call_count, 0 if already_saved else 1)
+ self.assertEqual(self.saved, {"volcengine": "synthetic-volcengine",
+ "deepgram": "synthetic-deepgram"})
+ self.assertEqual(self.draft, "")
+ self.assertEqual(view._asr_save_source, 0)
+
+ def test_failed_draft_save_blocks_switch_and_keeps_draft_for_retry(self):
+ view = self.view()
+ view._save_asr = Mock(side_effect=OSError("synthetic write failure"))
+ view._asr_provider_changed()
+ view._save_current.assert_not_called()
+ view._restore_controls.assert_called_once()
+ self.assertEqual(self.draft, "synthetic-volcengine")
+ self.assertEqual(self.saved, {"deepgram": "synthetic-deepgram"})
+
+ def test_failed_key_save_keeps_settings_open(self):
+ view = self.view()
+ view._save_asr = Mock(side_effect=OSError("synthetic write failure"))
+ view.trigger_picker = Mock()
+ view.vibekey_pickers = []
+ self.assertTrue(SettingsWindow._close(view))
+ view._save_current.assert_not_called()
+ self.assertEqual(self.draft, "synthetic-volcengine")
+
+ def test_provider_cannot_change_during_key_test(self):
+ view = self.view()
+ view._asr_testing = True
+ view._asr_provider_changed()
+ view._restore_controls.assert_called_once()
+ view._save_current.assert_not_called()
+ self.assertEqual(self.provider, "volcengine")
+
+ def test_provider_switch_refreshes_placeholder_and_clears_old_result(self):
+ for saved in (False, True):
+ with self.subTest(saved=saved):
+ view = self.view()
+ if not saved:
+ self.saved.pop("deepgram")
+ view._asr_provider_changed()
+ view.asr_key.set_placeholder_text.assert_called_with(
+ "Saved — leave blank to keep" if saved else "Enter speech API key")
+ if saved:
+ view.asr_status.set_text.assert_called_with("")
+
+
+class OnboardingKeyPersistenceTest(TestCase):
+ def view(self):
+ self.saved = {"deepgram": "synthetic-deepgram"}
+ self.provider = "volcengine"
+ self.draft = "synthetic-volcengine"
+ entry = Mock()
+ entry.get_text.side_effect = lambda: self.draft
+ entry.set_text.side_effect = lambda text: setattr(self, "draft", text)
+ actions = Mock()
+ actions.asr_has_key.side_effect = lambda: self.provider in self.saved
+ actions.save_asr.side_effect = lambda key: self.saved.__setitem__(self.provider, key)
+ actions.apply_asr_provider.side_effect = lambda provider: setattr(self, "provider", provider)
+ actions.is_preview_testing.return_value = False
+ view = SimpleNamespace(
+ _changing_asr_provider=False, _asr_testing=False,
+ _asr_key_save_source=0, _asr_key=entry, _asr_status=Mock(),
+ _asr_provider=Mock(), _asr_test_button=Mock(), _actions=actions,
+ _refresh=Mock(), set_feedback=Mock(), _window=Mock(),
+ )
+ view._asr_provider.get_selected.return_value = ASR_PROVIDERS.index("deepgram")
+ for name in ("_asr_provider_changed", "_save_asr_key_now", "_flush_asr_key",
+ "_test_asr_clicked", "_asr_tested", "_sync_asr_controls", "hide"):
+ setattr(view, name, MethodType(getattr(ControlWindow, name), view))
+ return view
+
+ def test_saved_and_pending_drafts_keep_their_provider(self):
+ for already_saved in (False, True):
+ with self.subTest(already_saved=already_saved):
+ view = self.view()
+ if already_saved:
+ self.assertTrue(view._save_asr_key_now())
+ else:
+ view._asr_key_save_source = 42
+ with patch("doubao_input.ui.control_window.GLib.source_remove"):
+ view._asr_provider_changed()
+ view._flush_asr_key()
+ self.assertEqual(self.saved, {"volcengine": "synthetic-volcengine",
+ "deepgram": "synthetic-deepgram"})
+ self.assertEqual(self.draft, "")
+ self.assertEqual(view._asr_key_save_source, 0)
+
+ def test_empty_draft_does_not_require_credentials_to_switch(self):
+ view = self.view()
+ self.draft = ""
+ view._asr_provider_changed()
+ self.assertEqual(self.provider, "deepgram")
+ view._actions.save_asr.assert_not_called()
+
+ def test_empty_entry_reflects_saved_key_for_current_provider(self):
+ view = self.view()
+ self.draft = ""
+ view._sync_asr_controls()
+ view._asr_test_button.set_sensitive.assert_called_with(False)
+ view._asr_key.set_placeholder_text.assert_called_with("Enter speech API key")
+ self.provider = "deepgram"
+ view._sync_asr_controls()
+ view._asr_test_button.set_sensitive.assert_called_with(True)
+ view._asr_key.set_placeholder_text.assert_called_with("Saved — leave blank to keep")
+
+ def test_failed_save_preserves_provider_draft_and_visible_window(self):
+ view = self.view()
+ view._actions.save_asr.side_effect = OSError("synthetic write failure")
+ view._asr_provider_changed()
+ view.hide()
+ self.assertEqual(self.provider, "volcengine")
+ self.assertEqual(self.draft, "synthetic-volcengine")
+ view._window.set_visible.assert_not_called()
+
+ def test_key_test_blocks_switch_and_restores_controls_on_completion(self):
+ view = self.view()
+ view._test_asr_clicked()
+ self.assertEqual(self.draft, "")
+ view._asr_provider.set_sensitive.assert_called_with(False)
+ view._asr_provider_changed()
+ self.assertEqual(self.provider, "volcengine")
+ completed = view._actions.test_asr.call_args.args[1]
+ completed("accepted", "")
+ self.assertFalse(view._asr_testing)
+ view._asr_provider.set_sensitive.assert_called_with(True)
diff --git a/tests/unit/test_delivery.py b/tests/unit/test_delivery.py
index 309c43c..7f67294 100644
--- a/tests/unit/test_delivery.py
+++ b/tests/unit/test_delivery.py
@@ -128,6 +128,23 @@ class DeliveryTest(TestCase):
self.enter.assert_not_called()
self.changed.assert_called_with("enter_skipped")
+ def test_enter_owns_status_callback_through_cancel_and_next_paste(self):
+ d = self.make()
+ callbacks = []
+ d.worker.submit = lambda work, done: callbacks.append(lambda: done(work()))
+ entered = Mock()
+ d.submit_enter("target", changed=entered)
+ d.cancel()
+ self.assertEqual([call.args[0] for call in entered.call_args_list], ["pending", "cancelled"])
+ self.changed.assert_not_called()
+ d.submit("new", "target")
+ callbacks.pop(0)()
+ self.assertTrue(d.busy)
+ self.queue.pop(0)()
+ callbacks.pop(0)()
+ self.changed.assert_called_with("attempted")
+ self.assertEqual(entered.call_count, 2)
+
def test_close_rejects_new_work_and_invalidates_timers(self):
d = self.make()
d.worker = Mock()
diff --git a/tests/unit/test_polish.py b/tests/unit/test_polish.py
index 6b0c0e8..04c7fba 100644
--- a/tests/unit/test_polish.py
+++ b/tests/unit/test_polish.py
@@ -37,7 +37,7 @@ class PolishTest(TestCase):
self.assertIn("Related sentences belong together", DEFAULT_POLISH_PROMPT_EN)
formatted = "引言。\n\n1. 核对需求\n2. 开发\n\n明天验收。"
body = json.dumps({"choices": [{"message": {"content": formatted}}]}).encode()
- with patch("doubao_input.polish.request.urlopen", return_value=Response(body)):
+ with patch("doubao_input.polish.open_request", return_value=Response(body)):
result = PolishClient().polish(
"synthetic text", base_url="https://example.com/v1", api_key="fake-key",
model="test", prompt=DEFAULT_POLISH_PROMPT_ZH)
@@ -55,7 +55,7 @@ class PolishTest(TestCase):
def test_contextual_sound_rules_reach_request_without_rewriting_input_locally(self):
raw = "请重心打开设置页面。"
settings = Settings()
- with patch("doubao_input.polish.request.urlopen", return_value=Response(
+ with patch("doubao_input.polish.open_request", return_value=Response(
b'{"choices":[{"message":{"content":"result"}}]}')) as call:
PolishClient().polish(raw, base_url="https://example.com/v1",
api_key="synthetic", model="test",
@@ -82,7 +82,7 @@ class PolishTest(TestCase):
b'data: [DONE]\n\n') if streaming else Response(
b'{"choices":[{"message":{"content":"polished"}}]}'))
seen = []
- with patch("doubao_input.polish.request.urlopen", return_value=response) as call:
+ with patch("doubao_input.polish.open_request", return_value=response) as call:
result = PolishClient().polish(
"synthetic text", base_url="https://open.bigmodel.cn" + path,
api_key="fake-key", model=model, prompt="Polish text",
@@ -102,7 +102,7 @@ class PolishTest(TestCase):
for base, expected in (("https://api.deepseek.com/v1", True),
("https://example.test/v1", False)):
response = Response(b'{"choices":[{"message":{"content":"ok"}}]}')
- with patch("doubao_input.polish.request.urlopen", return_value=response) as call:
+ with patch("doubao_input.polish.open_request", return_value=response) as call:
PolishClient().polish("text", base_url=base, api_key="key",
model="model", prompt="prompt")
payload = json.loads(call.call_args.args[0].data)
@@ -112,7 +112,7 @@ class PolishTest(TestCase):
def test_client_parses_compatible_response_without_leaking_key(self):
response = Response(json.dumps({"choices": [{"message": {"content": " polished "}}]}).encode())
- with patch("doubao_input.polish.request.urlopen", return_value=response) as open_url:
+ with patch("doubao_input.polish.open_request", return_value=response) as open_url:
result = PolishClient().polish("raw", base_url="https://example.test/v1",
api_key="secret", model="model", prompt="prompt")
self.assertEqual(result, "polished")
@@ -124,7 +124,7 @@ class PolishTest(TestCase):
b'data: {"choices":[{"delta":{"content":"text"}}]}\n\n'
b'data: [DONE]\n\n')
seen = []
- with patch("doubao_input.polish.request.urlopen",
+ with patch("doubao_input.polish.open_request",
return_value=StreamResponse(body)):
result = PolishClient().polish("raw", base_url="https://example.test/v1",
api_key="secret", model="model", prompt="prompt",
@@ -132,6 +132,15 @@ class PolishTest(TestCase):
self.assertEqual(result, "clear text")
self.assertEqual(seen, ["clear ", "clear text"])
+ def test_nonstream_rejects_truncated_and_filtered_results(self):
+ for reason in ("length", "content_filter", "unknown_failure"):
+ body = json.dumps({"choices": [{"message": {"content": "partial"},
+ "finish_reason": reason}]}).encode()
+ with self.subTest(reason=reason), patch("doubao_input.polish.open_request", return_value=Response(body)):
+ with self.assertRaisesRegex(ValueError, "ended before completion"):
+ PolishClient().polish("synthetic", base_url="https://example.test/v1",
+ api_key="synthetic", model="test", prompt="test")
+
def test_stream_rejects_partial_text_after_abrupt_eof_or_length_limit(self):
responses = (
b'data: {"choices":[{"delta":{"content":"partial"}}]}\n\n',
diff --git a/tests/unit/test_polish_transport.py b/tests/unit/test_polish_transport.py
new file mode 100644
index 0000000..efc9771
--- /dev/null
+++ b/tests/unit/test_polish_transport.py
@@ -0,0 +1,213 @@
+"""Bounded loopback HTTP checks; no paid endpoint or real credentials."""
+from concurrent.futures import ThreadPoolExecutor
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+import json
+import os
+from pathlib import Path
+import queue
+import shutil
+from socketserver import BaseRequestHandler, ThreadingTCPServer
+import ssl
+import subprocess
+import tempfile
+from threading import Event, Thread
+import time
+from unittest import TestCase
+from unittest.mock import patch
+from urllib import request
+
+from doubao_input.polish import PolishClient, PolishManager
+from doubao_input.polish_transport import RequestCancellation
+from doubao_input.settings import Settings
+
+
+class PolishTransportTest(TestCase):
+ def setUp(self):
+ self.stopped = Event()
+ self.streaming = Event()
+ self.requests = []
+ owner = self
+
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *_):
+ pass
+
+ def do_GET(self):
+ owner.requests.append((self.path, self.headers.get("Authorization")))
+ self.send_response(200)
+ self.end_headers()
+
+ def do_CONNECT(self):
+ owner.streaming.set()
+ try:
+ # Drip a partial status line beyond the overall deadline.
+ self.wfile.write(b"HTTP/1.1 200 ")
+ for _ in range(50):
+ if owner.stopped.wait(0.02):
+ break
+ self.wfile.write(b".")
+ self.wfile.flush()
+ except (BrokenPipeError, ConnectionResetError):
+ pass
+
+ def do_POST(self):
+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
+ text = body["messages"][-1]["content"]
+ owner.requests.append((text, self.headers.get("Authorization")))
+ if text.startswith("redirect"):
+ self.send_response(int(text.split("-")[1]))
+ self.send_header("Location", f"http://localhost:{owner.sink.server_port}/target")
+ self.end_headers()
+ return
+ try:
+ if text == "headers":
+ # Incomplete headers must also release the worker on cancel.
+ self.wfile.write(b"HTTP/1.1 200 OK\r\n")
+ else:
+ self.send_response(200)
+ self.end_headers()
+ if text in ("heartbeat", "headers"):
+ owner.streaming.set()
+ while not owner.stopped.wait(0.02):
+ self.wfile.write(b": heartbeat\n\n" if text == "heartbeat" else b"X-Wait: yes\r\n")
+ self.wfile.flush()
+ elif body["stream"]:
+ self.wfile.write(b'data: {"choices":[{"delta":{"content":"complete"},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n')
+ else:
+ self.wfile.write(b'{"choices":[{"message":{"content":"complete"},"finish_reason":"stop"}]}')
+ except (BrokenPipeError, ConnectionResetError):
+ pass
+
+ self.sink = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ for server in (self.sink, self.server):
+ thread = Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ self.addCleanup(thread.join, 2)
+ self.addCleanup(server.server_close)
+ self.addCleanup(server.shutdown)
+ self.addCleanup(self.stopped.set)
+ self.endpoint = f"http://127.0.0.1:{self.server.server_port}"
+ self.args = dict(base_url=self.endpoint, api_key="synthetic-key", model="synthetic", prompt="synthetic")
+
+ def test_redirect_never_reaches_destination_with_credentials(self):
+ for code in (301, 302, 303, 307, 308):
+ with self.subTest(code=code), self.assertRaises(ValueError):
+ PolishClient().polish(f"redirect-{code}", **self.args)
+ self.assertFalse(any(path == "/target" for path, _ in self.requests))
+
+ def test_https_verifies_certificate_and_cancels_body_read(self):
+ if not shutil.which("openssl"):
+ self.skipTest("openssl is required for the isolated TLS fixture")
+ with tempfile.TemporaryDirectory() as directory:
+ cert, key = Path(directory) / "cert.pem", Path(directory) / "key.pem"
+ subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes",
+ "-keyout", str(key), "-out", str(cert), "-days", "1", "-subj", "/CN=localhost",
+ "-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1"],
+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, check=True, timeout=10)
+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+ context.load_cert_chain(cert, key)
+ server = ThreadingHTTPServer(("127.0.0.1", 0), self.server.RequestHandlerClass)
+ server.socket = context.wrap_socket(server.socket, server_side=True)
+ thread = Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ args = dict(self.args, base_url=f"https://127.0.0.1:{server.server_port}")
+ try:
+ with self.assertRaises(ValueError):
+ PolishClient().polish("untrusted", **args, timeout=1)
+ with patch.dict(os.environ, {"SSL_CERT_FILE": str(cert)}):
+ self.assertEqual(PolishClient().polish("trusted", **args, timeout=1), "complete")
+ started = time.monotonic()
+ with self.assertRaises(ValueError):
+ PolishClient().polish("heartbeat", **args, timeout=0.2, on_progress=lambda _: None)
+ self.assertLess(time.monotonic() - started, 1.5)
+ finally:
+ self.stopped.set()
+ server.shutdown(); server.server_close(); thread.join(timeout=2)
+
+ def test_deadline_interrupts_heartbeat_and_header_reads(self):
+ for text in ("heartbeat", "headers"):
+ with self.subTest(text=text):
+ started = time.monotonic()
+ with self.assertRaises(ValueError):
+ PolishClient().polish(text, **self.args, timeout=0.2, on_progress=lambda _: None)
+ self.assertLess(time.monotonic() - started, 1.5)
+
+ def test_proxy_connect_is_covered_by_the_request_deadline(self):
+ args = dict(self.args, base_url="https://synthetic.invalid")
+ # Per-request fixture only; do not change this Mac's proxy settings.
+ with patch.object(request, "getproxies", return_value={"https": self.endpoint}), \
+ patch.object(request, "proxy_bypass", return_value=False):
+ started = time.monotonic()
+ with self.assertRaises(ValueError):
+ PolishClient().polish("synthetic", **args, timeout=0.15)
+ self.assertTrue(self.streaming.is_set())
+ self.assertLess(time.monotonic() - started, 0.7)
+
+ def test_explicit_cancel_interrupts_tls_handshake(self):
+ accepted = Event()
+ stopped = Event()
+
+ class Handler(BaseRequestHandler):
+ def handle(self):
+ self.request.settimeout(2)
+ self.request.recv(4096) # TLS ClientHello: handshake is in flight.
+ accepted.set()
+ stopped.wait(3)
+
+ server = ThreadingTCPServer(("127.0.0.1", 0), Handler)
+ thread = Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ args = dict(self.args, base_url=f"https://127.0.0.1:{server.server_address[1]}")
+ try:
+ with ThreadPoolExecutor(max_workers=1) as worker:
+ token = RequestCancellation()
+ future = worker.submit(PolishClient().polish, "synthetic", **args,
+ timeout=2, cancellation=token)
+ self.assertTrue(accepted.wait(1))
+ token.set()
+ with self.assertRaises(ValueError):
+ future.result(timeout=1)
+ finally:
+ stopped.set()
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=2)
+
+ def test_explicit_cancel_releases_worker_and_next_request_succeeds(self):
+ token = RequestCancellation()
+ with ThreadPoolExecutor(max_workers=1) as worker:
+ future = worker.submit(PolishClient().polish, "heartbeat", **self.args,
+ timeout=2, cancellation=token, on_progress=lambda _: None)
+ self.assertTrue(self.streaming.wait(1))
+ token.set()
+ with self.assertRaises(ValueError):
+ future.result(timeout=1)
+ next_request = worker.submit(PolishClient().polish, "next", **self.args, timeout=1)
+ self.assertEqual(next_request.result(timeout=2), "complete")
+
+ def test_manager_timeout_does_not_starve_next_final_request(self):
+ callbacks = queue.Queue()
+ manager = PolishManager(callbacks.put)
+ self.addCleanup(manager.close)
+ results = []
+ settings = Settings(polish_base_url=self.endpoint)
+ def drain_until_result():
+ deadline = time.monotonic() + 7
+ while not results and time.monotonic() < deadline:
+ try:
+ callbacks.get(timeout=0.1)()
+ except queue.Empty:
+ pass
+ self.assertTrue(results)
+ with patch("doubao_input.polish.polish_prompt_for_text", return_value="synthetic"):
+ manager.start("heartbeat", settings, "synthetic-key", lambda *args: results.append(args), progress=lambda _: None)
+ self.assertTrue(self.streaming.wait(1))
+ blocked = manager._future
+ drain_until_result()
+ self.assertIsNone(results.pop()[0])
+ with self.assertRaises(ValueError):
+ blocked.result(timeout=1)
+ manager.start("next", settings, "synthetic-key", lambda *args: results.append(args), progress=lambda _: None)
+ drain_until_result()
+ self.assertEqual(results, [("complete", "")])
diff --git a/tests/unit/test_product.py b/tests/unit/test_product.py
index 4027f69..306c1ea 100644
--- a/tests/unit/test_product.py
+++ b/tests/unit/test_product.py
@@ -51,7 +51,7 @@ class ProductTest(TestCase):
self.assertNotIn("private-device-identifier", data)
self.assertNotIn("cookies", data)
self.assertNotIn("transcript", data)
- self.assertEqual(json.loads(data)["product_version"], "1.6.0")
+ self.assertEqual(json.loads(data)["product_version"], "1.7.0")
self.assertEqual(json.loads(data)["recognition_provider"], "volcengine")
self.assertEqual(json.loads(data)["recent_stages"], [
{"stage": "first_result", "after_ms": 125}])
diff --git a/tests/unit/test_setup_actions.py b/tests/unit/test_setup_actions.py
index 87a618f..f5a25a1 100644
--- a/tests/unit/test_setup_actions.py
+++ b/tests/unit/test_setup_actions.py
@@ -119,7 +119,10 @@ class SetupActionsTest(unittest.TestCase):
def test_recognition_service_selection_applies_immediately(self):
control = SimpleNamespace(
_changing_asr_provider=False,
+ _asr_testing=False,
+ _flush_asr_key=Mock(return_value=True),
_asr_provider=Mock(),
+ _asr_status=Mock(),
_actions=Mock(),
set_feedback=Mock(),
_refresh=Mock(),
@@ -133,6 +136,8 @@ class SetupActionsTest(unittest.TestCase):
def test_rejected_recognition_service_selection_restores_saved_value(self):
control = SimpleNamespace(
_changing_asr_provider=False,
+ _asr_testing=False,
+ _flush_asr_key=Mock(return_value=True),
_asr_provider=Mock(),
_actions=Mock(),
set_feedback=Mock(),
@@ -147,6 +152,7 @@ class SetupActionsTest(unittest.TestCase):
def test_onboarding_official_key_test_saves_first_and_shows_result(self):
control = SimpleNamespace(
_asr_testing=False,
+ _asr_provider=Mock(),
_asr_key_save_source=0,
_asr_key=Mock(),
_asr_status=Mock(),
@@ -230,6 +236,7 @@ class SetupActionsTest(unittest.TestCase):
def test_official_key_test_saves_first_and_has_adjacent_feedback(self):
view = SimpleNamespace(
_asr_testing=False,
+ asr_provider=Mock(),
_asr_has_key=False,
_save_asr=Mock(),
_test_asr=Mock(),
@@ -249,4 +256,5 @@ class SetupActionsTest(unittest.TestCase):
completed = view._test_asr.call_args.args[1]
completed("API key accepted", "")
self.assertFalse(view._asr_testing)
+ view.asr_provider.set_sensitive.assert_called_with(True)
self.assertEqual(view.asr_status.set_text.call_args.args[0], "API key accepted")
diff --git a/tests/unit/test_speech_workbench.py b/tests/unit/test_speech_workbench.py
new file mode 100644
index 0000000..d34a273
--- /dev/null
+++ b/tests/unit/test_speech_workbench.py
@@ -0,0 +1,99 @@
+import tempfile
+from pathlib import Path
+import threading
+import unittest
+from doubao_input.input_latency import InputLatency
+from doubao_input.personal import PersonalStore
+from doubao_input.personal_corrections import confirmation
+from doubao_input.speech_workbench import SpeechWorkbench
+
+
+class SpeechWorkbenchTests(unittest.TestCase):
+ def test_drafts_persist_but_cannot_spend_api_calls(self):
+ with tempfile.TemporaryDirectory() as temp:
+ model = SpeechWorkbench(temp); row = model.add()
+ self.assertEqual(SpeechWorkbench(temp).samples, [row])
+ called = []
+ with self.assertRaises(ValueError):
+ model.compare(None, [], recognizer=lambda *_a, **_k: called.append(1))
+ self.assertEqual(called, [])
+
+ def test_same_audio_and_reference_isolation_with_negative_case(self):
+ with tempfile.TemporaryDirectory() as temp:
+ model = SpeechWorkbench(temp); row = model.add()
+ row.update(reference='Use Midjourney for art', protected_terms=['Midjourney'])
+ model.record(row, b'\x00\x00' * 160)
+ calls = []
+ def recognize(pcm, key, words, **kwargs):
+ calls.append((pcm, key, words))
+ return {'text': 'Use Midjourney for art' if not words else 'Use Midscene for art', 'latency_ms': 123}
+ results = model.compare('fake', ['Midscene'], recognizer=recognize)
+ self.assertEqual(calls[0][0], calls[1][0])
+ self.assertEqual([c[2] for c in calls], [[], ['Midscene']])
+ report = model.report(results)['modes']
+ self.assertEqual(report['raw']['protected_term_loss_rate'], 0)
+ self.assertEqual(report['hotwords']['protected_term_loss_rate'], 1)
+ self.assertEqual(Path(row['audio']).stat().st_mode & 0o777, 0o600)
+ self.assertEqual(SpeechWorkbench(temp).validated()[0]['reference'], row['reference'])
+
+ def test_cancellation_preserves_completed_results_and_prevents_next_upload(self):
+ with tempfile.TemporaryDirectory() as temp:
+ model = SpeechWorkbench(temp); row = model.add(); row['reference'] = 'Hello'
+ model.record(row, b'\x00\x00' * 16)
+ calls = []
+ def progress(_id, mode):
+ if mode == 'hotwords':
+ model.cancelled.set()
+ def recognize(*_args, cancel, **_kw):
+ calls.append(1)
+ return {'text': 'Hello', 'latency_ms': 1}
+ results = model.compare(None, [], progress=progress, recognizer=recognize)
+ self.assertEqual(len(results), 1)
+ self.assertEqual(len(calls), 1)
+
+ def test_cancel_after_asr_does_not_start_polishing(self):
+ with tempfile.TemporaryDirectory() as temp:
+ model = SpeechWorkbench(temp); row = model.add(); row['reference'] = 'Hello'
+ model.record(row, b'\x00\x00' * 16)
+ calls, polish_calls = [], []
+ def recognize(*_args, **_kwargs):
+ calls.append(1)
+ if len(calls) == 2:
+ model.cancelled.set()
+ return {'text': 'Hello', 'latency_ms': 1}
+ model.compare(None, [], recognizer=recognize, polisher=lambda text: polish_calls.append(text))
+ self.assertEqual(polish_calls, [])
+
+ def test_selected_second_occurrence_and_unicode(self):
+ text = '用 Midjourney 画图,用 Midjourney 写测试'
+ start = text.rindex('Midjourney')
+ result = confirmation(text, text, 'Midjourney', 'Midscene', (start, start + 10))
+ self.assertEqual(result[2], '用 Midjourney 画图,用 Midscene 写测试')
+ with self.assertRaises(ValueError):
+ confirmation(text, text, 'Midjourney', 'Midscene', (0, 3))
+
+ def test_latency_excludes_recording_and_preserves_old_history(self):
+ clock = [100.0]
+ timing = InputLatency(lambda: clock[0]); timing.mark('asr'); self.assertEqual(timing.values, {})
+ clock[0] = 130; timing.stop(); clock[0] = 130.25; timing.mark('asr')
+ clock[0] = 131; timing.mark('polish'); clock[0] = 131.1; timing.mark('delivery')
+ self.assertEqual(timing.values, {'asr': 250, 'polish': 750, 'delivery': 100, 'total': 1100})
+ with tempfile.TemporaryDirectory() as temp:
+ store = PersonalStore(Path(temp) / 'personal.sqlite3')
+ old = store.record('Old', 'Old'); self.assertEqual(store.timings(old), {})
+ store.save_timings(old, timing.values); self.assertEqual(store.timings(old), timing.values)
+ store.clear_history(); self.assertEqual(store.timings(old), {})
+ store.save_timings(old, timing.values); self.assertEqual(store.timings(old), {})
+
+ def test_recognizer_cancel_disconnects_without_waiting_full_timeout(self):
+ from doubao_input.speech_eval import recognize
+ cancel = threading.Event(); cancel.set()
+ class Client:
+ disconnected = False
+ def __init__(self, **_): pass
+ def prepare(self): pass
+ def connect(self, _): pass
+ def disconnect(self): self.disconnected = True
+ client = Client()
+ result = recognize(b'00', None, [], cancel=cancel, client_factory=lambda **_: client)
+ self.assertTrue(client.disconnected); self.assertIn('error', result)
diff --git a/tests/unit/test_transcription_sessions.py b/tests/unit/test_transcription_sessions.py
index 69f3dbd..c69ce92 100644
--- a/tests/unit/test_transcription_sessions.py
+++ b/tests/unit/test_transcription_sessions.py
@@ -143,7 +143,10 @@ class TranscriptionSessionTest(TestCase):
self.assertTrue(manager.app_state.error_message)
def test_audio_disconnect_resets_recording_and_releases_settings(self):
+ from doubao_input.diagnostics import DiagnosticTrace
manager = self.manager()
+ trace = DiagnosticTrace()
+ manager.on_diagnostic = trace.add
manager.app_state.recording_state = RecordingState.RECORDING
manager._priming = False
manager._audio_generation = 7
@@ -156,6 +159,18 @@ class TranscriptionSessionTest(TestCase):
manager.audio_capture.stop.assert_called_once()
self.assertEqual(manager.app_state.recording_state, RecordingState.IDLE)
self.assertIn("Microphone disconnected", manager.app_state.error_message)
+ self.assertIn("audio_failed", [event["stage"] for event in trace.snapshot()])
+
+ def test_broken_diagnostics_cannot_prevent_audio_failure_cleanup(self):
+ manager = self.manager()
+ manager.app_state.recording_state = RecordingState.RECORDING
+ manager.app_state.transcription_text = "synthetic partial"
+ manager.on_recover = Mock()
+ manager.on_diagnostic = Mock(side_effect=ValueError("synthetic failure"))
+ manager._deliver_audio_error(manager._audio_generation, RuntimeError("device removed"))
+ manager.on_recover.assert_called_once_with("synthetic partial")
+ manager.audio_capture.stop.assert_called_once()
+ self.assertEqual(manager.app_state.recording_state, RecordingState.IDLE)
def test_stale_audio_disconnect_cannot_reset_next_recording(self):
manager = self.manager()