Skip to content

Doubao-powered voice input for Linux, Wayland and Omarchy

feat: 发布 1.8.0 润色、通用输入与设置改进 (#82)

Leyang031d23e79bf1
diff --git a/README.md b/README.md
index 0b08ff4..f46f221 100644
--- a/README.md
+++ b/README.md
@@ -91,6 +91,14 @@ the stars static.
Turn on the **Voice polishing · Experimental** switch on the Trigger key page to configure an
OpenAI-compatible Base URL, API key, model and separate Chinese/English prompts.
+In the Linux GTK client, the polishing service can also be set to **ChatGPT plan**.
+Use **Continue with ChatGPT** to authorize Doubao Say, choose an account-specific model,
+then enable polishing. Account selection, disconnect, model refresh and **Manage usage**
+are available in the same panel. Credentials stay in an owner-only local store;
+the existing API endpoint, key and model settings are preserved. This option powers
+text polishing, while speech recognition continues through the selected speech service.
+The five-second original-text fallback also applies to connection, quota and renewal failures.
+The independent macOS development preview does not yet include this connection option.
Doubao Say selects a prompt from each transcript's dominant language. The bundled prompts remove
filler words and false starts, improves punctuation and organization, preserves
meaning, and can be edited or restored to its default.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 0e00285..f85f4d3 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -72,6 +72,8 @@ API Key 保存在 `~/.config/doubao-say/deepgram_api_key`(或对应的
中文与英文 Prompt;应用会根据每次转写的主要语言自动选择。内置 Prompt 会去除口水词、重复和口误,改善标点与结构,同时保留原意;用户可
自行修改,也可一键恢复默认内容。
+Linux GTK 客户端也可将“润色服务”设为 **ChatGPT 套餐**。点击 **Continue with ChatGPT**,授权豆包说使用套餐,选择当前账号可用的模型后开启润色。同一面板提供账号切换、退出连接、模型刷新和“管理用量”。凭据保存在仅限当前用户读取的本机独立文件中,原有 API 地址、密钥和模型设置分别保留。它只负责文字润色,语音识别继续使用已选服务;连接、额度或续期异常仍按五秒上限回退原文。独立的 macOS 开发预览版尚未包含此连接入口。
+
默认提示词会结合整段语义纠正平翘舌、前后鼻音及 n/l、f/h 等口音造成的明确近音误识别;有歧义时保留原文,不凭近音猜改姓名、数字或否定表达。更新会升级旧默认提示词,保留自定义内容。
明确按“第一、第二、第三”等分点说出的内容会整理成 Markdown 编号列表,每项单独一行;日期、排名和次数等普通叙述不强制转为列表。
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index 1ce7c4b..e7ebd71 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -1,21 +1,21 @@
-# Doubao Say 1.7.0
+# Doubao Say 1.8.0
-## Personal speech evaluation
+## ChatGPT polishing
-Mac and Linux now provide an in-app speech evaluation page. Record locally, review what you actually said, then compare the same recording with raw official ASR, personal hotwords and optional polishing. Review character errors, target terms, protected-term loss, failed samples and replay timings. Starting comparison explicitly uploads recordings to your configured paid official ASR. Reference text is only used for scoring and never becomes vocabulary or enters recognition requests. Drafts save automatically; recordings remain until deleted.
+Linux now supports ChatGPT as a polishing provider alongside the existing API-based providers. Recognition and polishing remain separate, and original recognition text stays available for review.
-## Selected corrections and input timings
+## Mac input recovery
-Select a wrong term to fill the correction form, review the exact occurrence replacement and confirm before it becomes memory. Original recognition and polishing output remain available. Future polishing uses confirmed corrections as contextual references. Input history shows recognition, remaining polishing, delivery and total waiting time after recording stops. Mac computes evaluation statistics in the background and reads timings in batches.
+Automatic input chooses direct accessibility insertion when the focused field supports it, otherwise clipboard paste. All applications follow the same capability-based rules. Explicit clipboard and direct-input choices remain available; existing preferences are retained. Failed delivery keeps text visible with a specific reason and supports retry. Shortcut release checks include Fn. If text was entered but Enter could not be sent, the message distinguishes those outcomes to avoid duplicate retries.
-## Input reliability
+## Settings and devices
-API-key drafts survive saves and provider changes across onboarding and settings. Polishing requests support cancellation during connection, TLS and response reads, reject redirects and incomplete output, and free the final request worker after timeout. Recording, retry delivery, microphone checks, evaluation and updates are coordinated. Mac synthetic paste shortcuts carry an event marker to prevent feedback into voice triggers.
+Opening the Mac app shows settings. Setup steps can be selected independently, successful checks show green ticks, and signed-in Doubao sessions hide the login action. Microphone lists refresh on device and default-input changes, with quick switching from the menu bar. Update availability appears beside the settings sidebar entry. Recent-text editing includes internal padding to keep the first line visible.
## Downloads and verification
-Developer ID signed, Apple-notarized Mac DMGs are available for Apple Silicon and Intel. Linux app/plugin archives support Python 3.11–3.14. Settings, login data, vocabulary and history are retained. SHA256SUMS covers all packages; update.json is the public update source.
+Developer ID signed, Apple-notarized DMGs are provided for Apple Silicon and Intel. Linux app and plugin archives support Python 3.11–3.14. SHA256SUMS and update.json cover the release packages.
-Automated verification uses synthetic credentials, recordings and loopback network services. It covers protocol framing, selected corrections, scoring, credential persistence, cancellation, input state transitions and native interfaces. Actual personal-accent accuracy, competitor parity, physical microphones, cross-application input and Intel hardware behavior have not been established by these checks.
+Automated checks cover input recovery, capability routing, shortcut-release timing, settings persistence, device-change handling and network protocol behavior. A real cmux 0.65.1 receiver accepted three synthetic text samples exactly once without changing the clipboard. That check did not establish physical-hotkey behavior, microphone/ASR accuracy, other applications or Intel hardware behavior.
-[Full changes](https://github.com/quanru/doubao-say/compare/v1.6.0...v1.7.0)
+[Full changes](https://github.com/quanru/doubao-say/compare/v1.7.0...v1.8.0)
diff --git a/debian/changelog b/debian/changelog
index 9e43f86..095454e 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,10 @@
+doubao-say (1.8.0-1) noble; urgency=medium
+
+ * Add ChatGPT polishing and its JWT verification dependencies.
+ * Improve input recovery, settings and microphone handling on macOS.
+
+ -- doubao-say contributors <[email protected]> Wed, 14 Oct 2026 08:00:00 +0800
+
doubao-say (1.7.0-1) noble; urgency=medium
* Add personal speech evaluation, selected corrections and input timings.
diff --git a/debian/control b/debian/control
index f56e7ae..a8ba0cb 100644
--- a/debian/control
+++ b/debian/control
@@ -16,6 +16,8 @@ Depends:
python3-cairo,
python3-websockets,
python3-evdev,
+ python3-jwt,
+ python3-cryptography,
gir1.2-gtk-4.0,
gir1.2-webkit-6.0,
libgtk-4-1,
diff --git a/macos/README.zh-CN.md b/macos/README.zh-CN.md
index 0b9ec1f..1fd66a5 100644
--- a/macos/README.zh-CN.md
+++ b/macos/README.zh-CN.md
@@ -1,6 +1,6 @@
-# 豆包说 macOS 开发预览版
+# 豆包说 macOS
-独立的 Swift 菜单栏应用,要求 macOS 13 及以上。界面默认英文,可选择简体中文或跟随系统。Mac 版提供与 Linux 版对应的识别服务、润色、录音手势、设置与文字恢复功能;权限、设备和输入接口使用 macOS 原生实现。逐项范围与验收边界见 [功能对照](PARITY.zh-CN.md)。尚未公开发布。
+独立的 Swift 菜单栏应用,要求 macOS 13 及以上。界面默认英文,可选择简体中文或跟随系统。Mac 版提供与 Linux 版对应的识别服务、润色、录音手势、设置与文字恢复功能;权限、设备和输入接口使用 macOS 原生实现。逐项范围与验收边界见 [功能对照](PARITY.zh-CN.md)。已提供 Developer ID 签名、Apple 公证的发行安装包。
## 构建与运行
@@ -15,12 +15,14 @@ open 'build/macos/arm64/Doubao Say.app'
## 首次使用与设置
-1. 首次启动会打开“设置”,也可从菜单栏波形图标打开。在“识别服务”中选择豆包账号、火山引擎官方 API 或 Deepgram Nova-3(英语)。豆包使用登录窗口;官方服务填写自己的 API Key,可先测试连接。火山资源 `volc.seedasr.sauc.duration` 已内置,不需要 App ID。Deepgram 使用美式英语、标点和智能格式化。
-2. 设置会自动保存,无需点击保存按钮。允许麦克风访问,并从“启用全局快捷键”授予辅助功能权限。系统要求本人输入密码时在系统弹窗完成,不向应用填写系统密码。
-3. 在“使用准备”中选择麦克风,先进行三秒本地检查,再进行五秒语音测试。语音测试会向已保存的识别服务发送音频,结果只显示在软件内,不粘贴,也不发送回车。全部检查完成后点击“完成设置”,后续启动不再自动打开使用准备。
+1. 打开应用会显示“设置”和 Dock 图标;已运行时再次打开也会恢复设置窗。关闭设置窗后仍可使用菜单栏和全局快捷键。在“识别服务”中选择豆包账号、火山引擎官方 API 或 Deepgram Nova-3(英语)。豆包使用登录窗口;官方服务填写自己的 API Key,可先测试连接。火山资源 `volc.seedasr.sauc.duration` 已内置,不需要 App ID。Deepgram 使用美式英语、标点和智能格式化。
+2. “使用准备”顶部四个步骤均可点击切换;检查或录音进行时暂时禁用切换,完成设置仍需通过全部检查。设置会自动保存,无需点击保存按钮。允许麦克风访问,并从“启用全局快捷键”授予辅助功能权限。系统要求本人输入密码时在系统弹窗完成,不向应用填写系统密码。
+3. 在“使用准备”中选择麦克风,先进行三秒本地检查,再进行五秒语音测试。语音测试会向已保存的识别服务发送音频,结果只显示在软件内,不粘贴,也不发送回车。全部检查完成后点击“完成设置”,后续打开应用仍显示设置窗。
4. 在目标应用的普通文本输入框中放好光标。默认 `Control+Option+空格`,可在“快捷键”中录制其他组合或单独修饰键;选键不使用麦克风。
5. 短按切换录音;按住达到默认 350 毫秒后说话,松开结束。开启“双击发送回车”时,短按需等待默认 300 毫秒确认,双击结束录音并在输入后发送回车,空闲时双击发送回车。可调整两项阈值或关闭双击。Fn 作为触发键时,其他按键也可结束当前录音。`Esc` 取消,单次最多 60 秒。
+麦克风列表会随设备插拔自动刷新,无需重新打开设置。也可从菜单栏“输入设备”直接选择麦克风或系统默认,切换后自动保存;录音、测试或输入处理中暂时禁用切换。选择“系统默认”时跟随系统输入设备;指定设备拔出后保留选择并提示不可用,重新接入后恢复显示。输入设备变化后需重新完成麦克风和语音检查。
+
按下触发键后,先在内存保存最多三秒本地预录音,确认单击或长按后再发送到识别服务。双击或取消会丢弃尚未确认的音频。设置修改后自动保存,录音和检查期间暂缓生效,结束后自动应用;已有网页登录、语言和自动粘贴选择保留。
“通用”中可选择麦克风、剪贴板或辅助功能直接输入、登录时启动、减少动态效果和四种波纹样式。“快捷键”还支持 Vibekey AU05 接收器的三键、两种旋转方向和旋钮按下映射;接收器支持默认关闭。登录时启动通过 macOS 登录项管理,可能需要在系统设置允许;注册失败会明确报错并回滚,不将失败显示为已保存。
@@ -41,9 +43,11 @@ open 'build/macos/arm64/Doubao Say.app'
输入前核对前台进程和原辅助功能输入元素,并等待快捷键修饰键松开。密码框不自动输入。输入目标变化或直接输入不可用时,文字保留在软件内。剪贴板在粘贴后延迟恢复,期间有新复制内容时不恢复;部分应用异步读取剪贴板可能晚于恢复时间。输入和回车前分别检查目标,但系统事件仍存在短暂竞争窗口,需要完全手动控制时关闭自动粘贴。
+新配置默认使用“自动选择”:根据目标输入框的能力选择方式,支持辅助功能文字插入时直接写入,否则使用剪贴板;不按应用名称区别处理。已有配置保留原来的选择,手动选择剪贴板或直接输入时严格使用该方式。直接写入失败后保留文字,不自动再次粘贴,以免重复输入。输入前等待录音快捷键释放(包括 Fn),并检查目标输入框是否仍一致。输入失败时浮窗保留文字和具体原因,可从菜单选择“三秒后重试输入”;成功后清除失败提示。
+
普通听写的音频发送到所选识别服务,不保存本地录音文件。“语音评测”中主动录制的样本会保存到本机,直到手动删除;点击“开始对比”后才上传样本。润色启用后,整段文字及停顿预览会发送到配置的接口;识别和模型用量由相应服务商向你的账号计费。会话和 API Key 分别保存在应用专属 macOS 钥匙串条目,登录 WebView 使用临时网站数据存储。偏好不包含凭证;可编辑的单条最近文字退出后消失,但完成的听写另存本机 30 天历史,可暂停或清空。诊断复制不包含转写、Cookie、账号或设备标识。
-更新检查查询项目 GitHub 最新稳定发行版,间隔 24 小时,也可手动检查。在“设置 → 更新”中点击下载并安装后,应用会下载适配当前架构的 Mac 更新包,核对哈希、开发者签名、公证和应用标识,再安装并重启。下载期间可以取消;检查更新本身不会静默安装。没有合格的 Mac 更新包时,可打开发行页查看,不会把 Linux 归档当成 Mac 安装包。
+更新检查查询项目 GitHub 最新稳定发行版,间隔 24 小时,也可手动检查。有新版时,左侧“软件更新”旁显示红点;确认已是最新版后红点消失。在“设置 → 更新”中点击下载并安装后,应用会下载适配当前架构的 Mac 更新包,核对哈希、开发者签名、公证和应用标识,再安装并重启。下载期间可以取消;检查更新本身不会静默安装。没有合格的 Mac 更新包时,可打开发行页查看,不会把 Linux 归档当成 Mac 安装包。
## 验证与分发
diff --git a/macos/Sources/AudioDevices.swift b/macos/Sources/AudioDevices.swift
index 2f18ddb..2881dd9 100644
--- a/macos/Sources/AudioDevices.swift
+++ b/macos/Sources/AudioDevices.swift
@@ -7,6 +7,15 @@ struct AudioInputDevice: Identifiable {
let audioID: AudioDeviceID
}
enum AudioDevices {
+ static func defaultInputUID() -> String? {
+ var address = AudioObjectPropertyAddress(mSelector: kAudioHardwarePropertyDefaultInputDevice,
+ mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMain)
+ var id = AudioDeviceID(0)
+ var size = UInt32(MemoryLayout<AudioDeviceID>.size)
+ guard AudioObjectGetPropertyData(AudioObjectID(kAudioObjectSystemObject), &address, 0, nil, &size, &id) == noErr,
+ id != kAudioObjectUnknown else { return nil }
+ return string(id, selector: kAudioDevicePropertyDeviceUID)
+ }
static func inputs() -> [AudioInputDevice] {
var address = AudioObjectPropertyAddress(mSelector: kAudioHardwarePropertyDevices, mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMain)
var size: UInt32 = 0
@@ -29,3 +38,28 @@ enum AudioDevices {
return value?.takeUnretainedValue() as String?
}
}
+
+/// Observe hardware changes without opening an input stream or requesting microphone access.
+final class AudioDeviceMonitor {
+ private let listener: AudioObjectPropertyListenerBlock
+ private(set) var registeredSelectors: [AudioObjectPropertySelector] = []
+ init(onChange: @escaping @MainActor () -> Void) {
+ listener = { _, _ in Task { @MainActor in onChange() } }
+ for selector in [kAudioHardwarePropertyDevices, kAudioHardwarePropertyDefaultInputDevice] {
+ var address = Self.address(selector)
+ if AudioObjectAddPropertyListenerBlock(AudioObjectID(kAudioObjectSystemObject), &address, .main, listener) == noErr {
+ registeredSelectors.append(selector)
+ }
+ }
+ }
+ deinit {
+ for selector in registeredSelectors {
+ var address = Self.address(selector)
+ AudioObjectRemovePropertyListenerBlock(AudioObjectID(kAudioObjectSystemObject), &address, .main, listener)
+ }
+ }
+ private static func address(_ selector: AudioObjectPropertySelector) -> AudioObjectPropertyAddress {
+ AudioObjectPropertyAddress(mSelector: selector, mScope: kAudioObjectPropertyScopeGlobal,
+ mElement: kAudioObjectPropertyElementMain)
+ }
+}
diff --git a/macos/Sources/DoubaoSayApp.swift b/macos/Sources/DoubaoSayApp.swift
index fef03e4..0d1ecfc 100644
--- a/macos/Sources/DoubaoSayApp.swift
+++ b/macos/Sources/DoubaoSayApp.swift
@@ -27,7 +27,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
private let state = AppState.shared
func applicationDidFinishLaunching(_ notification: Notification) {
- NSApp.setActivationPolicy(.accessory)
+ NSApp.setActivationPolicy(.regular)
overlay = OverlayPanel(appState: state)
if CommandLine.arguments.contains("--smoke-test") { smokeTest(); return }
if CommandLine.arguments.contains("--settings-smoke-test") { settingsSmokeTest(); return }
@@ -83,8 +83,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
? L("Update completed: ", "更新完成:") + current
: L("The update did not complete. You are still using the previous version; the updater log is kept beside the staged app.", "上次更新未完成,仍在使用旧版本;更新日志保存在待安装应用旁。")
settingsWindow.model.selectedTab = "updates"; settingsWindow.show()
- } else if !SettingsStore.shared.value.onboardingComplete { settingsWindow.show() }
+ } else { showInitialSettings() }
}
+ private func showInitialSettings() { settingsWindow.show() }
+ func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
+ settingsWindow?.show()
+ return true
+ }
+ func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false }
func applicationWillTerminate(_ notification: Notification) {
personalCleanup?.invalidate()
transcription?.cancel(); hotkey?.stop(); web?.destroyWebView(); settingsWindow?.close(); updates.cancel(); updateInstaller.cancel(); receiver.stop()
@@ -101,8 +107,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
if let error = state.errorMessage { add(error, nil).isEnabled = false }
menu.addItem(.separator())
add(L("Settings…", "设置…"), #selector(showSettings), ",")
+ let input = add(L("Input device", "输入设备"), nil)
+ input.submenu = microphoneMenu(devices: AudioDevices.inputs(), selected: SettingsStore.shared.value.microphoneID,
+ canSwitch: transcription.canInstallUpdate && !settingsWindow.model.setupBusy)
add(SettingsStore.shared.value.provider.name, nil).isEnabled = false
- if SettingsStore.shared.value.provider == .doubao { add(L("Sign in to Doubao…", "登录豆包…"), #selector(showLogin)) }
+ if SettingsStore.shared.value.provider == .doubao && state.loginStatus != .loggedIn {
+ add(L("Sign in to Doubao…", "登录豆包…"), #selector(showLogin))
+ }
if state.loginStatus == .loggedIn { add(L("Sign out", "退出登录"), #selector(logout)) }
add(L("Copy last result", "复制最近结果"), #selector(copyLast)).isEnabled = !state.lastTranscript.isEmpty
add(L("Retry input in 3 seconds", "三秒后重试输入"), #selector(retryLast)).isEnabled = !state.lastTranscript.isEmpty && state.recordingState == .idle && !state.inputPending && !state.evaluationBusy
@@ -128,6 +139,31 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
menu.addItem(.separator())
add(L("Quit Doubao Say", "退出豆包说"), #selector(quit), "q")
}
+ private func microphoneMenu(devices: [AudioInputDevice], selected: String, canSwitch: Bool) -> NSMenu {
+ let menu = NSMenu(); menu.autoenablesItems = false
+ func add(_ name: String, _ id: String, available: Bool = true) {
+ let item = NSMenuItem(title: name, action: #selector(selectMicrophone(_:)), keyEquivalent: "")
+ item.target = self; item.representedObject = id
+ item.state = selected == id ? .on : .off
+ item.isEnabled = canSwitch && available
+ menu.addItem(item)
+ }
+ add(L("System default", "系统默认"), "")
+ 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)
+ }
+ return menu
+ }
+ @objc private func selectMicrophone(_ sender: NSMenuItem) {
+ guard transcription.canInstallUpdate, let id = sender.representedObject as? String else { return }
+ if !settingsWindow.model.selectMicrophone(id) {
+ settingsWindow.model.feedback = L("Could not switch input device. Check the device and unsaved settings.", "未能切换输入设备,请检查设备和未保存设置。")
+ settingsWindow.show(refresh: false)
+ }
+ rebuildMenu()
+ }
@objc private func showLogin() { web.showLoginWindow() }
private func saveLogin() {
guard !extracting else { return }
@@ -310,8 +346,28 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
private var smokeHoldSeconds: Double { min(max(Double(ProcessInfo.processInfo.environment["DOUBAO_SMOKE_HOLD_SECONDS"] ?? "2") ?? 2, 2), 120) }
private func settingsSmokeTest() {
+ if let appearance = ProcessInfo.processInfo.environment["DOUBAO_SMOKE_APPEARANCE"] {
+ NSApp.appearance = NSAppearance(named: appearance == "dark" ? .darkAqua : .aqua)
+ }
settingsWindow = SettingsWindow(state: state)
+ if ProcessInfo.processInfo.environment["DOUBAO_SMOKE_MICROPHONE_MENU"] == "1" {
+ let devices = [AudioInputDevice(id: "synthetic-internal", name: "Internal", audioID: 1),
+ AudioInputDevice(id: "synthetic-usb", name: "USB", audioID: 2)]
+ let menu = microphoneMenu(devices: devices, selected: "synthetic-usb", canSwitch: true)
+ precondition(menu.items.filter { $0.state == .on }.count == 1)
+ precondition(menu.items.last?.state == .on && menu.items.last?.isEnabled == true)
+ let disconnected = microphoneMenu(devices: [], selected: "synthetic-usb", canSwitch: true)
+ precondition(disconnected.items.last?.state == .on && disconnected.items.last?.isEnabled == false)
+ let busy = microphoneMenu(devices: devices, selected: "", canSwitch: false)
+ precondition(busy.items.allSatisfy { !$0.isEnabled })
+ print("PASS: microphone menu checkmarks, unavailable device and busy-state protection; synthetic devices only")
+ }
state.lastTranscript = L("Synthetic recent text. No network or microphone used.", "合成的最近文字,未使用网络或麦克风。")
+ if ProcessInfo.processInfo.environment["DOUBAO_SMOKE_RECENT_LONG"] == "1" {
+ state.lastTranscript = L("ÁÉÎÖÜ — First line: synthetic text.", "第一行:合成文字,检查顶部是否完整。")
+ + "\n" + (1...100).map { L("Synthetic line ", "合成第 ") + String($0) }.joined(separator: "\n")
+ }
+ state.updateVersion = ProcessInfo.processInfo.environment["DOUBAO_SMOKE_UPDATE_VERSION"] ?? ""
settingsWindow.model.selectedTab = ProcessInfo.processInfo.environment["DOUBAO_SMOKE_TAB"] ?? "setup"
settingsWindow.model.draft.polishEnabled = true
settingsWindow.model.setupStep = min(max(Int(ProcessInfo.processInfo.environment["DOUBAO_SMOKE_SETUP_STEP"] ?? "0") ?? 0, 0), 3)
@@ -319,8 +375,25 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
state.loginStatus = .loggedIn
settingsWindow.model.doubaoSessionSaved = true
}
- settingsWindow.show(refresh: false)
+ if ProcessInfo.processInfo.environment["DOUBAO_SMOKE_SETUP_COMPLETE"] == "1" {
+ state.loginStatus = .loggedIn; settingsWindow.model.doubaoSessionSaved = true
+ state.microphoneChecked = true; state.voiceChecked = true
+ settingsWindow.model.shortcutAvailable = true
+ settingsWindow.model.shortcutReady = { true }
+ }
+ if ProcessInfo.processInfo.environment["DOUBAO_SMOKE_LAUNCH_CHECK"] == "1" {
+ showInitialSettings()
+ precondition(settingsWindow.isVisible, "Launch must show settings")
+ settingsWindow.hide()
+ precondition(!settingsWindow.isVisible)
+ _ = applicationShouldHandleReopen(NSApp, hasVisibleWindows: false)
+ precondition(settingsWindow.isVisible, "Reopening must restore settings")
+ precondition(NSApp.activationPolicy() == .regular, "App must appear in the Dock")
+ precondition(!applicationShouldTerminateAfterLastWindowClosed(NSApp))
+ print("PASS: launch shows settings, reopen restores settings, Dock visible, close keeps dictation running")
+ } else { settingsWindow.show(refresh: false) }
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
+ if ProcessInfo.processInfo.environment["DOUBAO_SMOKE_RECENT_LONG"] == "1" { self.settingsWindow.inspectRecentText() }
if let path = ProcessInfo.processInfo.environment["DOUBAO_SMOKE_IMAGE"] { self.settingsWindow.captureImage(to: path) }
print("PASS: native settings window rendered; synthetic state only")
DispatchQueue.main.asyncAfter(deadline: .now() + self.smokeHoldSeconds) { self.settingsWindow.close(); NSApp.terminate(nil) }
@@ -362,6 +435,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
let frontPID = NSWorkspace.shared.frontmostApplication?.processIdentifier
state.recordingState = .recording
state.transcriptionText = L("Midscene · macOS synthetic verification", "Midscene · macOS 合成验证")
+ if ProcessInfo.processInfo.environment["DOUBAO_SMOKE_INPUT_FAILURE"] == "1" {
+ state.recordingState = .idle
+ state.errorMessage = L("Synthetic input failure. Text kept.", "合成的输入失败,文字已保留。")
+ state.overlayStatus = L("Not entered · retry from menu", "未输入 · 文字已保留,可从菜单重试")
+ }
overlay.showOverlay()
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
let focusPreserved = NSWorkspace.shared.frontmostApplication?.processIdentifier == frontPID
diff --git a/macos/Sources/MacSettings.swift b/macos/Sources/MacSettings.swift
index 9325f95..c7a5623 100644
--- a/macos/Sources/MacSettings.swift
+++ b/macos/Sources/MacSettings.swift
@@ -34,7 +34,7 @@ struct MacSettings: Codable, Equatable {
var holdMilliseconds = 350
var doubleMilliseconds = 300
var doubleEnter = true
- var inputMethod = "clipboard"
+ var inputMethod = "auto"
var microphoneID = ""
var waveformStyle = "bars"
var reducedMotion = false
@@ -54,7 +54,7 @@ struct MacSettings: Codable, Equatable {
func validate() throws {
guard version == 1, (200...1500).contains(holdMilliseconds), (150...600).contains(doubleMilliseconds),
- ["clipboard", "direct"].contains(inputMethod), ["bars", "waves", "ripples", "basketball"].contains(waveformStyle),
+ ["auto", "clipboard", "direct"].contains(inputMethod), ["bars", "waves", "ripples", "basketball"].contains(waveformStyle),
microphoneID.count <= 256, !microphoneID.contains("\0"),
let url = URLComponents(string: polishBaseURL), ["http", "https"].contains(url.scheme ?? ""),
!(url.host ?? "").isEmpty, url.user == nil, url.password == nil, url.query == nil, url.fragment == nil, polishBaseURL.count <= 2048,
diff --git a/macos/Sources/OverlayView.swift b/macos/Sources/OverlayView.swift
index 541a000..386ab17 100644
--- a/macos/Sources/OverlayView.swift
+++ b/macos/Sources/OverlayView.swift
@@ -55,8 +55,9 @@ struct OverlayView: View {
}
.accessibilityHidden(true)
centeredText(statusText, color: OverlayAppearance.foreground)
+ .help(appState.errorMessage ?? statusText)
}
- centeredText(appState.errorMessage ?? String(appState.transcriptionText.suffix(600)),
+ centeredText(appState.transcriptionText.isEmpty ? (appState.errorMessage ?? "") : String(appState.transcriptionText.suffix(600)),
color: appState.errorMessage == nil ? OverlayAppearance.foreground : OverlayAppearance.red)
if polishing, let started = appState.polishStartedAt, timeline.date.timeIntervalSince(started) >= 3 {
Text(L("Press shortcut again to use original", "再次按快捷键使用原文"))
diff --git a/macos/Sources/PasteHelper.swift b/macos/Sources/PasteHelper.swift
index 4ff3d6e..b34d6f4 100644
--- a/macos/Sources/PasteHelper.swift
+++ b/macos/Sources/PasteHelper.swift
@@ -29,40 +29,70 @@ struct InputTarget {
@MainActor
final class PasteHelper {
+ enum Failure { case permission, missingTarget, targetChanged, modifiersHeld, eventUnavailable, directUnavailable, clipboardUnavailable, enterSkipped }
+ private(set) var failure: Failure?
+ 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 .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.", "无法发送粘贴快捷键。")
+ 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 .enterSkipped: return L("Text entered; Enter was skipped because focus or permissions changed.", "文字已输入;焦点或权限发生变化,未发送回车。")
+ case nil: return nil
+ }
+ }
private var generation = UUID()
+ private let modifierFlags: () -> CGEventFlags
+ init(modifierFlags: @escaping () -> CGEventFlags = { CGEventSource.flagsState(.combinedSessionState) }) {
+ self.modifierFlags = modifierFlags
+ }
+ static func useAccessibilityInput(method: String, selectedTextWritable: Bool) -> Bool {
+ if method == "direct" { return true }
+ return method == "auto" && selectedTextWritable
+ }
func cancel() { generation = UUID() }
- func deliver(_ text: String, target: InputTarget?, method: String = "clipboard", 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
let token = generation
let deadline = Date().addingTimeInterval(1)
+ func fail(_ reason: Failure) { self.failure = reason; completion(false) }
func attempt() {
guard token == self.generation else { return }
- guard let target = target, target.isCurrent(), AXIsProcessTrusted() else { completion(false); return }
- let flags = CGEventSource.flagsState(.combinedSessionState)
- if !flags.intersection([.maskControl, .maskAlternate, .maskShift, .maskCommand]).isEmpty {
- guard Date() < deadline else { completion(false); 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
}
- guard let (down, up) = Self.shortcutEvents(Shortcut(keyCode: 9, modifiers: 4)) else {
- completion(false); return
- }
- if method == "direct" {
+ var writable = DarwinBoolean(false)
+ let writableStatus = AXUIElementIsAttributeSettable(target.element, kAXSelectedTextAttribute as CFString, &writable)
+ if Self.useAccessibilityInput(method: method,
+ selectedTextWritable: writableStatus == .success && writable.boolValue) {
let status = AXUIElementSetAttributeValue(target.element, kAXSelectedTextAttribute as CFString, text as CFString)
- guard status == .success else { completion(false); return }
- if sendEnter { Self.enterAfterInput(target: target, token: token, isCurrent: { token == self.generation }, completion: completion) }
+ guard status == .success else { fail(.directUnavailable); return }
+ if sendEnter { self.enterAfterInput(target: target, isCurrent: { token == self.generation }, completion: completion) }
else { completion(true) }
return
}
+ guard let (down, up) = Self.shortcutEvents(Shortcut(keyCode: 9, modifiers: 4)) else {
+ fail(.eventUnavailable); return
+ }
let pasteboard = NSPasteboard.general
let saved = pasteboard.pasteboardItems?.map { item in
item.types.compactMap { type -> (NSPasteboard.PasteboardType, Data)? in
item.data(forType: type).map { (type, $0) }
}
} ?? []
- guard target.isCurrent() else { completion(false); return }
+ guard target.isCurrent() else { fail(.targetChanged); return }
pasteboard.clearContents()
- guard pasteboard.setString(text, forType: .string) else { completion(false); return }
+ 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
@@ -77,15 +107,18 @@ final class PasteHelper {
}
if !items.isEmpty { pasteboard.writeObjects(items) }
}
- if sendEnter { Self.enterAfterInput(target: target, token: token, isCurrent: { token == self.generation }, completion: completion) }
+ if sendEnter { self.enterAfterInput(target: target, isCurrent: { token == self.generation }, completion: completion) }
else { completion(true) }
}
attempt()
}
- private static func enterAfterInput(target: InputTarget, token: UUID, isCurrent: @escaping () -> Bool, completion: @escaping (Bool) -> Void) {
+ private func enterAfterInput(target: InputTarget, isCurrent: @escaping () -> Bool, completion: @escaping (Bool) -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
- guard isCurrent(), target.isCurrent() else { completion(false); return }
- sendShortcut(Shortcut(keyCode: 36, modifiers: 0)); completion(true)
+ guard isCurrent() else { return }
+ guard target.isCurrent(), AXIsProcessTrusted() else {
+ self.failure = .enterSkipped; completion(true); return
+ }
+ Self.sendShortcut(Shortcut(keyCode: 36, modifiers: 0)); completion(true)
}
}
static func sendShortcut(_ shortcut: Shortcut) {
diff --git a/macos/Sources/PersonalViews.swift b/macos/Sources/PersonalViews.swift
index 51070e8..360fe25 100644
--- a/macos/Sources/PersonalViews.swift
+++ b/macos/Sources/PersonalViews.swift
@@ -1,11 +1,53 @@
import SwiftUI
-struct PaddedTextEditor: View {
+struct PaddedTextEditor: NSViewRepresentable {
@Binding var text: String
- var body: some View {
- TextEditor(text: $text).scrollContentBackground(.hidden).padding(10)
- .background(Color(nsColor: .textBackgroundColor))
- .overlay(RoundedRectangle(cornerRadius: 6).stroke(Color.secondary.opacity(0.25)))
+ func makeCoordinator() -> Coordinator { Coordinator(text: $text) }
+ func makeNSView(context: Context) -> NSScrollView {
+ let scroll = NSTextView.scrollableTextView()
+ let editor = scroll.documentView as! NSTextView
+ scroll.hasHorizontalScroller = false
+ scroll.borderType = .noBorder
+ scroll.wantsLayer = true
+ scroll.layer?.cornerRadius = 6
+ scroll.layer?.borderWidth = 1
+ scroll.layer?.masksToBounds = true
+ editor.isRichText = false; editor.allowsUndo = true
+ editor.font = .systemFont(ofSize: 13)
+ editor.textColor = .textColor; editor.backgroundColor = .textBackgroundColor
+ editor.textContainerInset = NSSize(width: 12, height: 12)
+ editor.textContainer?.lineFragmentPadding = 0
+ editor.isHorizontallyResizable = false
+ editor.textContainer?.widthTracksTextView = true
+ editor.autoresizingMask = [.width]
+ editor.isAutomaticQuoteSubstitutionEnabled = false
+ editor.isAutomaticDashSubstitutionEnabled = false
+ editor.string = text
+ editor.delegate = context.coordinator
+ editor.setAccessibilityLabel(L("Editable text", "可编辑文字"))
+ return scroll
+ }
+ func updateNSView(_ scroll: NSScrollView, context: Context) {
+ guard let editor = scroll.documentView as? NSTextView else { return }
+ context.coordinator.text = $text
+ scroll.layer?.borderColor = NSColor.separatorColor.cgColor
+ editor.isEditable = context.environment.isEnabled
+ guard editor.string != text else { return }
+ let selection = editor.selectedRange()
+ editor.string = text
+ let length = (text as NSString).length
+ let start = min(selection.location, length)
+ editor.setSelectedRange(NSRange(location: start, length: min(selection.length, length - start)))
+ scroll.contentView.scroll(to: .zero)
+ scroll.reflectScrolledClipView(scroll.contentView)
+ }
+ final class Coordinator: NSObject, NSTextViewDelegate {
+ var text: Binding<String>
+ init(text: Binding<String>) { self.text = text }
+ func textDidChange(_ notification: Notification) {
+ guard let editor = notification.object as? NSTextView else { return }
+ text.wrappedValue = editor.string
+ }
}
}
diff --git a/macos/Sources/SettingsWindow.swift b/macos/Sources/SettingsWindow.swift
index 3dc8330..b9e7c8e 100644
--- a/macos/Sources/SettingsWindow.swift
+++ b/macos/Sources/SettingsWindow.swift
@@ -26,7 +26,7 @@ final class SettingsModel: ObservableObject {
@Published var shortcutAvailable = false
@Published var capturing = false { didSet { if !capturing { resumeAutosave() } } }
@Published var testing = false { didSet { if !testing { resumeAutosave() } } }
- @Published var microphones = AudioDevices.inputs()
+ @Published var microphones: [AudioInputDevice] = []
@Published var asrKeySaved = false
@Published var doubaoSessionSaved = false
@Published var polishKeySaved = false
@@ -63,8 +63,16 @@ final class SettingsModel: ObservableObject {
private var recordingObserver: AnyCancellable?
private var savedRecognitionKey = ""
private var savedPolishKey = ""
- init(state: AppState) {
+ private let microphoneInputs: () -> [AudioInputDevice]
+ private let defaultMicrophoneID: () -> String?
+ private var currentDefaultMicrophoneID: String?
+ private var deviceMonitor: AudioDeviceMonitor?
+ init(state: AppState, microphoneInputs: @escaping () -> [AudioInputDevice] = AudioDevices.inputs,
+ defaultMicrophoneID: @escaping () -> String? = AudioDevices.defaultInputUID) {
self.state = state
+ self.microphoneInputs = microphoneInputs; self.defaultMicrophoneID = defaultMicrophoneID
+ microphones = microphoneInputs(); currentDefaultMicrophoneID = defaultMicrophoneID()
+ deviceMonitor = AudioDeviceMonitor { [weak self] in self?.refreshMicrophones() }
recordingObserver = state.$recordingState.dropFirst().sink { [weak self] value in
guard value == .idle else { return }
// Published emits before the stored state changes.
@@ -95,12 +103,22 @@ final class SettingsModel: ObservableObject {
var isDoubaoSignedIn: Bool {
SettingsStore.shared.value.provider == .doubao ? state.loginStatus == .loggedIn : doubaoSessionSaved
}
+ func refreshMicrophones() {
+ let previous = draft.microphoneID.isEmpty ? currentDefaultMicrophoneID : draft.microphoneID
+ let previousDevice = microphones.first { $0.id == previous }
+ 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 {
+ state.microphoneChecked = false; state.voiceChecked = false
+ }
+ }
func refresh() {
guard !testing, !capturing, !hasPendingAutosave else { return }
suppressAutosave = true
defer { suppressAutosave = false }
draft = SettingsStore.shared.value
- microphones = AudioDevices.inputs()
+ refreshMicrophones()
doubaoSessionSaved = ASRParamsStore.hasSavedParams
asrKeySaved = draft.provider == .doubao ? doubaoSessionSaved : SecretStore.load(draft.provider.rawValue + "-api-key") != nil
polishKeySaved = SecretStore.load("polish-api-key") != nil
@@ -143,6 +161,22 @@ final class SettingsModel: ObservableObject {
}
}
var canAdvanceSetup: Bool { !setupBusy && (0...setupStep).allSatisfy { setupComplete($0) } }
+ func selectSetupStep(_ step: Int) {
+ guard (0..<4).contains(step), step != setupStep, !setupBusy, saveIfNeeded() else { return }
+ setupStep = step; feedback = ""
+ }
+ @discardableResult func selectMicrophone(_ id: String) -> Bool {
+ guard !setupBusy, !state.evaluationBusy, !state.inputPending,
+ id.isEmpty || microphoneInputs().contains(where: { $0.id == id }), saveIfNeeded() else { return false }
+ guard draft.microphoneID != id else { return true }
+ let previous = draft.microphoneID
+ draft.microphoneID = id
+ guard save() else {
+ suppressAutosave = true; draft.microphoneID = previous; suppressAutosave = false
+ hasPendingAutosave = false; feedback = saveStatus; return false
+ }
+ return true
+ }
func advanceSetup() {
guard saveIfNeeded(), canAdvanceSetup, setupStep < 3 else { return }
setupStep += 1; feedback = ""
@@ -290,13 +324,22 @@ struct SettingsView: View {
model.clearNavigationFocus?()
}
} label: {
- Label(page.1, systemImage: page.2)
+ HStack {
+ Label(page.1, systemImage: page.2)
+ Spacer(minLength: 4)
+ if page.0 == "updates" && !state.updateVersion.isEmpty {
+ Circle().fill(Color(nsColor: .systemRed)).frame(width: 8, height: 8)
+ .accessibilityHidden(true)
+ }
+ }
.font(.system(size: 13, weight: model.selectedTab == page.0 ? .semibold : .regular))
.frame(maxWidth: .infinity, alignment: .leading).padding(10)
.foregroundColor(model.selectedTab == page.0 ? .accentColor : .primary)
.background(RoundedRectangle(cornerRadius: 7).fill(model.selectedTab == page.0 ? Color.accentColor.opacity(0.12) : .clear))
.contentShape(RoundedRectangle(cornerRadius: 7))
}.buttonStyle(.plain).focused($sidebarFocus, equals: page.0)
+ .accessibilityLabel(page.0 == "updates" && !state.updateVersion.isEmpty
+ ? page.1 + L(", update available: ", ",有可用更新:") + state.updateVersion : page.1)
}
Spacer()
Text(L("Settings", "设置")).font(.caption).foregroundColor(.secondary).padding(12)
@@ -376,10 +419,16 @@ struct SettingsView: View {
VStack(alignment: .leading, spacing: 16) {
HStack(spacing: 12) {
ForEach(0..<4) { index in
- HStack(spacing: 6) {
- Image(systemName: index < model.setupStep && model.setupComplete(index) ? "checkmark.circle.fill" : "\(index + 1).circle\(index == model.setupStep ? ".fill" : "")")
- Text(setupTitles[index]).font(.system(size: 12, weight: index == model.setupStep ? .semibold : .regular))
- }.foregroundColor(index == model.setupStep ? .accentColor : .secondary)
+ Button { model.selectSetupStep(index) } label: {
+ HStack(spacing: 6) {
+ Image(systemName: model.setupComplete(index) ? "checkmark.circle.fill" : "\(index + 1).circle\(index == model.setupStep ? ".fill" : "")")
+ Text(setupTitles[index]).font(.system(size: 12, weight: index == model.setupStep ? .semibold : .regular))
+ }.foregroundColor(model.setupComplete(index) ? .green : (index == model.setupStep ? .accentColor : .secondary))
+ .padding(.vertical, 8).padding(.horizontal, 4).contentShape(Rectangle())
+ }.buttonStyle(.plain).disabled(model.setupBusy)
+ .accessibilityLabel(setupTitles[index])
+ .accessibilityValue((model.setupComplete(index) ? L("Completed", "已完成") : L("Pending", "待完成"))
+ + (index == model.setupStep ? L(", current step", ",当前步骤") : ""))
if index < 3 { Image(systemName: "chevron.right").font(.caption).foregroundColor(.secondary) }
}
}.padding(.horizontal, 16)
@@ -412,6 +461,7 @@ struct SettingsView: View {
microphonePicker
Button(L("Check microphone · 3 seconds", "检查麦克风 · 三秒")) { model.checkMicrophone() }.disabled(model.setupBusy)
Label(state.microphoneChecked ? L("Microphone checked", "麦克风检查通过") : L("Microphone check pending", "请先检查麦克风"), systemImage: state.microphoneChecked ? "checkmark.circle.fill" : "circle")
+ .foregroundColor(state.microphoneChecked ? .green : .secondary)
ProgressView(value: min(state.rms * 10, 1))
Text(L("This check stays on your Mac and sends no audio to a recognition service.", "此步骤仅在本机检查,不向识别服务发送音频。"))
}.formStyle(.grouped).padding(8)
@@ -421,6 +471,7 @@ struct SettingsView: View {
Button(L("Enable global shortcut", "启用全局快捷键")) { model.enableShortcut?() }
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 取消录音。"))
}.formStyle(.grouped).padding(8)
default:
@@ -433,6 +484,7 @@ struct SettingsView: View {
Text(L("This test sends audio to your selected service and never pastes text.", "此步骤会把音频发送至所选识别服务,不会粘贴文字。"))
Text(state.previewText).textSelection(.enabled).lineLimit(6)
Label(state.voiceChecked ? L("Voice test passed", "语音试说通过") : L("Voice test pending", "请先完成语音试说"), systemImage: state.voiceChecked ? "checkmark.circle.fill" : "circle")
+ .foregroundColor(state.voiceChecked ? .green : .secondary)
}.formStyle(.grouped).padding(8)
}
}
@@ -449,6 +501,9 @@ struct SettingsView: View {
Button(L("Test API key", "测试 API Key")) { model.testRecognition() }
Button(L("Clear saved key", "清除已存 Key")) { model.clearKey(model.draft.provider.rawValue + "-api-key") }
}.disabled(model.testing || state.recordingState != .idle)
+ Label(model.setupComplete(0) ? L("Recognition service ready", "识别服务已就绪") : L("Recognition check pending", "请先检查识别服务"),
+ systemImage: model.setupComplete(0) ? "checkmark.circle.fill" : "circle")
+ .foregroundColor(model.setupComplete(0) ? .green : .secondary)
Text(model.draft.provider == .volcengine ? L("One API Key; resource volc.seedasr.sauc.duration is built in. No App ID required.", "只需一个 API Key,已内置 volc.seedasr.sauc.duration,无需 App ID。") : L("Nova-3, US English, punctuation and smart formatting.", "Nova-3,美式英语,启用标点和智能格式化。"))
Text(L("Audio is sent to the selected service; usage is billed to your provider account.", "音频发送至所选服务,用量由服务商向你的账号计费。"))
}
@@ -464,7 +519,9 @@ struct SettingsView: View {
Text(model.isDoubaoSignedIn
? L("Your login session is saved securely. You can now test voice recognition.", "登录会话已安全保存,可以开始语音识别测试。")
: L("Sign in through the Doubao window to connect your account.", "请通过豆包登录窗口连接账号。"))
- Button(model.isDoubaoSignedIn ? L("Sign in again", "重新登录") : L("Sign in to Doubao", "登录豆包")) { model.signIn?() }
+ if !model.isDoubaoSignedIn {
+ Button(L("Sign in to Doubao", "登录豆包")) { model.signIn?() }
+ }
}
}
private var polishing: some View {
@@ -538,6 +595,7 @@ struct SettingsView: View {
Text(L("Language changes take effect immediately. Recognition and polishing languages are configured separately.", "语言切换立即生效。识别和润色语言由各自配置决定。"))
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("Direct accessibility input", "辅助功能直接输入")).tag("direct")
}
@@ -587,17 +645,43 @@ final class SettingsWindow: NSObject, NSWindowDelegate {
}
func show(refresh: Bool = true) {
if refresh { model.refresh() }
+ if window.isMiniaturized { window.deminiaturize(nil) }
NSApp.activate(ignoringOtherApps: true)
window.makeKeyAndOrderFront(nil)
window.makeFirstResponder(nil)
}
func windowWillClose(_ notification: Notification) { model.closeEditor() }
+ var isVisible: Bool { window.isVisible }
func close() { model.stopTests(); window.close() }
func hide() { window.orderOut(nil) }
func updateTitle() { window.title = "Doubao Say · " + L("Settings", "设置") }
func captureImage(to path: String) {
WindowCapture.request(window)
}
+ func inspectRecentText() {
+ func find(_ view: NSView) -> NSTextView? {
+ if let text = view as? NSTextView { return text }
+ return view.subviews.compactMap(find).first
+ }
+ guard let root = window.contentView, let text = find(root), let scroll = text.enclosingScrollView else {
+ print("FAIL: recent-text editor unavailable"); return
+ }
+ text.scrollRangeToVisible(NSRange(location: (text.string as NSString).length, length: 0))
+ text.scrollRangeToVisible(NSRange(location: 0, length: 0))
+ scroll.contentView.scroll(to: .zero); scroll.reflectScrolledClipView(scroll.contentView)
+ print("RECENT_TEXT_INSET: \(text.textContainerInset.height); scroll-top: \(scroll.contentView.bounds.minY)")
+ if ProcessInfo.processInfo.environment["DOUBAO_SMOKE_EXPECT_TEXT_PADDING"] == "1" {
+ precondition(text.textContainerInset.height >= 10, "The first line needs padding inside the text container")
+ precondition(scroll.contentView.bounds.minY == 0, "Returning to the top must show the first line")
+ let original = text.string
+ window.makeFirstResponder(text)
+ text.insertText("✓ ", replacementRange: NSRange(location: 0, length: 0))
+ precondition(model.state.lastTranscript == "✓ " + original, "Edits must update the transcript binding")
+ text.setSelectedRange(NSRange(location: 0, length: 2)); text.deleteBackward(nil)
+ precondition(model.state.lastTranscript == original, "Deleting must preserve the rest of the transcript")
+ print("PASS: recent-text internal padding, scroll-to-top and editing binding")
+ }
+ }
}
diff --git a/macos/Sources/TranscriptionManager.swift b/macos/Sources/TranscriptionManager.swift
index 469747b..045710f 100644
--- a/macos/Sources/TranscriptionManager.swift
+++ b/macos/Sources/TranscriptionManager.swift
@@ -120,14 +120,14 @@ final class TranscriptionManager {
Task { @MainActor in
guard let self = self, self.session == token, self.client != nil else { return }
let partial = self.rawText
- self.showFailure(L("Recognition failed. Check your connection and retry.", "识别失败,请检查连接后重试。"), status: L("Recognition failed", "识别失败"))
+ self.showFailure(L("Recognition failed. Check your connection and retry.", "识别失败,请检查连接后重试。"), status: L("Recognition failed · not entered", "识别失败 · 未输入"), keptText: partial)
if !partial.isEmpty { self.state.lastTranscript = partial; self.state.feedback = L("Incomplete recognition — not pasted", "识别未完成,未粘贴") }
}
}
transport.onAuthError = { [weak self] in
Task { @MainActor in
guard let self = self, self.session == token, self.client != nil else { return }
- self.showFailure(L("Session expired. Sign in again.", "登录已过期,请重新登录。"), status: L("Sign in required", "请重新登录"))
+ self.showFailure(L("Session expired. Sign in again.", "登录已过期,请重新登录。"), status: L("Sign in required", "请重新登录"), keptText: self.rawText)
if self.settings.provider == .doubao { ASRParamsStore.clear() }
self.state.loginStatus = .notLoggedIn
}
@@ -154,10 +154,9 @@ final class TranscriptionManager {
scheduleTimeout(seconds: 8, token: session) { [weak self] in
guard let self = self else { return }
let partial = self.rawText, testing = self.testMode
- self.cancel()
- if testing { self.state.previewText = partial }
- else if !partial.isEmpty { self.state.lastTranscript = partial }
- self.state.errorMessage = L("Recognition timed out. Partial text kept; review it before input.", "识别超时,已保留部分文字,请检查后再输入。")
+ let message = L("Recognition timed out. Partial text kept; review it before input.", "识别超时,已保留部分文字,请检查后再输入。")
+ if testing { self.cancel(); self.state.previewText = partial; self.state.errorMessage = message }
+ else { self.showFailure(message, status: L("Recognition timed out · not entered", "识别超时 · 未输入"), keptText: partial) }
}
}
private func armQuietCompletion(token: UUID) {
@@ -217,6 +216,7 @@ final class TranscriptionManager {
} else { state.feedback = L("Original text", "原文") }
if historyFailed { state.feedback += L(" Local history could not be saved.", " 本地历史保存失败。") }
guard UserDefaults.standard.object(forKey: "autoPaste") as? Bool ?? true else {
+ retainVisibleText(text, status: L("Automatic paste off · text kept", "自动粘贴已关闭 · 文字已保留"))
try? PersonalDataStore.shared.saveTimings(historyID, values: timing.values); return
}
let token = session
@@ -230,9 +230,25 @@ final class TranscriptionManager {
guard self?.session == token else { return }
self?.state.inputPending = false
self?.hotkey.setEscapeHandlingEnabled(false)
- if !sent { self?.state.errorMessage = L("Target changed or input failed. Text kept in the app.", "目标已变化或输入失败,文字已保留在应用中。") }
+ if !sent { self?.showInputFailure(text) }
+ else if let self = self, let notice = self.delivery.failureMessage {
+ self.state.feedback = notice
+ self.retainVisibleText(text, status: notice)
+ }
}
}
+ private func showInputFailure(_ text: String) {
+ let message = L("Target changed or input failed. Focus an editable field and choose Retry input in 3 seconds from the menu. Text is kept in Recent text.", "目标已变化或输入失败。请点击可编辑的输入框,再从菜单选择「三秒后重试输入」。文字已保留在「最近文字」。")
+ state.errorMessage = delivery.failureMessage.map { $0 + " " + message } ?? message
+ state.feedback = L("Not entered — text kept", "未输入,文字已保留")
+ retainVisibleText(text, status: delivery.failureMessage ?? L("Not entered · retry from menu", "未输入 · 文字已保留,可从菜单重试"))
+ }
+ private func retainVisibleText(_ text: String, status: String) {
+ state.transcriptionText = text
+ state.overlayStatus = status
+ overlay.showOverlay()
+ hotkey.setEscapeHandlingEnabled(true)
+ }
func finishWithEnter() {
guard !state.evaluationBusy, !state.inputPending else { return }
if state.recordingState == .polishing { sendEnter = true; polisher.useOriginal() }
@@ -266,6 +282,10 @@ final class TranscriptionManager {
self.state.inputPending = false
self.hotkey.setEscapeHandlingEnabled(false)
self.state.feedback = sent ? L("Input attempted", "已发送输入操作") : L("Target unavailable; text kept", "目标不可用,文字已保留")
+ if sent {
+ self.state.errorMessage = nil; self.state.transcriptionText = ""; self.state.overlayStatus = ""
+ self.overlay.hideOverlay()
+ } else { self.showInputFailure(text) }
}
}
retryTimeout = item
@@ -277,7 +297,7 @@ final class TranscriptionManager {
Task { @MainActor in
guard let self = self, self.session == audioToken else { return }
let partial = self.rawText
- self.showFailure(L("Audio input changed or disconnected. Check the selected microphone; nothing pasted.", "音频输入变化或断开,请检查所选麦克风;未粘贴文字。"))
+ self.showFailure(L("Audio input changed or disconnected. Check the selected microphone; nothing pasted.", "音频输入变化或断开,请检查所选麦克风;未粘贴文字。"), keptText: partial)
if !partial.isEmpty { self.state.lastTranscript = partial }
}
}
@@ -314,13 +334,16 @@ final class TranscriptionManager {
guard primed else { return }
primed = false; primedAudio.removeAll(); audio.stopCapture(); audio.onAudioData = nil; audio.onRMS = nil; audio.onError = nil; target = nil
}
- private func showFailure(_ message: String, status: String = L("Microphone unavailable", "麦克风不可用")) {
+ private func showFailure(_ message: String, status: String = L("Microphone unavailable", "麦克风不可用"), keptText: String = "") {
cancel()
state.errorMessage = message
state.overlayStatus = status
overlay.showOverlay()
hotkey.setEscapeHandlingEnabled(true)
- scheduleTimeout(seconds: 6, token: session) { [weak self] in self?.cancel() }
+ if !keptText.isEmpty {
+ state.lastTranscript = keptText
+ retainVisibleText(keptText, status: status)
+ } else { scheduleTimeout(seconds: 6, token: session) { [weak self] in self?.cancel() } }
}
func cancel() {
session = UUID(); timeout?.cancel(); timeout = nil; quietTimer?.cancel(); quietTimer = nil; finalGate = FinalResultGate()
diff --git a/macos/Tests/Input/DeliveryCheck.swift b/macos/Tests/Input/DeliveryCheck.swift
new file mode 100644
index 0000000..32581eb
--- /dev/null
+++ b/macos/Tests/Input/DeliveryCheck.swift
@@ -0,0 +1,93 @@
+import AppKit
+import ApplicationServices
+
+// Test the production delivery implementation with inert platform boundaries.
+enum Fixture {
+ static var trusted = true, current = true, writable = true
+ static var writeStatus = AXError.success
+ static var writes: [String] = []
+}
+func L(_ english: String, _ chinese: String) -> String { english }
+func AXIsProcessTrusted() -> Bool { Fixture.trusted }
+func AXUIElementIsAttributeSettable(_ element: AXUIElement, _ attribute: CFString, _ writable: UnsafeMutablePointer<DarwinBoolean>) -> AXError {
+ writable.pointee = DarwinBoolean(Fixture.writable); return .success
+}
+func AXUIElementSetAttributeValue(_ element: AXUIElement, _ attribute: CFString, _ value: CFTypeRef) -> AXError {
+ Fixture.writes.append(value as! String); return Fixture.writeStatus
+}
+struct InputTarget {
+ let pid = ProcessInfo.processInfo.processIdentifier
+ let element = AXUIElementCreateApplication(ProcessInfo.processInfo.processIdentifier)
+ func isCurrent() -> Bool { Fixture.current }
+}
+final class NSPasteboard {
+ typealias PasteboardType = AppKit.NSPasteboard.PasteboardType
+ static let general = NSPasteboard()
+ var pasteboardItems: [NSPasteboardItem]? = nil
+ var changeCount = 0
+ var pastedTexts: [String] = []
+ func clearContents() { changeCount += 1 }
+ @discardableResult func setString(_ text: String, forType: PasteboardType) -> Bool { pastedTexts.append(text); return true }
+ func writeObjects(_ items: [NSPasteboardItem]) { pasteboardItems = items; changeCount += 1 }
+}
+final class CGEvent {
+ static var posted = 0
+ init?(keyboardEventSource: CGEventSource?, virtualKey: CGKeyCode, keyDown: Bool) {}
+ var flags = CGEventFlags()
+ func setIntegerValueField(_ field: CGEventField, value: Int64) {}
+ func post(tap: CGEventTapLocation) { Self.posted += 1 }
+}
+struct Shortcut { let keyCode: UInt16; let modifiers: Int }
+enum HotkeyManager {
+ static let syntheticMarker: Int64 = 1
+ static func flags(_ value: Int) -> CGEventFlags { [] }
+}
+
+@main struct DeliveryCheck {
+ @MainActor static func main() {
+ func wait(_ seconds: Double) { RunLoop.current.run(until: Date().addingTimeInterval(seconds)) }
+ var flags = CGEventFlags()
+ let helper = PasteHelper(modifierFlags: { flags })
+ let target = InputTarget()
+ var result: Bool?
+ func send(_ destination: InputTarget? = target) {
+ result = nil; helper.deliver("synthetic words", target: destination) { result = $0 }
+ }
+ send()
+ 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)
+ precondition(result == false && helper.failure == .missingTarget)
+ Fixture.current = false; send()
+ precondition(result == false && helper.failure == .targetChanged && Fixture.writes.isEmpty)
+ Fixture.current = true; flags = .maskSecondaryFn; send()
+ precondition(result == nil && Fixture.writes.isEmpty, "Fn must be released before insertion")
+ flags = []; wait(0.15)
+ 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)
+ 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,
+ "An ambiguous AX failure must not trigger a second clipboard attempt")
+ Fixture.writeStatus = .success; Fixture.writes = []; result = nil
+ helper.deliver("synthetic words", target: target, sendEnter: true) { result = $0 }
+ Fixture.current = false; wait(0.3)
+ precondition(result == true && helper.failure == .enterSkipped && Fixture.writes.count == 1,
+ "Skipped Enter must not mark already-inserted text as failed or invite duplicate delivery")
+ Fixture.current = true; Fixture.writes = []; result = nil
+ Fixture.writable = false
+ helper.deliver("fallback text", target: target, method: "auto") { result = $0 }
+ wait(0.9)
+ precondition(result == true && Fixture.writes.isEmpty && CGEvent.posted == 2)
+ 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")
+ 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/RetryCheck.swift b/macos/Tests/Input/RetryCheck.swift
index c3a89e8..dfc3254 100644
--- a/macos/Tests/Input/RetryCheck.swift
+++ b/macos/Tests/Input/RetryCheck.swift
@@ -6,22 +6,30 @@ enum RecognitionProvider { case doubao, volcengine, deepgram; var rawValue: Stri
struct MacSettings { var provider: RecognitionProvider = .doubao; var polishEnabled = false; var inputMethod = "clipboard"; var microphoneID = "" }
@MainActor final class SettingsStore { static let shared = SettingsStore(); var value = MacSettings() }
enum SecretStore { static func load(_ key: String) -> String? { nil } }
-enum ASRParamsStore { static func load() -> Int? { nil }; static func clear() {} }
+enum ASRParamsStore { static var available = false; static func load() -> Int? { available ? 1 : nil }; static func clear() {} }
+enum AVCaptureDevice {
+ enum Status { case authorized, notDetermined }
+ static func authorizationStatus(for type: AVMediaType) -> Status { .authorized }
+ static func requestAccess(for type: AVMediaType, completionHandler: @escaping (Bool) -> Void) { completionHandler(true) }
+}
func L(_ english: String, _ chinese: String) -> String { english }
struct Shortcut { var keyCode: UInt16; var modifiers: Int }
-struct InputTarget { static func capture() -> InputTarget? { InputTarget() } }
+struct InputTarget { static var available = true; static func capture() -> InputTarget? { available ? InputTarget() : nil } }
@MainActor final class PasteHelper {
+ var failureMessage: String? { Self.failImmediately ? "Synthetic target unavailable" : nil }
static var events: [String] = []
static var pending: ((Bool) -> Void)?
+ static var failImmediately = false
func cancel() {}
func deliver(_ text: String, target: InputTarget?, method: String, sendEnter: Bool = false, completion: @escaping (Bool) -> Void) {
Self.events.append("paste"); Self.pending = completion
+ if Self.failImmediately { completion(false) }
}
static func sendShortcut(_ shortcut: Shortcut) { events.append("enter") }
}
final class AudioCaptureManager {
var onAudioData: ((Data) -> Void)?; var onRMS: ((Double) -> Void)?; var onError: (() -> Void)?
- func startCapture(deviceID: String) throws { fatalError("Audio must not be used") }
+ func startCapture(deviceID: String) throws {}
func stopCapture() {}
}
@MainActor final class OverlayPanel { var isVisible = false; func showOverlay() { isVisible = true }; func hideOverlay() { isVisible = false } }
@@ -46,10 +54,12 @@ protocol ASRTransport: AnyObject {
func sendAudio(_ data: Data); func finishSending(); func disconnect()
}
class DoubaoASRClient: ASRTransport {
+ static var latest: DoubaoASRClient?
+ init() { Self.latest = self }
var onOpen: (() -> Void)?; var onResult: ((String) -> Void)?; var onFinish: (() -> Void)?
var onAudioDrained: (() -> Void)?; var onError: (() -> Void)?; var onAuthError: (() -> Void)?
func sendAudio(_ data: Data) {}; func finishSending() {}; func disconnect() {}
- func connect(params: Int) { fatalError("Network must not be used") }
+ func connect(params: Int) { onOpen?() }
}
final class APIASRClient: DoubaoASRClient {
init(provider: RecognitionProvider) {}
@@ -94,5 +104,39 @@ final class PersonalDataStore {
wait()
precondition(PasteHelper.events == ["paste"])
print("PASS: retry single delivery, pending Enter suppression, cancellation and stale completion isolation; no real input")
+ ASRParamsStore.available = true; InputTarget.available = false; PasteHelper.failImmediately = true
+ let failureState = AppState(), failureOverlay = OverlayPanel(), failureHotkey = HotkeyManager()
+ let failureManager = TranscriptionManager(appState: failureState, overlayPanel: failureOverlay, hotkeyManager: failureHotkey)
+ failureManager.start(); failureHotkey.onHotkeyEvent?(.start)
+ RunLoop.current.run(until: Date().addingTimeInterval(0.1))
+ precondition(failureState.isRecording)
+ DoubaoASRClient.latest?.onResult?("synthetic recognized words")
+ RunLoop.current.run(until: Date().addingTimeInterval(0.1))
+ failureHotkey.onHotkeyEvent?(.stop)
+ RunLoop.current.run(until: Date().addingTimeInterval(0.1))
+ DoubaoASRClient.latest?.onFinish?()
+ RunLoop.current.run(until: Date().addingTimeInterval(0.1))
+ precondition(failureState.lastTranscript == "synthetic recognized words")
+ precondition(failureOverlay.isVisible && failureState.transcriptionText == failureState.lastTranscript,
+ "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)
+ precondition(!failureOverlay.isVisible && failureState.errorMessage == nil && !failureState.inputPending,
+ "Successful retry must clear the retained failure overlay")
+ failureHotkey.onHotkeyEvent?(.start)
+ RunLoop.current.run(until: Date().addingTimeInterval(0.1))
+ DoubaoASRClient.latest?.onResult?("synthetic partial words")
+ RunLoop.current.run(until: Date().addingTimeInterval(0.1))
+ failureHotkey.onHotkeyEvent?(.stop)
+ RunLoop.current.run(until: Date().addingTimeInterval(0.1))
+ let attempts = PasteHelper.events.count
+ DoubaoASRClient.latest?.onError?()
+ RunLoop.current.run(until: Date().addingTimeInterval(0.1))
+ precondition(failureOverlay.isVisible && failureState.transcriptionText == "synthetic partial words"
+ && failureState.lastTranscript == "synthetic partial words" && PasteHelper.events.count == attempts,
+ "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")
}
}
diff --git a/macos/Tests/Input/check-delivery.sh b/macos/Tests/Input/check-delivery.sh
new file mode 100644
index 0000000..f63653d
--- /dev/null
+++ b/macos/Tests/Input/check-delivery.sh
@@ -0,0 +1,15 @@
+#!/bin/bash
+set -euo pipefail
+cd "$(dirname "$0")/../../.."
+mkdir -p build/macos/tests
+python3 - <<'PY'
+from pathlib import Path
+source = Path('macos/Sources/PasteHelper.swift').read_text()
+body = source[source.index('@MainActor\nfinal class PasteHelper'):]
+Path('build/macos/tests/PasteHelperUnderTest.swift').write_text('import AppKit\nimport ApplicationServices\n' + body)
+PY
+xcrun swiftc -swift-version 5 -target "$(uname -m)-apple-macos13.0" \
+ -module-cache-path build/macos/module-cache \
+ build/macos/tests/PasteHelperUnderTest.swift macos/Tests/Input/DeliveryCheck.swift \
+ -o build/macos/tests/delivery-check
+build/macos/tests/delivery-check
diff --git a/macos/Tests/Settings/AutoSaveCheck.swift b/macos/Tests/Settings/AutoSaveCheck.swift
index 9950845..ad851d7 100644
--- a/macos/Tests/Settings/AutoSaveCheck.swift
+++ b/macos/Tests/Settings/AutoSaveCheck.swift
@@ -3,6 +3,19 @@ import AppKit
@main
struct AutoSaveCheck {
@MainActor static func main() {
+ precondition(PasteHelper.useAccessibilityInput(method: "auto", selectedTextWritable: true))
+ precondition(!PasteHelper.useAccessibilityInput(method: "auto", selectedTextWritable: false))
+ precondition(!PasteHelper.useAccessibilityInput(method: "clipboard", selectedTextWritable: true),
+ "Explicit clipboard selection must be respected even for writable fields")
+ precondition(PasteHelper.useAccessibilityInput(method: "direct", selectedTextWritable: false))
+ for method in ["auto", "clipboard", "direct"] {
+ var settings = MacSettings(); settings.inputMethod = method
+ try! settings.validate()
+ let decoded = try! JSONDecoder().decode(MacSettings.self, from: JSONEncoder().encode(settings))
+ precondition(decoded.inputMethod == method, "Existing input choices must survive settings round trips")
+ }
+ precondition(MacSettings().inputMethod == "auto")
+ print("PASS: capability-based automatic routing and explicit input choices; settings remain compatible")
let hotkey = HotkeyManager()
for shortcut in [Shortcut(keyCode: 9, modifiers: 4), Shortcut(keyCode: 49, modifiers: 3), Shortcut(keyCode: 58, modifiers: 0)] {
var settings = MacSettings(); settings.shortcut = shortcut
@@ -17,6 +30,31 @@ struct AutoSaveCheck {
}
print("PASS: synthetic paste bypasses configurable hotkeys; no event tap or posted key events")
func wait(_ seconds: Double) { RunLoop.current.run(until: Date().addingTimeInterval(seconds)) }
+ let monitor = AudioDeviceMonitor { }
+ precondition(monitor.registeredSelectors.count == 2, "Device and default-input listeners must register")
+ let builtIn = AudioInputDevice(id: "synthetic-internal", name: "Internal", audioID: 1)
+ let usb = AudioInputDevice(id: "synthetic-usb", name: "USB", audioID: 2)
+ var devices = [builtIn]
+ var defaultID: String? = builtIn.id
+ let deviceState = AppState()
+ let deviceModel = SettingsModel(state: deviceState, microphoneInputs: { devices }, defaultMicrophoneID: { defaultID })
+ deviceModel.draft = MacSettings()
+ deviceState.microphoneChecked = true; deviceState.voiceChecked = true
+ devices.append(usb); deviceModel.refreshMicrophones()
+ precondition(deviceModel.microphones.count == 2 && deviceState.microphoneChecked,
+ "Inserting an unrelated device must refresh the list without invalidating the active input")
+ defaultID = usb.id; deviceModel.refreshMicrophones()
+ precondition(deviceModel.draft.microphoneID.isEmpty && !deviceState.microphoneChecked && !deviceState.voiceChecked,
+ "System-default changes must invalidate checks without changing the saved selection")
+ deviceModel.draft.microphoneID = usb.id
+ deviceState.microphoneChecked = true; deviceState.voiceChecked = true
+ devices = [builtIn]; defaultID = builtIn.id; deviceModel.refreshMicrophones()
+ 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")
+ devices.append(usb); deviceModel.refreshMicrophones()
+ precondition(deviceModel.microphones.contains { $0.id == usb.id } && deviceModel.draft.microphoneID == usb.id)
+ print("PASS: hardware listeners registered; simulated insert/remove/default changes refresh inputs and preserve selection")
let state = AppState()
let model = SettingsModel(state: state)
model.draft = MacSettings()
@@ -25,6 +63,17 @@ struct AutoSaveCheck {
let defaults = UserDefaults(suiteName: suite)!
defer { defaults.removePersistentDomain(forName: suite) }
let store = SettingsStore(defaults: defaults)
+ deviceModel.apply = { settings, _, _ in try store.save(settings) }
+ precondition(deviceModel.selectMicrophone(builtIn.id) && store.value.microphoneID == builtIn.id)
+ precondition(deviceModel.selectMicrophone("") && store.value.microphoneID.isEmpty)
+ precondition(!deviceModel.selectMicrophone("missing-device") && store.value.microphoneID.isEmpty)
+ deviceState.recordingState = .recording
+ precondition(!deviceModel.selectMicrophone(usb.id) && store.value.microphoneID.isEmpty)
+ deviceState.recordingState = .idle
+ deviceModel.apply = { _, _, _ in throw MacSettings.SettingsError.invalid }
+ precondition(!deviceModel.selectMicrophone(usb.id) && deviceModel.draft.microphoneID.isEmpty && store.value.microphoneID.isEmpty,
+ "Failed switches must preserve the saved and displayed selection")
+ print("PASS: microphone switches persist, recording blocks switching, missing devices and save failures preserve selection")
var reject = false
model.apply = { settings, recognition, polish in
if reject { throw MacSettings.SettingsError.invalid }
@@ -74,6 +123,20 @@ struct AutoSaveCheck {
let wizard = SettingsModel(state: wizardState)
wizard.draft = MacSettings()
wizard.apply = { settings, _, _ in try store.save(settings) }
+ wizard.selectSetupStep(3)
+ precondition(wizard.setupStep == 3 && !wizard.canAdvanceSetup, "Direct navigation must not bypass completion checks")
+ for step in [1, 2, 0, 3, 0] {
+ wizard.selectSetupStep(step)
+ precondition(wizard.setupStep == step, "Every setup step must be selectable")
+ }
+ wizard.selectSetupStep(-1); wizard.selectSetupStep(4)
+ precondition(wizard.setupStep == 0, "Invalid steps must be ignored")
+ wizard.testing = true; wizard.selectSetupStep(2)
+ precondition(wizard.setupStep == 0, "Testing must prevent navigation")
+ wizard.testing = false; wizardState.recordingState = .recording; wizard.selectSetupStep(2)
+ precondition(wizard.setupStep == 0, "Recording must prevent navigation")
+ wizardState.recordingState = .idle
+ print("PASS: direct step navigation, completion gates and active-test/recording protection")
wizard.advanceSetup()
precondition(wizard.setupStep == 0, "Login is required before microphone setup")
wizardState.loginStatus = .loggedIn; wizard.doubaoSessionSaved = true
diff --git a/macos/build.sh b/macos/build.sh
index faecc6b..c7f9291 100755
--- a/macos/build.sh
+++ b/macos/build.sh
@@ -26,7 +26,7 @@ version = re.search(r'^version = "([^"]+)"', pathlib.Path('pyproject.toml').read
info = dict(CFBundleIdentifier='md.lifeos.doubao-say.macos', CFBundleName='Doubao Say',
CFBundleDisplayName='Doubao Say', CFBundleExecutable='DoubaoSay', CFBundlePackageType='APPL',
CFBundleShortVersionString=version, CFBundleVersion='1', LSMinimumSystemVersion='13.0',
- LSUIElement=True, NSHighResolutionCapable=True, CFBundleIconFile='AppIcon',
+ LSUIElement=False, NSHighResolutionCapable=True, CFBundleIconFile='AppIcon',
NSMicrophoneUsageDescription='Doubao Say uses your microphone to transcribe speech with Doubao.')
pathlib.Path(sys.argv[1], 'Contents/Info.plist').write_bytes(plistlib.dumps(info))
PY
diff --git a/macos/check.sh b/macos/check.sh
index 97401d3..29e503f 100755
--- a/macos/check.sh
+++ b/macos/check.sh
@@ -32,3 +32,4 @@ xcrun swiftc -swift-version 5 -target "$(uname -m)-apple-macos13.0" \
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
diff --git a/macos/runtime-check.py b/macos/runtime-check.py
index 53eb925..385c14f 100644
--- a/macos/runtime-check.py
+++ b/macos/runtime-check.py
@@ -18,11 +18,41 @@ info_path.write_bytes(plistlib.dumps(info))
subprocess.run(['codesign', '--force', '--sign', '-', str(bundle)], check=True)
for language in ['en', 'zh']:
cases = [('overlay', '--smoke-test', '')]
+ if '--launch-settings' in sys.argv[3:]:
+ cases = [(f'launch-{status}', '--settings-smoke-test', 'general') for status in ['available', 'latest']]
+ if '--setup-completion' in sys.argv[3:]:
+ cases = [(f'setup-{status}-{theme}', '--settings-smoke-test', 'setup')
+ for status in ['complete', 'pending'] for theme in ['light', 'dark']]
+ if '--doubao-session' in sys.argv[3:]:
+ cases = [(f'doubao-{status}', '--settings-smoke-test', 'recognition') for status in ['signed-in', 'signed-out']]
+ if '--recent-text' in sys.argv[3:]:
+ cases = [(f'recent-text-{length}', '--settings-smoke-test', 'result') for length in ['short', 'long']]
+ if '--microphone-menu' in sys.argv[3:]:
+ cases = [('microphone-menu', '--settings-smoke-test', 'general')]
+ if '--input-failure' in sys.argv[3:]:
+ cases = [('input-failure', '--smoke-test', '')]
if '--settings' in sys.argv[3:]:
cases += [(f'settings-{tab}', '--settings-smoke-test', tab) for tab in ['setup', 'recognition', 'polishing', 'shortcuts', 'general', 'result']]
for label, argument, tab in cases:
env = dict(os.environ, DOUBAO_SMOKE_IMAGE=str(output / f'{label}-{language}.png'), DOUBAO_SMOKE_TAB=tab)
+ if label == 'input-failure':
+ env['DOUBAO_SMOKE_INPUT_FAILURE'] = '1'
+ if label == 'microphone-menu':
+ env['DOUBAO_SMOKE_MICROPHONE_MENU'] = '1'
+ if label == 'recent-text-long':
+ env['DOUBAO_SMOKE_RECENT_LONG'] = '1'
+ if '--expect-text-padding' in sys.argv[3:]:
+ env['DOUBAO_SMOKE_EXPECT_TEXT_PADDING'] = '1'
+ if label.startswith('doubao-'):
+ env['DOUBAO_SMOKE_SIGNED_IN'] = '1' if label == 'doubao-signed-in' else '0'
+ if label.startswith('launch-'):
+ env.update(DOUBAO_SMOKE_LAUNCH_CHECK='1',
+ DOUBAO_SMOKE_UPDATE_VERSION='1.8.0' if label.endswith('available') else '')
command = [str(bundle / 'Contents/MacOS/DoubaoSay'), argument, '-language', language]
+ if label.startswith('setup-') and '--setup-completion' in sys.argv[3:]:
+ env.update(DOUBAO_SMOKE_SETUP_STEP='1',
+ DOUBAO_SMOKE_SETUP_COMPLETE='1' if label.startswith('setup-complete-') else '0',
+ DOUBAO_SMOKE_APPEARANCE='dark' if label.endswith('-dark') else 'light')
lines = []
capture_path = output / f'{label}-{language}.png'
process = subprocess.Popen(command, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
diff --git a/manifest.json b/manifest.json
index b152078..5a6b7a8 100644
--- a/manifest.json
+++ b/manifest.json
@@ -2,7 +2,7 @@
"schemaVersion": 1,
"id": "md.lifeos.doubao-say",
"name": "Doubao Say",
- "version": "1.7.0",
+ "version": "1.8.0",
"author": "quanru and contributors",
"description": "Doubao Say turns speech into polished text with live captions and configurable tap or hold triggers on Wayland.",
"kinds": [
diff --git a/packaging/INSTALL.md b/packaging/INSTALL.md
index 4205760..af8d1d0 100644
--- a/packaging/INSTALL.md
+++ b/packaging/INSTALL.md
@@ -1,4 +1,4 @@
-# Doubao Say 1.7.0
+# Doubao Say 1.8.0
[Website](https://doubao-say.lifeos.md/) · [简体中文安装指南](https://doubao-say.lifeos.md/zh/guide/install)
diff --git a/packaging/install-release.py b/packaging/install-release.py
index 668d866..0e8d627 100644
--- a/packaging/install-release.py
+++ b/packaging/install-release.py
@@ -132,7 +132,7 @@ def main():
subprocess.run([sys.executable, "-m", "venv", "--system-site-packages", str(runtime)], check=True)
subprocess.run([str(runtime / "bin/python"), "-m", "pip", "install", "--no-index",
"--find-links", str(root / "wheels"), "-r", str(root / "runtime-requirements.txt")], check=True)
- subprocess.run([str(runtime / "bin/python"), "-c", "import evdev, websockets, sounddevice, gi, cairo"], check=True)
+ subprocess.run([str(runtime / "bin/python"), "-c", "import evdev, websockets, sounddevice, gi, cairo, jwt, cryptography"], check=True)
previous_desktop = launcher_file.read_bytes() if launcher_file.exists() else None
if target.exists():
previous = target / ".desktop-before-install"
diff --git a/packaging/runtime-requirements.txt b/packaging/runtime-requirements.txt
index 46896f2..c679237 100644
--- a/packaging/runtime-requirements.txt
+++ b/packaging/runtime-requirements.txt
@@ -1,4 +1,6 @@
-# Complete Python dependency set tested for the 1.4.0 release.
+# Complete Python dependency set for the 1.8.0 release.
+PyJWT[crypto]==2.15.1
+cryptography==50.0.2
websockets==17.1
sounddevice==0.5.6
evdev==2.0.0
diff --git a/packaging/store/doubao-say.spec b/packaging/store/doubao-say.spec
index 9ba4dd1..705804f 100644
--- a/packaging/store/doubao-say.spec
+++ b/packaging/store/doubao-say.spec
@@ -13,6 +13,8 @@ Requires: python3-gobject
Requires: python3-cairo
Requires: python3-websockets
Requires: python3-evdev
+Requires: python3-jwt
+Requires: python3-cryptography
Requires: gtk4
Requires: webkitgtk6.0
Requires: pipewire-utils
diff --git a/packaging/store/md.lifeos.DoubaoSay.json b/packaging/store/md.lifeos.DoubaoSay.json
index 1683709..bb63ed0 100644
--- a/packaging/store/md.lifeos.DoubaoSay.json
+++ b/packaging/store/md.lifeos.DoubaoSay.json
@@ -104,6 +104,45 @@
}
]
},
+ {
+ "name": "python-pyjwt",
+ "buildsystem": "simple",
+ "build-commands": [
+ "pip3 install --no-index --no-deps --prefix=/app *.whl"
+ ],
+ "sources": [
+ {
+ "type": "file",
+ "url": "https://files.pythonhosted.org/packages/50/ca/44de4e75f8aadc457f0634be3b542815078ded46dca30efb960edeecad6e/pyjwt-2.15.1-py3-none-any.whl",
+ "sha256": "42d59d631f7768a1028a64c7ff581a9bf7519804daf91fc5b6c56e30eec5e193"
+ }
+ ]
+ },
+ {
+ "name": "python-cryptography",
+ "buildsystem": "simple",
+ "build-commands": [
+ "pip3 install --no-index --no-deps --prefix=/app *.whl"
+ ],
+ "sources": [
+ {
+ "type": "file",
+ "url": "https://files.pythonhosted.org/packages/71/37/6202e488cc1eb625ea110c292c6bda92823176e023f427d8d5660ce8d632/cryptography-50.0.2-cp311-abi3-manylinux_2_34_aarch64.whl",
+ "sha256": "87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04",
+ "only-arches": [
+ "aarch64"
+ ]
+ },
+ {
+ "type": "file",
+ "url": "https://files.pythonhosted.org/packages/d3/69/2c833a049475e0a3444e94c7d0aca0aa51d166374a449b09e92ac98138de/cryptography-50.0.2-cp311-abi3-manylinux_2_34_x86_64.whl",
+ "sha256": "9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079",
+ "only-arches": [
+ "x86_64"
+ ]
+ }
+ ]
+ },
{
"name": "doubao-say",
"buildsystem": "simple",
diff --git a/pyproject.toml b/pyproject.toml
index 658c8a2..9669820 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "doubao-say"
-version = "1.7.0"
+version = "1.8.0"
description = "Global push-to-hold voice input for Linux/Wayland, backed by Doubao ASR"
readme = "README.md"
requires-python = ">=3.11"
@@ -19,6 +19,7 @@ classifiers = [
"Topic :: Utilities",
]
dependencies = [
+ "PyJWT[crypto]>=2.10,<3",
"websockets>=12",
"sounddevice>=0.4.6",
"evdev>=1.4",
diff --git a/src/doubao_input/app.py b/src/doubao_input/app.py
index 44a3a39..862b724 100644
--- a/src/doubao_input/app.py
+++ b/src/doubao_input/app.py
@@ -52,7 +52,11 @@ from doubao_input.recognition_providers import recognition_provider
logger = logging.getLogger(__name__)
-class DoubaoInputApp(Gtk.Application):
+from doubao_input.app_voice import VoiceMixin
+from doubao_input.app_runtime import RuntimeMixin
+
+
+class DoubaoInputApp(VoiceMixin, RuntimeMixin, Gtk.Application):
def __init__(self, background: bool = False, trigger_debug: bool = False) -> None:
super().__init__(
application_id="md.lifeos.DoubaoSay",
@@ -160,776 +164,15 @@ class DoubaoInputApp(Gtk.Application):
self._control.show()
# The tray indicates idle readiness; overlays are reserved for capture.
- def _on_shutdown(self, _app) -> None:
- logger.info("shutting down")
- if self._escape_timer is not None:
- GLib.source_remove(self._escape_timer)
- self._escape_timer = None
- if self._escape_guard:
- self._escape_guard.close()
- if self._tray:
- self._tray.close()
- self._tray = None
- if self._tm:
- self._tm.audio_capture.stop()
- self._tm.asr_client.disconnect()
- if self._setup_session:
- self._setup_session.dismiss()
- if self._triggers:
- self._triggers.close()
- if self._delivery:
- self._delivery.close(self._injector.close)
- if self._polisher:
- self._polisher.close()
- if getattr(self, "_asr_probe", None):
- self._asr_probe.disconnect()
- self._asr_probe = None
- if self._update_checker:
- self._update_checker.close()
- if self._update_timer:
- GLib.source_remove(self._update_timer)
- self._update_timer = None
# ---- build ----
- def _build(self) -> None:
- self._overlay = Overlay(self.app_state)
- self._injector = Injector()
- self._delivery = Delivery(GLib.timeout_add, focused_target,
- lambda text, target, cancelled: self._injector.inject(text, expected_target=target, cancelled=cancelled,
- method=self.settings.input_method),
- lambda target, cancelled: self._injector.send_enter(expected_target=target, cancelled=cancelled),
- self._delivery_changed, InputWorker(GLib.idle_add))
- self._polisher = PolishManager(GLib.idle_add)
-
- # ---- TranscriptionManager (state machine) ----
- tm = self._new_transcription_manager()
- # Replace its audio_capture with our instance so we can wire RMS
- self._audio_capture = AudioCapture(on_rms=self._on_audio_rms)
- self._audio_capture.device = self.settings.microphone
- self._overlay.reduced_motion = self.settings.reduced_motion
- self._overlay.waveform_style = self.settings.waveform_style
- tm.audio_capture = self._audio_capture
-
- tm.on_show_login = self._connect_recognition
- tm.on_overlay_show = lambda: self._overlay.show(tr("Starting voice recognition…", "正在启动语音识别…"))
- tm.on_overlay_hide = self._hide_recording_overlay
- tm.on_overlay_update = self._recording_text_updated
- tm.on_paste = self._do_paste
- tm.on_empty_complete = self._empty_complete
- tm.on_recover = self._recover_partial
- tm.on_cancel_enabled_changed = lambda enabled: None
- tm.on_auth_expired = self._on_auth_expired
- tm.on_params_needed = self._provide_params
- tm.on_diagnostic = self._trace_input
- self._tm = tm
-
- # ---- Control window ----
- self._control = ControlWindow(
- app_state=self.app_state,
- on_login_clicked=self._connect_recognition,
- on_quit_clicked=self._quit,
- on_check_mic_clicked=self._check_mic,
- app=self,
- actions=SetupActions(
- test_voice=self._test_voice,
- cancel_preview=self._cancel_voice_test,
- open_settings=self._show_settings,
- is_preview_testing=lambda: self._preview_testing,
- summary=self._summary,
- complete_setup=self._complete_setup,
- apply_key=self._apply_trigger_key,
- capture_key=self._begin_key_capture,
- cancel_key_capture=self._end_key_capture,
- polish_settings=lambda: self.settings,
- polish_has_key=self._polish_has_key,
- save_polish=self._save_polish,
- test_polish=self._test_polish,
- apply_microphone=self._apply_microphone,
- apply_asr_provider=self._apply_asr_provider,
- asr_has_key=self._api_key_has_saved,
- save_asr=self._save_asr_key,
- test_asr=self._test_asr_key,
- check_updates=lambda: self._update_checker.check(force=True),
- install_update=self._install_update,
- open_personal=self._show_personal,
- ),
- )
- self._update_checker = UpdateChecker(GLib.idle_add, self._update_available, status=self._update_status)
- try:
- self._personal_store.history(limit=0)
- except Exception:
- self._control.set_feedback(tr("Could not open local input history.", "无法打开本地输入历史。"))
- self._update_checker.check()
- update_result = consume_update_result()
- if update_result and not update_result["success"]:
- self.app_state.error_message = tr("The previous update failed. The previous installation was restored; details are in the update log.", "上次更新失败,已恢复旧安装;详情保存在更新日志中。")
- self._update_timer = GLib.timeout_add_seconds(3600, self._check_updates)
-
- self._setup_session = SetupSession(self._audio_capture, self._overlay,
- self._control.set_feedback, self._control.set_preview, tm.handle_cancel,
- GLib.timeout_add, GLib.source_remove, self._control.refresh)
- self._escape_guard = EscapeGuard(lambda message: self._control.set_feedback(
- tr("Could not protect Escape: ", "无法拦截 Esc:") + message))
- self._escape_timer = GLib.timeout_add(50, self._sync_escape)
- self._triggers = TriggerController(TriggerReader, GLib.timeout_add, GLib.source_remove,
- escape_edge=self._escape_guard.edge,
- start=self._voice_start, stop=self._voice_stop, toggle=self._voice_toggle,
- enter=self._voice_enter, cancel_input=self._cancel_input,
- shortcut=self._injector.send_shortcut,
- prime=self._voice_prime, discard=self._tm.discard_primed_audio,
- is_recording=lambda: self.app_state.is_recording,
- debug_edge=self._debug_edge, error=lambda message: logger.warning("PTT error: %s", message))
-
- # ---- Initial state: cached params? ----
- self._sync_recognition_status()
-
- # ---- PTT trigger ----
- from doubao_input.ui.tray import Tray
- try:
- self._tray = Tray(self.app_state, self._control.show, menu_entries=[
- (lambda: tr("Open control center", "打开控制中心"), self._control.show),
- (lambda: tr("Settings", "设置"), lambda: (self._control.show(), self._show_settings())),
- (lambda: tr("Check microphone", "检查麦克风"), self._check_mic),
- (lambda: tr("Copy recent result", "复制最近结果"), self._copy_recent),
- (lambda: tr("Cancel recording / input", "取消录音或输入"), self._cancel_input),
- ])
- except GLib.Error:
- logger.exception("System tray unavailable; desktop launcher remains usable")
- self._triggers.configure(self.settings)
- if self._trigger_debug_requested:
- from doubao_input.ui.trigger_debug import TriggerDebug
- self._debug_session = TriggerDebug(self, self._exit_trigger_debug)
- logger.info("build complete")
-
- def _exit_trigger_debug(self):
- if self._debug_session:
- session, self._debug_session = self._debug_session, None
- session.close()
- return True
-
- def _update_available(self, info):
- self._control.set_update(info)
- self._overlay.set_update(info)
-
- def _update_status(self, value):
- if self._update_installing:
- return
- if value == "current":
- self._control.set_update(None); self._overlay.set_update(None)
- messages = {
- "checking": tr("Checking for updates…", "正在检查更新…"),
- "current": tr("You are using the latest version.", "当前已是最新版本。"),
- "available": tr("Update available. Click Update to download and restart.", "发现新版本,点击更新即可下载并重启。"),
- "failed": tr("Could not check for updates. Try again later.", "更新检查失败,请稍后重试。"),
- }
- self._control.set_update_status(messages[value], value == "checking")
-
- def _install_update(self, info):
- if self._update_installing:
- return
- if self._busy():
- self._control.set_feedback(tr("Finish dictation or testing before updating.", "请先结束听写或测试,再安装更新。"))
- return
- if not self._control.flush_edits() or (self._settings_window and not self._settings_window.flush_edits()) or (self._personal_window and not self._personal_window.flush()):
- self._control.set_feedback(tr("Correct unsaved settings before updating.", "请先修正未保存的设置,再更新。"))
- return
- self._update_installing = True
- self._control.set_update_status(tr("Downloading update…", "正在下载更新…"), True)
- def prepared(scratch, error):
- self._update_installing = False
- if error or self._busy():
- if scratch:
- shutil.rmtree(scratch)
- self._control.set_update_status(tr("Update was not installed: ", "更新未安装:") + (error or tr("finish dictation first", "请先结束听写")))
- return False
- if not self._control.flush_edits() or (self._settings_window and not self._settings_window.flush_edits()) or (self._personal_window and not self._personal_window.flush()):
- shutil.rmtree(scratch)
- self._control.set_update_status(tr("Correct unsaved settings before updating.", "请先修正未保存的设置,再更新。"))
- return False
- try:
- launch_update(scratch)
- except OSError:
- shutil.rmtree(scratch)
- self._control.set_update_status(tr("Could not start the updater; the installed app is unchanged.", "无法启动更新程序,已安装的应用未改变。"))
- return False
- self._quit()
- return False
- def worker():
- scratch = None
- try:
- def status(message):
- phases = {
- "Downloading release source…": tr("Downloading release source…", "正在下载更新源码…"),
- "Downloading update…": tr("Downloading update…", "正在下载更新…"),
- "Verifying update…": tr("Verifying update…", "正在核验更新包…"),
- }
- GLib.idle_add(lambda: self._control.set_update_status(phases.get(message, message), True))
- scratch = prepare_update(info, status=status)
- error = None
- except Exception as exc:
- logger.info("Update preparation failed (%s)", type(exc).__name__)
- message = str(exc)
- if "Local changes exist" in message:
- error = tr("Local source changes exist. Commit or move them before updating.", "源码中有本地修改,请先提交或移走,再更新。")
- elif "package manager" in message:
- error = tr("Use your package manager to update this installation.", "此安装由系统包管理器管理,请通过包管理器更新。")
- elif "Release is missing" in message:
- error = tr("No update package matches this CPU and Python version.", "此版本没有匹配当前 CPU 和 Python 的更新包。")
- else:
- error = tr("Check the connection, release package and installation permissions.", "请检查网络、更新包和安装目录权限。")
- GLib.idle_add(prepared, scratch, error)
- Thread(target=worker, name="doubao-update-download", daemon=True).start()
-
- def _remember_input(self, original, output, polished):
- store = getattr(self, "_personal_store", None)
- if not store:
- return
- try:
- self._history_id = store.record(original, output, polished)
- except Exception:
- self._history_id = None
- self._control.set_feedback(tr("Could not save local input history. Input is still available.", "本地输入历史保存失败,文字仍可输入。"))
-
- def _can_evaluate_speech(self):
- audio = getattr(self, "_audio_capture", None)
- # A held gesture may be buffering audio while the visible state is idle.
- return not self._busy() and not (audio and audio.is_capturing)
-
- def _show_personal(self):
- from doubao_input.ui.personal_window import PersonalWindow
- if self._personal_window is None:
- self._personal_window = PersonalWindow(self._personal_store, lambda: self.settings, self._polish_key, self.recent, self._retry_recent, self._can_evaluate_speech)
- self._personal_window.show()
-
- def _check_updates(self):
- try:
- self._personal_store.history(limit=0)
- except Exception:
- logger.warning("Could not prune local history")
- self._update_checker.check()
- return True
-
- def _debug_edge(self, code, pressed):
- if not self._debug_session:
- return False
- if key_codes_match(code, self.settings.doubao_key):
- self._debug_session.edge(pressed)
- return True
-
- def _apply_trigger_key(self, key, modifiers=()):
- from dataclasses import replace
- key, modifiers = canonical_shortcut(key, modifiers)
- self.apply_settings(replace(self.settings, doubao_key=key,
- doubao_modifiers=modifiers))
-
- def _apply_microphone(self, device):
- from dataclasses import replace
- self.apply_settings(replace(self.settings, microphone=device))
-
- def _apply_asr_provider(self, provider):
- from dataclasses import replace
- self.apply_settings(replace(self.settings, asr_provider=provider))
-
- def apply_settings(self, settings):
- settings.validate()
- if settings.autostart and "/omarchy/plugins/" in __file__:
- raise ValueError(tr("This installation is started by Omarchy. Disable plugin startup before using a standalone autostart installation.",
- "当前安装由 Omarchy 插件启动。请勿同时启用独立应用自启动。"))
- if self._busy() or self._triggers.busy:
- raise ValueError(tr("Finish the current operation and release the trigger before saving", "请先结束当前操作并松开触发键,再保存设置"))
- previous = self.settings
- if previous.asr_provider != settings.asr_provider:
- # A modal Settings window can open while onboarding's debounce is
- # pending. Both drafts still belong to the provider being left.
- for view in (self._control, self._settings_window):
- if view and not view._flush_asr_key():
- raise ValueError(tr(
- "Save the current API key before switching services.",
- "请先保存当前 API Key,再切换识别服务。"))
-
- def apply_runtime(value, strict):
- self._triggers.configure(value, strict=strict)
- self._audio_capture.device = value.microphone
- self._overlay.reduced_motion = value.reduced_motion
- self._overlay.waveform_style = value.waveform_style
-
- apply_preferences(previous, settings,
- lambda value: apply_runtime(value, True),
- lambda value: apply_runtime(value, False))
- self.settings = settings
- if previous.asr_provider != settings.asr_provider:
- self._configure_recognition_backend()
- self._sync_recognition_status()
- self._setup_session.voice_ok = False
- if previous.microphone != settings.microphone:
- self._setup_session.microphone_ok = self._setup_session.voice_ok = False
- self._control.refresh()
-
- def _trace_input(self, stage):
- self._diagnostics.add(stage)
- if stage == "gesture_confirmed":
- self._input_latency.reset()
- elif stage == "stop_requested":
- self._input_latency.stop()
-
- def _new_transcription_manager(self):
- provider = recognition_provider(self.settings.asr_provider)
- return TranscriptionManager(
- self.app_state,
- asr_client=provider.new_client(),
- credential_store=provider.credential_store,
- interactive_auth=provider.interactive_auth,
- clear_rejected_credentials=provider.clear_rejected_credentials,
- )
-
- def _configure_recognition_backend(self):
- if self._asr_probe:
- self._asr_probe.disconnect()
- self._asr_probe = None
- provider = recognition_provider(self.settings.asr_provider)
- self._tm.configure_backend(
- provider.new_client(),
- provider.credential_store,
- interactive_auth=provider.interactive_auth,
- clear_rejected_credentials=provider.clear_rejected_credentials,
- )
-
- def _recognition_ready(self):
- try:
- return recognition_provider(
- self.settings.asr_provider
- ).credential_store.has_saved()
- except (OSError, ValueError):
- return False
-
- def _sync_recognition_status(self):
- self.app_state.login_status = (LoginStatus.LOGGED_IN if self._recognition_ready()
- else LoginStatus.NOT_LOGGED_IN)
# ---- Voice commands (GTK main thread) ----
- def _voice_start(self):
- if getattr(self, "_polish_mode", None) == "final" and self._polisher.busy:
- self._cancel_polish(use_original=True)
- return
- if getattr(self, "_personal_window", None) and self._personal_window.evaluation and self._personal_window.evaluation.active:
- return
- if self._mic_test_running or self._triggers.capturing or self._recovery_timer:
- return
- if self.app_state.recording_state == RecordingState.IDLE and not self._paste_pending:
- if not self._preview_testing:
- self._setup_session.dismiss()
- self._enter_after_paste = False
- self._target = None if self._preview_testing else focused_target()
- self._reset_prepolish()
- self._tm.handle_toggle()
-
- def _voice_prime(self):
- if (not self._mic_test_running and not self._triggers.capturing
- and not self._recovery_timer and not self._paste_pending
- and getattr(self, "_polish_mode", None) != "final"
- and not (getattr(self, "_personal_window", None) and self._personal_window.evaluation and self._personal_window.evaluation.active)):
- self._tm.prime_recording()
-
- def _voice_stop(self):
- if getattr(self, "_polish_mode", None) == "final" and self._polisher.busy:
- self._cancel_polish(use_original=True)
- return
- if self.app_state.recording_state in (RecordingState.STARTING, RecordingState.RECORDING):
- self._tm.handle_toggle()
-
- def _voice_toggle(self):
- if getattr(self, "_personal_window", None) and self._personal_window.evaluation and self._personal_window.evaluation.active:
- return
- if getattr(self, "_polish_mode", None) == "final" and self._polisher.busy:
- self._cancel_polish(use_original=True)
- return
- if self.app_state.recording_state == RecordingState.IDLE:
- if self._mic_test_running or self._triggers.capturing or self._recovery_timer:
- return
- if not self._paste_pending:
- if not self._preview_testing:
- self._setup_session.dismiss()
- self._enter_after_paste = False
- self._target = None if self._preview_testing else focused_target()
- self._reset_prepolish()
- self._tm.handle_toggle()
- else:
- self._voice_stop()
-
- def _voice_enter(self):
- if getattr(self, "_personal_window", None) and self._personal_window.evaluation and self._personal_window.evaluation.active:
- return
- if self._mic_test_running or self._triggers.capturing or self._recovery_timer:
- return
- if self._preview_testing:
- self._voice_stop()
- return
- if getattr(self, "_polish_mode", None) == "final" and self._polisher.busy:
- self._cancel_polish(use_original=True, send_enter=True)
- return
- if self._paste_pending:
- self._delivery.request_enter()
- elif self.app_state.recording_state == RecordingState.IDLE:
- self._send_enter()
- else:
- self._enter_after_paste = True
- self._voice_stop()
-
- def _send_enter(self):
- self._delivery.submit_enter(focused_target(), changed=self._enter_changed)
- return GLib.SOURCE_REMOVE
-
- def _enter_changed(self, status):
- messages = {
- "pending": tr("Sending Enter…", "正在发送回车…"),
- "attempted": tr("Enter sent.", "已发送回车。"),
- "cancelled": tr("Enter cancelled.", "已取消回车。"),
- }
- self._control.set_feedback(messages.get(status, tr(
- "Enter not sent; check the target field.", "未发送回车,请检查目标输入框。")))
-
- def _empty_complete(self):
- if self._preview_testing:
- self._setup_session.complete_voice("")
- self._control.refresh()
- return
- self._enter_after_paste = False
- self._control.set_feedback(tr("No speech recognized. Nothing was sent.", "没有识别到语音,未发送任何内容。"))
# ---- Paste ----
- def _hide_recording_overlay(self):
- # Transcription resets to IDLE immediately after handing us the final
- # text. Keep the same single overlay visible while the network polish
- # is still running instead of making that phase look like a hang.
- if self._polish_mode != "final":
- self._overlay.hide()
-
- def _do_paste(self, text: str) -> None:
- if self._setup_session.complete_voice(text):
- self._control.refresh()
- return
- latency = getattr(self, "_input_latency", None)
- if latency:
- latency.mark("asr")
- text = DoubaoInputApp._uncommitted_text(self, text)
- if not text:
- return
- send_enter, self._enter_after_paste = self._enter_after_paste, False
- if self.settings.polish_enabled:
- self._cancel_prepolish_timer()
- if self._preview_polish.snapshot == text and self._preview_polish.result:
- result = self._preview_polish.result
- self._reset_prepolish(cancel_request=False)
- self._submit_transcript(result, self._target, send_enter, original=text)
- return
- api_key = self._polish_key()
- if api_key:
- self.recent.keep(text, "polishing")
- self._control.set_result(text, tr("Polishing… press the trigger to use the original",
- "正在润色…再次按快捷键可直接使用原文"))
- self._overlay.show_polishing(text)
- self._polish_context = (text, self._target, send_enter)
- if getattr(self, "_polish_mode", None) == "pre" and self._preview_polish.inflight == text and self._polisher.busy:
- self._polish_mode = "final"
- return
- # Do not wait for an in-flight speculative request here. It
- # may be stuck in an uninterruptible network read. A final
- # request has its own executor and an intentionally shorter
- # timeout, so release-to-paste stays bounded.
- self._polisher.cancel()
- self._polish_mode = "final"
- logger.info("Starting final polish request")
- self._polisher.start(text, self.settings, api_key, self._polish_finished,
- progress=self._polish_progress)
- return
- self._control.set_feedback(tr("Polishing is enabled but no API key is saved; using the original text.",
- "润色已开启但没有保存 API Key,本次使用原文。"))
- self._submit_transcript(text, self._target, send_enter)
-
- def _submit_transcript(self, text, target, send_enter=False, *, original=None):
- latency = getattr(self, "_input_latency", None)
- if latency:
- latency.mark("polish")
- self._remember_input(original if original is not None else text, text, original is not None)
- self.recent.keep(text)
- self._control.set_result(self.recent.text, tr("Ready to input", "准备输入"))
- self._overlay.set_status(
- tr("Polished · Sending text…", "润色完成 · 正在输入…") if original
- else tr("Sending text…", "正在输入…"))
- # Never hide/restore an arbitrary foreground settings window to force input.
- # A missing or changed target keeps the text in recovery instead.
- if not self._delivery.submit(text, target, send_enter):
- logger.warning("Delivery rejected before it could start")
- self._delivery_changed("failed")
-
- def _polish_finished(self, result, error):
- self._polish_mode = None
- context, self._polish_context = self._polish_context, None
- if not context:
- return
- original, target, send_enter = context
- if result:
- logger.info("Final polish completed; submitting delivery")
- self._submit_transcript(result, target, send_enter, original=original)
- else:
- logger.warning("Final polish failed or timed out; using original text")
- self._control.set_feedback(error + tr("; using the original text.", ";本次使用原文。"))
- self._submit_transcript(original, target, send_enter)
-
- def _polish_progress(self, text):
- if not text:
- return
- if self._polish_mode == "final":
- self._overlay.set_text(text)
- elif self._polish_mode == "pre" and self.app_state.is_recording:
- self._overlay.set_text(text)
-
- def _recording_text_updated(self, text):
- text = self._uncommitted_text(text)
- if self._polish_mode == "pre" and text.strip() == self._preview_polish.inflight:
- return
- if self._preview_polish.result and text.strip() == self._preview_polish.snapshot:
- return
- self._overlay.set_status(tr("Listening…", "正在聆听…"))
- self._overlay.set_text(text)
-
- def _uncommitted_text(self, text):
- # Every session delivers once, with its full correction context.
- return text.strip()
-
- def _cancel_polish(self, *, use_original=False, send_enter=False):
- context, self._polish_context = self._polish_context, None
- self._polisher.cancel()
- self._polish_mode = None
- self._reset_prepolish(cancel_request=False)
- self._overlay.hide()
- if use_original and context:
- original, target, pending_enter = context
- self._submit_transcript(original, target, send_enter or pending_enter)
- self._control.set_feedback(tr("Polishing cancelled; original text used.",
- "已停止润色并使用原文。"))
-
- def _delivery_changed(self, status):
- store = getattr(self, "_personal_store", None)
- if store:
- try:
- store.status(self._history_id, status)
- latency = getattr(self, "_input_latency", None)
- if latency and status != "pending":
- latency.mark("delivery")
- store.save_timings(self._history_id, latency.values)
- except Exception:
- logger.warning("Could not update local input history")
- diagnostics = getattr(self, "_diagnostics", None)
- if diagnostics:
- diagnostics.add("delivery_pending" if status == "pending"
- else "delivery_finished")
- self.recent.status = status
- messages = {
- "pending": tr("Sending text…", "正在输入…"),
- "attempted": tr("Input sent. If text is missing, copy or retry below.", "已发送输入操作;若未出现文字,可在下方复制或重试。"),
- "target_changed": tr("Target changed or unavailable. Text kept; choose a target and retry.", "目标窗口已变化或无法确认。文字已保留,请选择目标后重试。"),
- "failed": tr("Input failed. Your text is kept here; some may already have been entered. For direct typing, check wtype and desktop support.", "输入失败,文字已保留;可能已有部分文字输入。使用直接输入时,请检查 wtype 和桌面支持。"),
- "enter_skipped": tr("Input attempted; Enter skipped because the target changed or input failed.", "已尝试输入;因目标变化或输入失败,未发送回车。"),
- "cancelled": tr("Input cancelled. Text already entered cannot be withdrawn.", "已取消输入,已输入的文字无法撤回。"),
- }
- self._control.set_result(self.recent.text, messages.get(status, status))
- self._control.set_feedback(messages.get(status, status))
- if status != "pending":
- self._overlay.hide()
- if status in ("target_changed", "failed", "enter_skipped"):
- self._notify_recovery()
-
- def _notify_recovery(self):
- notice = Gio.Notification.new(tr("Doubao Say", "豆包说"))
- notice.set_body(tr("Your text is kept in the app. Open Doubao Say to copy or retry.",
- "文字已保留在应用中,打开豆包说即可复制或重试。"))
- notice.set_default_action("app.open-control")
- self.send_notification("input-recovery", notice)
-
- def _recover_partial(self, text):
- self._enter_after_paste = False
- if self._preview_testing:
- self._control.set_preview(text)
- return
- self.recent.keep(text, "partial")
- self._control.set_result(self.recent.text, tr("Incomplete recognition — not pasted", "识别未完成,未粘贴"))
- self._notify_recovery()
-
- def _copy_recent(self):
- if self.recent.text:
- from gi.repository import Gdk
- Gdk.Display.get_default().get_clipboard().set(self.recent.text)
- self._control.set_feedback(tr("Copied. Clipboard contents remain until replaced.", "已复制;剪贴板内容会保留到被替换。"))
-
- def _clear_recent(self):
- self._cancel_input()
- self.recent.clear()
- self._control.set_result("", tr("Cleared from app memory; system clipboard is unchanged.", "已清除应用内文字,系统剪贴板不变。"))
-
- def _retry_recent(self):
- if self._busy() or not self.recent.text:
- self._control.set_feedback(tr("Finish the current operation first.", "请先结束当前操作。"))
- return
- self._control.set_feedback(tr("Choose your target text field within 3 seconds. No Enter will be sent.", "请在三秒内点击目标输入框,本次不会发送回车。"))
- text = self.recent.text
- def retry():
- self._recovery_timer = None
- self._remember_input(text, text, False)
- self._delivery.submit(text, focused_target())
- return False
- self._recovery_timer = GLib.timeout_add(3000, retry)
-
- def _cancel_input(self):
- if getattr(self, "_personal_window", None) and self._personal_window.evaluation:
- self._personal_window.evaluation.cancel()
- self._enter_after_paste = False
- if self._triggers:
- self._triggers.cancel_gesture()
- if self._setup_session:
- self._setup_session.dismiss()
- if self._recovery_timer:
- GLib.source_remove(self._recovery_timer)
- self._recovery_timer = None
- if self._delivery:
- self._delivery.cancel()
- if self._polisher:
- self._cancel_polish()
- if self._tm:
- self._tm.handle_cancel()
-
- def _busy(self):
- return (bool(getattr(self, "_asr_probe", None)) or bool(getattr(self, "_personal_window", None) and self._personal_window.evaluation and self._personal_window.evaluation.active) or self.app_state.recording_state != RecordingState.IDLE or self._mic_test_running
- or self._paste_pending or (self._triggers is not None and self._triggers.capturing)
- or self._recovery_timer is not None
- or bool(self._polisher and self._polisher.busy))
-
- def _save_polish(self, settings, api_key=None):
- # PolishSettings can outlive other UI changes and hold a stale full
- # Settings snapshot. Merge only its fields into the current settings so
- # a delayed polish save cannot revert the trigger key or other options.
- settings = replace(self.settings,
- polish_enabled=settings.polish_enabled,
- polish_base_url=settings.polish_base_url,
- polish_model=settings.polish_model,
- polish_prompt_zh=settings.polish_prompt_zh,
- polish_prompt_en=settings.polish_prompt_en)
- settings.validate()
- previous_key = self._polish_key()
- effective_key = api_key or previous_key
- if settings.polish_enabled and not effective_key:
- raise ValueError(tr("Enter an API key before enabling polishing.",
- "开启润色前请填写 API Key。"))
- if api_key:
- ApiKeyStore.save(api_key)
- try:
- self.apply_settings(settings)
- except Exception:
- if previous_key:
- ApiKeyStore.save(previous_key)
- elif api_key:
- ApiKeyStore.clear()
- raise
-
- def _test_polish(self, settings, api_key, completed):
- settings.validate()
- key = api_key or self._polish_key()
- if not key:
- raise ValueError(tr("Enter an API key first.", "请先填写 API Key。"))
- if self._busy():
- raise ValueError(tr("Finish the current operation first.", "请先结束当前操作。"))
- self._polisher.start(tr("Um, I think, I think this is a test.", "嗯,我觉得,就是说,这是一个测试。"),
- settings, key, completed)
-
- def _polish_key(self):
- try:
- return ApiKeyStore.load()
- except OSError:
- logger.exception("Could not read polishing API key")
- return ""
-
- def _polish_has_key(self):
- return bool(self._polish_key())
-
- def _on_audio_rms(self, rms):
- self._overlay.push_rms(rms)
- speaking = rms >= 0.012
- if speaking != self._rms_speaking:
- self._rms_speaking = speaking
- GLib.idle_add(self._prepolish_speech_changed, speaking)
-
- def _prepolish_text_changed(self, _state, text):
- if not self.settings.polish_enabled or not self.app_state.is_recording:
- return
- text = DoubaoInputApp._uncommitted_text(self, text)
- self._preview_polish.invalidate(text)
- if self._polish_mode == "pre" and text.strip() != self._preview_polish.inflight:
- self._polisher.cancel()
- self._polish_mode = None
- self._preview_polish.inflight = ""
- if not self._rms_speaking and text.strip():
- self._arm_prepolish()
-
- def _prepolish_speech_changed(self, speaking):
- if not self.settings.polish_enabled or not self.app_state.is_recording:
- return False
- if speaking:
- self._cancel_prepolish_timer()
- # RMS includes breathing and room noise. Only a changed ASR
- # transcript invalidates work; otherwise the same text gets
- # repeatedly cancelled and submitted again.
- elif self.app_state.transcription_text.strip():
- self._arm_prepolish()
- return False
-
- def _arm_prepolish(self):
- self._preview_polish.arm(self._start_prepolish)
-
- def _cancel_prepolish_timer(self):
- self._preview_polish.cancel_timer()
-
- def _start_prepolish(self):
- text = self._uncommitted_text(self.app_state.transcription_text)
- key = self._polish_key()
- if (not text or not key or self._rms_speaking or not self.app_state.is_recording
- or self._polisher.busy):
- return False
- if text == self._preview_polish.snapshot:
- return False
- self._preview_polish.begin(text)
- self._polish_mode = "pre"
- logger.info("Starting speculative polish request")
- self._overlay.set_status(tr("Polishing preview · still listening", "预润色中 · 仍在聆听"))
- self._overlay.set_text(text)
- self._polisher.start(text, self.settings, key, self._prepolish_finished,
- speculative=True, progress=self._polish_progress)
- return False
-
- def _prepolish_finished(self, result, error):
- if self._polish_mode == "final":
- self._polish_finished(result, error)
- return
- snapshot = self._preview_polish.inflight
- self._polish_mode = None
- self._preview_polish.inflight = ""
- if (snapshot and snapshot == self._uncommitted_text(self.app_state.transcription_text)
- and self.app_state.is_recording):
- if not result:
- result = snapshot
- self._control.set_feedback(tr("Polishing unavailable; using original text.", "润色未完成,本次使用原文。"))
- self._preview_polish.finish(snapshot, result)
- self._overlay.set_status(tr("Preview ready · finish recording to paste", "预览就绪 · 结束录音后上屏"))
- self._overlay.set_text(result)
-
- def _reset_prepolish(self, *, cancel_request=True):
- self._cancel_prepolish_timer()
- if cancel_request and self._polish_mode == "pre" and self._polisher:
- self._polisher.cancel()
- self._polish_mode = None
- self._preview_polish.reset()
def _summary(self):
key = trigger_shortcut_display(self.settings.doubao_key, self.settings.doubao_modifiers)
diff --git a/src/doubao_input/app_runtime.py b/src/doubao_input/app_runtime.py
new file mode 100644
index 0000000..0594698
--- /dev/null
+++ b/src/doubao_input/app_runtime.py
@@ -0,0 +1,416 @@
+"""Runtime assembly, preferences and update lifecycle."""
+from __future__ import annotations
+
+import logging
+import signal
+import shutil
+from threading import Thread
+from dataclasses import replace
+
+import gi
+
+gi.require_version("Gtk", "4.0")
+from gi.repository import Gio, GLib, Gtk # type: ignore
+
+from doubao_input.doubao.app_state import AppState, LoginStatus, RecordingState
+from doubao_input.doubao.audio_capture import AudioCapture
+from doubao_input.inject.delivery import Delivery
+from doubao_input.inject.target import focused_target
+from doubao_input.result import RecentResult
+from doubao_input.doubao.params_store import ParamsStore
+from doubao_input.doubao.transcription import TranscriptionManager
+from doubao_input.inject.injector import Injector
+from doubao_input.trigger.reader import TriggerReader
+from doubao_input.trigger.controller import TriggerController
+from doubao_input.setup_session import SetupSession
+from doubao_input.inject.worker import InputWorker
+from doubao_input.preferences import apply_preferences
+from doubao_input.settings import (Settings, canonical_shortcut,
+ key_codes_match, trigger_shortcut_display)
+from doubao_input.i18n import set_language, tr
+from doubao_input.ui.control_window import ControlWindow
+from doubao_input.ui.setup_actions import SetupActions
+from doubao_input.ui.overlay import Overlay
+from doubao_input.polish import ApiKeyStore, PolishManager
+from doubao_input.updates import UpdateChecker
+from doubao_input.update_install import prepare as prepare_update, launch as launch_update, consume_result as consume_update_result
+from doubao_input.polish_preview import PolishPreview
+from doubao_input.trigger.escape_guard import EscapeGuard
+from doubao_input.diagnostics import DiagnosticTrace, report as diagnostic_report
+from doubao_input.recognition_providers import recognition_provider
+
+logger = logging.getLogger(__name__)
+
+
+
+def _application_class():
+ from doubao_input.app import DoubaoInputApp
+ return DoubaoInputApp
+
+
+class RuntimeMixin:
+ def _on_shutdown(self, _app) -> None:
+ from doubao_input.chatgpt import close_chatgpt
+ close_chatgpt()
+ logger.info("shutting down")
+ if self._escape_timer is not None:
+ GLib.source_remove(self._escape_timer)
+ self._escape_timer = None
+ if self._escape_guard:
+ self._escape_guard.close()
+ if self._tray:
+ self._tray.close()
+ self._tray = None
+ if self._tm:
+ self._tm.audio_capture.stop()
+ self._tm.asr_client.disconnect()
+ if self._setup_session:
+ self._setup_session.dismiss()
+ if self._triggers:
+ self._triggers.close()
+ if self._delivery:
+ self._delivery.close(self._injector.close)
+ if self._polisher:
+ self._polisher.close()
+ if getattr(self, "_asr_probe", None):
+ self._asr_probe.disconnect()
+ self._asr_probe = None
+ if self._update_checker:
+ self._update_checker.close()
+ if self._update_timer:
+ GLib.source_remove(self._update_timer)
+ self._update_timer = None
+
+
+ def _build(self) -> None:
+ self._overlay = Overlay(self.app_state)
+ self._injector = Injector()
+ self._delivery = Delivery(GLib.timeout_add, focused_target,
+ lambda text, target, cancelled: self._injector.inject(text, expected_target=target, cancelled=cancelled,
+ method=self.settings.input_method),
+ lambda target, cancelled: self._injector.send_enter(expected_target=target, cancelled=cancelled),
+ self._delivery_changed, InputWorker(GLib.idle_add))
+ self._polisher = PolishManager(GLib.idle_add)
+
+ # ---- TranscriptionManager (state machine) ----
+ tm = self._new_transcription_manager()
+ # Replace its audio_capture with our instance so we can wire RMS
+ self._audio_capture = AudioCapture(on_rms=self._on_audio_rms)
+ self._audio_capture.device = self.settings.microphone
+ self._overlay.reduced_motion = self.settings.reduced_motion
+ self._overlay.waveform_style = self.settings.waveform_style
+ tm.audio_capture = self._audio_capture
+
+ tm.on_show_login = self._connect_recognition
+ tm.on_overlay_show = lambda: self._overlay.show(tr("Starting voice recognition…", "正在启动语音识别…"))
+ tm.on_overlay_hide = self._hide_recording_overlay
+ tm.on_overlay_update = self._recording_text_updated
+ tm.on_paste = self._do_paste
+ tm.on_empty_complete = self._empty_complete
+ tm.on_recover = self._recover_partial
+ tm.on_cancel_enabled_changed = lambda enabled: None
+ tm.on_auth_expired = self._on_auth_expired
+ tm.on_params_needed = self._provide_params
+ tm.on_diagnostic = self._trace_input
+ self._tm = tm
+
+ # ---- Control window ----
+ self._control = ControlWindow(
+ app_state=self.app_state,
+ on_login_clicked=self._connect_recognition,
+ on_quit_clicked=self._quit,
+ on_check_mic_clicked=self._check_mic,
+ app=self,
+ actions=SetupActions(
+ test_voice=self._test_voice,
+ cancel_preview=self._cancel_voice_test,
+ open_settings=self._show_settings,
+ is_preview_testing=lambda: self._preview_testing,
+ summary=self._summary,
+ complete_setup=self._complete_setup,
+ apply_key=self._apply_trigger_key,
+ capture_key=self._begin_key_capture,
+ cancel_key_capture=self._end_key_capture,
+ polish_settings=lambda: self.settings,
+ polish_has_key=self._polish_has_key,
+ save_polish=self._save_polish,
+ test_polish=self._test_polish,
+ apply_microphone=self._apply_microphone,
+ apply_asr_provider=self._apply_asr_provider,
+ asr_has_key=self._api_key_has_saved,
+ save_asr=self._save_asr_key,
+ test_asr=self._test_asr_key,
+ check_updates=lambda: self._update_checker.check(force=True),
+ install_update=self._install_update,
+ open_personal=self._show_personal,
+ ),
+ )
+ self._update_checker = UpdateChecker(GLib.idle_add, self._update_available, status=self._update_status)
+ try:
+ self._personal_store.history(limit=0)
+ except Exception:
+ self._control.set_feedback(tr("Could not open local input history.", "无法打开本地输入历史。"))
+ self._update_checker.check()
+ update_result = consume_update_result()
+ if update_result and not update_result["success"]:
+ self.app_state.error_message = tr("The previous update failed. The previous installation was restored; details are in the update log.", "上次更新失败,已恢复旧安装;详情保存在更新日志中。")
+ self._update_timer = GLib.timeout_add_seconds(3600, self._check_updates)
+
+ self._setup_session = SetupSession(self._audio_capture, self._overlay,
+ self._control.set_feedback, self._control.set_preview, tm.handle_cancel,
+ GLib.timeout_add, GLib.source_remove, self._control.refresh)
+ self._escape_guard = EscapeGuard(lambda message: self._control.set_feedback(
+ tr("Could not protect Escape: ", "无法拦截 Esc:") + message))
+ self._escape_timer = GLib.timeout_add(50, self._sync_escape)
+ self._triggers = TriggerController(TriggerReader, GLib.timeout_add, GLib.source_remove,
+ escape_edge=self._escape_guard.edge,
+ start=self._voice_start, stop=self._voice_stop, toggle=self._voice_toggle,
+ enter=self._voice_enter, cancel_input=self._cancel_input,
+ shortcut=self._injector.send_shortcut,
+ prime=self._voice_prime, discard=self._tm.discard_primed_audio,
+ is_recording=lambda: self.app_state.is_recording,
+ debug_edge=self._debug_edge, error=lambda message: logger.warning("PTT error: %s", message))
+
+ # ---- Initial state: cached params? ----
+ self._sync_recognition_status()
+
+ # ---- PTT trigger ----
+ from doubao_input.ui.tray import Tray
+ try:
+ self._tray = Tray(self.app_state, self._control.show, menu_entries=[
+ (lambda: tr("Open control center", "打开控制中心"), self._control.show),
+ (lambda: tr("Settings", "设置"), lambda: (self._control.show(), self._show_settings())),
+ (lambda: tr("Check microphone", "检查麦克风"), self._check_mic),
+ (lambda: tr("Copy recent result", "复制最近结果"), self._copy_recent),
+ (lambda: tr("Cancel recording / input", "取消录音或输入"), self._cancel_input),
+ ])
+ except GLib.Error:
+ logger.exception("System tray unavailable; desktop launcher remains usable")
+ self._triggers.configure(self.settings)
+ if self._trigger_debug_requested:
+ from doubao_input.ui.trigger_debug import TriggerDebug
+ self._debug_session = TriggerDebug(self, self._exit_trigger_debug)
+ logger.info("build complete")
+
+
+ def _exit_trigger_debug(self):
+ if self._debug_session:
+ session, self._debug_session = self._debug_session, None
+ session.close()
+ return True
+
+
+ def _update_available(self, info):
+ self._control.set_update(info)
+ self._overlay.set_update(info)
+
+
+ def _update_status(self, value):
+ if self._update_installing:
+ return
+ if value == "current":
+ self._control.set_update(None); self._overlay.set_update(None)
+ messages = {
+ "checking": tr("Checking for updates…", "正在检查更新…"),
+ "current": tr("You are using the latest version.", "当前已是最新版本。"),
+ "available": tr("Update available. Click Update to download and restart.", "发现新版本,点击更新即可下载并重启。"),
+ "failed": tr("Could not check for updates. Try again later.", "更新检查失败,请稍后重试。"),
+ }
+ self._control.set_update_status(messages[value], value == "checking")
+
+
+ def _install_update(self, info):
+ if self._update_installing:
+ return
+ if self._busy():
+ self._control.set_feedback(tr("Finish dictation or testing before updating.", "请先结束听写或测试,再安装更新。"))
+ return
+ if not self._control.flush_edits() or (self._settings_window and not self._settings_window.flush_edits()) or (self._personal_window and not self._personal_window.flush()):
+ self._control.set_feedback(tr("Correct unsaved settings before updating.", "请先修正未保存的设置,再更新。"))
+ return
+ self._update_installing = True
+ self._control.set_update_status(tr("Downloading update…", "正在下载更新…"), True)
+ def prepared(scratch, error):
+ self._update_installing = False
+ if error or self._busy():
+ if scratch:
+ shutil.rmtree(scratch)
+ self._control.set_update_status(tr("Update was not installed: ", "更新未安装:") + (error or tr("finish dictation first", "请先结束听写")))
+ return False
+ if not self._control.flush_edits() or (self._settings_window and not self._settings_window.flush_edits()) or (self._personal_window and not self._personal_window.flush()):
+ shutil.rmtree(scratch)
+ self._control.set_update_status(tr("Correct unsaved settings before updating.", "请先修正未保存的设置,再更新。"))
+ return False
+ try:
+ launch_update(scratch)
+ except OSError:
+ shutil.rmtree(scratch)
+ self._control.set_update_status(tr("Could not start the updater; the installed app is unchanged.", "无法启动更新程序,已安装的应用未改变。"))
+ return False
+ self._quit()
+ return False
+ def worker():
+ scratch = None
+ try:
+ def status(message):
+ phases = {
+ "Downloading release source…": tr("Downloading release source…", "正在下载更新源码…"),
+ "Downloading update…": tr("Downloading update…", "正在下载更新…"),
+ "Verifying update…": tr("Verifying update…", "正在核验更新包…"),
+ }
+ GLib.idle_add(lambda: self._control.set_update_status(phases.get(message, message), True))
+ scratch = prepare_update(info, status=status)
+ error = None
+ except Exception as exc:
+ logger.info("Update preparation failed (%s)", type(exc).__name__)
+ message = str(exc)
+ if "Local changes exist" in message:
+ error = tr("Local source changes exist. Commit or move them before updating.", "源码中有本地修改,请先提交或移走,再更新。")
+ elif "package manager" in message:
+ error = tr("Use your package manager to update this installation.", "此安装由系统包管理器管理,请通过包管理器更新。")
+ elif "Release is missing" in message:
+ error = tr("No update package matches this CPU and Python version.", "此版本没有匹配当前 CPU 和 Python 的更新包。")
+ else:
+ error = tr("Check the connection, release package and installation permissions.", "请检查网络、更新包和安装目录权限。")
+ GLib.idle_add(prepared, scratch, error)
+ Thread(target=worker, name="doubao-update-download", daemon=True).start()
+
+
+ def _remember_input(self, original, output, polished):
+ store = getattr(self, "_personal_store", None)
+ if not store:
+ return
+ try:
+ self._history_id = store.record(original, output, polished)
+ except Exception:
+ self._history_id = None
+ self._control.set_feedback(tr("Could not save local input history. Input is still available.", "本地输入历史保存失败,文字仍可输入。"))
+
+
+ def _can_evaluate_speech(self):
+ audio = getattr(self, "_audio_capture", None)
+ # A held gesture may be buffering audio while the visible state is idle.
+ return not self._busy() and not (audio and audio.is_capturing)
+
+
+ def _show_personal(self):
+ from doubao_input.ui.personal_window import PersonalWindow
+ if self._personal_window is None:
+ self._personal_window = PersonalWindow(self._personal_store, lambda: self.settings, self._polish_key, self.recent, self._retry_recent, self._can_evaluate_speech)
+ self._personal_window.show()
+
+
+ def _check_updates(self):
+ try:
+ self._personal_store.history(limit=0)
+ except Exception:
+ logger.warning("Could not prune local history")
+ self._update_checker.check()
+ return True
+
+
+ def _debug_edge(self, code, pressed):
+ if not self._debug_session:
+ return False
+ if key_codes_match(code, self.settings.doubao_key):
+ self._debug_session.edge(pressed)
+ return True
+
+
+ def _apply_trigger_key(self, key, modifiers=()):
+ from dataclasses import replace
+ key, modifiers = canonical_shortcut(key, modifiers)
+ self.apply_settings(replace(self.settings, doubao_key=key,
+ doubao_modifiers=modifiers))
+
+
+ def _apply_microphone(self, device):
+ from dataclasses import replace
+ self.apply_settings(replace(self.settings, microphone=device))
+
+
+ def _apply_asr_provider(self, provider):
+ from dataclasses import replace
+ self.apply_settings(replace(self.settings, asr_provider=provider))
+
+
+ def apply_settings(self, settings):
+ settings.validate()
+ if settings.autostart and "/omarchy/plugins/" in __file__:
+ raise ValueError(tr("This installation is started by Omarchy. Disable plugin startup before using a standalone autostart installation.",
+ "当前安装由 Omarchy 插件启动。请勿同时启用独立应用自启动。"))
+ if self._busy() or self._triggers.busy:
+ raise ValueError(tr("Finish the current operation and release the trigger before saving", "请先结束当前操作并松开触发键,再保存设置"))
+ previous = self.settings
+ if previous.asr_provider != settings.asr_provider:
+ # A modal Settings window can open while onboarding's debounce is
+ # pending. Both drafts still belong to the provider being left.
+ for view in (self._control, self._settings_window):
+ if view and not view._flush_asr_key():
+ raise ValueError(tr(
+ "Save the current API key before switching services.",
+ "请先保存当前 API Key,再切换识别服务。"))
+
+ def apply_runtime(value, strict):
+ self._triggers.configure(value, strict=strict)
+ self._audio_capture.device = value.microphone
+ self._overlay.reduced_motion = value.reduced_motion
+ self._overlay.waveform_style = value.waveform_style
+
+ apply_preferences(previous, settings,
+ lambda value: apply_runtime(value, True),
+ lambda value: apply_runtime(value, False))
+ self.settings = settings
+ if previous.asr_provider != settings.asr_provider:
+ self._configure_recognition_backend()
+ self._sync_recognition_status()
+ self._setup_session.voice_ok = False
+ if previous.microphone != settings.microphone:
+ self._setup_session.microphone_ok = self._setup_session.voice_ok = False
+ self._control.refresh()
+
+
+ def _trace_input(self, stage):
+ self._diagnostics.add(stage)
+ if stage == "gesture_confirmed":
+ self._input_latency.reset()
+ elif stage == "stop_requested":
+ self._input_latency.stop()
+
+
+ def _new_transcription_manager(self):
+ provider = recognition_provider(self.settings.asr_provider)
+ return TranscriptionManager(
+ self.app_state,
+ asr_client=provider.new_client(),
+ credential_store=provider.credential_store,
+ interactive_auth=provider.interactive_auth,
+ clear_rejected_credentials=provider.clear_rejected_credentials,
+ )
+
+
+ def _configure_recognition_backend(self):
+ if self._asr_probe:
+ self._asr_probe.disconnect()
+ self._asr_probe = None
+ provider = recognition_provider(self.settings.asr_provider)
+ self._tm.configure_backend(
+ provider.new_client(),
+ provider.credential_store,
+ interactive_auth=provider.interactive_auth,
+ clear_rejected_credentials=provider.clear_rejected_credentials,
+ )
+
+
+ def _recognition_ready(self):
+ try:
+ return recognition_provider(
+ self.settings.asr_provider
+ ).credential_store.has_saved()
+ except (OSError, ValueError):
+ return False
+
+
+ def _sync_recognition_status(self):
+ self.app_state.login_status = (LoginStatus.LOGGED_IN if self._recognition_ready()
+ else LoginStatus.NOT_LOGGED_IN)
diff --git a/src/doubao_input/app_voice.py b/src/doubao_input/app_voice.py
new file mode 100644
index 0000000..f0b75a9
--- /dev/null
+++ b/src/doubao_input/app_voice.py
@@ -0,0 +1,521 @@
+"""Voice delivery and polishing lifecycle."""
+from __future__ import annotations
+
+import logging
+import signal
+import shutil
+from threading import Thread
+from dataclasses import replace
+
+import gi
+
+gi.require_version("Gtk", "4.0")
+from gi.repository import Gio, GLib, Gtk # type: ignore
+
+from doubao_input.doubao.app_state import AppState, LoginStatus, RecordingState
+from doubao_input.doubao.audio_capture import AudioCapture
+from doubao_input.inject.delivery import Delivery
+from doubao_input.inject.target import focused_target
+from doubao_input.result import RecentResult
+from doubao_input.doubao.params_store import ParamsStore
+from doubao_input.doubao.transcription import TranscriptionManager
+from doubao_input.inject.injector import Injector
+from doubao_input.trigger.reader import TriggerReader
+from doubao_input.trigger.controller import TriggerController
+from doubao_input.setup_session import SetupSession
+from doubao_input.inject.worker import InputWorker
+from doubao_input.preferences import apply_preferences
+from doubao_input.settings import (Settings, canonical_shortcut,
+ key_codes_match, trigger_shortcut_display)
+from doubao_input.i18n import set_language, tr
+from doubao_input.ui.control_window import ControlWindow
+from doubao_input.ui.setup_actions import SetupActions
+from doubao_input.ui.overlay import Overlay
+from doubao_input.polish import ApiKeyStore, PolishManager
+from doubao_input.updates import UpdateChecker
+from doubao_input.update_install import prepare as prepare_update, launch as launch_update, consume_result as consume_update_result
+from doubao_input.polish_preview import PolishPreview
+from doubao_input.trigger.escape_guard import EscapeGuard
+from doubao_input.diagnostics import DiagnosticTrace, report as diagnostic_report
+from doubao_input.recognition_providers import recognition_provider
+
+logger = logging.getLogger(__name__)
+
+
+
+def _application_class():
+ from doubao_input.app import DoubaoInputApp
+ return DoubaoInputApp
+
+
+class VoiceMixin:
+ def _voice_start(self):
+ if getattr(self, "_polish_mode", None) == "final" and self._polisher.busy:
+ self._cancel_polish(use_original=True)
+ return
+ if getattr(self, "_personal_window", None) and self._personal_window.evaluation and self._personal_window.evaluation.active:
+ return
+ if self._mic_test_running or self._triggers.capturing or self._recovery_timer:
+ return
+ if self.app_state.recording_state == RecordingState.IDLE and not self._paste_pending:
+ if not self._preview_testing:
+ self._setup_session.dismiss()
+ self._enter_after_paste = False
+ self._target = None if self._preview_testing else focused_target()
+ self._reset_prepolish()
+ self._tm.handle_toggle()
+
+
+ def _voice_prime(self):
+ if (not self._mic_test_running and not self._triggers.capturing
+ and not self._recovery_timer and not self._paste_pending
+ and getattr(self, "_polish_mode", None) != "final"
+ and not (getattr(self, "_personal_window", None) and self._personal_window.evaluation and self._personal_window.evaluation.active)):
+ self._tm.prime_recording()
+
+
+ def _voice_stop(self):
+ if getattr(self, "_polish_mode", None) == "final" and self._polisher.busy:
+ self._cancel_polish(use_original=True)
+ return
+ if self.app_state.recording_state in (RecordingState.STARTING, RecordingState.RECORDING):
+ self._tm.handle_toggle()
+
+
+ def _voice_toggle(self):
+ if getattr(self, "_personal_window", None) and self._personal_window.evaluation and self._personal_window.evaluation.active:
+ return
+ if getattr(self, "_polish_mode", None) == "final" and self._polisher.busy:
+ self._cancel_polish(use_original=True)
+ return
+ if self.app_state.recording_state == RecordingState.IDLE:
+ if self._mic_test_running or self._triggers.capturing or self._recovery_timer:
+ return
+ if not self._paste_pending:
+ if not self._preview_testing:
+ self._setup_session.dismiss()
+ self._enter_after_paste = False
+ self._target = None if self._preview_testing else focused_target()
+ self._reset_prepolish()
+ self._tm.handle_toggle()
+ else:
+ self._voice_stop()
+
+
+ def _voice_enter(self):
+ if getattr(self, "_personal_window", None) and self._personal_window.evaluation and self._personal_window.evaluation.active:
+ return
+ if self._mic_test_running or self._triggers.capturing or self._recovery_timer:
+ return
+ if self._preview_testing:
+ self._voice_stop()
+ return
+ if getattr(self, "_polish_mode", None) == "final" and self._polisher.busy:
+ self._cancel_polish(use_original=True, send_enter=True)
+ return
+ if self._paste_pending:
+ self._delivery.request_enter()
+ elif self.app_state.recording_state == RecordingState.IDLE:
+ self._send_enter()
+ else:
+ self._enter_after_paste = True
+ self._voice_stop()
+
+
+ def _send_enter(self):
+ self._delivery.submit_enter(focused_target(), changed=self._enter_changed)
+ return GLib.SOURCE_REMOVE
+
+
+ def _enter_changed(self, status):
+ messages = {
+ "pending": tr("Sending Enter…", "正在发送回车…"),
+ "attempted": tr("Enter sent.", "已发送回车。"),
+ "cancelled": tr("Enter cancelled.", "已取消回车。"),
+ }
+ self._control.set_feedback(messages.get(status, tr(
+ "Enter not sent; check the target field.", "未发送回车,请检查目标输入框。")))
+
+
+ def _empty_complete(self):
+ if self._preview_testing:
+ self._setup_session.complete_voice("")
+ self._control.refresh()
+ return
+ self._enter_after_paste = False
+ self._control.set_feedback(tr("No speech recognized. Nothing was sent.", "没有识别到语音,未发送任何内容。"))
+
+
+ def _hide_recording_overlay(self):
+ # Transcription resets to IDLE immediately after handing us the final
+ # text. Keep the same single overlay visible while the network polish
+ # is still running instead of making that phase look like a hang.
+ if self._polish_mode != "final":
+ self._overlay.hide()
+
+
+ def _do_paste(self, text: str) -> None:
+ if self._setup_session.complete_voice(text):
+ self._control.refresh()
+ return
+ latency = getattr(self, "_input_latency", None)
+ if latency:
+ latency.mark("asr")
+ text = _application_class()._uncommitted_text(self, text)
+ if not text:
+ return
+ send_enter, self._enter_after_paste = self._enter_after_paste, False
+ if self.settings.polish_enabled:
+ self._cancel_prepolish_timer()
+ if self._preview_polish.snapshot == text and self._preview_polish.result:
+ result = self._preview_polish.result
+ self._reset_prepolish(cancel_request=False)
+ self._submit_transcript(result, self._target, send_enter, original=text)
+ return
+ api_key = self._polish_key()
+ if api_key:
+ self.recent.keep(text, "polishing")
+ self._control.set_result(text, tr("Polishing… press the trigger to use the original",
+ "正在润色…再次按快捷键可直接使用原文"))
+ self._overlay.show_polishing(text)
+ self._polish_context = (text, self._target, send_enter)
+ if getattr(self, "_polish_mode", None) == "pre" and self._preview_polish.inflight == text and self._polisher.busy:
+ self._polish_mode = "final"
+ return
+ # Do not wait for an in-flight speculative request here. It
+ # may be stuck in an uninterruptible network read. A final
+ # request has its own executor and an intentionally shorter
+ # timeout, so release-to-paste stays bounded.
+ self._polisher.cancel()
+ self._polish_mode = "final"
+ logger.info("Starting final polish request")
+ self._polisher.start(text, self.settings, api_key, self._polish_finished,
+ progress=self._polish_progress)
+ return
+ self._control.set_feedback(tr("Polishing is enabled but no API key is saved; using the original text.",
+ "润色已开启但没有保存 API Key,本次使用原文。"))
+ self._submit_transcript(text, self._target, send_enter)
+
+
+ def _submit_transcript(self, text, target, send_enter=False, *, original=None):
+ latency = getattr(self, "_input_latency", None)
+ if latency:
+ latency.mark("polish")
+ self._remember_input(original if original is not None else text, text, original is not None)
+ self.recent.keep(text)
+ self._control.set_result(self.recent.text, tr("Ready to input", "准备输入"))
+ self._overlay.set_status(
+ tr("Polished · Sending text…", "润色完成 · 正在输入…") if original
+ else tr("Sending text…", "正在输入…"))
+ # Never hide/restore an arbitrary foreground settings window to force input.
+ # A missing or changed target keeps the text in recovery instead.
+ if not self._delivery.submit(text, target, send_enter):
+ logger.warning("Delivery rejected before it could start")
+ self._delivery_changed("failed")
+
+
+ def _polish_finished(self, result, error):
+ self._polish_mode = None
+ context, self._polish_context = self._polish_context, None
+ if not context:
+ return
+ original, target, send_enter = context
+ if result:
+ logger.info("Final polish completed; submitting delivery")
+ self._submit_transcript(result, target, send_enter, original=original)
+ else:
+ logger.warning("Final polish failed or timed out; using original text")
+ self._control.set_feedback(error + tr("; using the original text.", ";本次使用原文。"))
+ self._submit_transcript(original, target, send_enter)
+
+
+ def _polish_progress(self, text):
+ if not text:
+ return
+ if self._polish_mode == "final":
+ self._overlay.set_text(text)
+ elif self._polish_mode == "pre" and self.app_state.is_recording:
+ self._overlay.set_text(text)
+
+
+ def _recording_text_updated(self, text):
+ text = self._uncommitted_text(text)
+ if self._polish_mode == "pre" and text.strip() == self._preview_polish.inflight:
+ return
+ if self._preview_polish.result and text.strip() == self._preview_polish.snapshot:
+ return
+ self._overlay.set_status(tr("Listening…", "正在聆听…"))
+ self._overlay.set_text(text)
+
+
+ def _uncommitted_text(self, text):
+ # Every session delivers once, with its full correction context.
+ return text.strip()
+
+
+ def _cancel_polish(self, *, use_original=False, send_enter=False):
+ context, self._polish_context = self._polish_context, None
+ self._polisher.cancel()
+ self._polish_mode = None
+ self._reset_prepolish(cancel_request=False)
+ self._overlay.hide()
+ if use_original and context:
+ original, target, pending_enter = context
+ self._submit_transcript(original, target, send_enter or pending_enter)
+ self._control.set_feedback(tr("Polishing cancelled; original text used.",
+ "已停止润色并使用原文。"))
+
+
+ def _delivery_changed(self, status):
+ store = getattr(self, "_personal_store", None)
+ if store:
+ try:
+ store.status(self._history_id, status)
+ latency = getattr(self, "_input_latency", None)
+ if latency and status != "pending":
+ latency.mark("delivery")
+ store.save_timings(self._history_id, latency.values)
+ except Exception:
+ logger.warning("Could not update local input history")
+ diagnostics = getattr(self, "_diagnostics", None)
+ if diagnostics:
+ diagnostics.add("delivery_pending" if status == "pending"
+ else "delivery_finished")
+ self.recent.status = status
+ messages = {
+ "pending": tr("Sending text…", "正在输入…"),
+ "attempted": tr("Input sent. If text is missing, copy or retry below.", "已发送输入操作;若未出现文字,可在下方复制或重试。"),
+ "target_changed": tr("Target changed or unavailable. Text kept; choose a target and retry.", "目标窗口已变化或无法确认。文字已保留,请选择目标后重试。"),
+ "failed": tr("Input failed. Your text is kept here; some may already have been entered. For direct typing, check wtype and desktop support.", "输入失败,文字已保留;可能已有部分文字输入。使用直接输入时,请检查 wtype 和桌面支持。"),
+ "enter_skipped": tr("Input attempted; Enter skipped because the target changed or input failed.", "已尝试输入;因目标变化或输入失败,未发送回车。"),
+ "cancelled": tr("Input cancelled. Text already entered cannot be withdrawn.", "已取消输入,已输入的文字无法撤回。"),
+ }
+ self._control.set_result(self.recent.text, messages.get(status, status))
+ self._control.set_feedback(messages.get(status, status))
+ if status != "pending":
+ self._overlay.hide()
+ if status in ("target_changed", "failed", "enter_skipped"):
+ self._notify_recovery()
+
+
+ def _notify_recovery(self):
+ notice = Gio.Notification.new(tr("Doubao Say", "豆包说"))
+ notice.set_body(tr("Your text is kept in the app. Open Doubao Say to copy or retry.",
+ "文字已保留在应用中,打开豆包说即可复制或重试。"))
+ notice.set_default_action("app.open-control")
+ self.send_notification("input-recovery", notice)
+
+
+ def _recover_partial(self, text):
+ self._enter_after_paste = False
+ if self._preview_testing:
+ self._control.set_preview(text)
+ return
+ self.recent.keep(text, "partial")
+ self._control.set_result(self.recent.text, tr("Incomplete recognition — not pasted", "识别未完成,未粘贴"))
+ self._notify_recovery()
+
+
+ def _copy_recent(self):
+ if self.recent.text:
+ from gi.repository import Gdk
+ Gdk.Display.get_default().get_clipboard().set(self.recent.text)
+ self._control.set_feedback(tr("Copied. Clipboard contents remain until replaced.", "已复制;剪贴板内容会保留到被替换。"))
+
+
+ def _clear_recent(self):
+ self._cancel_input()
+ self.recent.clear()
+ self._control.set_result("", tr("Cleared from app memory; system clipboard is unchanged.", "已清除应用内文字,系统剪贴板不变。"))
+
+
+ def _retry_recent(self):
+ if self._busy() or not self.recent.text:
+ self._control.set_feedback(tr("Finish the current operation first.", "请先结束当前操作。"))
+ return
+ self._control.set_feedback(tr("Choose your target text field within 3 seconds. No Enter will be sent.", "请在三秒内点击目标输入框,本次不会发送回车。"))
+ text = self.recent.text
+ def retry():
+ self._recovery_timer = None
+ self._remember_input(text, text, False)
+ self._delivery.submit(text, focused_target())
+ return False
+ self._recovery_timer = GLib.timeout_add(3000, retry)
+
+
+ def _cancel_input(self):
+ if getattr(self, "_personal_window", None) and self._personal_window.evaluation:
+ self._personal_window.evaluation.cancel()
+ self._enter_after_paste = False
+ if self._triggers:
+ self._triggers.cancel_gesture()
+ if self._setup_session:
+ self._setup_session.dismiss()
+ if self._recovery_timer:
+ GLib.source_remove(self._recovery_timer)
+ self._recovery_timer = None
+ if self._delivery:
+ self._delivery.cancel()
+ if self._polisher:
+ self._cancel_polish()
+ if self._tm:
+ self._tm.handle_cancel()
+
+
+ def _busy(self):
+ return (bool(getattr(self, "_asr_probe", None)) or bool(getattr(self, "_personal_window", None) and self._personal_window.evaluation and self._personal_window.evaluation.active) or self.app_state.recording_state != RecordingState.IDLE or self._mic_test_running
+ or self._paste_pending or (self._triggers is not None and self._triggers.capturing)
+ or self._recovery_timer is not None
+ or bool(self._polisher and self._polisher.busy))
+
+
+ def _save_polish(self, settings, api_key=None):
+ # PolishSettings can outlive other UI changes and hold a stale full
+ # Settings snapshot. Merge only its fields into the current settings so
+ # a delayed polish save cannot revert the trigger key or other options.
+ settings = replace(self.settings,
+ polish_enabled=settings.polish_enabled,
+ polish_provider=settings.polish_provider,
+ polish_chatgpt_model=settings.polish_chatgpt_model,
+ polish_base_url=settings.polish_base_url,
+ polish_model=settings.polish_model,
+ polish_prompt_zh=settings.polish_prompt_zh,
+ polish_prompt_en=settings.polish_prompt_en)
+ settings.validate()
+ previous_key = ApiKeyStore.load()
+ effective_key = api_key or previous_key
+ if settings.polish_provider == "chatgpt":
+ from doubao_input.chatgpt import chatgpt_client
+ if settings.polish_enabled and (not chatgpt_client().ready() or not settings.polish_chatgpt_model):
+ raise ValueError(tr("Connect ChatGPT and select a model before enabling polishing.",
+ "请先连接 ChatGPT 并选择模型,再启用润色。"))
+ elif settings.polish_enabled and not effective_key:
+ raise ValueError(tr("Enter an API key before enabling polishing.",
+ "开启润色前请填写 API Key。"))
+ if api_key:
+ ApiKeyStore.save(api_key)
+ try:
+ self.apply_settings(settings)
+ except Exception:
+ if previous_key:
+ ApiKeyStore.save(previous_key)
+ elif api_key:
+ ApiKeyStore.clear()
+ raise
+
+
+ def _test_polish(self, settings, api_key, completed):
+ settings.validate()
+ if settings.polish_provider == "chatgpt":
+ from doubao_input.chatgpt import chatgpt_client
+ if not chatgpt_client().ready() or not settings.polish_chatgpt_model:
+ raise ValueError(tr("Connect ChatGPT and select a model first.", "请先连接 ChatGPT 并选择模型。"))
+ key = "chatgpt-plan"
+ else:
+ key = api_key or self._polish_key()
+ if not key:
+ raise ValueError(tr("Enter an API key first.", "请先填写 API Key。"))
+ if self._busy():
+ raise ValueError(tr("Finish the current operation first.", "请先结束当前操作。"))
+ self._polisher.start(tr("Um, I think, I think this is a test.", "嗯,我觉得,就是说,这是一个测试。"),
+ settings, key, completed)
+
+
+ def _polish_key(self):
+ try:
+ if getattr(self.settings, "polish_provider", "api") == "chatgpt":
+ from doubao_input.chatgpt import chatgpt_client
+ return "chatgpt-plan" if chatgpt_client().ready() else ""
+ return ApiKeyStore.load()
+ except (OSError, ValueError):
+ logger.exception("Could not read polishing API key")
+ return ""
+
+
+ def _polish_has_key(self):
+ return bool(self._polish_key())
+
+
+ def _on_audio_rms(self, rms):
+ self._overlay.push_rms(rms)
+ speaking = rms >= 0.012
+ if speaking != self._rms_speaking:
+ self._rms_speaking = speaking
+ GLib.idle_add(self._prepolish_speech_changed, speaking)
+
+
+ def _prepolish_text_changed(self, _state, text):
+ if not self.settings.polish_enabled or not self.app_state.is_recording:
+ return
+ text = _application_class()._uncommitted_text(self, text)
+ self._preview_polish.invalidate(text)
+ if self._polish_mode == "pre" and text.strip() != self._preview_polish.inflight:
+ self._polisher.cancel()
+ self._polish_mode = None
+ self._preview_polish.inflight = ""
+ if not self._rms_speaking and text.strip():
+ self._arm_prepolish()
+
+
+ def _prepolish_speech_changed(self, speaking):
+ if not self.settings.polish_enabled or not self.app_state.is_recording:
+ return False
+ if speaking:
+ self._cancel_prepolish_timer()
+ # RMS includes breathing and room noise. Only a changed ASR
+ # transcript invalidates work; otherwise the same text gets
+ # repeatedly cancelled and submitted again.
+ elif self.app_state.transcription_text.strip():
+ self._arm_prepolish()
+ return False
+
+
+ def _arm_prepolish(self):
+ self._preview_polish.arm(self._start_prepolish)
+
+
+ def _cancel_prepolish_timer(self):
+ self._preview_polish.cancel_timer()
+
+
+ def _start_prepolish(self):
+ text = self._uncommitted_text(self.app_state.transcription_text)
+ key = self._polish_key()
+ if (not text or not key or self._rms_speaking or not self.app_state.is_recording
+ or self._polisher.busy):
+ return False
+ if text == self._preview_polish.snapshot:
+ return False
+ self._preview_polish.begin(text)
+ self._polish_mode = "pre"
+ logger.info("Starting speculative polish request")
+ self._overlay.set_status(tr("Polishing preview · still listening", "预润色中 · 仍在聆听"))
+ self._overlay.set_text(text)
+ self._polisher.start(text, self.settings, key, self._prepolish_finished,
+ speculative=True, progress=self._polish_progress)
+ return False
+
+
+ def _prepolish_finished(self, result, error):
+ if self._polish_mode == "final":
+ self._polish_finished(result, error)
+ return
+ snapshot = self._preview_polish.inflight
+ self._polish_mode = None
+ self._preview_polish.inflight = ""
+ if (snapshot and snapshot == self._uncommitted_text(self.app_state.transcription_text)
+ and self.app_state.is_recording):
+ if not result:
+ result = snapshot
+ self._control.set_feedback(tr("Polishing unavailable; using original text.", "润色未完成,本次使用原文。"))
+ self._preview_polish.finish(snapshot, result)
+ self._overlay.set_status(tr("Preview ready · finish recording to paste", "预览就绪 · 结束录音后上屏"))
+ self._overlay.set_text(result)
+
+
+ def _reset_prepolish(self, *, cancel_request=True):
+ self._cancel_prepolish_timer()
+ if cancel_request and self._polish_mode == "pre" and self._polisher:
+ self._polisher.cancel()
+ self._polish_mode = None
+ self._preview_polish.reset()
diff --git a/src/doubao_input/chatgpt.py b/src/doubao_input/chatgpt.py
new file mode 100644
index 0000000..6cf88e5
--- /dev/null
+++ b/src/doubao_input/chatgpt.py
@@ -0,0 +1,271 @@
+"""Application-owned accounts, renewal and text polishing with ChatGPT plan usage."""
+from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout
+import json
+from threading import Event, Lock
+import time
+from urllib import request
+import uuid
+import webbrowser
+
+from doubao_input import chatgpt_auth as auth
+from doubao_input.chatgpt_store import ChatGPTStore, active_account
+from doubao_input.polish_transport import open_request, RequestCancellation
+
+
+class ChatGPTClient:
+ def __init__(self, directory=None):
+ self.store = ChatGPTStore(directory)
+ self._signing = None
+ self._lock = Lock()
+ self._renewal = None
+ self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="chatgpt-renewal")
+ self._requests = set()
+ self._generation = 0
+
+ def state(self, timeout=1):
+ with self.store.transaction(timeout=timeout) as data:
+ return {"active_id": data.get("active_id"), "signing_in": self._signing is not None,
+ "accounts": [{"id": account["id"],
+ "label": account.get("email") or account.get("name") or "ChatGPT",
+ "connected": bool(account.get("subject") and account.get("access")),
+ "sharing": bool(account.get("subject") and account.get("access")
+ and auth.DIRECT_SCOPE in account.get("scopes", []))}
+ for account in data["accounts"]]}
+
+ def ready(self):
+ try:
+ state = self.state(timeout=0)
+ except ValueError:
+ return False
+ return any(item["id"] == state["active_id"] and item["sharing"] for item in state["accounts"])
+
+ def _invalidate(self):
+ with self._lock:
+ self._generation += 1
+ for cancellation in self._requests:
+ cancellation.set()
+
+ def sign_in(self, new_account=False):
+ with self._lock:
+ if self._signing is not None:
+ raise auth.ChatGPTError("sign_in_pending", "ChatGPT sign-in is already in progress")
+ cancelled = self._signing = Event()
+ try:
+ with self.store.transaction(timeout=1) as data:
+ account = None if new_account else active_account(data)
+ account = dict(account) if account else None
+ host_id = data["host_id"]
+ profile_id = account["id"] if account else str(uuid.uuid4())
+
+ def save_registration(client_id):
+ with self.store.transaction() as data:
+ if not any(item["id"] == profile_id for item in data["accounts"]):
+ data["accounts"].append({"id": profile_id, "client_id": client_id, "scopes": []})
+ data.setdefault("active_id", profile_id)
+
+ result = auth.sign_in(host_id, account, cancelled, save_registration)
+ if cancelled.is_set():
+ raise auth.ChatGPTError("cancelled", "ChatGPT sign-in cancelled")
+ self._invalidate()
+ with self.store.transaction() as data:
+ if cancelled.is_set():
+ raise auth.ChatGPTError("cancelled", "ChatGPT sign-in cancelled")
+ previous = next(item for item in data["accounts"] if item["id"] == profile_id)
+ previous.update(result)
+ data["active_id"] = profile_id
+ return self.state()
+ finally:
+ with self._lock:
+ self._signing = None
+
+ def cancel_sign_in(self):
+ with self._lock:
+ if self._signing is not None:
+ self._signing.set()
+
+ def select(self, profile_id):
+ if self._signing is not None:
+ raise auth.ChatGPTError("sign_in_pending", "Finish or cancel sign-in before switching accounts")
+ self._invalidate()
+ with self.store.transaction() as data:
+ if not any(item["id"] == profile_id for item in data["accounts"]):
+ raise auth.ChatGPTError("unknown_account", "ChatGPT account not found")
+ data["active_id"] = profile_id
+ return self.state()
+
+ def sign_out(self):
+ self.cancel_sign_in()
+ self._invalidate()
+ revoked = True
+ with self.store.transaction() as data:
+ account = active_account(data)
+ if account:
+ if account.get("refresh"):
+ try:
+ discovery = auth.json_request(auth.ISSUER + "/.well-known/openid-configuration", timeout=10)
+ endpoint = discovery.get("revocation_endpoint", "")
+ from urllib.parse import urlsplit
+ if urlsplit(endpoint).scheme != "https" or urlsplit(endpoint).netloc != "auth.openai.com":
+ raise ValueError()
+ auth.json_request(endpoint, fields={"token": account["refresh"],
+ "token_type_hint": "refresh_token", "client_id": account["client_id"]}, timeout=10)
+ except ValueError:
+ revoked = False
+ self._clear_tokens(account)
+ return revoked
+
+ @staticmethod
+ def _clear_tokens(account):
+ for field in ("access", "refresh", "identity", "expires", "refresh_after"):
+ account.pop(field, None)
+ account["scopes"] = []
+
+ def _renew(self):
+ failure = None
+ result = None
+ with self.store.transaction() as data:
+ account = active_account(data)
+ if not account or not account.get("subject") or not account.get("access"):
+ raise auth.ChatGPTError("reauth_required", "Connect ChatGPT first")
+ if account.get("expires", 0) > time.time() + 120:
+ return account["access"]
+ if (account.get("refresh_after") or 0) > time.time():
+ if account.get("expires", 0) <= time.time():
+ raise auth.ChatGPTError("refresh_not_ready", "Try renewing ChatGPT access again shortly")
+ return account["access"]
+ if not account.get("refresh"):
+ raise auth.ChatGPTError("reauth_required", "Reconnect ChatGPT")
+ try:
+ token = auth.token_request({"grant_type": "refresh_token", "client_id": account["client_id"],
+ "refresh_token": account["refresh"], "resource": auth.RESOURCE})
+ if token.get("id_token"):
+ identity = auth.verify_identity(token["id_token"], account["client_id"])
+ if identity["subject"] != account["subject"]:
+ raise auth.ChatGPTError("invalid_identity", "Reconnect ChatGPT")
+ account.update(auth.token_fields(token, account))
+ result = account["access"]
+ except auth.ChatGPTError as exc:
+ if exc.code not in {"reauth_required", "invalid_identity"}:
+ raise
+ self._clear_tokens(account)
+ failure = auth.ChatGPTError("reauth_required", "Reconnect ChatGPT")
+ if failure:
+ raise failure
+ return result
+
+ def access(self, timeout=30):
+ with self.store.transaction(timeout=min(timeout, 1)) as data:
+ account = active_account(data)
+ if not account or not account.get("access") or not account.get("subject"):
+ raise auth.ChatGPTError("reauth_required", "Connect ChatGPT first")
+ if auth.DIRECT_SCOPE not in account.get("scopes", []):
+ raise auth.ChatGPTError("sharing_required", "Enable ChatGPT plan usage for Doubao Say")
+ if account.get("expires", 0) > time.time() + 120:
+ return account["access"]
+ # Renewal belongs to the connection, not to a five-second polish request.
+ # A cancelled caller must not discard a replacement rotating token.
+ with self._lock:
+ if self._renewal is None or self._renewal.done():
+ self._renewal = self._executor.submit(self._renew)
+ renewal = self._renewal
+ try:
+ result = renewal.result(timeout=timeout)
+ except FutureTimeout:
+ raise auth.ChatGPTError("renewal_pending", "ChatGPT access is renewing; using original text") from None
+ with self.store.transaction(timeout=1) as data:
+ if auth.DIRECT_SCOPE not in (active_account(data) or {}).get("scopes", []):
+ raise auth.ChatGPTError("sharing_required", "Enable ChatGPT plan usage for Doubao Say")
+ return result
+
+ def models(self):
+ generation = self._generation
+ data = auth.json_request(auth.RESOURCE + "/models", token=self.access())
+ if generation != self._generation:
+ raise auth.ChatGPTError("account_changed", "ChatGPT account changed; refresh its model list")
+ if not isinstance(data.get("models"), list):
+ raise auth.ChatGPTError("invalid_models", "Unable to load ChatGPT models")
+ return [{"slug": item["slug"], "label": item["display_name"]} for item in data["models"]
+ if isinstance(item, dict) and item.get("visibility") == "list"
+ and isinstance(item.get("slug"), str) and isinstance(item.get("display_name"), str)]
+
+ def polish(self, text, *, model, prompt, timeout=5, on_progress=None, cancellation=None, **_):
+ cancellation = cancellation or RequestCancellation()
+ cancellation.check()
+ started = time.monotonic()
+ generation = self._generation
+ token = self.access(timeout=max(0.01, timeout - (time.monotonic() - started)))
+ if generation != self._generation:
+ raise auth.ChatGPTError("account_changed", "ChatGPT account changed")
+ cancellation.check()
+ remaining = timeout - (time.monotonic() - started)
+ if remaining <= 0:
+ raise ValueError("Polishing exceeded 5 seconds")
+ payload = {"model": model, "store": False, "stream": True,
+ "input": [{"role": "developer", "content": prompt}, {"role": "user", "content": text}]}
+ req = request.Request(auth.RESOURCE + "/responses", data=json.dumps(payload).encode(),
+ headers={"Authorization": "Bearer " + token, "Content-Type": "application/json"})
+ with self._lock:
+ if generation != self._generation:
+ raise auth.ChatGPTError("account_changed", "ChatGPT account changed")
+ self._requests.add(cancellation)
+ try:
+ with open_request(req, timeout=remaining, cancellation=cancellation) as response:
+ result = completed_text(response, on_progress)
+ cancellation.check()
+ if generation != self._generation:
+ raise auth.ChatGPTError("account_changed", "ChatGPT account changed")
+ return result
+ except (OSError, ValueError) as exc:
+ if isinstance(exc, auth.ChatGPTError):
+ raise
+ raise ValueError("ChatGPT polishing did not complete; using original text") from None
+ finally:
+ with self._lock:
+ self._requests.discard(cancellation)
+
+ def close(self):
+ self.cancel_sign_in()
+ self._invalidate()
+ self._executor.shutdown(wait=False, cancel_futures=False)
+
+
+def completed_text(response, progress=None):
+ text, frame, count, completed = "", [], 0, False
+ for raw in response:
+ count += len(raw)
+ if count > 1_000_000:
+ raise ValueError("ChatGPT response is too large")
+ line = raw.decode("utf-8").rstrip("\r\n")
+ if line.startswith("data:"):
+ frame.append(line[5:].lstrip())
+ elif not line and frame:
+ event = json.loads("\n".join(frame))
+ frame = []
+ kind = event.get("type")
+ if kind == "response.output_text.delta":
+ text += event.get("delta", "")
+ if progress:
+ progress(text)
+ elif kind == "response.completed":
+ completed = True
+ break
+ elif kind in {"response.failed", "response.incomplete", "error"}:
+ raise auth.ChatGPTError("inference_failed", "ChatGPT did not finish; check your plan usage")
+ if not completed or not text.strip():
+ raise auth.ChatGPTError("incomplete", "ChatGPT response ended before completion")
+ return text.strip()
+
+
+_client = None
+
+
+def chatgpt_client():
+ global _client
+ if _client is None:
+ _client = ChatGPTClient()
+ return _client
+
+
+def close_chatgpt():
+ if _client is not None:
+ _client.close()
diff --git a/src/doubao_input/chatgpt_auth.py b/src/doubao_input/chatgpt_auth.py
new file mode 100644
index 0000000..da7b621
--- /dev/null
+++ b/src/doubao_input/chatgpt_auth.py
@@ -0,0 +1,212 @@
+"""Sign in with ChatGPT using the documented local PKCE/OIDC protocol."""
+import base64
+from datetime import datetime
+import hashlib
+from http.server import BaseHTTPRequestHandler, HTTPServer
+import json
+import math
+from queue import Empty, Queue
+import secrets
+from threading import Thread
+import time
+from urllib import error, parse, request
+import webbrowser
+
+from doubao_input.polish_transport import open_request
+
+ISSUER = "https://auth.openai.com"
+RESOURCE = "https://api.openai.com/v1"
+DIRECT_SCOPE = "chatgpt.tokens.use.direct"
+USAGE_URL = "https://chatgpt.com/settings/usage"
+UNUSABLE = {"invalid_grant", "invalid_refresh_token", "token_expired",
+ "refresh_token_expired", "refresh_token_invalidated", "refresh_token_reused"}
+
+
+class ChatGPTError(ValueError):
+ def __init__(self, code, message):
+ super().__init__(message)
+ self.code = code
+
+
+def json_request(url, *, fields=None, timeout=30, token=None):
+ headers = {"Accept": "application/json"}
+ payload = None
+ if fields is not None:
+ payload = parse.urlencode(fields).encode()
+ headers["Content-Type"] = "application/x-www-form-urlencoded"
+ if token:
+ headers["Authorization"] = "Bearer " + token
+ req = request.Request(url, data=payload, headers=headers)
+ try:
+ with open_request(req, timeout=timeout) as response:
+ raw = response.read(1_000_001)
+ if len(raw) > 1_000_000:
+ raise ChatGPTError("invalid_response", "ChatGPT response is too large")
+ return json.loads(raw) if raw else {}
+ except error.HTTPError as exc:
+ # HTTP errors are closed by open_request; never echo a credentialed body.
+ raise ChatGPTError("request_failed", "ChatGPT request failed; check the connection and usage") from exc
+ except (error.URLError, OSError, ValueError) as exc:
+ if isinstance(exc, ChatGPTError):
+ raise
+ raise ChatGPTError("request_failed", "ChatGPT request failed; try again") from None
+
+
+def token_request(fields):
+ req = request.Request(ISSUER + "/api/accounts/oauth/token",
+ data=parse.urlencode(fields).encode(),
+ headers={"Content-Type": "application/x-www-form-urlencoded"})
+ def classify(exc):
+ try:
+ raw = exc.read(100_001)
+ data = json.loads(raw) if len(raw) <= 100_000 else {}
+ code = data.get("error")
+ exc.machine_code = code.get("code") if isinstance(code, dict) else code
+ except (ValueError, OSError):
+ exc.machine_code = None
+
+ try:
+ with open_request(req, timeout=30, on_error=classify) as response:
+ raw = response.read(1_000_001)
+ if len(raw) > 1_000_000:
+ raise ChatGPTError("invalid_response", "Invalid ChatGPT token response")
+ data = json.loads(raw)
+ except error.HTTPError as exc:
+ code = getattr(exc, "machine_code", None)
+ unusable = isinstance(code, str) and code in UNUSABLE
+ kind = "reauth_required" if unusable else "invalid_client" if code == "invalid_client" else "token_request_failed"
+ raise ChatGPTError(kind, "Reconnect ChatGPT" if unusable else "ChatGPT token exchange failed") from None
+ except (OSError, ValueError, error.URLError):
+ raise ChatGPTError("token_request_failed", "ChatGPT token exchange failed") from None
+ if (not isinstance(data, dict) or not isinstance(data.get("access_token"), str)
+ or not data["access_token"] or str(data.get("token_type", "")).lower() != "bearer"
+ or not isinstance(data.get("expires_in"), (int, float))
+ or not math.isfinite(data["expires_in"]) or data["expires_in"] <= 0
+ or ("scope" in data and not isinstance(data["scope"], str))
+ or ("refresh_token" in data and not isinstance(data["refresh_token"], str))):
+ raise ChatGPTError("invalid_response", "Invalid ChatGPT token response")
+ return data
+
+
+def token_fields(data, previous=None):
+ previous = previous or {}
+ earliest = data.get("earliest_refresh_at")
+ if isinstance(earliest, str):
+ try:
+ parsed = datetime.fromisoformat(earliest.replace("Z", "+00:00"))
+ if parsed.tzinfo is None:
+ raise ValueError()
+ earliest = parsed.timestamp()
+ except ValueError:
+ raise ChatGPTError("invalid_response", "Invalid ChatGPT refresh time") from None
+ if earliest is not None and (not isinstance(earliest, (int, float)) or not math.isfinite(earliest)):
+ raise ChatGPTError("invalid_response", "Invalid ChatGPT refresh time")
+ return {"access": data["access_token"], "refresh": data.get("refresh_token", previous.get("refresh")),
+ "identity": data.get("id_token", previous.get("identity")),
+ "expires": time.time() + data["expires_in"], "refresh_after": earliest,
+ "scopes": data["scope"].split() if "scope" in data else previous.get("scopes", [])}
+
+
+def verify_identity(token, client_id, nonce=None):
+ import jwt
+ try:
+ keys = jwt.PyJWKClient(ISSUER + "/.well-known/jwks.json", timeout=15)
+ key = keys.get_signing_key_from_jwt(token)
+ claims = jwt.decode(token, key.key, algorithms=["RS256"], issuer=ISSUER,
+ audience=client_id, options={"require": ["exp", "iat", "sub"]})
+ if not claims.get("sub") or (nonce is not None and claims.get("nonce") != nonce):
+ raise ValueError()
+ return {"subject": claims["sub"],
+ "email": claims.get("email") if isinstance(claims.get("email"), str) else None,
+ "name": claims.get("name") if isinstance(claims.get("name"), str) else None}
+ except (jwt.PyJWTError, ValueError):
+ raise ChatGPTError("invalid_identity", "ChatGPT identity verification failed") from None
+
+
+def callback_values(url, state, client_id=None):
+ query = parse.parse_qs(parse.urlsplit(url).query)
+ value = lambda key: query.get(key, [""])[0]
+ if not secrets.compare_digest(value("state"), state):
+ raise ChatGPTError("invalid_state", "Invalid ChatGPT sign-in callback")
+ if value("error"):
+ raise ChatGPTError("access_denied", "ChatGPT sign-in was not approved")
+ issued = value("client_id") or client_id
+ if not issued or issued == "dynamic_agent_client" or (client_id and issued != client_id):
+ raise ChatGPTError("invalid_client", "Unexpected ChatGPT registration")
+ if not value("code"):
+ raise ChatGPTError("missing_code", "Missing ChatGPT authorization code")
+ return issued, value("code")
+
+
+def sign_in(host_id, account, cancelled, save_registration, open_browser=webbrowser.open):
+ account = account or {}
+ state, nonce, verifier = (secrets.token_urlsafe(32) for _ in range(3))
+ challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip("=")
+ queue = Queue(maxsize=1)
+
+ class Callback(BaseHTTPRequestHandler):
+ def log_message(self, *_):
+ pass
+
+ def do_GET(self):
+ status, message = 200, "Return to Doubao Say to finish connecting ChatGPT."
+ try:
+ if (parse.urlsplit(self.path).path != "/auth/callback"
+ or self.headers.get("Host") != f"127.0.0.1:{self.server.server_port}" or not queue.empty()):
+ self.send_error(404)
+ return
+ result = callback_values(self.path, state, account.get("client_id"))
+ queue.put_nowait(result)
+ except ChatGPTError as exc:
+ status, message = 400, "Return to Doubao Say and try signing in again."
+ if exc.code != "invalid_state" and queue.empty():
+ queue.put_nowait(exc)
+ self.send_response(status)
+ self.send_header("Content-Type", "text/plain; charset=utf-8")
+ self.send_header("Cache-Control", "no-store")
+ self.send_header("Referrer-Policy", "no-referrer")
+ self.send_header("Content-Security-Policy", "default-src 'none'")
+ self.end_headers()
+ self.wfile.write(message.encode())
+
+ server = HTTPServer(("127.0.0.1", 0), Callback)
+ server.timeout = 1
+ serving = Thread(target=server.serve_forever, daemon=True)
+ serving.start()
+ redirect = f"http://127.0.0.1:{server.server_port}/auth/callback"
+ fields = {"client_id": account.get("client_id", "dynamic_agent_client"), "ext_agent_host_id": host_id,
+ "response_type": "code", "redirect_uri": redirect, "resource": RESOURCE,
+ "scope": "openid profile email offline_access resource.invoke " + DIRECT_SCOPE,
+ "state": state, "nonce": nonce, "code_challenge": challenge, "code_challenge_method": "S256"}
+ if not account.get("client_id"):
+ fields["agent_name_hint"] = "Doubao Say"
+ if account.get("identity"):
+ fields["id_token_hint"] = account["identity"]
+ if account.get("email"):
+ fields["login_hint"] = account["email"]
+ try:
+ if not open_browser(ISSUER + "/api/accounts/authorize?" + parse.urlencode(fields)):
+ raise ChatGPTError("browser_failed", "Open your browser to connect ChatGPT")
+ deadline = time.monotonic() + 300
+ while True:
+ if cancelled.is_set() or time.monotonic() >= deadline:
+ raise ChatGPTError("cancelled", "ChatGPT sign-in cancelled")
+ try:
+ result = queue.get(timeout=0.1)
+ break
+ except Empty:
+ pass
+ if isinstance(result, Exception):
+ raise result
+ client_id, code = result
+ save_registration(client_id)
+ data = token_request({"grant_type": "authorization_code", "client_id": client_id, "code": code,
+ "code_verifier": verifier, "redirect_uri": redirect, "resource": RESOURCE})
+ identity = verify_identity(data.get("id_token", ""), client_id, nonce)
+ if account.get("subject") and identity["subject"] != account["subject"]:
+ raise ChatGPTError("account_mismatch", "Reconnect using the original ChatGPT account")
+ return {"client_id": client_id, **identity, **token_fields(data)}
+ finally:
+ server.shutdown()
+ server.server_close()
+ serving.join(timeout=2)
diff --git a/src/doubao_input/chatgpt_store.py b/src/doubao_input/chatgpt_store.py
new file mode 100644
index 0000000..c36c871
--- /dev/null
+++ b/src/doubao_input/chatgpt_store.py
@@ -0,0 +1,59 @@
+"""Owner-only, process-locked storage for this app's ChatGPT connection."""
+from contextlib import contextmanager
+import fcntl
+import json
+import os
+import stat
+import time
+import uuid
+
+from doubao_input.settings import config_dir, write_atomic
+
+
+class ChatGPTStore:
+ def __init__(self, directory=None):
+ self.directory = directory or config_dir() / "doubao-say" / "chatgpt"
+
+ @contextmanager
+ def transaction(self, timeout=35):
+ self.directory.mkdir(mode=0o700, parents=True, exist_ok=True)
+ if self.directory.is_symlink():
+ raise ValueError("Unsafe ChatGPT credential directory")
+ self.directory.chmod(0o700)
+ flags = os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW
+ descriptor = os.open(self.directory / "connection.lock", flags, 0o600)
+ try:
+ deadline = time.monotonic() + timeout
+ while True:
+ try:
+ fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ break
+ except BlockingIOError:
+ if time.monotonic() >= deadline:
+ raise ValueError("ChatGPT connection is busy; try again shortly")
+ time.sleep(0.02)
+ path = self.directory / "accounts.json"
+ try:
+ info = path.lstat()
+ if not stat.S_ISREG(info.st_mode) or path.is_symlink():
+ raise ValueError("Unsafe ChatGPT credential file")
+ path.chmod(0o600)
+ try:
+ data = json.loads(path.read_text())
+ except (ValueError, UnicodeError):
+ raise ValueError("Invalid ChatGPT connection data") from None
+ if (not isinstance(data, dict) or data.get("version") != 1
+ or not isinstance(data.get("accounts"), list)):
+ raise ValueError("Invalid ChatGPT connection data")
+ uuid.UUID(data["host_id"].removeprefix("urn:uuid:"))
+ except FileNotFoundError:
+ data = {"version": 1, "host_id": "urn:uuid:" + str(uuid.uuid4()), "accounts": []}
+ yield data
+ write_atomic(path, json.dumps(data).encode())
+ finally:
+ fcntl.flock(descriptor, fcntl.LOCK_UN)
+ os.close(descriptor)
+
+
+def active_account(data):
+ return next((item for item in data["accounts"] if item["id"] == data.get("active_id")), None)
diff --git a/src/doubao_input/polish.py b/src/doubao_input/polish.py
index 40bab07..2060287 100644
--- a/src/doubao_input/polish.py
+++ b/src/doubao_input/polish.py
@@ -67,6 +67,10 @@ def chat_completions_url(base_url):
class PolishClient:
+ def polish_chatgpt(self, text, **options):
+ from doubao_input.chatgpt import chatgpt_client
+ return chatgpt_client().polish(text, **options)
+
def polish(self, text, *, base_url, api_key, model, prompt, timeout=25,
on_progress=None, cancellation=None):
body = {"model": model, "temperature": 0.2,
@@ -184,9 +188,12 @@ class PolishManager:
return False
self._dispatch(deliver_progress)
- future = executor.submit(self._client.polish, text,
+ using_chatgpt = getattr(settings, "polish_provider", "api") == "chatgpt"
+ operation = self._client.polish_chatgpt if using_chatgpt else self._client.polish
+ future = executor.submit(operation, text,
base_url=settings.polish_base_url, api_key=api_key,
- model=settings.polish_model, prompt=polish_prompt_for_text(text, settings),
+ model=settings.polish_chatgpt_model if using_chatgpt else settings.polish_model,
+ prompt=polish_prompt_for_text(text, settings),
timeout=timeout, on_progress=report if progress else None, cancellation=cancellation)
self._future = future
diff --git a/src/doubao_input/polish_transport.py b/src/doubao_input/polish_transport.py
index 32cae4e..e1ee0c4 100644
--- a/src/doubao_input/polish_transport.py
+++ b/src/doubao_input/polish_transport.py
@@ -96,7 +96,7 @@ class _NoRedirect(request.HTTPRedirectHandler):
@contextmanager
-def open_request(req, *, timeout, cancellation=None):
+def open_request(req, *, timeout, cancellation=None, on_error=None):
cancellation = cancellation or RequestCancellation()
cancellation.check()
@@ -123,7 +123,11 @@ def open_request(req, *, timeout, cancellation=None):
yield response
cancellation.check()
except error.HTTPError as exc:
- exc.close()
+ try:
+ if on_error is not None:
+ on_error(exc)
+ finally:
+ exc.close()
raise
finally:
deadline.cancel()
diff --git a/src/doubao_input/preflight.py b/src/doubao_input/preflight.py
index 4a2da3a..0d76c99 100644
--- a/src/doubao_input/preflight.py
+++ b/src/doubao_input/preflight.py
@@ -10,7 +10,7 @@ from doubao_input.desktop import is_x11
def check_runtime():
# pw-record is required by check_system() and provides native capture.
# sounddevice is only an optional PortAudio fallback.
- return {**check_system(), **_check_modules(("evdev", "websockets"))}
+ return {**check_system(), **_check_modules(("evdev", "websockets", "jwt", "cryptography"))}
def _check_modules(modules):
diff --git a/src/doubao_input/product.py b/src/doubao_input/product.py
index ba72000..883a4e1 100644
--- a/src/doubao_input/product.py
+++ b/src/doubao_input/product.py
@@ -1,6 +1,6 @@
"""Single runtime source for Doubao Say release identity."""
-VERSION = "1.7.0"
+VERSION = "1.8.0"
REPOSITORY_URL = "https://github.com/quanru/doubao-say"
LATEST_RELEASE_API = "https://api.github.com/repos/quanru/doubao-say/releases/latest"
LATEST_RELEASE_FEED = REPOSITORY_URL + "/releases/latest/download/update.json"
diff --git a/src/doubao_input/settings.py b/src/doubao_input/settings.py
index 7ae3ee3..d640ee1 100644
--- a/src/doubao_input/settings.py
+++ b/src/doubao_input/settings.py
@@ -235,6 +235,8 @@ class Settings:
reduced_motion: bool = False
waveform_style: str = "bars"
polish_enabled: bool = False
+ polish_provider: str = "api"
+ polish_chatgpt_model: str = ""
polish_base_url: str = "https://api.openai.com/v1"
polish_model: str = "gpt-4o-mini"
polish_prompt_zh: str = DEFAULT_POLISH_PROMPT_ZH
@@ -256,6 +258,11 @@ class Settings:
raise ValueError("Invalid preference type")
if type(self.polish_enabled) is not bool:
raise ValueError(tr("Invalid polishing setting", "无效的润色设置"))
+ if self.polish_provider not in ("api", "chatgpt"):
+ raise ValueError(tr("Invalid polishing provider", "无效的润色服务"))
+ if (not isinstance(self.polish_chatgpt_model, str) or len(self.polish_chatgpt_model) > 256
+ or any(c in self.polish_chatgpt_model for c in "\n\r\x00")):
+ raise ValueError(tr("Invalid ChatGPT model", "无效的 ChatGPT 模型"))
try:
endpoint = urlsplit(self.polish_base_url)
except (TypeError, ValueError) as exc:
diff --git a/src/doubao_input/ui/chatgpt_settings.py b/src/doubao_input/ui/chatgpt_settings.py
new file mode 100644
index 0000000..f2e3958
--- /dev/null
+++ b/src/doubao_input/ui/chatgpt_settings.py
@@ -0,0 +1,150 @@
+"""Native account controls; all tokens remain inside the local connection client."""
+from concurrent.futures import ThreadPoolExecutor
+import webbrowser
+import weakref
+
+from gi.repository import GLib, Gtk
+
+from doubao_input.chatgpt import chatgpt_client
+from doubao_input.chatgpt_auth import USAGE_URL
+from doubao_input.i18n import tr
+
+
+class ChatGPTSettings(Gtk.Box):
+ def __init__(self, model, changed, client=None):
+ super().__init__(orientation=Gtk.Orientation.VERTICAL, spacing=8)
+ self.client = client or chatgpt_client()
+ self._changed = changed
+ self._updating = False
+ self._closed = False
+ self._busy = False
+ self._revision = 0
+ self._owns_sign_in = False
+ self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="chatgpt-settings")
+ weakref.finalize(self, self._executor.shutdown, wait=False, cancel_futures=True)
+ self.append(Gtk.Label(xalign=0, wrap=True, label=tr(
+ "Connect ChatGPT to polish speech with your existing plan. Recognition still uses your selected speech service. Requests count toward your ChatGPT usage; the five-second original-text fallback still applies.",
+ "连接 ChatGPT,使用已有套餐润色文字。语音识别仍由已选语音服务提供;请求计入 ChatGPT 用量,超过五秒仍回退原文。")))
+ self.status = Gtk.Label(xalign=0, wrap=True)
+ self.append(self.status)
+ self.accounts = Gtk.ComboBoxText()
+ self.append(Gtk.Label(xalign=0, label=tr("ChatGPT account", "ChatGPT 账号")))
+ self.accounts.connect("changed", self._selected)
+ self.append(self.accounts)
+ self.models = Gtk.ComboBoxText()
+ self.append(Gtk.Label(xalign=0, label=tr("ChatGPT model", "ChatGPT 模型")))
+ self.models.connect("changed", self._model_changed)
+ self.append(self.models)
+ self.model = model
+ actions = Gtk.Box(spacing=8)
+ self.connect_button = Gtk.Button(label="Continue with ChatGPT")
+ self.connect_button.connect("clicked", lambda *_: self._connect())
+ actions.append(self.connect_button)
+ cancel = Gtk.Button(label=tr("Cancel sign-in", "取消登录"))
+ cancel.connect("clicked", lambda *_: self.client.cancel_sign_in())
+ actions.append(cancel)
+ self.append(actions)
+ actions = Gtk.Box(spacing=8)
+ add = Gtk.Button(label=tr("Add account", "添加账号"))
+ add.connect("clicked", lambda *_: self._connect(new_account=True))
+ actions.append(add)
+ disconnect = Gtk.Button(label=tr("Disconnect", "退出连接"))
+ disconnect.connect("clicked", lambda *_: self._run(self._disconnect))
+ actions.append(disconnect)
+ usage = Gtk.Button(label=tr("Manage usage", "管理用量"))
+ usage.connect("clicked", lambda *_: webbrowser.open(USAGE_URL))
+ actions.append(usage)
+ self.append(actions)
+ refresh = Gtk.Button(label=tr("Refresh models", "刷新模型"))
+ refresh.connect("clicked", lambda *_: self._run(lambda: None))
+ self.append(refresh)
+ self.connect("unmap", self._close)
+ self.connect("map", self._mapped)
+ self._run(lambda: None)
+
+ def _connect(self, new_account=False):
+ if self._busy or self._closed:
+ return
+ self._owns_sign_in = True
+ self._run(lambda: self.client.sign_in(new_account=new_account))
+
+ def _disconnect(self):
+ if not self.client.sign_out():
+ raise ValueError(tr("Local connection cleared. Review app access in ChatGPT settings.",
+ "本机连接已清除,请到 ChatGPT 设置检查应用授权。"))
+
+ def _run(self, operation):
+ if self._busy or self._closed:
+ return
+ self._busy = True
+ revision = self._revision
+ self.connect_button.set_sensitive(False)
+ self.status.set_text(tr("Connecting to ChatGPT…", "正在处理 ChatGPT 连接…"))
+
+ def work():
+ try:
+ operation()
+ state = self.client.state()
+ models = self.client.models() if self.client.ready() else []
+ result = state, models, ""
+ except Exception:
+ result = None, [], tr("ChatGPT connection could not finish. Try again or manage usage.",
+ "ChatGPT 连接未完成,请重试或检查用量。")
+ GLib.idle_add(self._finished, revision, *result)
+ self._executor.submit(work)
+
+ def _finished(self, revision, state, models, message):
+ if self._closed or revision != self._revision:
+ return False
+ self._busy = False
+ self._owns_sign_in = False
+ self.connect_button.set_sensitive(True)
+ self._updating = True
+ try:
+ self.accounts.remove_all()
+ self.models.remove_all()
+ if state:
+ for account in state["accounts"]:
+ self.accounts.append(account["id"], account["label"])
+ if state["active_id"]:
+ self.accounts.set_active_id(state["active_id"])
+ for item in models:
+ self.models.append(item["slug"], item["label"])
+ available = [item["slug"] for item in models]
+ selected = self.model if self.model in available else available[0] if available else None
+ if selected:
+ self.models.set_active_id(selected)
+ else:
+ self.models.set_active(-1)
+ finally:
+ self._updating = False
+ self._model_changed()
+ self.status.set_text(message or tr("ChatGPT plan connected" if models else "ChatGPT is not connected for plan usage",
+ "ChatGPT 套餐已连接" if models else "尚未连接 ChatGPT 套餐"))
+ return False
+
+ def _selected(self, *_):
+ profile_id = self.accounts.get_active_id()
+ if not self._updating and profile_id:
+ self._run(lambda: self.client.select(profile_id))
+
+ def _model_changed(self, *_):
+ if not self._updating:
+ self.model = self.models.get_active_id() or ""
+ self._changed()
+
+ def ready(self):
+ return bool(self.model) and self.client.ready()
+
+ def _close(self, *_):
+ self._closed = True
+ self._revision += 1
+ self._busy = False
+ if self._owns_sign_in:
+ self.client.cancel_sign_in()
+ self._owns_sign_in = False
+
+ def _mapped(self, *_):
+ if self._closed:
+ self._closed = False
+ self._run(lambda: None)
diff --git a/src/doubao_input/ui/polish_settings.py b/src/doubao_input/ui/polish_settings.py
index dfc2db3..fc3db8c 100644
--- a/src/doubao_input/ui/polish_settings.py
+++ b/src/doubao_input/ui/polish_settings.py
@@ -6,6 +6,7 @@ from gi.repository import GLib, Gtk, Pango
from doubao_input.i18n import tr
from doubao_input.settings import DEFAULT_POLISH_PROMPT_EN, DEFAULT_POLISH_PROMPT_ZH
from doubao_input.reasoning import reasoning_policy
+from doubao_input.ui.chatgpt_settings import ChatGPTSettings
class PolishSettings(Gtk.Box):
@@ -29,6 +30,15 @@ class PolishSettings(Gtk.Box):
self.status = Gtk.Label(xalign=0, wrap=True)
self.append(self.status)
+ self.provider = Gtk.ComboBoxText()
+ self.provider.append("api", tr("API key", "API Key"))
+ self.provider.append("chatgpt", tr("ChatGPT plan", "ChatGPT 套餐"))
+ self.provider.set_active_id(settings.polish_provider)
+ self.append(self._row(tr("Polishing service", "润色服务"), self.provider))
+ self.chatgpt = ChatGPTSettings(settings.polish_chatgpt_model, self._queue_save)
+ self.chatgpt.set_visible(settings.polish_provider == "chatgpt")
+ self.append(self.chatgpt)
+
self.details = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
self.append(self.details)
self.details.append(Gtk.Label(xalign=0, wrap=True, label=tr(
@@ -43,8 +53,9 @@ class PolishSettings(Gtk.Box):
self.api_key.set_invisible_char("•")
self.api_key.set_placeholder_text(tr("Saved — leave blank to keep" if has_key else "Required when enabled",
"已保存,留空则保持不变" if has_key else "启用时必填"))
- self.details.append(self._row("Base URL", self.base_url))
- self.details.append(self._row("Model", self.model))
+ self.api_rows = [self._row("Base URL", self.base_url), self._row("Model", self.model)]
+ for row in self.api_rows:
+ self.details.append(row)
self.latency_guidance = Gtk.Label(xalign=0, wrap=True, label=tr(
"Choose a small, fast model and turn thinking off, even for Flash/Lite models. Try DeepSeek Flash (deepseek-flash) or Gemini 2.5 Flash-Lite (gemini-2.5-flash-lite) on their official endpoints; thinking-off is requested automatically. Large reasoning models may exceed the 5-second limit and fall back to your original text.",
"优先选择小型、低延迟模型,并关闭思考,Flash/Lite 模型也不例外。建议使用 DeepSeek Flash(deepseek-flash)或 Gemini 2.5 Flash-Lite(gemini-2.5-flash-lite)的官方接口,应用会自动请求关闭思考。大型推理模型可能超过五秒上限,导致回退原文。"))
@@ -56,7 +67,9 @@ class PolishSettings(Gtk.Box):
self.base_url.connect("changed", self._update_reasoning_notice)
self.model.connect("changed", self._update_reasoning_notice)
self._update_reasoning_notice()
- self.details.append(self._row("API Key", self.api_key))
+ key_row = self._row("API Key", self.api_key)
+ self.api_rows.append(key_row)
+ self.details.append(key_row)
self.details.append(Gtk.Label(xalign=0, wrap=True, label=tr(
"The API key is stored separately with owner-only permissions and excluded from diagnostics.",
"API Key 使用仅限当前用户读取的独立文件保存,不会出现在诊断信息中。")))
@@ -107,6 +120,23 @@ class PolishSettings(Gtk.Box):
self.prompt_zh.get_buffer().connect("changed", self._queue_save)
self.prompt_en.get_buffer().connect("changed", self._queue_save)
self.connect("unmap", self._flush)
+ self.provider.connect("changed", self._provider_changed)
+ self._provider_changed(save=False)
+
+ def _provider_changed(self, *_, save=True):
+ using_chatgpt = self.provider.get_active_id() == "chatgpt"
+ self.chatgpt.set_visible(using_chatgpt)
+ for row in self.api_rows:
+ row.set_visible(not using_chatgpt)
+ self.latency_guidance.set_visible(not using_chatgpt)
+ self.reasoning_notice.set_visible(not using_chatgpt)
+ if save:
+ self._queue_save()
+
+ def _ready(self):
+ if self.provider.get_active_id() == "chatgpt":
+ return self.chatgpt.ready()
+ return bool(self._has_key or self.api_key.get_text().strip())
def _row(self, title, widget):
row = Gtk.Box(spacing=12)
@@ -129,6 +159,7 @@ class PolishSettings(Gtk.Box):
prompt_en = en_buffer.get_text(en_buffer.get_start_iter(),
en_buffer.get_end_iter(), True)
settings = replace(self._settings, polish_enabled=self.enabled.get_active(),
+ polish_provider=self.provider.get_active_id(), polish_chatgpt_model=self.chatgpt.model,
polish_base_url=self.base_url.get_text().strip(),
polish_model=self.model.get_text().strip(),
polish_prompt_zh=prompt_zh, polish_prompt_en=prompt_en)
@@ -148,9 +179,9 @@ class PolishSettings(Gtk.Box):
return
enabled = self.enabled.get_active()
self.details.set_visible(enabled)
- if enabled and not self._has_key:
- self.status.set_text(tr("Enter an API key to enable voice polishing.",
- "请输入 API Key 以启用语音润色。"))
+ if enabled and not self._ready():
+ self.status.set_text(tr("Connect the selected service and choose a model to enable polishing.",
+ "请连接已选服务并选择模型,以启用润色。"))
return
if self._save_now():
self.status.set_text(tr("Voice polishing enabled." if enabled else "Voice polishing disabled.",
@@ -179,9 +210,9 @@ class PolishSettings(Gtk.Box):
def _save_now(self):
if self._changing:
return True
- if self.enabled.get_active() and not (self._has_key or self.api_key.get_text().strip()):
- self.status.set_text(tr("Enter an API key to enable voice polishing.",
- "请输入 API Key 以启用语音润色。"))
+ if self.enabled.get_active() and not self._ready():
+ self.status.set_text(tr("Connect the selected service and choose a model to enable polishing.",
+ "请连接已选服务并选择模型,以启用润色。"))
return False
try:
settings, key = self._values()
diff --git a/tests/README.md b/tests/README.md
index 1fe9192..5232ad0 100644
--- a/tests/README.md
+++ b/tests/README.md
@@ -130,6 +130,31 @@ sessions in English and Chinese. It exercises real GTK controls, temporary
credential stores, cross-window saves and main-loop completion, retaining
screenshots. Audio, keyboard injection, update checks and ASR transport are inert.
+## ChatGPT plan connection checks
+
+`tests.unit.test_chatgpt` verifies the independent PKCE/OIDC connection, RSA
+identity validation, account storage, serialized token renewal, cancellation,
+and required final completion events. All credentials and network replies in
+these unit tests are synthetic.
+
+On Linux with the application's GTK dependencies and Pillow installed, run the
+bounded native settings fixture inside an owned Xvfb desktop and a private bus:
+
+```sh
+GTK_A11Y=none SIWC_UI_SCREENSHOTS=artifacts/verification/siwc/native \
+ SIWC_UI_LANGUAGE=en PYTHONPATH=src timeout --signal=TERM --kill-after=5s 35s \
+ dbus-run-session -- .venv/bin/python tests/manual/chatgpt_ui.py
+```
+
+Repeat with `SIWC_UI_LANGUAGE=zh` for Chinese. This fixture exercises real GTK
+controls with a synthetic connection: provider selection, account connection,
+model choice, enabling without an API key, preservation of existing API
+settings, and hiding/reopening the connection card. It does not verify live
+OAuth, actual plan inference, token expiry, audio capture or paste delivery.
+Live sign-in must use a separate app-owned account store; never copy credentials
+from Codex or another product. The independent macOS preview has no ChatGPT
+connection UI in this change.
+
## Personal speech and correction checks
`tests.unit.test_personal_corrections` verifies explicit confirmation, immutable
diff --git a/tests/contracts/test_debian_package.py b/tests/contracts/test_debian_package.py
index 4d4a742..774bd08 100644
--- a/tests/contracts/test_debian_package.py
+++ b/tests/contracts/test_debian_package.py
@@ -1,6 +1,7 @@
"""Guard the Debian install path against fetching executable Python packages."""
from pathlib import Path
import unittest
+import tomllib
from unittest.mock import patch
from doubao_input import preflight
@@ -14,14 +15,16 @@ class DebianPackageTest(unittest.TestCase):
with patch.object(preflight, "check_system", return_value={"pw-record": True}), \
patch.object(preflight, "_check_modules", return_value={"evdev": True, "websockets": True}) as modules:
self.assertTrue(all(preflight.check_runtime().values()))
- modules.assert_called_once_with(("evdev", "websockets"))
+ modules.assert_called_once_with(("evdev", "websockets", "jwt", "cryptography"))
def test_runtime_dependencies_are_distribution_packages(self):
+ version = tomllib.loads((ROOT / "pyproject.toml").read_text())["project"]["version"]
+ self.assertTrue((ROOT / "debian/changelog").read_text().startswith(f"doubao-say ({version}-1)"))
control = (ROOT / "debian/control").read_text()
postinst = (ROOT / "debian/postinst").read_text()
rules = (ROOT / "debian/rules").read_text()
- for package in ("python3-websockets", "python3-evdev", "pipewire-bin"):
+ for package in ("python3-websockets", "python3-evdev", "python3-jwt", "python3-cryptography", "pipewire-bin"):
self.assertIn(package, control)
self.assertNotIn("pip", postinst)
self.assertNotIn("venv", postinst)
diff --git a/tests/contracts/test_release.py b/tests/contracts/test_release.py
index fae2a99..eae1e38 100644
--- a/tests/contracts/test_release.py
+++ b/tests/contracts/test_release.py
@@ -49,7 +49,7 @@ class ReleaseTest(unittest.TestCase):
notes = (ROOT / "RELEASE_NOTES.md").read_text()
self.assertIn("--notes-file RELEASE_NOTES.md", workflow)
self.assertNotIn("--generate-notes", workflow)
- for expected in ("Doubao Say 1.7.0", "hotwords", "confirmed corrections", "evaluation"):
+ for expected in ("Doubao Say 1.8.0", "ChatGPT", "accessibility", "clipboard", "microphone"):
self.assertIn(expected, " ".join(notes.split()))
def test_both_archives_exclude_ignored_source_files(self):
diff --git a/tests/contracts/test_version_check.py b/tests/contracts/test_version_check.py
index 3390ecf..27bdd72 100644
--- a/tests/contracts/test_version_check.py
+++ b/tests/contracts/test_version_check.py
@@ -11,13 +11,13 @@ SPEC.loader.exec_module(VERSION_CHECK)
class VersionCheckTests(unittest.TestCase):
def test_sources_are_aligned_at_current_release(self):
- self.assertEqual(VERSION_CHECK.validate(root=ROOT), "1.7.0")
+ self.assertEqual(VERSION_CHECK.validate(root=ROOT), "1.8.0")
def test_exact_release_tag_is_accepted(self):
- self.assertEqual(VERSION_CHECK.validate("v1.7.0", ROOT), "1.7.0")
+ self.assertEqual(VERSION_CHECK.validate("v1.8.0", ROOT), "1.8.0")
def test_wrong_release_tag_is_rejected(self):
- with self.assertRaisesRegex(ValueError, "must be 'v1.7.0'"):
+ with self.assertRaisesRegex(ValueError, "must be 'v1.8.0'"):
VERSION_CHECK.validate("v1.1.0", ROOT)
diff --git a/tests/manual/asr_key_ui.py b/tests/manual/asr_key_ui.py
index b236e64..818b9dd 100644
--- a/tests/manual/asr_key_ui.py
+++ b/tests/manual/asr_key_ui.py
@@ -45,11 +45,11 @@ def main():
with tempfile.TemporaryDirectory(prefix="doubao-asr-ui-") as directory, \
ExitStack() as cleanup, \
patch.dict(os.environ, {"XDG_CONFIG_HOME": directory + "/config", "XDG_DATA_HOME": directory + "/data"}), \
- patch("doubao_input.app.Overlay"), patch("doubao_input.app.AudioCapture"), \
- patch("doubao_input.app.EscapeGuard"), patch("doubao_input.app.UpdateChecker"), \
+ patch("doubao_input.app_runtime.Overlay"), patch("doubao_input.app_runtime.AudioCapture"), \
+ patch("doubao_input.app_runtime.EscapeGuard"), patch("doubao_input.app_runtime.UpdateChecker"), \
patch("doubao_input.doubao.transcription.AudioCapture"), \
- patch("doubao_input.app.TriggerReader") as reader, \
- patch("doubao_input.app.Injector"), patch("doubao_input.ui.tray.Tray"), \
+ patch("doubao_input.app_runtime.TriggerReader") as reader, \
+ patch("doubao_input.app_runtime.Injector"), patch("doubao_input.ui.tray.Tray"), \
patch("doubao_input.app.ParamsStore.has_saved", return_value=False), \
patch("doubao_input.ui.control_window.microphones", return_value=[]), \
patch("doubao_input.ui.settings_window.microphones", return_value=[]):
diff --git a/tests/manual/chatgpt_ui.py b/tests/manual/chatgpt_ui.py
new file mode 100644
index 0000000..ce93e92
--- /dev/null
+++ b/tests/manual/chatgpt_ui.py
@@ -0,0 +1,116 @@
+"""Bounded real-GTK controls with synthetic connections; no audio or live OAuth."""
+from contextlib import ExitStack
+from dataclasses import replace
+import os
+from pathlib import Path
+import tempfile
+import time
+from unittest.mock import patch
+
+import gi
+gi.require_version("Gtk", "4.0")
+from gi.repository import GLib, Gtk
+
+from safety import hard_deadline
+from doubao_input.i18n import set_language
+from doubao_input.settings import Settings
+from doubao_input.ui.polish_settings import PolishSettings
+
+
+class Connection:
+ connected = False
+ active = "synthetic-one"
+
+ def state(self):
+ accounts = [{"id": self.active, "label": "[email protected]", "connected": True, "sharing": True}]
+ return {"accounts": accounts if self.connected else [], "active_id": self.active if self.connected else None}
+
+ def ready(self):
+ return self.connected
+
+ def sign_in(self, new_account=False):
+ self.connected = True
+ return self.state()
+
+ def cancel_sign_in(self):
+ pass
+
+ def sign_out(self):
+ self.connected = False
+ return True
+
+ def select(self, profile_id):
+ self.active = profile_id
+ return self.state()
+
+ def models(self):
+ return [{"slug": "synthetic-fast", "label": "Synthetic Fast"},
+ {"slug": "synthetic-standard", "label": "Synthetic Standard"}]
+
+
+def pump(seconds=0.3):
+ deadline = time.monotonic() + seconds
+ context = GLib.MainContext.default()
+ while time.monotonic() < deadline:
+ for _ in range(50):
+ if not context.pending():
+ break
+ context.iteration(False)
+ time.sleep(0.005)
+
+
+def capture(name):
+ directory = os.environ.get("SIWC_UI_SCREENSHOTS")
+ if directory:
+ from PIL import ImageGrab
+ destination = Path(directory)
+ destination.mkdir(parents=True, exist_ok=True)
+ ImageGrab.grab(xdisplay=os.environ["DISPLAY"]).save(destination / (name + ".png"))
+
+
+def main():
+ Gtk.init()
+ with tempfile.TemporaryDirectory(prefix="doubao-siwc-ui-") as directory, ExitStack() as cleanup:
+ cleanup.enter_context(patch.dict(os.environ, {"XDG_CONFIG_HOME": directory}))
+ set_language(os.environ.get("SIWC_UI_LANGUAGE", "en"))
+ connection = Connection()
+ cleanup.enter_context(patch("doubao_input.ui.chatgpt_settings.chatgpt_client", return_value=connection))
+ settings = Settings(polish_base_url="https://example.invalid/v1", polish_model="legacy-api-model")
+ saves = []
+ window = Gtk.Window(title="Doubao Say · isolated ChatGPT settings")
+ cleanup.callback(window.destroy)
+ window.set_default_size(600, 860)
+ box = PolishSettings(settings, False, lambda state, key: saves.append((state, key)), lambda *_: None)
+ scroll = Gtk.ScrolledWindow()
+ scroll.set_child(box)
+ window.set_child(scroll)
+ window.present()
+ pump()
+ box.provider.set_active_id("chatgpt")
+ pump()
+ capture("disconnected")
+ box.chatgpt.connect_button.emit("clicked")
+ pump(0.8)
+ assert box.chatgpt.model == "synthetic-fast"
+ box.enabled.set_active(True)
+ pump(0.8)
+ assert saves[-1][0].polish_enabled
+ assert saves[-1][0].polish_provider == "chatgpt"
+ assert saves[-1][0].polish_base_url == settings.polish_base_url
+ assert saves[-1][0].polish_model == settings.polish_model
+ assert saves[-1][0].polish_chatgpt_model == "synthetic-fast"
+ assert saves[-1][1] is None
+ capture("connected")
+ box.provider.set_active_id("api")
+ pump()
+ box.provider.set_active_id("chatgpt")
+ pump(0.8)
+ assert box.chatgpt.ready(), "Reopening the card must keep its controls operational"
+ window.destroy()
+ pump()
+ print("PASS: native settings preserve API configuration and select ChatGPT without an API key")
+
+
+if __name__ == "__main__":
+ with hard_deadline(30):
+ main()
diff --git a/tests/manual/refactor_smoke.py b/tests/manual/refactor_smoke.py
index 0a0dc1e..e7269a0 100644
--- a/tests/manual/refactor_smoke.py
+++ b/tests/manual/refactor_smoke.py
@@ -25,14 +25,14 @@ def main():
with tempfile.TemporaryDirectory(prefix="doubao-gtk-refactor-") as directory, \
ExitStack() as cleanup, \
patch.dict(os.environ, {"XDG_CONFIG_HOME": directory + "/config", "XDG_DATA_HOME": directory + "/data"}), \
- patch("doubao_input.app.Overlay"), patch("doubao_input.app.AudioCapture"), \
- patch("doubao_input.app.EscapeGuard"), patch("doubao_input.app.UpdateChecker"), \
+ patch("doubao_input.app_runtime.Overlay"), patch("doubao_input.app_runtime.AudioCapture"), \
+ patch("doubao_input.app_runtime.EscapeGuard"), patch("doubao_input.app_runtime.UpdateChecker"), \
patch("doubao_input.doubao.transcription.AudioCapture"), \
- patch("doubao_input.app.TriggerReader") as reader, \
- patch("doubao_input.app.Injector") as injector, \
+ patch("doubao_input.app_runtime.TriggerReader") as reader, \
+ patch("doubao_input.app_runtime.Injector") as injector, \
patch("doubao_input.ui.tray.Tray"), \
patch("doubao_input.app.ParamsStore.has_saved", return_value=False), \
- patch("doubao_input.app.focused_target", return_value="fake-target"), \
+ patch("doubao_input.app_runtime.focused_target", return_value="fake-target"), \
patch("doubao_input.ui.settings_window.microphones", return_value=[]):
reader.return_value.start.return_value = True
injector.return_value.inject.return_value = True
diff --git a/tests/unit/test_app_edges.py b/tests/unit/test_app_edges.py
index 2c7bff5..d1d48b3 100644
--- a/tests/unit/test_app_edges.py
+++ b/tests/unit/test_app_edges.py
@@ -21,11 +21,11 @@ class AppLifecycleEdgesTest(TestCase):
def test_update_before_settings_are_opened_downloads_and_launches(self):
with tempfile.TemporaryDirectory() as root, patch(
"doubao_input.app.GLib.unix_signal_add"), patch(
- "doubao_input.app.prepare_update", return_value=Path(root)), patch(
- "doubao_input.app.launch_update") as launch, patch(
+ "doubao_input.app_runtime.prepare_update", return_value=Path(root)), patch(
+ "doubao_input.app_runtime.launch_update") as launch, patch(
"doubao_input.app.GLib.idle_add",
side_effect=lambda callback, *args: callback(*args)), patch(
- "doubao_input.app.Thread") as thread:
+ "doubao_input.app_runtime.Thread") as thread:
app = DoubaoInputApp()
self.assertIsNone(app._settings_window)
app._control = Mock()
@@ -262,7 +262,7 @@ class AppSetupEdgesTest(TestCase):
return saved
app._control._flush_asr_key.side_effect = flush
app._settings_window._flush_asr_key.side_effect = flush
- with patch("doubao_input.app.apply_preferences") as apply:
+ with patch("doubao_input.app_runtime.apply_preferences") as apply:
if saved:
DoubaoInputApp.apply_settings(app, Settings(asr_provider="deepgram"))
self.assertEqual(owners, ["volcengine", "volcengine"])
@@ -371,7 +371,7 @@ class PersonalHistoryDeliveryTest(TestCase):
Mock(return_value=True),
lambda status: DoubaoInputApp._delivery_changed(app, status),
SimpleNamespace(submit=lambda work, done: done(work())))
- with patch("doubao_input.app.focused_target", return_value="target"):
+ with patch("doubao_input.app_voice.focused_target", return_value="target"):
DoubaoInputApp._send_enter(app)
self.assertEqual(store.history()[0]["status"], "target_changed")
self.assertEqual(app.recent.status, "target_changed")
diff --git a/tests/unit/test_chatgpt.py b/tests/unit/test_chatgpt.py
new file mode 100644
index 0000000..71d347e
--- /dev/null
+++ b/tests/unit/test_chatgpt.py
@@ -0,0 +1,149 @@
+"""Synthetic local-protocol checks; no real accounts, audio or desktop actions."""
+from concurrent.futures import ThreadPoolExecutor
+import io
+import json
+from pathlib import Path
+from tempfile import TemporaryDirectory
+import time
+from types import SimpleNamespace
+from http.server import BaseHTTPRequestHandler, HTTPServer
+from threading import Thread
+import unittest
+from unittest.mock import patch
+
+from doubao_input import chatgpt_auth as auth
+from doubao_input.chatgpt import ChatGPTClient, completed_text
+from doubao_input.chatgpt_store import ChatGPTStore
+
+
+class ChatGPTTest(unittest.TestCase):
+ def fixture(self, directory):
+ client = ChatGPTClient(Path(directory))
+ with client.store.transaction() as data:
+ data["active_id"] = "synthetic"
+ data["accounts"].append({"id": "synthetic", "client_id": "issued", "subject": "subject",
+ "access": "synthetic-old-access", "refresh": "synthetic-refresh", "expires": 1,
+ "scopes": [auth.DIRECT_SCOPE]})
+ self.addCleanup(client.close)
+ return client
+
+ def test_callback_checks_state_before_success_or_denial_and_pins_registration(self):
+ url = "http://127.0.0.1/auth/callback?state=expected&code=synthetic&client_id=issued"
+ self.assertEqual(auth.callback_values(url, "expected"), ("issued", "synthetic"))
+ for state, client in [("other", None), ("expected", "another")]:
+ with self.assertRaises(auth.ChatGPTError):
+ auth.callback_values(url, state, client)
+ with self.assertRaises(auth.ChatGPTError) as denied:
+ auth.callback_values(url + "&error=access_denied", "expected")
+ self.assertEqual(denied.exception.code, "access_denied")
+
+ def test_refresh_is_serialized_between_instances_and_state_is_display_only(self):
+ with TemporaryDirectory() as directory:
+ first = self.fixture(directory)
+ second = ChatGPTClient(Path(directory))
+ self.addCleanup(second.close)
+ def rotate(_):
+ time.sleep(0.04)
+ return {"access_token": "synthetic-replacement", "refresh_token": "synthetic-rotated",
+ "token_type": "Bearer", "expires_in": 3600}
+ with patch.object(auth, "token_request", side_effect=rotate) as refresh, ThreadPoolExecutor(2) as pool:
+ futures = [pool.submit(client.access) for client in (first, second)]
+ self.assertEqual([future.result(timeout=2) for future in futures], ["synthetic-replacement"] * 2)
+ self.assertEqual(refresh.call_count, 1)
+ display = json.dumps(first.state())
+ self.assertNotIn("synthetic-replacement", display)
+ self.assertNotIn("synthetic-rotated", display)
+ self.assertEqual((Path(directory) / "accounts.json").stat().st_mode & 0o777, 0o600)
+
+ def test_cancelled_polish_wait_does_not_discard_rotated_refresh_credentials(self):
+ with TemporaryDirectory() as directory:
+ client = self.fixture(directory)
+ def rotate(_):
+ time.sleep(0.05)
+ return {"access_token": "synthetic-replacement", "refresh_token": "synthetic-rotated",
+ "token_type": "Bearer", "expires_in": 3600}
+ with patch.object(auth, "token_request", side_effect=rotate):
+ with self.assertRaises(auth.ChatGPTError) as pending:
+ client.access(timeout=0.001)
+ self.assertEqual(pending.exception.code, "renewal_pending")
+ client._renewal.result(timeout=2)
+ with client.store.transaction() as data:
+ self.assertEqual(data["accounts"][0]["refresh"], "synthetic-rotated")
+
+ def test_unusable_refresh_clears_tokens_but_preserves_app_identity(self):
+ with TemporaryDirectory() as directory:
+ client = self.fixture(directory)
+ with patch.object(auth, "token_request", side_effect=auth.ChatGPTError("reauth_required", "Reconnect")):
+ with self.assertRaises(auth.ChatGPTError):
+ client.access()
+ with client.store.transaction() as data:
+ self.assertEqual(data["accounts"][0]["client_id"], "issued")
+ self.assertNotIn("access", data["accounts"][0])
+ self.assertNotIn("refresh", data["accounts"][0])
+
+ def test_refresh_http_error_is_classified_before_the_response_is_closed(self):
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *_):
+ pass
+
+ def do_POST(self):
+ body = json.dumps({"error": "refresh_token_invalidated"}).encode()
+ self.send_response(400)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ server = HTTPServer(("127.0.0.1", 0), Handler)
+ thread = Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ self.addCleanup(server.server_close)
+ self.addCleanup(thread.join, 2)
+ self.addCleanup(server.shutdown)
+ with patch.object(auth, "ISSUER", f"http://127.0.0.1:{server.server_port}"):
+ with self.assertRaises(auth.ChatGPTError) as failed:
+ auth.token_request({"refresh_token": "synthetic"})
+ self.assertEqual(failed.exception.code, "reauth_required")
+
+ def test_earliest_refresh_time_and_scope_narrowing_are_preserved(self):
+ token = {"access_token": "synthetic", "expires_in": 3600, "earliest_refresh_at": 1791871200}
+ previous = {"refresh": "previous", "scopes": [auth.DIRECT_SCOPE]}
+ self.assertEqual(auth.token_fields(token, previous)["refresh_after"], 1791871200)
+ self.assertEqual(auth.token_fields(token, previous)["refresh"], "previous")
+ self.assertEqual(auth.token_fields({**token, "scope": ""}, previous)["scopes"], [])
+
+ def test_partial_output_never_succeeds_after_failure_or_early_eof(self):
+ text = 'data: {"type":"response.output_text.delta","delta":"Synthetic 😊"}\n\n'
+ for terminal in ("", 'data: {"type":"response.failed"}\n\n', 'data: {"type":"response.incomplete"}\n\n'):
+ with self.assertRaises(ValueError):
+ completed_text(io.BytesIO((text + terminal).encode()))
+ complete = 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ self.assertEqual(completed_text(io.BytesIO((text + complete).encode())), "Synthetic 😊")
+
+ def test_store_rolls_back_failed_update_and_refuses_symlinks(self):
+ with TemporaryDirectory() as directory:
+ store = ChatGPTStore(Path(directory) / "safe")
+ with store.transaction() as data:
+ host = data["host_id"]
+ with self.assertRaises(RuntimeError), store.transaction() as data:
+ data["host_id"] = "wrong"
+ raise RuntimeError("Synthetic failure")
+ with store.transaction() as data:
+ self.assertEqual(data["host_id"], host)
+ (Path(directory) / "link").symlink_to(Path(directory) / "safe", target_is_directory=True)
+ with self.assertRaises(ValueError), ChatGPTStore(Path(directory) / "link").transaction():
+ pass
+
+ def test_identity_verifies_rsa_signature_issuer_audience_expiry_and_nonce(self):
+ import jwt
+ from cryptography.hazmat.primitives.asymmetric import rsa
+ private = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ claims = {"sub": "synthetic", "iss": auth.ISSUER, "aud": "issued",
+ "exp": int(time.time()) + 60, "iat": int(time.time()), "nonce": "expected"}
+ keys = SimpleNamespace(get_signing_key_from_jwt=lambda _: SimpleNamespace(key=private.public_key()))
+ with patch.object(jwt, "PyJWKClient", return_value=keys):
+ signed = jwt.encode(claims, private, algorithm="RS256")
+ self.assertEqual(auth.verify_identity(signed, "issued", "expected")["subject"], "synthetic")
+ for patch_claim in ({"aud": "other"}, {"iss": "https://example.invalid"}, {"exp": 1}, {"nonce": "other"}):
+ with self.assertRaises(auth.ChatGPTError):
+ auth.verify_identity(jwt.encode({**claims, **patch_claim}, private, algorithm="RS256"), "issued", "expected")
diff --git a/tests/unit/test_desktop.py b/tests/unit/test_desktop.py
index 4bbd424..3084e4e 100644
--- a/tests/unit/test_desktop.py
+++ b/tests/unit/test_desktop.py
@@ -57,6 +57,8 @@ class DesktopTest(TestCase):
self.assertTrue(all(optional.values()))
self.assertNotIn("evdev", results)
self.assertIn("evdev", preflight.check_runtime())
+ self.assertIn("jwt", preflight.check_runtime())
+ self.assertIn("cryptography", preflight.check_runtime())
self.assertNotIn("sounddevice", preflight.check_runtime())
def test_missing_x11_tool_is_optional_and_reported(self):
diff --git a/tests/unit/test_polish_settings_persistence.py b/tests/unit/test_polish_settings_persistence.py
index 3d71322..ce57ce0 100644
--- a/tests/unit/test_polish_settings_persistence.py
+++ b/tests/unit/test_polish_settings_persistence.py
@@ -17,11 +17,13 @@ class PolishSettingsPersistenceTest(unittest.TestCase):
_has_key=False, _testing=False, _save=Mock(), _test=Mock(),
enabled=Mock(), details=Mock(), api_key=Mock(), status=Mock(),
test_status=Mock(), _set_testing=Mock(), _set_test_result=Mock(),
+ provider=Mock(), chatgpt=Mock(),
)
+ view.provider.get_active_id.return_value = 'api'
view.enabled.get_active.return_value = True
view.api_key.get_text.return_value = "synthetic-key"
view._values = Mock(return_value=(Settings(polish_enabled=True), "synthetic-key"))
- for name in ("_save_now", "_flush", "_run_save", "_toggled", "_test_clicked"):
+ for name in ("_ready", "_save_now", "_flush", "_run_save", "_toggled", "_test_clicked"):
setattr(view, name, MethodType(getattr(PolishSettings, name), view))
return view
diff --git a/tests/unit/test_product.py b/tests/unit/test_product.py
index 306c1ea..6ad09e9 100644
--- a/tests/unit/test_product.py
+++ b/tests/unit/test_product.py
@@ -51,7 +51,7 @@ class ProductTest(TestCase):
self.assertNotIn("private-device-identifier", data)
self.assertNotIn("cookies", data)
self.assertNotIn("transcript", data)
- self.assertEqual(json.loads(data)["product_version"], "1.7.0")
+ self.assertEqual(json.loads(data)["product_version"], "1.8.0")
self.assertEqual(json.loads(data)["recognition_provider"], "volcengine")
self.assertEqual(json.loads(data)["recent_stages"], [
{"stage": "first_result", "after_ms": 125}])