Skip to content

Doubao-powered voice input for Linux, Wayland and Omarchy

fix(input): cancel pending transcription and deliver at the current cursor (#89)

Leyangf4bd9c046abe
diff --git a/README.md b/README.md
index a3275eb..3ce804d 100644
--- a/README.md
+++ b/README.md
@@ -2,6 +2,8 @@
> **macOS development preview:** A native Swift menu-bar client supports Doubao web sign-in, official Volcengine and Deepgram recognition, optional polishing, configurable shortcuts, microphone selection and input recovery. See the [Mac build and usage guide](macos/README.zh-CN.md) (Chinese). No Developer ID signed or notarized Mac release is available yet.
+On macOS, dictation is delivered to the current cursor after the shortcut keys are released. Clipboard paste does not require the recording-time input field to remain focused. Auto mode uses the current accessible field when available, otherwise clipboard paste; Direct mode requires a current accessible input.
+
On macOS, closing the last settings or sign-in window keeps dictation available
from the menu bar while removing the app from the Dock and Cmd+Tab. Opening a
window restores both entries; minimized windows keep their Dock entry.
@@ -229,7 +231,8 @@ Your keyboard must report Fn as a Linux key; otherwise choose another key.
- Tap to start; tap again to finish and paste.
- 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.
+- On macOS, keys other than Escape during voice input finishes dictation without performing its original action, including Enter and shortcut chords. Escape cancels immediately during recording, transcription, polishing or pending input; cancelled recognition is never pasted. Their releases are swallowed as well. Double-tap sends Enter only while idle.
+- If two accidental taps leave a transcription pending, press Escape to cancel and record again immediately. In Linux portal mode, use **Cancel input** in the control center or tray instead.
- 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/README.zh-CN.md b/README.zh-CN.md
index 8865708..d9a6117 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -2,6 +2,8 @@
> **macOS 开发预览版**:已提供原生 Swift 菜单栏客户端,支持豆包网页登录、火山和 Deepgram 识别、可选润色、自定义快捷键、麦克风选择和文字恢复。构建、权限及功能范围见 [macOS 使用说明](macos/README.zh-CN.md)。尚未发布签名公证的 Mac 安装包。
+macOS 在快捷键释放后向当前光标输入文字。剪贴板粘贴不要求保持录音开始时的输入框;自动模式优先使用当前可识别的输入框,否则粘贴。直接输入模式需要当前存在可识别的输入框。
+
[官网](https://doubao-say.lifeos.md/zh/) · [English](README.md)
![豆包说在 Omarchy Linux 上运行的界面](images/readme-cn.jpeg)
@@ -167,6 +169,7 @@ Esc 可停止后续输入,但不能撤回已输入的文字;焦点变化时
如果键盘没有向 Linux 上报 Fn 按键,请选择其他键。
- 短按开始,再按一次结束并粘贴。
+- 误触两次后如果停在转写阶段,可按 Esc 立即取消,再重新录音;被取消的识别结果不会粘贴。Linux Portal 模式请使用控制中心或托盘的「取消输入」。macOS 的 Esc 在录音、转写、润色和等待输入期间均用于取消,其他按键仍用于结束并上屏。
- 使用 Fn 作为触发键时,录音期间按其他键也会结束并粘贴。Esc 仍用于取消;结束录音的按键仍会传给前台应用。
- 长按超过阈值开始说话,松开结束并粘贴。
- 可直接选择一个预设,或选择**录制快捷键…**来录制 Ctrl+Alt+Space 这样的组合键;任何时候只会生效一个快捷键。
diff --git a/macos/README.zh-CN.md b/macos/README.zh-CN.md
index 28545b7..9976dc4 100644
--- a/macos/README.zh-CN.md
+++ b/macos/README.zh-CN.md
@@ -19,7 +19,7 @@ open 'build/macos/arm64/Doubao Say.app'
2. “使用准备”顶部四个步骤均可点击切换;检查或录音进行时暂时禁用切换,完成设置仍需通过全部检查。设置会自动保存,无需点击保存按钮。允许麦克风访问,并从“启用全局快捷键”授予辅助功能权限。系统要求本人输入密码时在系统弹窗完成,不向应用填写系统密码。
3. 在“使用准备”中选择麦克风,先进行三秒本地检查,再进行五秒语音测试。语音测试会向已保存的识别服务发送音频,结果只显示在软件内,不粘贴,也不发送回车。全部检查完成后点击“完成设置”,后续打开应用仍显示设置窗。关闭最后一个设置或登录窗口后,应用保留菜单栏运行,并从 Dock 和 Cmd+Tab 隐藏;通过菜单栏或重新打开应用显示窗口时恢复。最小化窗口仍保留 Dock 入口。
4. 在目标应用的普通文本输入框中放好光标。默认 `Control+Option+空格`,可在“快捷键”中录制其他组合或单独修饰键;选键不使用麦克风。
-5. 短按切换录音;按住达到默认 350 毫秒后说话,松开结束。开始录音时可用默认 300 毫秒的双击识别阈值,可调整两项阈值或关闭双击。语音输入期间,其他按键(包括 `Esc`、回车、修饰键和快捷键组合)统一结束录音并上屏,不执行原有按键操作,也不额外发送回车。整个组合及其松开事件会被拦截,完成输入后恢复正常键盘操作。VibeKey 的按钮和旋钮也使用同一规则。非语音输入状态下,`Esc` 可关闭保留文字的浮窗,空闲时双击仍可发送回车。单次录音最多 60 秒。
+5. 短按切换录音;按住达到默认 350 毫秒后说话,松开结束。开始录音时可用默认 300 毫秒的双击识别阈值,可调整两项阈值或关闭双击。语音输入期间,其他按键(包括回车、修饰键和快捷键组合)统一结束录音并上屏,不执行原有按键操作,也不额外发送回车。整个组合及其松开事件会被拦截,完成输入后恢复正常键盘操作。VibeKey 的按钮和旋钮也使用同一规则。`Esc` 在录音、转写、润色和等待输入期间立即取消,随后可重新录音;被取消的识别结果不会上屏。非语音输入状态下,`Esc` 可关闭保留文字的浮窗,空闲时双击仍可发送回车。单次录音最多 60 秒。
麦克风列表会随设备插拔自动刷新,无需重新打开设置。也可从菜单栏“输入设备”直接选择麦克风或系统默认,切换后自动保存;录音、测试或输入处理中暂时禁用切换。选择“系统默认”时持续跟随系统输入设备;指定设备拔出后保留偏好,自动回退到系统默认或其他可用麦克风,重新接入后恢复使用。设置页显示实际可用的输入设备。录音中设备变化会重新连接音频流,保留当前识别会话;若短暂重试后仍无可用输入,才停止并提示错误。输入设备变化后需重新完成麦克风和语音检查。
@@ -41,7 +41,7 @@ ChatGPT 凭据使用本应用独立的 macOS 钥匙串条目,不借用 Codex
转写稳定、低于语音阈值并静音 1.2 秒后启动预润色。音量变化只暂停计时,文字变化才使旧请求失效,避免背景噪声反复发请求。结束录音后可复用同一段文字的预润色结果或仍在运行的请求;不同文字重新请求,旧返回不能上屏。
-每次润色最多五秒,包含网络等待。失败、超时、空返回、截断或无效流式响应均使用 ASR 原文,部分润色结果不自动上屏。最终润色期间,任意按键都会直接使用原文并上屏,按键本身被拦截;如需取消整个输入,可从菜单选择「取消输入」。浮窗显示润色状态和流式预览,保持输入框焦点。
+每次润色最多五秒,包含网络等待。失败、超时、空返回、截断或无效流式响应均使用 ASR 原文,部分润色结果不自动上屏。最终润色期间,除 `Esc` 外的任意按键都会直接使用原文并上屏,按键本身被拦截;如需取消整个输入,可按 `Esc` 或从菜单选择「取消输入」。浮窗显示润色状态和流式预览,保持输入框焦点。
## 文字恢复与隐私
diff --git a/macos/Sources/HotkeyManager.swift b/macos/Sources/HotkeyManager.swift
index 024d1c9..620947f 100644
--- a/macos/Sources/HotkeyManager.swift
+++ b/macos/Sources/HotkeyManager.swift
@@ -151,6 +151,15 @@ final class HotkeyManager {
}
if type == .keyUp, blockedKeys.remove(physicalCode) != nil { return nil }
if type == .flagsChanged && !modifierPressed, blockedModifiers.remove(physicalCode) != nil { return nil }
+ // Cancellation takes priority over the generic finish-on-any-key rule,
+ // including while ASR or polishing is still pending. Retain the key until
+ // release so neither repeats nor key-up escape into the target app.
+ if code == 53 && type == .keyDown && (active || shortcutDown || gesture.isPending) {
+ if blockedKeys.insert(physicalCode).inserted {
+ resetGesture(); onHotkeyEvent?(.cancel)
+ }
+ 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))
@@ -171,7 +180,6 @@ final class HotkeyManager {
if interceptingInput && firstPress && !draining { stopFromAuxiliaryKey() }
return nil
}
- if code == 53 && type == .keyDown && (active || shortcutDown || gesture.isPending) { resetGesture(); onHotkeyEvent?(.cancel); return nil }
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
diff --git a/macos/Sources/OverlayView.swift b/macos/Sources/OverlayView.swift
index 386ab17..afef097 100644
--- a/macos/Sources/OverlayView.swift
+++ b/macos/Sources/OverlayView.swift
@@ -89,7 +89,7 @@ struct OverlayView: View {
case .idle: return ""
case .starting: return L("Starting voice recognition…", "正在启动语音识别…")
case .recording: return L("Listening…", "正在聆听…")
- case .stopping: return L("Transcribing…", "正在转写…")
+ case .stopping: return L("Transcribing… · Esc to cancel", "正在转写… · Esc 取消")
case .polishing: return L("Polishing…", "润色中")
}
}
diff --git a/macos/Sources/PasteHelper.swift b/macos/Sources/PasteHelper.swift
index bf54faf..7bcc7dc 100644
--- a/macos/Sources/PasteHelper.swift
+++ b/macos/Sources/PasteHelper.swift
@@ -1,10 +1,12 @@
import AppKit
import ApplicationServices
-/// Only deliver to the exact accessible input element captured before recording.
+/// Track an accessible input, or the current cursor for clipboard-only delivery.
struct InputTarget {
let pid: pid_t
let element: AXUIElement
+ var cursorOnly = false
+ var cursorScope: Scope? = nil
enum Focus { case ready(InputTarget), unavailable, window, notEditable }
struct Scope: Equatable {
let pid: pid_t
@@ -44,7 +46,29 @@ struct InputTarget {
subrole as? String != kAXSecureTextFieldSubrole else { return .notEditable }
return .ready(InputTarget(pid: app.processIdentifier, element: element))
}
+ /// Custom editors may accept Command-V without exposing a text-field AX role.
+ static func captureCursor() -> InputTarget? {
+ guard AXIsProcessTrusted(), let app = NSWorkspace.shared.frontmostApplication,
+ app.processIdentifier != ProcessInfo.processInfo.processIdentifier else { return nil }
+ let application = AXUIElementCreateApplication(app.processIdentifier)
+ var value: CFTypeRef?
+ let status = AXUIElementCopyAttributeValue(application, kAXFocusedUIElementAttribute as CFString, &value)
+ let element: AXUIElement
+ if status == .success, let value, CFGetTypeID(value) == AXUIElementGetTypeID() {
+ element = unsafeBitCast(value, to: AXUIElement.self)
+ } else {
+ element = application
+ }
+ var subrole: CFTypeRef?
+ AXUIElementCopyAttributeValue(element, kAXSubroleAttribute as CFString, &subrole)
+ guard subrole as? String != kAXSecureTextFieldSubrole else { return nil }
+ return InputTarget(pid: app.processIdentifier, element: element, cursorOnly: true, cursorScope: scope())
+ }
func isCurrent() -> Bool {
+ if cursorOnly {
+ guard let current = Self.captureCursor() else { return false }
+ return current.pid == pid && current.cursorScope == cursorScope && CFEqual(current.element, element)
+ }
guard let current = InputTarget.capture() else { return false }
return current.pid == pid && CFEqual(current.element, element)
}
@@ -59,7 +83,7 @@ final class PasteHelper {
var failureMessage: String? {
switch failure {
case .permission: return L("Allow Accessibility access in System Settings.", "请在系统设置中允许辅助功能权限。")
- case .missingTarget: return L("No editable input field was focused when recording started.", "开始录音时未找到可编辑的输入框,请先点击输入框再录音。")
+ case .missingTarget: return L("No input target is available. Focus the destination and retry input.", "未找到输入目标,请点击要输入的位置后重试输入。")
case .targetChanged: return L("The focused input field changed during dictation.", "听写期间目标输入框发生了变化。")
case .modifiersHeld: return L("Release the shortcut keys before retrying input.", "快捷键尚未释放,请松开后重试输入。")
case .eventUnavailable: return L("Could not create the paste shortcut.", "无法发送粘贴快捷键。")
@@ -80,7 +104,7 @@ final class PasteHelper {
return method == "auto" && selectedTextWritable
}
func cancel() { generation = UUID() }
- func deliver(_ text: String, target: InputTarget?, method: String = "auto", sendEnter: Bool = false, completion: @escaping (Bool) -> Void) {
+ func deliver(_ text: String, target _: InputTarget?, method: String = "auto", sendEnter: Bool = false, completion: @escaping (Bool) -> Void) {
cancel()
failure = nil
usedClipboard = false
@@ -95,17 +119,20 @@ final class PasteHelper {
func attempt() {
guard token == self.generation else { return }
guard AXIsProcessTrusted() else { fail(.permission); return }
- guard let target = target else { fail(.missingTarget); return }
- guard target.isCurrent() else { fail(.targetChanged); return }
let flags = self.modifierFlags()
if !flags.intersection([.maskControl, .maskAlternate, .maskShift, .maskCommand, .maskSecondaryFn]).isEmpty {
guard Date() < deadline else { fail(.modifiersHeld); return }
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { attempt() }
return
}
+ // Resolve the destination at delivery time, after shortcut release.
+ // Clipboard input follows the current cursor, just like Command-V.
+ let target = method == "clipboard" ? InputTarget.captureCursor()
+ : (InputTarget.capture() ?? (method == "direct" ? nil : InputTarget.captureCursor()))
+ guard let target else { fail(.missingTarget); return }
var writable = DarwinBoolean(false)
let writableStatus = AXUIElementIsAttributeSettable(target.element, kAXSelectedTextAttribute as CFString, &writable)
- if Self.useAccessibilityInput(method: method,
+ if !target.cursorOnly && 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)"
@@ -124,7 +151,6 @@ final class PasteHelper {
item.data(forType: type).map { (type, $0) }
}
} ?? []
- guard target.isCurrent() else { fail(.targetChanged); return }
pasteboard.clearContents()
guard pasteboard.setString(text, forType: .string) else { fail(.clipboardUnavailable); return }
let changeCount = pasteboard.changeCount
@@ -143,7 +169,6 @@ final class PasteHelper {
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
diff --git a/macos/Sources/TranscriptionManager.swift b/macos/Sources/TranscriptionManager.swift
index 2a162ec..e96b902 100644
--- a/macos/Sources/TranscriptionManager.swift
+++ b/macos/Sources/TranscriptionManager.swift
@@ -155,6 +155,7 @@ final class TranscriptionManager {
func stopRecording() {
guard state.recordingState == .starting || state.recordingState == .recording else { return }
latency.stop(at: ProcessInfo.processInfo.systemUptime)
+ state.overlayStatus = "" // A listening preview must not hide the transcription cancellation hint.
setState(.stopping); audio.stopCapture(); client?.finishSending()
polisher.prepareFinal(text: rawText)
// Bound slow handshakes without authorizing delivery of incomplete text.
diff --git a/macos/Tests/Input/DeliveryCheck.swift b/macos/Tests/Input/DeliveryCheck.swift
index 787254b..156c0ab 100644
--- a/macos/Tests/Input/DeliveryCheck.swift
+++ b/macos/Tests/Input/DeliveryCheck.swift
@@ -3,7 +3,7 @@ import ApplicationServices
// Test the production delivery implementation with inert platform boundaries.
enum Fixture {
- static var trusted = true, current = true, writable = true
+ static var trusted = true, current = true, writable = true, cursorAvailable = true, fieldAvailable = true
static var writeStatus = AXError.success
static var writes: [String] = []
}
@@ -18,6 +18,9 @@ func AXUIElementSetAttributeValue(_ element: AXUIElement, _ attribute: CFString,
struct InputTarget {
let pid = ProcessInfo.processInfo.processIdentifier
let element = AXUIElementCreateApplication(ProcessInfo.processInfo.processIdentifier)
+ var cursorOnly = false
+ static func capture() -> InputTarget? { Fixture.fieldAvailable ? InputTarget() : nil }
+ static func captureCursor() -> InputTarget? { Fixture.cursorAvailable ? InputTarget(cursorOnly: true) : nil }
func isCurrent() -> Bool { Fixture.current }
}
final class NSPasteboard {
@@ -60,17 +63,19 @@ enum HotkeyManager {
precondition(result == true && Fixture.writes == ["synthetic words"] && helper.failure == nil)
Fixture.writes = []; Fixture.trusted = false; send()
precondition(result == false && helper.failure == .permission && Fixture.writes.isEmpty)
- Fixture.trusted = true; send(nil)
+ Fixture.trusted = true; Fixture.fieldAvailable = false; Fixture.cursorAvailable = false; send(nil)
precondition(result == false && helper.failure == .missingTarget)
+ Fixture.fieldAvailable = true; Fixture.cursorAvailable = true
Fixture.current = false; send()
- precondition(result == false && helper.failure == .targetChanged && Fixture.writes.isEmpty)
+ precondition(result == true && Fixture.writes == ["synthetic words"], "Delivery must resolve the current field instead of rejecting the recording-time target")
+ Fixture.writes = []
Fixture.current = true; flags = .maskSecondaryFn; send()
precondition(result == nil && Fixture.writes.isEmpty, "Fn must be released before insertion")
- flags = []; wait(0.15)
+ flags = []; wait(0.4)
precondition(result == true && Fixture.writes == ["synthetic words"], "Release must insert exactly once")
Fixture.writes = []; flags = .maskControl; send(); wait(1.15)
precondition(result == false && helper.failure == .modifiersHeld && Fixture.writes.isEmpty)
- send(); helper.cancel(); flags = []; wait(0.15)
+ send(); helper.cancel(); flags = []; wait(0.4)
precondition(result == nil && Fixture.writes.isEmpty, "Cancellation must prevent late insertion")
Fixture.writeStatus = .cannotComplete; send()
precondition(result == false && helper.failure == .directUnavailable && Fixture.writes.count == 1 && CGEvent.posted == 0 && NSPasteboard.general.pastedTexts.isEmpty,
@@ -97,17 +102,29 @@ enum HotkeyManager {
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)
+ helper.cancel(); wait(0.4)
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 = false; wait(0.4)
+ precondition(result == true && CGEvent.posted == 6, "Clipboard paste must follow current focus")
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,
+ NSPasteboard.general.clearContents(); wait(0.4)
+ precondition(result == false && helper.failure == .clipboardChanged && CGEvent.posted == 6,
"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")
+ Fixture.cursorAvailable = true; Fixture.fieldAvailable = false
+ let posted = CGEvent.posted
+ send(nil); wait(0.4)
+ precondition(result == true && helper.usedClipboard && Fixture.writes.isEmpty && CGEvent.posted == posted + 2,
+ "Missing AX text fields must paste once at the current cursor, never write an arbitrary AX element")
+ helper.deliver("direct only", target: nil, method: "direct") { result = $0 }
+ precondition(result == false && helper.failure == .missingTarget)
+ send(nil); Fixture.current = false; wait(0.4)
+ precondition(result == true && CGEvent.posted == posted + 4)
+ Fixture.current = true
+ send(nil); helper.cancel(); wait(0.4)
+ precondition(result == nil && CGEvent.posted == posted + 4)
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/KeyInterceptionCheck.swift b/macos/Tests/Input/KeyInterceptionCheck.swift
index 4612291..c1e1100 100644
--- a/macos/Tests/Input/KeyInterceptionCheck.swift
+++ b/macos/Tests/Input/KeyInterceptionCheck.swift
@@ -8,7 +8,7 @@ import AppKit
}
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] {
+ for code: UInt16 in [0, 36, 49, 48, 51, 123, 122] {
let manager = HotkeyManager()
var settings = MacSettings(); settings.shortcut = shortcut
manager.configure(settings)
@@ -60,10 +60,21 @@ import AppKit
"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)
+ for recording in [true, false] {
+ let cancellable = HotkeyManager()
+ var cancels = 0
+ cancellable.onHotkeyEvent = { if case .cancel = $0 { cancels += 1 } }
+ cancellable.setEscapeHandlingEnabled(true, recording: recording, interceptKeys: true)
+ precondition(cancellable.handle(.keyDown, key(53, true)) == nil)
+ precondition(cancels == 1, "Escape must cancel recording and transcribing immediately")
+ precondition(cancellable.handle(.keyDown, key(53, true)) == nil && cancels == 1,
+ "Held Escape must cancel only once")
+ cancellable.setEscapeHandlingEnabled(false)
+ precondition(cancellable.handle(.keyUp, key(53, false)) == nil,
+ "Cancelled Escape release must not reach the foreground")
+ precondition(cancellable.handle(.keyDown, key(0, true)) != nil,
+ "Typing must resume immediately after cancellation")
+ }
manager.setEscapeHandlingEnabled(true, recording: true)
let synthetic = key(9, true, flags: .maskCommand)
synthetic.setIntegerValueField(.eventSourceUserData, value: HotkeyManager.syntheticMarker)
@@ -74,6 +85,7 @@ import AppKit
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")
+ precondition(manager.handle(.keyUp, key(53, false)) == nil)
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,
diff --git a/macos/Tests/Input/RetryCheck.swift b/macos/Tests/Input/RetryCheck.swift
index 24251ad..f617f58 100644
--- a/macos/Tests/Input/RetryCheck.swift
+++ b/macos/Tests/Input/RetryCheck.swift
@@ -162,6 +162,30 @@ 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 cancelledState = AppState(), cancelledHotkey = HotkeyManager()
+ let cancelledManager = TranscriptionManager(appState: cancelledState, overlayPanel: OverlayPanel(), hotkeyManager: cancelledHotkey)
+ cancelledManager.start()
+ cancelledHotkey.onHotkeyEvent?(.start)
+ RunLoop.current.run(until: Date().addingTimeInterval(0.1))
+ let oldTransport = DoubaoASRClient.latest!
+ cancelledState.overlayStatus = "Preview ready · finish to input"
+ cancelledHotkey.onHotkeyEvent?(.stop)
+ RunLoop.current.run(until: Date().addingTimeInterval(0.1))
+ precondition(cancelledState.recordingState == .stopping)
+ precondition(cancelledState.overlayStatus.isEmpty, "A stale listening preview must not hide the stopping cancellation hint")
+ cancelledHotkey.onHotkeyEvent?(.cancel)
+ RunLoop.current.run(until: Date().addingTimeInterval(0.1))
+ precondition(cancelledState.recordingState == .idle && !cancelledState.inputPending)
+ cancelledHotkey.onHotkeyEvent?(.start)
+ RunLoop.current.run(until: Date().addingTimeInterval(0.1))
+ let pasteCount = PasteHelper.events.count
+ oldTransport.onResult?("discarded words"); oldTransport.onFinish?(); oldTransport.onError?()
+ RunLoop.current.run(until: Date().addingTimeInterval(0.1))
+ precondition(cancelledState.isRecording && cancelledState.transcriptionText.isEmpty && cancelledState.errorMessage == nil,
+ "Cancelled recognition callbacks must not mutate a new recording")
+ precondition(PasteHelper.events.count == pasteCount, "Cancelled text must never be pasted")
+ cancelledManager.cancel()
+ print("PASS: cancelled finalization immediately allows another recording and rejects stale ASR callbacks")
let recoveredState = AppState(), recoveredHotkey = HotkeyManager()
let recoveredManager = TranscriptionManager(appState: recoveredState, overlayPanel: OverlayPanel(), hotkeyManager: recoveredHotkey)
recoveredManager.start()
diff --git a/src/doubao_input/ui/overlay.py b/src/doubao_input/ui/overlay.py
index 5ce3a46..e229787 100644
--- a/src/doubao_input/ui/overlay.py
+++ b/src/doubao_input/ui/overlay.py
@@ -20,6 +20,7 @@ from doubao_input.i18n import tr
from doubao_input.ui.voice_motion import VoiceMotion
from doubao_input.ui.waveform import draw_waveform
from doubao_input.product import VERSION
+from doubao_input.trigger.backend import trigger_backend
import cairo
import gi
@@ -259,11 +260,13 @@ class Overlay:
self._state = value
if self._css_provider is not None:
self._load_css()
- if not self._text and self._polishing_since is None:
+ if (not self._text or value == "stopping") and self._polishing_since is None:
state_status = {
"starting": tr("Starting voice recognition…", "正在启动语音识别…"),
"recording": tr("Listening…", "正在聆听…"),
- "stopping": tr("Transcribing…", "正在转写…"),
+ "stopping": (tr("Transcribing… · Cancel input to stop", "正在转写… · 可取消输入")
+ if trigger_backend() == "portal" else
+ tr("Transcribing… · Esc to cancel", "正在转写… · Esc 取消")),
}.get(value)
if state_status:
self._status_text = state_status
diff --git a/tests/unit/test_overlay_status.py b/tests/unit/test_overlay_status.py
new file mode 100644
index 0000000..7de885a
--- /dev/null
+++ b/tests/unit/test_overlay_status.py
@@ -0,0 +1,29 @@
+"""Waiting for recognition must expose the available cancellation action."""
+from unittest import TestCase
+from unittest.mock import Mock, patch
+
+from doubao_input.i18n import set_language
+from doubao_input.ui.overlay import Overlay
+
+
+class OverlayStatusTest(TestCase):
+ def test_transcribing_hint_is_visible_with_or_without_partial_text(self):
+ self.addCleanup(set_language, "en")
+ for language, esc, portal in (
+ ("en", "Transcribing… · Esc to cancel", "Transcribing… · Cancel input to stop"),
+ ("zh_CN", "正在转写… · Esc 取消", "正在转写… · 可取消输入"),
+ ):
+ set_language(language)
+ for backend, expected in (("evdev", esc), ("portal", portal)):
+ for text in ("", "synthetic partial words"):
+ with self.subTest(language=language, backend=backend, text=bool(text)):
+ overlay = Overlay.__new__(Overlay)
+ overlay._css_provider = None
+ overlay._polishing_since = None
+ overlay._text = text
+ overlay._refresh_label = Mock()
+ with patch("doubao_input.ui.overlay.trigger_backend", return_value=backend):
+ overlay._apply_state("stopping")
+ self.assertEqual(overlay._status_text, expected)
+ self.assertEqual(overlay._text, text)
+ overlay._refresh_label.assert_called_once_with()
diff --git a/tests/unit/test_transcription_sessions.py b/tests/unit/test_transcription_sessions.py
index c69ce92..fe076a3 100644
--- a/tests/unit/test_transcription_sessions.py
+++ b/tests/unit/test_transcription_sessions.py
@@ -5,6 +5,35 @@ from doubao_input.doubao.transcription import TranscriptionManager
class TranscriptionSessionTest(TestCase):
+ def test_cancel_during_finalization_releases_session_and_ignores_late_results(self):
+ manager = self.manager()
+ manager.app_state.login_status = LoginStatus.LOGGED_IN
+ manager.credential_store = Mock()
+ manager.on_paste = Mock()
+ manager.on_overlay_hide = Mock()
+ manager._later = Mock(return_value=123)
+ manager.app_state.recording_state = RecordingState.RECORDING
+ manager._stop_recording()
+ old_result, old_finish = manager.asr_client.on_result, manager.asr_client.on_finish
+ pending = []
+ with patch("doubao_input.doubao.transcription.GLib.source_remove"), patch(
+ "doubao_input.doubao.transcription.GLib.idle_add",
+ side_effect=lambda callback, *args: pending.append((callback, args))):
+ manager.handle_cancel()
+ self.assertEqual(manager.app_state.recording_state, RecordingState.IDLE)
+ self.assertFalse(manager.awaiting_final_result)
+ self.assertIsNone(manager.safety_timer_id)
+ manager.on_overlay_hide.assert_called_once()
+ manager.handle_toggle()
+ self.assertEqual(manager.app_state.recording_state, RecordingState.STARTING)
+ old_result("discarded words")
+ old_finish()
+ for callback, args in pending:
+ callback(*args)
+ self.assertEqual(manager.app_state.transcription_text, "")
+ self.assertEqual(manager.app_state.recording_state, RecordingState.STARTING)
+ manager.on_paste.assert_not_called()
+
def test_official_backend_uses_its_credential_store_without_web_login(self):
client, store = Mock(), Mock()
credentials = object()
diff --git a/tests/unit/test_trigger_controller.py b/tests/unit/test_trigger_controller.py
index 0f86f6a..7c0973a 100644
--- a/tests/unit/test_trigger_controller.py
+++ b/tests/unit/test_trigger_controller.py
@@ -37,6 +37,15 @@ class TriggerControllerTest(TestCase):
def aux(self, action, pressed=True):
self.readers[-1].callbacks["on_aux"](action, pressed)
+ def test_escape_cancels_while_waiting_for_final_transcription(self):
+ # No longer recording, but recognition is still pending.
+ self.recording_active = False
+ self.edge(1, True)
+ self.edge(1, False)
+ self.cancel.assert_called_once_with()
+ self.stop.assert_not_called()
+ self.toggle.assert_not_called()
+
def test_capture_only_returns_after_release_and_restores_listener(self):
result = Mock()
self.control.begin_capture(result)