Skip to content

Doubao-powered voice input for Linux, Wayland and Omarchy

fix(macOS): stabilize dictation delivery and microphone switching

quanru7c761fe34d0f
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index f206cb8..0ec37ca 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -64,6 +64,11 @@ relevant scenario when fixing a covered user-visible flow.
## Review and release
+Use English for all GitHub-facing content in this repository: issue and pull
+request titles, descriptions and comments, commit messages, release titles and
+release notes. Keep explicitly localized UI strings and documentation in their
+specified languages. Conversation with the maintainer may remain in Chinese.
+
Use small conventional commits (`fix(login): ...`, `test(packaging): ...`). Explain
the user-visible problem, approach, tests and remaining limitations in a PR.
Run `make check` and the relevant manual acceptance before proposing a release.
diff --git a/README.md b/README.md
index f46f221..64e8642 100644
--- a/README.md
+++ b/README.md
@@ -211,7 +211,8 @@ Modifier keys are logical choices: either the left or right physical key works.
Your keyboard must report Fn as a Linux key; otherwise choose another key.
- Tap to start; tap again to finish and paste.
-- With Fn as the trigger, pressing another key while recording also finishes and pastes. Escape still cancels; the finishing key still reaches the foreground app.
+- On Linux, with Fn as the trigger, pressing another key while recording also finishes and pastes. Escape still cancels; the finishing key still reaches the foreground app.
+- On macOS, any key during voice input finishes dictation without performing its original action, including Escape, Enter and shortcut chords. Their releases are swallowed as well. Double-tap sends Enter only while idle.
- Hold past the threshold to speak; release to finish and paste.
- Select one preset, or choose **Record a shortcut…** to capture a custom combination such as Ctrl+Alt+Space. Only one trigger is active.
- Press the active trigger twice to send Enter without dictation. This can submit messages or execute terminal commands.
diff --git a/macos/ACCEPTANCE.zh-CN.md b/macos/ACCEPTANCE.zh-CN.md
index a48305f..19236ec 100644
--- a/macos/ACCEPTANCE.zh-CN.md
+++ b/macos/ACCEPTANCE.zh-CN.md
@@ -48,7 +48,10 @@
- [ ] 火山、Deepgram 的真实凭证测试及录音试说。
- [ ] 首次使用准备、完成设置后的重启、旧设置迁移。
- [ ] 自定义组合、单修饰键、双击回车、Fn 下其他按键结束,以及预录音取消。
-- [ ] 麦克风切换、断开与重连;本地检查不发送音频,试说不输入文字。
+- [ ] 选择“系统默认”,录音超过两秒后切换系统输入设备,继续收到新麦克风音频。
+- [ ] 指定 USB / 蓝牙麦克风,录音中拔出或断开后自动回退,保留本次识别会话;重新接入后恢复指定设备。
+- [ ] 所选设备不在场时仍可开始录音;设置页显示回退设备。完全没有输入时有界重试后提示错误。
+- [ ] 重连等待期间结束录音,不再自动开启麦克风。本地检查不发送音频,试说不输入文字。
- [ ] 辅助功能直接输入、目标变化时拒绝输入、输入后回车及编辑后的三秒重试。
- [ ] Vibekey AU05 的认证、热插拔、六种动作与自定义映射。
- [ ] 签名安装后的登录项注册、系统审批状态及退出登录后重启。
diff --git a/macos/Package.swift b/macos/Package.swift
index a336fde..28d4320 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", "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"]),
+ .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", "InputTargetCapture.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 1fd66a5..ca6e256 100644
--- a/macos/README.zh-CN.md
+++ b/macos/README.zh-CN.md
@@ -19,9 +19,9 @@ open 'build/macos/arm64/Doubao Say.app'
2. “使用准备”顶部四个步骤均可点击切换;检查或录音进行时暂时禁用切换,完成设置仍需通过全部检查。设置会自动保存,无需点击保存按钮。允许麦克风访问,并从“启用全局快捷键”授予辅助功能权限。系统要求本人输入密码时在系统弹窗完成,不向应用填写系统密码。
3. 在“使用准备”中选择麦克风,先进行三秒本地检查,再进行五秒语音测试。语音测试会向已保存的识别服务发送音频,结果只显示在软件内,不粘贴,也不发送回车。全部检查完成后点击“完成设置”,后续打开应用仍显示设置窗。
4. 在目标应用的普通文本输入框中放好光标。默认 `Control+Option+空格`,可在“快捷键”中录制其他组合或单独修饰键;选键不使用麦克风。
-5. 短按切换录音;按住达到默认 350 毫秒后说话,松开结束。开启“双击发送回车”时,短按需等待默认 300 毫秒确认,双击结束录音并在输入后发送回车,空闲时双击发送回车。可调整两项阈值或关闭双击。Fn 作为触发键时,其他按键也可结束当前录音。`Esc` 取消,单次最多 60 秒。
+5. 短按切换录音;按住达到默认 350 毫秒后说话,松开结束。开始录音时可用默认 300 毫秒的双击识别阈值,可调整两项阈值或关闭双击。语音输入期间,其他按键(包括 `Esc`、回车、修饰键和快捷键组合)统一结束录音并上屏,不执行原有按键操作,也不额外发送回车。整个组合及其松开事件会被拦截,完成输入后恢复正常键盘操作。VibeKey 的按钮和旋钮也使用同一规则。非语音输入状态下,`Esc` 可关闭保留文字的浮窗,空闲时双击仍可发送回车。单次录音最多 60 秒。
-麦克风列表会随设备插拔自动刷新,无需重新打开设置。也可从菜单栏“输入设备”直接选择麦克风或系统默认,切换后自动保存;录音、测试或输入处理中暂时禁用切换。选择“系统默认”时跟随系统输入设备;指定设备拔出后保留选择并提示不可用,重新接入后恢复显示。输入设备变化后需重新完成麦克风和语音检查。
+麦克风列表会随设备插拔自动刷新,无需重新打开设置。也可从菜单栏“输入设备”直接选择麦克风或系统默认,切换后自动保存;录音、测试或输入处理中暂时禁用切换。选择“系统默认”时持续跟随系统输入设备;指定设备拔出后保留偏好,自动回退到系统默认或其他可用麦克风,重新接入后恢复使用。设置页显示实际可用的输入设备。录音中设备变化会重新连接音频流,保留当前识别会话;若短暂重试后仍无可用输入,才停止并提示错误。输入设备变化后需重新完成麦克风和语音检查。
按下触发键后,先在内存保存最多三秒本地预录音,确认单击或长按后再发送到识别服务。双击或取消会丢弃尚未确认的音频。设置修改后自动保存,录音和检查期间暂缓生效,结束后自动应用;已有网页登录、语言和自动粘贴选择保留。
@@ -35,16 +35,18 @@ open 'build/macos/arm64/Doubao Say.app'
转写稳定、低于语音阈值并静音 1.2 秒后启动预润色。音量变化只暂停计时,文字变化才使旧请求失效,避免背景噪声反复发请求。结束录音后可复用同一段文字的预润色结果或仍在运行的请求;不同文字重新请求,旧返回不能上屏。
-每次润色最多五秒,包含网络等待。失败、超时、空返回、截断或无效流式响应均使用 ASR 原文,部分润色结果不自动上屏。最终润色期间再次按听写快捷键可直接使用原文;`Esc` 取消整个输入。浮窗显示润色状态和流式预览,保持输入框焦点。
+每次润色最多五秒,包含网络等待。失败、超时、空返回、截断或无效流式响应均使用 ASR 原文,部分润色结果不自动上屏。最终润色期间,任意按键都会直接使用原文并上屏,按键本身被拦截;如需取消整个输入,可从菜单选择「取消输入」。浮窗显示润色状态和流式预览,保持输入框焦点。
## 文字恢复与隐私
-“最近文字”只保留一条内存文字,可编辑、复制、清除,或点击“三秒后重试”并切换到目标输入框。倒计时和输入完成前不能重复重试,也不响应新的听写或独立回车;可按 `Esc` 或从菜单选择“取消输入”。重试不发送回车。关闭“自动粘贴”后每次手动复制。识别或音频中断时保留部分文字,不自动输入。
+“最近文字”只保留一条内存文字,可编辑、复制、清除,或点击“三秒后重试”并切换到目标输入框。倒计时和输入完成前不能重复重试,也不响应新的听写或独立回车;重试倒计时可按 `Esc` 取消,输入操作可从菜单选择“取消输入”。重试不发送回车。关闭“自动粘贴”后每次手动复制。识别或音频中断时保留部分文字,不自动输入。
-输入前核对前台进程和原辅助功能输入元素,并等待快捷键修饰键松开。密码框不自动输入。输入目标变化或直接输入不可用时,文字保留在软件内。剪贴板在粘贴后延迟恢复,期间有新复制内容时不恢复;部分应用异步读取剪贴板可能晚于恢复时间。输入和回车前分别检查目标,但系统事件仍存在短暂竞争窗口,需要完全手动控制时关闭自动粘贴。
+输入前核对前台进程和原辅助功能输入元素,并等待快捷键修饰键松开。模拟快捷键在松开时释放修饰键标记,避免粘贴后系统继续报告 Command 被按住。密码框不自动输入。输入目标变化或直接输入不可用时,文字保留在软件内。剪贴板方式会用识别结果替换剪贴板内容,并在发送粘贴后保留这段文字,避免目标应用延迟读取时拿到旧内容;也可手动再次粘贴。粘贴发出前中止时,仅在剪贴板尚未被其他操作改写的情况下恢复原内容。输入和回车前分别检查目标,但系统事件仍存在短暂竞争窗口,需要完全手动控制时关闭自动粘贴。
新配置默认使用“自动选择”:根据目标输入框的能力选择方式,支持辅助功能文字插入时直接写入,否则使用剪贴板;不按应用名称区别处理。已有配置保留原来的选择,手动选择剪贴板或直接输入时严格使用该方式。直接写入失败后保留文字,不自动再次粘贴,以免重复输入。输入前等待录音快捷键释放(包括 Fn),并检查目标输入框是否仍一致。输入失败时浮窗保留文字和具体原因,可从菜单选择“三秒后重试输入”;成功后清除失败提示。
+刚切换应用时,若系统暂时无法提供输入框焦点,或只返回窗口本身,但已能确定前台应用和窗口,会在 500 毫秒内每隔 50 毫秒重新读取焦点。期间切换应用、窗口或取消录音会终止恢复;已取得的输入框不会被替换。明确聚焦在非输入控件上或无法确定原窗口时不重试。“复制诊断信息”会记录焦点是否恢复、超时或发生变化,不包含输入文字。
+
普通听写的音频发送到所选识别服务,不保存本地录音文件。“语音评测”中主动录制的样本会保存到本机,直到手动删除;点击“开始对比”后才上传样本。润色启用后,整段文字及停顿预览会发送到配置的接口;识别和模型用量由相应服务商向你的账号计费。会话和 API Key 分别保存在应用专属 macOS 钥匙串条目,登录 WebView 使用临时网站数据存储。偏好不包含凭证;可编辑的单条最近文字退出后消失,但完成的听写另存本机 30 天历史,可暂停或清空。诊断复制不包含转写、Cookie、账号或设备标识。
更新检查查询项目 GitHub 最新稳定发行版,间隔 24 小时,也可手动检查。有新版时,左侧“软件更新”旁显示红点;确认已是最新版后红点消失。在“设置 → 更新”中点击下载并安装后,应用会下载适配当前架构的 Mac 更新包,核对哈希、开发者签名、公证和应用标识,再安装并重启。下载期间可以取消;检查更新本身不会静默安装。没有合格的 Mac 更新包时,可打开发行页查看,不会把 Linux 归档当成 Mac 安装包。
@@ -81,3 +83,5 @@ open 'build/macos/arm64/Doubao Say.app'
「输入历史」记录本应用的识别原文、最终文字、润色和输入状态。数据仅存本机,超过 30 天自动清理,不记录音频、试说测试或其他应用的键盘输入。可以暂停记录、查看原文、放回最近文字编辑,以及清空历史。
「本地词频」统计已发送的润色结果。「AI 整理高频词」仅发送候选词与次数到现有润色服务,最长等待 25 秒,不上传完整历史。AI 返回的新造词会被拒绝;选择候选后点击「添加所选词汇」才会修改词库。普通听写润色仍保持五秒截止。
+
+麦克风热切换本地验证:在已授权麦克风访问的终端中,先运行 `bash macos/Tests/Settings/check.sh`,再运行 `build/macos/tests/microphone-route-check`。该检查使用真实音频引擎,只统计 PCM 字节数;通过注入设备列表和默认设备变化覆盖回退、重连、短暂断开与停止后不重启,不修改系统默认设备,不保存或发送音频。此测试不能代替 USB / 蓝牙设备的实际拔插验收。
diff --git a/macos/Sources/AppState.swift b/macos/Sources/AppState.swift
index 83465d9..0d1844e 100644
--- a/macos/Sources/AppState.swift
+++ b/macos/Sources/AppState.swift
@@ -21,6 +21,7 @@ class AppState: ObservableObject {
@Published var evaluationBusy = false
@Published var inputPending = false
+ @Published var inputDiagnostic = "No input attempt"
@Published var updateVersion = ""
@Published var updateStatus = ""
@Published var updateBusy = false
diff --git a/macos/Sources/AudioCaptureManager.swift b/macos/Sources/AudioCaptureManager.swift
index 0c82874..d4fdaed 100644
--- a/macos/Sources/AudioCaptureManager.swift
+++ b/macos/Sources/AudioCaptureManager.swift
@@ -10,9 +10,19 @@ class AudioCaptureManager {
private var callback: ((Data) -> Void)?
private var isCapturing = false
private var captureGeneration = UUID()
- private var startedAt: TimeInterval = 0
- private var startupRecoveryAvailable = true
+ private var preferredDeviceID = ""
+ private(set) var activeDevice: AudioInputDevice?
+ private var deviceMonitor: AudioDeviceMonitor?
+ private var recoveryWork: DispatchWorkItem?
+ private var recoveryAttempts = 0
private var configurationObserver: NSObjectProtocol?
+ private let inputDevices: () -> [AudioInputDevice]
+ private let defaultInputUID: () -> String?
+ init(inputDevices: @escaping () -> [AudioInputDevice] = AudioDevices.inputs,
+ defaultInputUID: @escaping () -> String? = AudioDevices.defaultInputUID) {
+ self.inputDevices = inputDevices
+ self.defaultInputUID = defaultInputUID
+ }
var onError: (() -> Void)?
private var rmsCallback: ((Double) -> Void)?
var onRMS: ((Double) -> Void)? {
@@ -27,25 +37,35 @@ class AudioCaptureManager {
}
func startCapture(deviceID: String = "") throws {
- try beginCapture(deviceID: deviceID, allowStartupRecovery: true)
- }
- private func beginCapture(deviceID: String, allowStartupRecovery: Bool) throws {
guard !isCapturing else { return }
+ preferredDeviceID = deviceID
+ recoveryAttempts = 0
+ try beginCapture()
+ isCapturing = true
+ deviceMonitor = AudioDeviceMonitor { [weak self] in self?.hardwareChanged() }
+ }
+
+ private func resolvedDevice() -> AudioInputDevice? {
+ AudioDevices.resolve(preferred: preferredDeviceID, inputs: inputDevices(),
+ defaultUID: defaultInputUID())
+ }
+
+ private func beginCapture() throws {
+ guard let device = resolvedDevice() else {
+ throw NSError(domain: "AudioCapture", code: -3,
+ userInfo: [NSLocalizedDescriptionKey: "No audio input available"])
+ }
let token = UUID()
lock.lock(); captureGeneration = token; lock.unlock()
- startupRecoveryAvailable = allowStartupRecovery
- startedAt = ProcessInfo.processInfo.systemUptime
-
let engine = AVAudioEngine()
let inputNode = engine.inputNode
- if !deviceID.isEmpty {
- guard let device = AudioDevices.inputs().first(where: { $0.id == deviceID }), let unit = inputNode.audioUnit else {
- throw NSError(domain: "AudioCapture", code: -3)
- }
- var id = device.audioID
- guard AudioUnitSetProperty(unit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &id, UInt32(MemoryLayout.size(ofValue: id))) == noErr else {
- throw NSError(domain: "AudioCapture", code: -4)
- }
+ // Explicitly resolve even System default: a running engine does not reliably
+ // rebind when the default changes to a device with the same audio format.
+ guard let unit = inputNode.audioUnit else { throw NSError(domain: "AudioCapture", code: -4) }
+ var id = device.audioID
+ guard AudioUnitSetProperty(unit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0,
+ &id, UInt32(MemoryLayout.size(ofValue: id))) == noErr else {
+ throw NSError(domain: "AudioCapture", code: -4)
}
let inputFormat = inputNode.outputFormat(forBus: 0)
@@ -66,9 +86,17 @@ class AudioCaptureManager {
throw NSError(domain: "AudioCapture", code: -2,
userInfo: [NSLocalizedDescriptionKey: "Cannot create audio format converter"])
}
+ var reportedInput = false
inputNode.installTap(onBus: 0, bufferSize: 4096, format: inputFormat) {
[weak self] buffer, _ in
guard let self = self, self.isCurrent(token) else { return }
+ if !reportedInput && buffer.frameLength > 0 {
+ reportedInput = true
+ DispatchQueue.main.async { [weak self] in
+ guard let self, self.isCapturing, self.isCurrent(token) else { return }
+ self.recoveryAttempts = 0
+ }
+ }
self.processAudioBuffer(buffer, converter: conv, token: token, onAudioData: self.onAudioData)
}
@@ -80,35 +108,63 @@ class AudioCaptureManager {
}
self.audioEngine = engine
- self.isCapturing = true
+ self.activeDevice = device
configurationObserver = NotificationCenter.default.addObserver(forName: .AVAudioEngineConfigurationChange, object: engine, queue: nil) { [weak self, weak engine] _ in
// Never tear down an engine on the notification's internal audio queue.
DispatchQueue.main.async {
- guard let self = self, let engine = engine, self.isCurrent(token), self.isCapturing else { return }
+ guard let self, let engine, self.isCurrent(token), self.isCapturing else { return }
let format = engine.inputNode.outputFormat(forBus: 0)
- let deviceAvailable = deviceID.isEmpty || AudioDevices.inputs().contains { $0.id == deviceID }
- let formatMatches = format.sampleRate == inputFormat.sampleRate && format.channelCount == inputFormat.channelCount
- if deviceAvailable && engine.isRunning && formatMatches { return }
- if deviceAvailable && self.startupRecoveryAvailable && ProcessInfo.processInfo.systemUptime - self.startedAt <= 2 {
- self.stopCapture()
- do { try self.beginCapture(deviceID: deviceID, allowStartupRecovery: false) }
- catch { self.onError?() }
- } else { self.onError?() }
+ if self.resolvedDevice() == self.activeDevice && engine.isRunning &&
+ format.sampleRate == inputFormat.sampleRate && format.channelCount == inputFormat.channelCount { return }
+ self.scheduleRecovery()
}
}
}
+
+ func hardwareChanged() {
+ guard isCapturing, resolvedDevice() != activeDevice || audioEngine?.isRunning != true else { return }
+ scheduleRecovery()
+ }
+
+ private func scheduleRecovery() {
+ guard isCapturing, recoveryWork == nil else { return }
+ // Coalesce CoreAudio's device/default/configuration notifications. Retain the
+ // callbacks and ASR session while replacing only the microphone stream.
+ if recoveryAttempts >= 4 {
+ stopCapture()
+ onError?()
+ return
+ }
+ stopEngine()
+ let token = captureGeneration
+ let work = DispatchWorkItem { [weak self] in
+ guard let self, self.isCapturing, self.isCurrent(token) else { return }
+ self.recoveryWork = nil
+ self.recoveryAttempts += 1
+ do { try self.beginCapture() }
+ catch { self.scheduleRecovery() }
+ }
+ recoveryWork = work
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: work)
+ }
private func isCurrent(_ token: UUID) -> Bool {
lock.lock(); defer { lock.unlock() }; return captureGeneration == token
}
func stopCapture() {
+ isCapturing = false
+ recoveryWork?.cancel(); recoveryWork = nil
+ deviceMonitor = nil
+ stopEngine()
+ }
+
+ private func stopEngine() {
lock.lock(); captureGeneration = UUID(); lock.unlock()
- guard isCapturing else { return }
if let observer = configurationObserver { NotificationCenter.default.removeObserver(observer); configurationObserver = nil }
audioEngine?.inputNode.removeTap(onBus: 0)
audioEngine?.stop()
audioEngine = nil
- isCapturing = false
+ activeDevice = nil
}
// MARK: - Audio Processing
diff --git a/macos/Sources/AudioDevices.swift b/macos/Sources/AudioDevices.swift
index 2881dd9..53d6b44 100644
--- a/macos/Sources/AudioDevices.swift
+++ b/macos/Sources/AudioDevices.swift
@@ -1,12 +1,18 @@
import Foundation
import CoreAudio
-struct AudioInputDevice: Identifiable {
+struct AudioInputDevice: Identifiable, Equatable {
let id: String
let name: String
let audioID: AudioDeviceID
}
enum AudioDevices {
+ /// Keep the user's preference, but never bind capture to a disconnected device.
+ static func resolve(preferred: String, inputs: [AudioInputDevice], defaultUID: String?) -> AudioInputDevice? {
+ inputs.first { $0.id == preferred }
+ ?? inputs.first { $0.id == defaultUID }
+ ?? inputs.first
+ }
static func defaultInputUID() -> String? {
var address = AudioObjectPropertyAddress(mSelector: kAudioHardwarePropertyDefaultInputDevice,
mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMain)
diff --git a/macos/Sources/DoubaoSayApp.swift b/macos/Sources/DoubaoSayApp.swift
index 0d1ecfc..3f0b29d 100644
--- a/macos/Sources/DoubaoSayApp.swift
+++ b/macos/Sources/DoubaoSayApp.swift
@@ -152,7 +152,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
if !devices.isEmpty { menu.addItem(.separator()) }
for device in devices { add(device.name, device.id) }
if !selected.isEmpty && !devices.contains(where: { $0.id == selected }) {
- add(L("Saved device unavailable", "已保存的设备不可用"), selected, available: false)
+ add(L("Saved device disconnected · automatic fallback", "所选设备已断开 · 自动回退"), selected, available: false)
}
return menu
}
@@ -279,6 +279,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
receiver.onAction = { [weak self] action, down in
guard let self = self else { return }
let settings = SettingsStore.shared.value
+ if down && (self.state.recordingState != .idle || self.state.inputPending) {
+ self.hotkey.stopFromAuxiliaryKey()
+ return
+ }
switch action {
case "record":
if let custom = settings.vibekeyRecord { if down { PasteHelper.sendShortcut(custom) } }
@@ -321,8 +325,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
alert.informativeText = L("""
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.
+ Your configured shortcut: tap to start, hold to talk; double-tap sends Enter while idle.
+ During voice input, any key stops and inputs text; the key itself is blocked, including Escape and Enter.
+ Outside voice input, Escape dismisses kept text or cancels retry. Maximum recording: 60 seconds.
If the input target changes, use Copy last result from this menu.
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.
@@ -331,8 +336,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
""", """
配置识别服务,并启用麦克风和全局快捷键权限。
录音前将光标放到输入框。
- 使用你配置的快捷键:短按切换录音,长按说话;双击发送回车。
- Esc 取消。单次最多录音 60 秒。
+ 使用你配置的快捷键:短按开始录音,长按说话;空闲时双击发送回车。
+ 语音输入期间,任意按键都结束并上屏,按键本身被拦截,包括 Esc 和回车。
+ 非语音输入状态下,Esc 可关闭保留文字或取消重试。单次最多录音 60 秒。
输入目标变化时,请从菜单复制最近结果。
普通听写音频发送至所选识别服务,不保存本地录音文件。
语音评测录音会保存在本机,直到手动删除;开始对比时才上传。
diff --git a/macos/Sources/HotkeyManager.swift b/macos/Sources/HotkeyManager.swift
index 6eb1705..024d1c9 100644
--- a/macos/Sources/HotkeyManager.swift
+++ b/macos/Sources/HotkeyManager.swift
@@ -11,6 +11,10 @@ final class HotkeyManager {
private var gestureTimer: Timer?
private var active = false
private var recording = false
+ private var interceptingInput = false
+ private var blockedKeys = Set<UInt16>()
+ private var blockedModifiers = Set<UInt16>()
+ private var withheldTriggerModifiers = Set<UInt16>()
private var shortcut = Shortcut()
private var gesture = ShortcutGesture()
private var shortcutDown = false
@@ -34,6 +38,14 @@ final class HotkeyManager {
private static func modifierBit(_ code: UInt16) -> Int {
[UInt16(59): 1, 58: 2, 55: 4, 56: 8, 63: 16][canonical(code)] ?? 0
}
+ private static func modifierPressed(_ code: UInt16, flags: CGEventFlags) -> Bool {
+ // IOLLEvent.h device masks distinguish releasing one side while the other is held.
+ let masks: [UInt16: (UInt64, UInt64)] = [59: (0x1, 0x2001), 62: (0x2000, 0x2001),
+ 56: (0x2, 0x6), 60: (0x4, 0x6), 55: (0x8, 0x18), 54: (0x10, 0x18),
+ 58: (0x20, 0x60), 61: (0x40, 0x60)]
+ if let (device, pair) = masks[code], flags.rawValue & pair != 0 { return flags.rawValue & device != 0 }
+ return modifiers(flags) & modifierBit(code) != 0
+ }
func configure(_ settings: MacSettings) {
resetGesture(); shortcut = settings.shortcut
gesture.holdSeconds = Double(settings.holdMilliseconds) / 1000
@@ -42,7 +54,8 @@ final class HotkeyManager {
}
func start() {
guard eventTap == nil else { return }
- let mask = (1 << CGEventType.keyDown.rawValue) | (1 << CGEventType.keyUp.rawValue) | (1 << CGEventType.flagsChanged.rawValue)
+ // Type 14 carries AppKit system-defined media-key events.
+ let mask = (1 << CGEventType.keyDown.rawValue) | (1 << CGEventType.keyUp.rawValue) | (1 << CGEventType.flagsChanged.rawValue) | (1 << 14)
guard let tap = CGEvent.tapCreate(tap: .cgSessionEventTap, place: .headInsertEventTap,
options: .defaultTap, eventsOfInterest: CGEventMask(mask), callback: { _, type, event, info in
guard let info = info else { return Unmanaged.passUnretained(event) }
@@ -69,6 +82,7 @@ final class HotkeyManager {
if let tap = eventTap { CGEvent.tapEnable(tap: tap, enable: false); CFMachPortInvalidate(tap) }
if let source = source { CFRunLoopRemoveSource(CFRunLoopGetMain(), source, .commonModes) }
eventTap = nil; source = nil; resetGesture()
+ blockedKeys.removeAll(); blockedModifiers.removeAll(); withheldTriggerModifiers.removeAll(); interceptingInput = false
}
func captureShortcut(_ completion: @escaping (Shortcut?) -> Void) {
guard available, !active else { completion(nil); return }
@@ -82,7 +96,15 @@ final class HotkeyManager {
let completion = capture; capture = nil
if let completion = completion { DispatchQueue.main.async { completion(value) } }
}
- func setEscapeHandlingEnabled(_ enabled: Bool, recording: Bool = false) { active = enabled; self.recording = recording }
+ func setEscapeHandlingEnabled(_ enabled: Bool, recording: Bool = false, interceptKeys: Bool? = nil) {
+ active = enabled; self.recording = recording
+ interceptingInput = interceptKeys ?? recording
+ // Keep swallowed keys until their releases, even after delivery finishes.
+ }
+ func stopFromAuxiliaryKey() {
+ gesture.reset(); shortcutDown = false
+ onHotkeyEvent?(.stop)
+ }
func auxiliaryRecord(_ pressed: Bool) {
let now = ProcessInfo.processInfo.systemUptime
emit(pressed ? gesture.down(at: now) : gesture.up(at: now))
@@ -104,6 +126,7 @@ final class HotkeyManager {
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) }
+ blockedKeys.removeAll(); blockedModifiers.removeAll(); withheldTriggerModifiers.removeAll()
resetGesture(); return Unmanaged.passUnretained(event)
}
let code = Self.canonical(UInt16(event.getIntegerValueField(.keyboardEventKeycode)))
@@ -120,13 +143,41 @@ final class HotkeyManager {
}
return Unmanaged.passUnretained(event)
}
+ let physicalCode = UInt16(event.getIntegerValueField(.keyboardEventKeycode))
+ let modifierPressed = type == .flagsChanged && Self.modifierPressed(physicalCode, flags: event.flags)
+ if type == .flagsChanged && !modifierPressed, withheldTriggerModifiers.remove(physicalCode) != nil {
+ if shortcutDown { shortcutDown = false; emit(gesture.up(at: ProcessInfo.processInfo.systemUptime)) }
+ return nil
+ }
+ if type == .keyUp, blockedKeys.remove(physicalCode) != nil { return nil }
+ if type == .flagsChanged && !modifierPressed, blockedModifiers.remove(physicalCode) != nil { return nil }
+ let draining = !blockedKeys.isEmpty || !blockedModifiers.isEmpty
+ if type.rawValue == 14, let media = NSEvent(cgEvent: event), media.subtype.rawValue == 8 {
+ let mediaCode = UInt16(0x8000 | ((media.data1 >> 16) & 0x7fff))
+ let keyState = (media.data1 >> 8) & 0xff
+ if keyState == 0x0b, blockedKeys.remove(mediaCode) != nil { return nil }
+ if keyState == 0x0a && (interceptingInput || draining) {
+ let firstPress = blockedKeys.insert(mediaCode).inserted
+ if interceptingInput && firstPress && !draining { stopFromAuxiliaryKey() }
+ return nil
+ }
+ return Unmanaged.passUnretained(event)
+ }
+ if (type == .keyDown || modifierPressed || (type == .flagsChanged && code == 57)) && (interceptingInput || draining) {
+ let firstPress: Bool
+ if modifierPressed { firstPress = blockedModifiers.insert(physicalCode).inserted }
+ else if type == .keyDown { firstPress = blockedKeys.insert(physicalCode).inserted }
+ else { firstPress = true }
+ if interceptingInput && firstPress && !draining { stopFromAuxiliaryKey() }
+ return nil
+ }
if code == 53 && type == .keyDown && (active || shortcutDown || gesture.isPending) { resetGesture(); onHotkeyEvent?(.cancel); return nil }
- if shortcut.keyCode == 63 && recording && type == .keyDown && code != 63 { onHotkeyEvent?(.stop); return Unmanaged.passUnretained(event) }
let now = ProcessInfo.processInfo.systemUptime
let modifierShortcut = Self.modifierBit(shortcut.keyCode)
let down = modifierShortcut != 0 ? (type == .flagsChanged && code == shortcut.keyCode && mods & modifierShortcut != 0) : type == .keyDown
if down && code == shortcut.keyCode && (mods & ~modifierShortcut) == shortcut.modifiers {
- shortcutDown = true; emit(gesture.down(at: now)); return modifierShortcut == 0 ? nil : Unmanaged.passUnretained(event)
+ if modifierShortcut != 0 { withheldTriggerModifiers.insert(physicalCode) }
+ shortcutDown = true; emit(gesture.down(at: now)); return nil
}
if shortcutDown && ((type == .keyUp && code == shortcut.keyCode) || (type == .flagsChanged && (mods & shortcut.modifiers != shortcut.modifiers || (modifierShortcut != 0 && mods & modifierShortcut == 0)))) {
shortcutDown = false; emit(gesture.up(at: now)); return type == .keyUp ? nil : Unmanaged.passUnretained(event)
diff --git a/macos/Sources/InputTargetCapture.swift b/macos/Sources/InputTargetCapture.swift
new file mode 100644
index 0000000..e533161
--- /dev/null
+++ b/macos/Sources/InputTargetCapture.swift
@@ -0,0 +1,59 @@
+import Foundation
+
+/// Recover only a temporarily unavailable AX focus, within the original window.
+@MainActor
+final class InputTargetCapture {
+ private let scope: () -> InputTarget.Scope?
+ private let focus: () -> InputTarget.Focus
+ private let now: () -> Date
+ private let retry: (@escaping () -> Void) -> Void
+ private var generation = UUID()
+ private(set) var diagnostic = "capture=not-started"
+ init(scope: @escaping () -> InputTarget.Scope? = InputTarget.scope,
+ focus: @escaping () -> InputTarget.Focus = InputTarget.readFocus,
+ now: @escaping () -> Date = Date.init,
+ retry: @escaping (@escaping () -> Void) -> Void = { action in
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { action() }
+ }) {
+ self.scope = scope; self.focus = focus; self.now = now; self.retry = retry
+ }
+ func cancel() { generation = UUID() }
+ func begin(completion: @escaping (InputTarget?) -> Void) {
+ cancel()
+ let token = generation
+ let original = scope()
+ let deadline = now().addingTimeInterval(0.5)
+ var retried = false
+ var waitedForWindow = false
+ diagnostic = "capture=waiting"
+ completion(nil)
+ func attempt() {
+ guard self.generation == token else { return }
+ if retried && self.now() >= deadline {
+ self.diagnostic = "capture=timed-out"; return
+ }
+ if let original, self.scope() != original {
+ self.diagnostic = "capture=scope-changed"; return
+ }
+ let result = self.focus()
+ // Focus reads can block while an app activates; check the window again.
+ if let original, self.scope() != original {
+ self.diagnostic = "capture=scope-changed"; return
+ }
+ switch result {
+ case .ready(let target):
+ self.diagnostic = waitedForWindow ? "capture=recovered-window" : (retried ? "capture=recovered" : "capture=ready")
+ completion(target)
+ case .notEditable:
+ self.diagnostic = "capture=not-editable"
+ case .window, .unavailable:
+ if case .window = result { waitedForWindow = true; self.diagnostic = "capture=waiting-window" }
+ guard original != nil else { self.diagnostic = "capture=scope-unavailable"; return }
+ guard self.now() < deadline else { self.diagnostic = "capture=timed-out"; return }
+ retried = true
+ self.retry { attempt() }
+ }
+ }
+ attempt()
+ }
+}
diff --git a/macos/Sources/PasteHelper.swift b/macos/Sources/PasteHelper.swift
index b34d6f4..bf54faf 100644
--- a/macos/Sources/PasteHelper.swift
+++ b/macos/Sources/PasteHelper.swift
@@ -5,21 +5,44 @@ import ApplicationServices
struct InputTarget {
let pid: pid_t
let element: AXUIElement
- static func capture() -> InputTarget? {
+ enum Focus { case ready(InputTarget), unavailable, window, notEditable }
+ struct Scope: Equatable {
+ let pid: pid_t
+ let window: AXUIElement
+ static func == (lhs: Scope, rhs: Scope) -> Bool {
+ lhs.pid == rhs.pid && CFEqual(lhs.window, rhs.window)
+ }
+ }
+ static func scope() -> Scope? {
guard AXIsProcessTrusted(), let app = NSWorkspace.shared.frontmostApplication,
app.processIdentifier != ProcessInfo.processInfo.processIdentifier else { return nil }
var value: CFTypeRef?
+ guard AXUIElementCopyAttributeValue(AXUIElementCreateApplication(app.processIdentifier),
+ kAXFocusedWindowAttribute as CFString, &value) == .success,
+ let value, CFGetTypeID(value) == AXUIElementGetTypeID() else { return nil }
+ return Scope(pid: app.processIdentifier, window: unsafeBitCast(value, to: AXUIElement.self))
+ }
+ static func capture() -> InputTarget? {
+ if case .ready(let target) = readFocus() { return target }
+ return nil
+ }
+ static func readFocus() -> Focus {
+ guard AXIsProcessTrusted(), let app = NSWorkspace.shared.frontmostApplication,
+ app.processIdentifier != ProcessInfo.processInfo.processIdentifier else { return .unavailable }
+ var value: CFTypeRef?
guard AXUIElementCopyAttributeValue(AXUIElementCreateApplication(app.processIdentifier),
kAXFocusedUIElementAttribute as CFString, &value) == .success,
- let value = value, CFGetTypeID(value) == AXUIElementGetTypeID() else { return nil }
+ let value = value, CFGetTypeID(value) == AXUIElementGetTypeID() else { return .unavailable }
let element = unsafeBitCast(value, to: AXUIElement.self)
var role: CFTypeRef?
var subrole: CFTypeRef?
- AXUIElementCopyAttributeValue(element, kAXRoleAttribute as CFString, &role)
+ guard AXUIElementCopyAttributeValue(element, kAXRoleAttribute as CFString, &role) == .success else { return .unavailable }
+ // App activation can expose the window before its text responder is ready.
+ if role as? String == kAXWindowRole { return .window }
AXUIElementCopyAttributeValue(element, kAXSubroleAttribute as CFString, &subrole)
guard [kAXTextFieldRole, kAXTextAreaRole, kAXComboBoxRole].contains(role as? String ?? ""),
- subrole as? String != kAXSecureTextFieldSubrole else { return nil }
- return InputTarget(pid: app.processIdentifier, element: element)
+ subrole as? String != kAXSecureTextFieldSubrole else { return .notEditable }
+ return .ready(InputTarget(pid: app.processIdentifier, element: element))
}
func isCurrent() -> Bool {
guard let current = InputTarget.capture() else { return false }
@@ -29,8 +52,10 @@ struct InputTarget {
@MainActor
final class PasteHelper {
- enum Failure { case permission, missingTarget, targetChanged, modifiersHeld, eventUnavailable, directUnavailable, clipboardUnavailable, enterSkipped }
+ enum Failure { case permission, missingTarget, targetChanged, modifiersHeld, eventUnavailable, directUnavailable, clipboardUnavailable, clipboardChanged, enterSkipped }
private(set) var failure: Failure?
+ private(set) var usedClipboard = false
+ private(set) var diagnostic = "No input attempt"
var failureMessage: String? {
switch failure {
case .permission: return L("Allow Accessibility access in System Settings.", "请在系统设置中允许辅助功能权限。")
@@ -40,6 +65,7 @@ final class PasteHelper {
case .eventUnavailable: return L("Could not create the paste shortcut.", "无法发送粘贴快捷键。")
case .directUnavailable: return L("This field rejected direct input. Text is kept; focus the field and retry.", "此输入框拒绝直接输入,文字已保留,请点击输入框后重试。")
case .clipboardUnavailable: return L("Could not write text to the clipboard.", "无法将文字写入剪贴板。")
+ case .clipboardChanged: return L("The clipboard changed before paste. Text is kept.", "粘贴前剪贴板发生变化,文字已保留。")
case .enterSkipped: return L("Text entered; Enter was skipped because focus or permissions changed.", "文字已输入;焦点或权限发生变化,未发送回车。")
case nil: return nil
}
@@ -57,9 +83,15 @@ final class PasteHelper {
func deliver(_ text: String, target: InputTarget?, method: String = "auto", sendEnter: Bool = false, completion: @escaping (Bool) -> Void) {
cancel()
failure = nil
+ usedClipboard = false
+ diagnostic = "method=\(method); stage=checking"
let token = generation
let deadline = Date().addingTimeInterval(1)
- func fail(_ reason: Failure) { self.failure = reason; completion(false) }
+ func fail(_ reason: Failure) {
+ self.failure = reason
+ self.diagnostic += "; failure=\(reason)"
+ completion(false)
+ }
func attempt() {
guard token == self.generation else { return }
guard AXIsProcessTrusted() else { fail(.permission); return }
@@ -76,6 +108,7 @@ final class PasteHelper {
if Self.useAccessibilityInput(method: method,
selectedTextWritable: writableStatus == .success && writable.boolValue) {
let status = AXUIElementSetAttributeValue(target.element, kAXSelectedTextAttribute as CFString, text as CFString)
+ self.diagnostic = "method=\(method); route=accessibility; AXStatus=\(status.rawValue)"
guard status == .success else { fail(.directUnavailable); return }
if sendEnter { self.enterAfterInput(target: target, isCurrent: { token == self.generation }, completion: completion) }
else { completion(true) }
@@ -84,6 +117,7 @@ final class PasteHelper {
guard let (down, up) = Self.shortcutEvents(Shortcut(keyCode: 9, modifiers: 4)) else {
fail(.eventUnavailable); return
}
+ self.usedClipboard = true
let pasteboard = NSPasteboard.general
let saved = pasteboard.pasteboardItems?.map { item in
item.types.compactMap { type -> (NSPasteboard.PasteboardType, Data)? in
@@ -94,10 +128,8 @@ final class PasteHelper {
pasteboard.clearContents()
guard pasteboard.setString(text, forType: .string) else { fail(.clipboardUnavailable); return }
let changeCount = pasteboard.changeCount
- 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.
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
+ self.diagnostic = "method=\(method); route=clipboard; stage=waiting"
+ func restoreClipboard() {
guard pasteboard.changeCount == changeCount else { return }
pasteboard.clearContents()
let items = saved.map { values -> NSPasteboardItem in
@@ -107,8 +139,28 @@ final class PasteHelper {
}
if !items.isEmpty { pasteboard.writeObjects(items) }
}
- if sendEnter { self.enterAfterInput(target: target, isCurrent: { token == self.generation }, completion: completion) }
- else { completion(true) }
+ // Let clipboard ownership settle, then revalidate before posting any key.
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.08) {
+ guard token == self.generation else { restoreClipboard(); return }
+ guard AXIsProcessTrusted() else { restoreClipboard(); fail(.permission); return }
+ guard target.isCurrent() else { restoreClipboard(); fail(.targetChanged); return }
+ guard pasteboard.changeCount == changeCount else { fail(.clipboardChanged); return }
+ guard self.modifierFlags().intersection([.maskControl, .maskAlternate, .maskShift, .maskCommand, .maskSecondaryFn]).isEmpty else {
+ restoreClipboard(); fail(.modifiersHeld); return
+ }
+ down.post(tap: .cghidEventTap)
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.02) {
+ // Always release a posted key, including after cancellation.
+ up.post(tap: .cghidEventTap)
+ // There is no acknowledgement that the target has read the
+ // pasteboard. Keep the dictated text: restoring on a timer
+ // can make a delayed paste insert the previous contents.
+ guard token == self.generation else { return }
+ self.diagnostic = "method=\(method); route=clipboard; result=shortcut-posted-unverified"
+ if sendEnter { self.enterAfterInput(target: target, isCurrent: { token == self.generation }, completion: completion) }
+ else { completion(true) }
+ }
+ }
}
attempt()
}
@@ -130,7 +182,10 @@ final class PasteHelper {
let down = CGEvent(keyboardEventSource: source, virtualKey: shortcut.keyCode, keyDown: true),
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.flags = flags
+ // This is a complete synthetic chord. Keeping Command on V-up leaves
+ // the session reporting Command down after paste, blocking later input.
+ up.flags = []
down.setIntegerValueField(.eventSourceUserData, value: HotkeyManager.syntheticMarker)
up.setIntegerValueField(.eventSourceUserData, value: HotkeyManager.syntheticMarker)
return (down, up)
diff --git a/macos/Sources/SettingsWindow.swift b/macos/Sources/SettingsWindow.swift
index b9e7c8e..79e77dc 100644
--- a/macos/Sources/SettingsWindow.swift
+++ b/macos/Sources/SettingsWindow.swift
@@ -103,13 +103,20 @@ final class SettingsModel: ObservableObject {
var isDoubaoSignedIn: Bool {
SettingsStore.shared.value.provider == .doubao ? state.loginStatus == .loggedIn : doubaoSessionSaved
}
+ var effectiveMicrophone: AudioInputDevice? {
+ AudioDevices.resolve(preferred: draft.microphoneID, inputs: microphones, defaultUID: currentDefaultMicrophoneID)
+ }
+ var microphoneStatus: String {
+ guard let device = effectiveMicrophone else { return L("No microphone available", "没有可用的麦克风") }
+ if !draft.microphoneID.isEmpty && device.id != draft.microphoneID {
+ return L("Saved microphone disconnected. Using: ", "所选麦克风已断开,自动使用:") + device.name
+ }
+ return L("Using: ", "当前使用:") + device.name
+ }
func refreshMicrophones() {
- let previous = draft.microphoneID.isEmpty ? currentDefaultMicrophoneID : draft.microphoneID
- let previousDevice = microphones.first { $0.id == previous }
+ let previous = effectiveMicrophone
microphones = microphoneInputs(); currentDefaultMicrophoneID = defaultMicrophoneID()
- let current = draft.microphoneID.isEmpty ? currentDefaultMicrophoneID : draft.microphoneID
- let currentDevice = microphones.first { $0.id == current }
- if previous != current || previousDevice?.audioID != currentDevice?.audioID {
+ if previous != effectiveMicrophone {
state.microphoneChecked = false; state.voiceChecked = false
}
}
@@ -472,7 +479,7 @@ struct SettingsView: View {
HStack { Text(model.draft.shortcut.label); Button(L("Choose shortcut", "选择快捷键")) { model.chooseShortcut() } }.disabled(model.setupBusy)
Label(model.shortcutAvailable ? L("Shortcut ready", "快捷键已就绪") : L("Shortcut permission required", "请启用快捷键权限"), systemImage: model.shortcutAvailable ? "checkmark.circle.fill" : "circle")
.foregroundColor(model.shortcutAvailable ? .green : .secondary)
- Text(L("Tap to start or stop; hold to talk. Esc cancels recording.", "短按开始或结束,长按说话;Esc 取消录音。"))
+ Text(L("Tap to start; hold to talk. During voice input, any key stops and inputs text.", "短按开始,长按说话;语音输入期间,任意按键都结束并上屏。"))
}.formStyle(.grouped).padding(8)
default:
Form {
@@ -553,8 +560,8 @@ struct SettingsView: View {
ScrollView {
VStack(alignment: .leading, spacing: 14) {
HStack { Text(L("Dictation: ", "听写:") + model.draft.shortcut.label); Button(L("Choose shortcut", "选择快捷键")) { model.chooseShortcut() } }
- Text(L("Tap to toggle; hold to talk. Double-tap finishes and sends Enter, or sends Enter while idle.", "短按切换录音,长按说话。双击结束并发送回车,空闲时双击发送回车。"))
- Toggle(L("Double-tap sends Enter", "双击发送回车"), isOn: $model.draft.doubleEnter)
+ Text(L("Tap to start; hold to talk. Any key finishes voice input without its original action. Double-tap sends Enter while idle.", "短按开始录音,长按说话。语音输入期间任意按键都结束上屏,不执行原按键动作;空闲时双击发送回车。"))
+ Toggle(L("Double-tap sends Enter when idle", "空闲时双击发送回车"), isOn: $model.draft.doubleEnter)
Stepper(L("Hold threshold: ", "长按阈值:") + "\(model.draft.holdMilliseconds) ms", value: $model.draft.holdMilliseconds, in: 200...1500, step: 50)
Stepper(L("Double-tap interval: ", "双击间隔:") + "\(model.draft.doubleMilliseconds) ms", value: $model.draft.doubleMilliseconds, in: 150...600, step: 50)
Divider()
@@ -579,12 +586,18 @@ struct SettingsView: View {
HStack { Text(title + ": " + value); Spacer(); Button(L("Choose", "选择")) { model.chooseShortcut(destination) } }
}
private var microphonePicker: some View {
- Picker(L("Microphone", "麦克风"), selection: $model.draft.microphoneID) {
- Text(L("System default", "系统默认")).tag("")
- ForEach(model.microphones) { Text($0.name).tag($0.id) }
- if !model.draft.microphoneID.isEmpty && !model.microphones.contains(where: { $0.id == model.draft.microphoneID }) {
- Text(L("Saved device unavailable", "已保存的设备不可用")).tag(model.draft.microphoneID)
- }
+ VStack(alignment: .leading, spacing: 4) {
+ Picker(L("Microphone", "麦克风"), selection: Binding(
+ get: { model.draft.microphoneID },
+ set: { _ = model.selectMicrophone($0) }
+ )) {
+ Text(L("System default", "系统默认")).tag("")
+ ForEach(model.microphones) { Text($0.name).tag($0.id) }
+ if !model.draft.microphoneID.isEmpty && !model.microphones.contains(where: { $0.id == model.draft.microphoneID }) {
+ Text(L("Saved device disconnected · automatic fallback", "所选设备已断开 · 自动回退")).tag(model.draft.microphoneID)
+ }
+ }.disabled(model.setupBusy || state.evaluationBusy || state.inputPending)
+ Text(model.microphoneStatus).font(.caption).foregroundColor(.secondary)
}
}
private var general: some View {
@@ -596,7 +609,7 @@ struct SettingsView: View {
microphonePicker
Picker(L("Input method", "输入方式"), selection: $model.draft.inputMethod) {
Text(L("Automatic (direct input when supported)", "自动选择(支持时直接输入)")).tag("auto")
- Text(L("Clipboard (restores previous contents)", "剪贴板(恢复原内容)")).tag("clipboard")
+ Text(L("Clipboard (keeps dictated text)", "剪贴板(保留识别文字)")).tag("clipboard")
Text(L("Direct accessibility input", "辅助功能直接输入")).tag("direct")
}
Text(L("Direct input needs an editable accessibility field. If unavailable, text stays in the app.", "直接输入需要可编辑的辅助功能输入框,不可用时文字保留在应用中。"))
@@ -611,7 +624,7 @@ struct SettingsView: View {
}
Button(L("Copy diagnostics", "复制诊断信息")) {
let settings = SettingsStore.shared.value
- PasteHelper.copyOnly("Doubao Say macOS\nVersion: \(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "development")\nSystem: \(ProcessInfo.processInfo.operatingSystemVersionString)\nProvider: \(settings.provider.rawValue)\nShortcut: \(settings.shortcut.label)\nPolishing: \(settings.polishEnabled)\nInput: \(settings.inputMethod)\nMicrophone check: \(state.microphoneChecked)\nVoice check: \(state.voiceChecked)")
+ PasteHelper.copyOnly("Doubao Say macOS\nVersion: \(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "development")\nSystem: \(ProcessInfo.processInfo.operatingSystemVersionString)\nProvider: \(settings.provider.rawValue)\nShortcut: \(settings.shortcut.label)\nPolishing: \(settings.polishEnabled)\nInput: \(settings.inputMethod)\nDelivery: \(state.inputDiagnostic)\nMicrophone check: \(state.microphoneChecked)\nVoice check: \(state.voiceChecked)")
model.feedback = L("Diagnostics copied without credentials, device IDs or transcripts.", "已复制诊断信息,不含凭证、设备标识或转写。")
}
}.formStyle(.grouped).padding(8)
diff --git a/macos/Sources/TranscriptionManager.swift b/macos/Sources/TranscriptionManager.swift
index 045710f..ab24b9a 100644
--- a/macos/Sources/TranscriptionManager.swift
+++ b/macos/Sources/TranscriptionManager.swift
@@ -8,6 +8,7 @@ final class TranscriptionManager {
private let hotkey: HotkeyManager
private let audio = AudioCaptureManager()
private let delivery = PasteHelper()
+ private let targetCapture = InputTargetCapture()
private var client: ASRTransport?
private let polisher = PolishCoordinator()
private var polishAvailable = false
@@ -59,22 +60,24 @@ final class TranscriptionManager {
hotkey.start()
}
func startRecording() {
- defer { hotkey.setEscapeHandlingEnabled(state.recordingState != .idle || state.inputPending || overlay.isVisible, recording: state.isRecording) }
+ defer { hotkey.setEscapeHandlingEnabled(state.recordingState != .idle || state.inputPending || overlay.isVisible, recording: state.isRecording,
+ interceptKeys: state.recordingState != .idle || state.inputPending) }
if state.recordingState == .polishing { polisher.useOriginal(); return }
guard state.recordingState == .idle, !state.inputPending, !state.evaluationBusy, canRecord?() ?? true else { return }
settings = SettingsStore.shared.value
delivery.cancel()
+ if !primed { captureTarget() }
let params = settings.provider == .doubao ? ASRParamsStore.load() : nil
let apiKey = settings.provider == .doubao ? nil : SecretStore.load(settings.provider.rawValue + "-api-key")
- guard params != nil || !(apiKey ?? "").isEmpty else { discardPrime(); onLoginNeeded?(); return }
+ guard params != nil || !(apiKey ?? "").isEmpty else { discardPrime(); clearTarget(); onLoginNeeded?(); return }
guard AVCaptureDevice.authorizationStatus(for: .audio) == .authorized else {
+ discardPrime(); clearTarget()
state.errorMessage = L("Enable microphone access in System Settings.", "请在系统设置中允许麦克风访问。")
if AVCaptureDevice.authorizationStatus(for: .audio) == .notDetermined {
AVCaptureDevice.requestAccess(for: .audio) { _ in }
}
return
}
- if !primed { target = testMode ? nil : InputTarget.capture() }
session = UUID()
let token = session
let transport: ASRTransport = settings.provider == .doubao ? DoubaoASRClient() : APIASRClient(provider: settings.provider)
@@ -202,6 +205,7 @@ final class TranscriptionManager {
latency.mark("polish", at: ProcessInfo.processInfo.systemUptime)
var timing = latency
let captured = target
+ let captureDiagnostic = targetCapture.diagnostic
let enter = sendEnter
let original = rawText
var historyID: String?
@@ -220,14 +224,15 @@ final class TranscriptionManager {
try? PersonalDataStore.shared.saveTimings(historyID, values: timing.values); return
}
let token = session
- hotkey.setEscapeHandlingEnabled(true)
+ hotkey.setEscapeHandlingEnabled(true, interceptKeys: 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")
+ try? PersonalDataStore.shared.status(historyID, sent ? (self?.delivery.usedClipboard == true ? "attempted" : "sent") : "failed")
guard self?.session == token else { return }
+ self?.state.inputDiagnostic = captureDiagnostic + "; " + (self?.delivery.diagnostic ?? "No input attempt")
self?.state.inputPending = false
self?.hotkey.setEscapeHandlingEnabled(false)
if !sent { self?.showInputFailure(text) }
@@ -277,8 +282,9 @@ final class TranscriptionManager {
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")
+ try? PersonalDataStore.shared.status(historyID, sent ? (self.delivery.usedClipboard ? "attempted" : "sent") : "failed")
guard self.session == token else { return }
+ self.state.inputDiagnostic = self.delivery.diagnostic
self.state.inputPending = false
self.hotkey.setEscapeHandlingEnabled(false)
self.state.feedback = sent ? L("Input attempted", "已发送输入操作") : L("Target unavailable; text kept", "目标不可用,文字已保留")
@@ -321,7 +327,7 @@ final class TranscriptionManager {
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
+ captureTarget(); primedAudio.removeAll(); primed = true
audio.onAudioData = { [weak self] data in
Task { @MainActor in
guard let self = self, self.primed, self.primedAudio.count + data.count <= 96_000 else { return }
@@ -332,7 +338,14 @@ final class TranscriptionManager {
}
private func discardPrime() {
guard primed else { return }
- primed = false; primedAudio.removeAll(); audio.stopCapture(); audio.onAudioData = nil; audio.onRMS = nil; audio.onError = nil; target = nil
+ clearTarget()
+ primed = false; primedAudio.removeAll(); audio.stopCapture(); audio.onAudioData = nil; audio.onRMS = nil; audio.onError = nil
+ }
+ private func clearTarget() { targetCapture.cancel(); target = nil }
+ private func captureTarget() {
+ target = nil
+ guard !testMode else { targetCapture.cancel(); return }
+ targetCapture.begin { [weak self] in self?.target = $0 }
}
private func showFailure(_ message: String, status: String = L("Microphone unavailable", "麦克风不可用"), keptText: String = "") {
cancel()
@@ -346,17 +359,18 @@ final class TranscriptionManager {
} else { scheduleTimeout(seconds: 6, token: session) { [weak self] in self?.cancel() } }
}
func cancel() {
+ clearTarget()
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
+ client?.disconnect(); client = nil
setState(.idle); overlay.hideOverlay(); state.transcriptionText = ""; state.overlayStatus = ""; state.rms = 0
}
private func setState(_ value: RecordingState) {
if value == .polishing { state.polishStartedAt = Date() }
else { state.polishStartedAt = nil }
state.recordingState = value
- hotkey.setEscapeHandlingEnabled(value != .idle, recording: value == .starting || value == .recording)
+ hotkey.setEscapeHandlingEnabled(value != .idle, recording: value == .starting || value == .recording, interceptKeys: value != .idle)
}
}
diff --git a/macos/Tests/Input/DeliveryCheck.swift b/macos/Tests/Input/DeliveryCheck.swift
index 32581eb..787254b 100644
--- a/macos/Tests/Input/DeliveryCheck.swift
+++ b/macos/Tests/Input/DeliveryCheck.swift
@@ -40,7 +40,7 @@ final class CGEvent {
struct Shortcut { let keyCode: UInt16; let modifiers: Int }
enum HotkeyManager {
static let syntheticMarker: Int64 = 1
- static func flags(_ value: Int) -> CGEventFlags { [] }
+ static func flags(_ value: Int) -> CGEventFlags { value & 4 != 0 ? .maskCommand : [] }
}
@main struct DeliveryCheck {
@@ -48,6 +48,9 @@ enum HotkeyManager {
func wait(_ seconds: Double) { RunLoop.current.run(until: Date().addingTimeInterval(seconds)) }
var flags = CGEventFlags()
let helper = PasteHelper(modifierFlags: { flags })
+ let (down, up) = PasteHelper.shortcutEvents(Shortcut(keyCode: 9, modifiers: 4))!
+ precondition(down.flags.contains(.maskCommand) && up.flags.isEmpty,
+ "Synthetic paste must release its modifier flags on key-up")
let target = InputTarget()
var result: Bool?
func send(_ destination: InputTarget? = target) {
@@ -80,14 +83,31 @@ enum HotkeyManager {
Fixture.current = true; Fixture.writes = []; result = nil
Fixture.writable = false
helper.deliver("fallback text", target: target, method: "auto") { result = $0 }
- wait(0.9)
+ let clipboardWriteCount = NSPasteboard.general.changeCount
+ precondition(result == nil && CGEvent.posted == 0, "Paste must wait for clipboard ownership to settle")
+ wait(1.2)
precondition(result == true && Fixture.writes.isEmpty && CGEvent.posted == 2)
+ precondition(NSPasteboard.general.changeCount == clipboardWriteCount,
+ "A delayed target must still find the dictated text after the former restore deadline")
precondition(NSPasteboard.general.pastedTexts == ["fallback text"], "Unsupported fields must use the clipboard route")
Fixture.writable = true; result = nil
helper.deliver("clipboard choice", target: target, method: "clipboard") { result = $0 }
wait(0.9)
precondition(result == true && Fixture.writes.isEmpty && CGEvent.posted == 4)
precondition(NSPasteboard.general.pastedTexts == ["fallback text", "clipboard choice"], "Explicit clipboard choice must override available AX capability")
+ result = nil
+ helper.deliver("cancel before paste", target: target, method: "clipboard") { result = $0 }
+ helper.cancel(); wait(0.15)
+ precondition(result == nil && CGEvent.posted == 4, "Cancellation during settling must prevent all key events")
+ helper.deliver("changed focus", target: target, method: "clipboard") { result = $0 }
+ Fixture.current = false; wait(0.15)
+ precondition(result == false && helper.failure == .targetChanged && CGEvent.posted == 4)
+ Fixture.current = true; result = nil
+ helper.deliver("changed clipboard", target: target, method: "clipboard") { result = $0 }
+ NSPasteboard.general.clearContents(); wait(0.15)
+ precondition(result == false && helper.failure == .clipboardChanged && CGEvent.posted == 4,
+ "A changed clipboard must never paste unrelated contents or overwrite newer clipboard data")
+ precondition(!helper.diagnostic.contains("changed clipboard"), "Diagnostics must not contain dictated text")
print("PASS: capability-based delivery, explicit clipboard choice, permission/focus failures, Fn release, held-key timeout and cancellation; all platform effects are inert")
}
}
diff --git a/macos/Tests/Input/FocusCaptureCheck.swift b/macos/Tests/Input/FocusCaptureCheck.swift
new file mode 100644
index 0000000..55ac694
--- /dev/null
+++ b/macos/Tests/Input/FocusCaptureCheck.swift
@@ -0,0 +1,67 @@
+import Foundation
+
+// No AX reads, app activation, clipboard writes or keyboard events.
+struct InputTarget {
+ enum Focus { case ready(InputTarget), unavailable, window, notEditable }
+ struct Scope: Equatable { let pid: Int; let window: Int }
+ let id: Int
+ static func scope() -> Scope? { nil }
+ static func readFocus() -> Focus { .unavailable }
+}
+
+@main struct FocusCaptureCheck {
+ @MainActor static func main() {
+ var clock = Date(timeIntervalSince1970: 0)
+ var pending: [() -> Void] = []
+ func wait(_ seconds: Double) {
+ let steps = Int((seconds / 0.05).rounded(.up))
+ for _ in 0..<steps {
+ clock = clock.addingTimeInterval(0.05)
+ let tasks = pending; pending = []
+ tasks.forEach { $0() }
+ }
+ }
+ var scope: InputTarget.Scope? = .init(pid: 1, window: 1)
+ var focus = InputTarget.Focus.unavailable
+ var reads = 0
+ var received: [Int] = []
+ let capture = InputTargetCapture(scope: { scope }, focus: { reads += 1; return focus }, now: { clock }, retry: { pending.append($0) })
+ func begin() { received = []; capture.begin { if let target = $0 { received.append(target.id) } } }
+ begin()
+ wait(0.12); focus = .ready(InputTarget(id: 1)); wait(0.12)
+ precondition(received == [1] && capture.diagnostic == "capture=recovered",
+ "First activation with unavailable focus must recover without a second recording")
+ focus = .ready(InputTarget(id: 2)); wait(0.12)
+ precondition(received == [1], "A captured input must never be replaced by a later focus")
+ begin()
+ precondition(received == [2] && capture.diagnostic == "capture=ready")
+
+ focus = .window; begin(); wait(0.1)
+ precondition(received.isEmpty && capture.diagnostic == "capture=waiting-window")
+ focus = .ready(InputTarget(id: 9)); wait(0.1)
+ precondition(received == [9] && capture.diagnostic == "capture=recovered-window",
+ "A focused window during activation is pending focus, not a non-editable control")
+
+ focus = .unavailable; begin(); scope = .init(pid: 2, window: 1)
+ focus = .ready(InputTarget(id: 3)); wait(0.12)
+ precondition(received.isEmpty && capture.diagnostic == "capture=scope-changed")
+ scope = .init(pid: 1, window: 1); focus = .unavailable; begin()
+ scope = .init(pid: 1, window: 2); focus = .ready(InputTarget(id: 4)); wait(0.12)
+ precondition(received.isEmpty && capture.diagnostic == "capture=scope-changed",
+ "Same-app window changes must not redirect dictation")
+ scope = .init(pid: 1, window: 1); focus = .unavailable; begin()
+ capture.cancel(); focus = .ready(InputTarget(id: 5)); wait(0.12)
+ precondition(received.isEmpty, "Cancelled capture must not leak a late target into another session")
+
+ focus = .notEditable; begin(); let nonEditableReads = reads
+ focus = .ready(InputTarget(id: 6)); wait(0.12)
+ precondition(received.isEmpty && reads == nonEditableReads && capture.diagnostic == "capture=not-editable")
+ scope = nil; focus = .unavailable; begin(); let noScopeReads = reads
+ scope = .init(pid: 1, window: 1); focus = .ready(InputTarget(id: 7)); wait(0.12)
+ precondition(received.isEmpty && reads == noScopeReads && capture.diagnostic == "capture=scope-unavailable")
+ focus = .unavailable; begin(); wait(0.6); let timedOutReads = reads
+ focus = .ready(InputTarget(id: 8)); wait(0.12)
+ precondition(received.isEmpty && reads == timedOutReads && capture.diagnostic == "capture=timed-out")
+ print("PASS: activation focus recovery, exact app/window scope, fixed target, cancellation, non-editable focus and bounded timeout; no real input")
+ }
+}
diff --git a/macos/Tests/Input/KeyInterceptionCheck.swift b/macos/Tests/Input/KeyInterceptionCheck.swift
new file mode 100644
index 0000000..4612291
--- /dev/null
+++ b/macos/Tests/Input/KeyInterceptionCheck.swift
@@ -0,0 +1,90 @@
+import AppKit
+
+@main struct KeyInterceptionCheck {
+ static func key(_ code: UInt16, _ down: Bool, flags: CGEventFlags = []) -> CGEvent {
+ let event = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: down)!
+ event.flags = flags
+ return event
+ }
+ static func main() {
+ for shortcut in [Shortcut(keyCode: 49, modifiers: 3), Shortcut(keyCode: 63, modifiers: 0)] {
+ for code: UInt16 in [0, 36, 53, 49, 48, 51, 123, 122] {
+ let manager = HotkeyManager()
+ var settings = MacSettings(); settings.shortcut = shortcut
+ manager.configure(settings)
+ var stops = 0, other = 0
+ manager.onHotkeyEvent = { if case .stop = $0 { stops += 1 } else { other += 1 } }
+ manager.setEscapeHandlingEnabled(true, recording: true)
+ precondition(manager.handle(.keyDown, key(code, true)) == nil)
+ precondition(manager.handle(.keyDown, key(code, true)) == nil, "Held-key repeat must be swallowed")
+ precondition(stops == 1 && other == 0, "Every recording key must stop, never cancel or send Enter")
+ manager.setEscapeHandlingEnabled(false)
+ precondition(manager.handle(.keyUp, key(code, false)) == nil, "Release must remain swallowed after delivery")
+ precondition(manager.handle(.keyDown, key(0, true)) != nil, "Ordinary typing must resume when idle")
+ }
+ }
+ let trigger = HotkeyManager()
+ var triggerSettings = MacSettings(); triggerSettings.shortcut = Shortcut(keyCode: 63, modifiers: 0)
+ triggerSettings.doubleEnter = false; trigger.configure(triggerSettings)
+ var triggerStops = 0
+ trigger.onHotkeyEvent = { if case .stop = $0 { triggerStops += 1 } }
+ precondition(trigger.handle(.flagsChanged, key(63, true, flags: .maskSecondaryFn)) == nil,
+ "The voice trigger must not reach the system's original Fn action")
+ trigger.setEscapeHandlingEnabled(true, recording: true)
+ precondition(trigger.handle(.keyDown, key(0, true, flags: .maskSecondaryFn)) == nil && triggerStops == 1)
+ trigger.setEscapeHandlingEnabled(false)
+ precondition(trigger.handle(.flagsChanged, key(63, false)) == nil && triggerStops == 1,
+ "Releasing the original trigger after finishing must not perform its system action or restart recording")
+ precondition(trigger.handle(.keyUp, key(0, false)) == nil)
+ let manager = HotkeyManager()
+ var stops = 0
+ manager.onHotkeyEvent = { if case .stop = $0 { stops += 1 } else { preconditionFailure("Unexpected gesture") } }
+ for modifier: UInt16 in [55, 59, 58, 56, 63] {
+ let flags = HotkeyManager.flags([UInt16(55): 4, 59: 1, 58: 2, 56: 8, 63: 16][modifier]!)
+ manager.setEscapeHandlingEnabled(true, recording: true)
+ let before = stops
+ precondition(manager.handle(.flagsChanged, key(modifier, true, flags: flags)) == nil)
+ precondition(manager.handle(.keyDown, key(8, true, flags: flags)) == nil)
+ precondition(stops == before + 1, "A shortcut chord must produce one stop")
+ manager.setEscapeHandlingEnabled(false)
+ precondition(manager.handle(.flagsChanged, key(modifier, false)) == nil)
+ precondition(manager.handle(.keyUp, key(8, false)) == nil)
+ precondition(manager.handle(.keyDown, key(0, true)) != nil)
+ }
+ manager.setEscapeHandlingEnabled(false)
+ precondition(manager.handle(.flagsChanged, key(59, true, flags: CGEventFlags(rawValue: CGEventFlags.maskControl.rawValue | 0x1))) != nil)
+ manager.setEscapeHandlingEnabled(true, recording: true)
+ precondition(manager.handle(.flagsChanged, key(62, true, flags: CGEventFlags(rawValue: CGEventFlags.maskControl.rawValue | 0x2001))) == nil)
+ manager.setEscapeHandlingEnabled(false)
+ precondition(manager.handle(.flagsChanged, key(59, false, flags: CGEventFlags(rawValue: CGEventFlags.maskControl.rawValue | 0x2000))) != nil,
+ "The original trigger modifier release must not become a new blocked press")
+ precondition(manager.handle(.flagsChanged, key(62, false)) == nil)
+ precondition(manager.handle(.keyDown, key(0, true)) != nil, "Both modifier sides must drain without leaving keyboard interception stuck")
+ manager.setEscapeHandlingEnabled(true, interceptKeys: true)
+ precondition(manager.handle(.keyDown, key(53, true)) == nil, "Finishing input must not cancel on Escape")
+ manager.setEscapeHandlingEnabled(false)
+ precondition(manager.handle(.keyUp, key(53, false)) == nil)
+ manager.setEscapeHandlingEnabled(true, recording: true)
+ let synthetic = key(9, true, flags: .maskCommand)
+ synthetic.setIntegerValueField(.eventSourceUserData, value: HotkeyManager.syntheticMarker)
+ let before = stops
+ precondition(manager.handle(.keyDown, synthetic) != nil && stops == before, "Our output must bypass interception")
+ manager.setEscapeHandlingEnabled(false)
+ manager.setEscapeHandlingEnabled(true)
+ var cancelled = false
+ manager.onHotkeyEvent = { if case .cancel = $0 { cancelled = true } }
+ precondition(manager.handle(.keyDown, key(53, true)) == nil && cancelled, "Escape still dismisses kept text outside input")
+ manager.onHotkeyEvent = { if case .stop = $0 { stops += 1 } else { preconditionFailure("Unexpected media gesture") } }
+ manager.setEscapeHandlingEnabled(true, recording: true)
+ let mediaDown = NSEvent.otherEvent(with: .systemDefined, location: .zero, modifierFlags: [], timestamp: 0,
+ windowNumber: 0, context: nil, subtype: 8, data1: 0x0a00, data2: 0)!.cgEvent!
+ let mediaUp = NSEvent.otherEvent(with: .systemDefined, location: .zero, modifierFlags: [], timestamp: 0,
+ windowNumber: 0, context: nil, subtype: 8, data1: 0x0b00, data2: 0)!.cgEvent!
+ let mediaBefore = stops
+ precondition(manager.handle(mediaDown.type, mediaDown) == nil && stops == mediaBefore + 1)
+ manager.setEscapeHandlingEnabled(false)
+ precondition(manager.handle(mediaUp.type, mediaUp) == nil)
+ precondition(manager.handle(mediaDown.type, mediaDown) != nil, "Media keys must resume when idle")
+ print("PASS: recording keys, Escape/Enter, modifiers, shortcut chords, media keys, repeats, post-delivery releases and synthetic-output bypass; no event tap or real key posting")
+ }
+}
diff --git a/macos/Tests/Input/RetryCheck.swift b/macos/Tests/Input/RetryCheck.swift
index dfc3254..8dfe187 100644
--- a/macos/Tests/Input/RetryCheck.swift
+++ b/macos/Tests/Input/RetryCheck.swift
@@ -14,14 +14,25 @@ enum AVCaptureDevice {
}
func L(_ english: String, _ chinese: String) -> String { english }
struct Shortcut { var keyCode: UInt16; var modifiers: Int }
-struct InputTarget { static var available = true; static func capture() -> InputTarget? { available ? InputTarget() : nil } }
+struct InputTarget {
+ enum Focus { case ready(InputTarget), unavailable, window, notEditable }
+ struct Scope: Equatable { let window: Int }
+ static var available = true
+ static func scope() -> Scope? { Scope(window: 1) }
+ static func readFocus() -> Focus { available ? .ready(InputTarget()) : .unavailable }
+ static func capture() -> InputTarget? { available ? InputTarget() : nil }
+}
@MainActor final class PasteHelper {
+ var diagnostic = "Synthetic delivery diagnostic"
+ var usedClipboard = false
var failureMessage: String? { Self.failImmediately ? "Synthetic target unavailable" : nil }
static var events: [String] = []
static var pending: ((Bool) -> Void)?
static var failImmediately = false
+ static var targetAvailable = false
func cancel() {}
func deliver(_ text: String, target: InputTarget?, method: String, sendEnter: Bool = false, completion: @escaping (Bool) -> Void) {
+ Self.targetAvailable = target != nil
Self.events.append("paste"); Self.pending = completion
if Self.failImmediately { completion(false) }
}
@@ -36,7 +47,7 @@ final class AudioCaptureManager {
final class HotkeyManager {
enum HotkeyEvent { case start, stop, cancel, enter, prime, discard }
var onHotkeyEvent: ((HotkeyEvent) -> Void)?
- func setEscapeHandlingEnabled(_ enabled: Bool, recording: Bool = false) {}
+ func setEscapeHandlingEnabled(_ enabled: Bool, recording: Bool = false, interceptKeys: Bool? = nil) {}
func start() {}
}
@MainActor final class PolishCoordinator {
@@ -74,6 +85,10 @@ final class PersonalDataStore {
@main struct RetryCheck {
@MainActor static func main() {
+ // Keep run-loop waits bounded even when the only pending work is on GCD.
+ let wake = Timer(timeInterval: 0.01, repeats: true) { _ in }
+ RunLoop.current.add(wake, forMode: .default)
+ defer { wake.invalidate() }
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())
@@ -121,7 +136,14 @@ final class PersonalDataStore {
"Failed input after the stop shortcut must keep the recognized text visible")
precondition(failureState.errorMessage != nil && !failureState.inputPending)
InputTarget.available = true; PasteHelper.failImmediately = false
- failureManager.retryLast(); wait(); PasteHelper.pending?(true)
+ PasteHelper.pending = nil
+ failureManager.retryLast()
+ let retryDeadline = Date().addingTimeInterval(8)
+ while PasteHelper.pending == nil && Date() < retryDeadline {
+ RunLoop.current.run(until: Date().addingTimeInterval(0.01))
+ }
+ precondition(PasteHelper.pending != nil, "The retry countdown must reach delivery before completing it")
+ PasteHelper.pending?(true)
precondition(!failureOverlay.isVisible && failureState.errorMessage == nil && !failureState.inputPending,
"Successful retry must clear the retained failure overlay")
failureHotkey.onHotkeyEvent?(.start)
@@ -138,5 +160,27 @@ final class PersonalDataStore {
"Recognition failure after stopping must retain incomplete text without pasting it")
failureManager.cancel()
print("PASS: start/stop shortcut with unavailable target retains text and shows visible delivery failure; no real input")
+ let recoveredState = AppState(), recoveredHotkey = HotkeyManager()
+ let recoveredManager = TranscriptionManager(appState: recoveredState, overlayPanel: OverlayPanel(), hotkeyManager: recoveredHotkey)
+ recoveredManager.start()
+ InputTarget.available = false
+ recoveredHotkey.onHotkeyEvent?(.prime)
+ RunLoop.current.run(until: Date().addingTimeInterval(0.1))
+ recoveredHotkey.onHotkeyEvent?(.start)
+ RunLoop.current.run(until: Date().addingTimeInterval(0.1))
+ recoveredHotkey.onHotkeyEvent?(.discard)
+ InputTarget.available = true
+ RunLoop.current.run(until: Date().addingTimeInterval(0.1))
+ DoubaoASRClient.latest?.onResult?("synthetic first activation words")
+ RunLoop.current.run(until: Date().addingTimeInterval(0.1))
+ recoveredHotkey.onHotkeyEvent?(.stop)
+ RunLoop.current.run(until: Date().addingTimeInterval(0.1))
+ DoubaoASRClient.latest?.onFinish?()
+ RunLoop.current.run(until: Date().addingTimeInterval(0.1))
+ PasteHelper.pending?(true)
+ precondition(PasteHelper.targetAvailable, "A primed session must use the recovered target on its first recording: state=\(recoveredState.recordingState), diagnostic=\(recoveredState.inputDiagnostic), last=\(recoveredState.lastTranscript)")
+ precondition(recoveredState.inputDiagnostic.contains("capture=recovered"))
+ recoveredManager.cancel()
+ print("PASS: actual transcription controller preserves focus recovery across prime/start and reports its capture diagnostic; no real input")
}
}
diff --git a/macos/Tests/Live/MicrophoneRouteCheck.swift b/macos/Tests/Live/MicrophoneRouteCheck.swift
new file mode 100644
index 0000000..2c3813b
--- /dev/null
+++ b/macos/Tests/Live/MicrophoneRouteCheck.swift
@@ -0,0 +1,79 @@
+import AppKit
+import AVFoundation
+
+/// Opt-in local capture: changes only injected device snapshots, never system settings.
+/// Counts PCM bytes in memory; no audio is saved or sent to a recognition service.
+@main struct MicrophoneRouteCheck {
+ @MainActor static func main() {
+ guard AVCaptureDevice.authorizationStatus(for: .audio) == .authorized else {
+ print("SKIP: microphone permission unavailable"); exit(77)
+ }
+ let hardware = AudioDevices.inputs()
+ guard let first = AudioDevices.resolve(preferred: "", inputs: hardware, defaultUID: AudioDevices.defaultInputUID()) else { print("SKIP: no input hardware"); exit(77) }
+ // A second UID over the same device also exercises engine replacement on one-mic Macs.
+ let second = hardware.first(where: { $0.id != first.id }) ?? AudioInputDevice(id: "fixture-secondary", name: first.name, audioID: first.audioID)
+ var inputs = [first, second], defaultUID = first.id
+ let audio = AudioCaptureManager(inputDevices: { inputs }, defaultInputUID: { defaultUID })
+ let lock = NSLock()
+ var bytes = 0
+ var failures = 0
+ audio.onAudioData = { data in lock.lock(); bytes += data.count; lock.unlock() }
+ audio.onError = { failures += 1 }
+ func received() -> Int { lock.lock(); defer { lock.unlock() }; return bytes }
+ Task { @MainActor in
+ func pause(_ seconds: Double) async { try? await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000)) }
+ @MainActor func expectInput(_ device: AudioInputDevice, _ label: String) async {
+ // Do not count buffers emitted by the old stream before recovery.
+ await pause(0.6)
+ let before = received()
+ for _ in 0..<50 {
+ if audio.activeDevice == device && received() > before { break }
+ await pause(0.1)
+ }
+ precondition(audio.activeDevice == device && received() > before && failures == 0, label)
+ print("PASS: \(label)")
+ }
+ do {
+ try audio.startCapture()
+ await expectInput(first, "initial system default produces PCM")
+ await pause(2.1) // Beyond the old startup-only recovery window.
+ defaultUID = second.id; audio.hardwareChanged()
+ await expectInput(second, "running capture follows default after startup")
+ audio.stopCapture()
+ try audio.startCapture(deviceID: first.id)
+ await expectInput(first, "explicit preference overrides system default")
+ inputs = [second]; audio.hardwareChanged()
+ await expectInput(second, "missing preferred input falls back without ending session")
+ inputs = [first, second]; audio.hardwareChanged()
+ await expectInput(first, "preferred input reconnects")
+ audio.stopCapture()
+ inputs = [second]
+ try audio.startCapture(deviceID: first.id)
+ await expectInput(second, "stale saved UID starts with available fallback")
+ inputs = []; audio.hardwareChanged()
+ // Temporary enumeration gaps should recover before the bounded retry expires.
+ await pause(0.35)
+ inputs = [second]; audio.hardwareChanged()
+ await expectInput(second, "transient missing-device snapshot recovers")
+ inputs = []; audio.hardwareChanged()
+ audio.stopCapture()
+ await pause(1.2)
+ precondition(audio.activeDevice == nil && failures == 0, "Stop must cancel pending recovery")
+ print("PASS: stop cancels pending recovery")
+ inputs = [second]
+ try audio.startCapture()
+ await expectInput(second, "new capture starts after cancelled recovery")
+ inputs = []; audio.hardwareChanged()
+ await pause(1.6)
+ precondition(audio.activeDevice == nil && failures == 1, "Persistent absence must report one bounded failure")
+ print("PASS: persistent absence reports one error")
+ print("PASS: live PCM with simulated hardware snapshots; physical unplug not tested; no audio saved or sent")
+ audio.stopCapture()
+ NSApp.terminate(nil)
+ } catch {
+ audio.stopCapture(); print("FAIL: capture could not start (\((error as NSError).code))"); exit(1)
+ }
+ }
+ NSApplication.shared.run()
+ }
+}
diff --git a/macos/Tests/Settings/AutoSaveCheck.swift b/macos/Tests/Settings/AutoSaveCheck.swift
index ad851d7..e4e45e4 100644
--- a/macos/Tests/Settings/AutoSaveCheck.swift
+++ b/macos/Tests/Settings/AutoSaveCheck.swift
@@ -52,8 +52,16 @@ struct AutoSaveCheck {
precondition(deviceModel.microphones.count == 1 && deviceModel.draft.microphoneID == usb.id
&& !deviceState.microphoneChecked && !deviceState.voiceChecked,
"Unplugging the selected device must preserve its UID and invalidate checks")
+ precondition(deviceModel.effectiveMicrophone == builtIn,
+ "Disconnected preference must fall back to the available input")
devices.append(usb); deviceModel.refreshMicrophones()
+ precondition(deviceModel.effectiveMicrophone == usb, "Reconnected preferred input must recover")
precondition(deviceModel.microphones.contains { $0.id == usb.id } && deviceModel.draft.microphoneID == usb.id)
+ precondition(AudioDevices.resolve(preferred: "", inputs: [builtIn, usb], defaultUID: usb.id) == usb)
+ precondition(AudioDevices.resolve(preferred: usb.id, inputs: [builtIn, usb], defaultUID: builtIn.id) == usb)
+ precondition(AudioDevices.resolve(preferred: usb.id, inputs: [builtIn], defaultUID: usb.id) == builtIn,
+ "A stale system default during unplug must still select an available input")
+ precondition(AudioDevices.resolve(preferred: usb.id, inputs: [], defaultUID: usb.id) == nil)
print("PASS: hardware listeners registered; simulated insert/remove/default changes refresh inputs and preserve selection")
let state = AppState()
let model = SettingsModel(state: state)
diff --git a/macos/Tests/Settings/check.sh b/macos/Tests/Settings/check.sh
index 69fb085..b835e27 100644
--- a/macos/Tests/Settings/check.sh
+++ b/macos/Tests/Settings/check.sh
@@ -10,3 +10,8 @@ xcrun swiftc -swift-version 5 -target "$(uname -m)-apple-macos13.0" \
-module-cache-path build/macos/module-cache \
"${sources[@]}" macos/Tests/Settings/AutoSaveCheck.swift -o build/macos/tests/autosave-check
build/macos/tests/autosave-check
+# Compile the opt-in microphone route check without recording audio in CI.
+xcrun swiftc -swift-version 5 -target "$(uname -m)-apple-macos13.0" \
+ -module-cache-path build/macos/module-cache \
+ macos/Sources/AudioDevices.swift macos/Sources/AudioCaptureManager.swift \
+ macos/Tests/Live/MicrophoneRouteCheck.swift -o build/macos/tests/microphone-route-check
diff --git a/macos/check.sh b/macos/check.sh
index 29e503f..52e6264 100755
--- a/macos/check.sh
+++ b/macos/check.sh
@@ -29,7 +29,20 @@ 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 \
+ macos/Sources/InputTargetCapture.swift macos/Sources/TranscriptionManager.swift macos/Tests/Input/RetryCheck.swift \
-o build/macos/tests/retry-check
build/macos/tests/retry-check
bash macos/Tests/Input/check-delivery.sh
+
+xcrun swiftc -swift-version 5 -target "$(uname -m)-apple-macos13.0" \
+ -module-cache-path build/macos/module-cache \
+ macos/Sources/InputTargetCapture.swift macos/Tests/Input/FocusCaptureCheck.swift \
+ -o build/macos/tests/focus-capture-check
+build/macos/tests/focus-capture-check
+
+xcrun swiftc -swift-version 5 -target "$(uname -m)-apple-macos13.0" \
+ -module-cache-path build/macos/module-cache \
+ macos/Sources/Strings.swift macos/Sources/PolishDefaults.swift macos/Sources/MacSettings.swift \
+ macos/Sources/ShortcutGesture.swift macos/Sources/HotkeyManager.swift macos/Tests/Input/KeyInterceptionCheck.swift \
+ -o build/macos/tests/key-interception-check
+build/macos/tests/key-interception-check