Skip to content

Doubao-powered voice input for Linux, Wayland and Omarchy

feat(macOS): add ChatGPT polishing and model dropdown [skip ci]

quanru01b4b2c62ec2
diff --git a/README.md b/README.md
index ce439c2..5dfd520 100644
--- a/README.md
+++ b/README.md
@@ -102,7 +102,15 @@ 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.
+If ChatGPT reports a plan usage limit, further polishing pauses and keeps the
+original text. Open **Manage usage** to review the plan or app limit, then use
+**Retry plan usage** when available; signing in again is not required for a quota error.
+The native macOS app also offers **ChatGPT plan** in Voice polishing. Its shared
+connection serves dictation, AI vocabulary organization and polishing comparisons;
+credentials stay in the app's Keychain. Recognition remains on the selected speech
+service, and existing API configuration is preserved. Choose a model from the
+dropdown; reconnect, add/disconnect accounts and refresh models through **Account
+options**. Usage-limit actions appear when needed.
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 f85f4d3..c1c9291 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -72,7 +72,11 @@ API Key 保存在 `~/.config/doubao-say/deepgram_api_key`(或对应的
中文与英文 Prompt;应用会根据每次转写的主要语言自动选择。内置 Prompt 会去除口水词、重复和口误,改善标点与结构,同时保留原意;用户可
自行修改,也可一键恢复默认内容。
-Linux GTK 客户端也可将“润色服务”设为 **ChatGPT 套餐**。点击 **Continue with ChatGPT**,授权豆包说使用套餐,选择当前账号可用的模型后开启润色。同一面板提供账号切换、退出连接、模型刷新和“管理用量”。凭据保存在仅限当前用户读取的本机独立文件中,原有 API 地址、密钥和模型设置分别保留。它只负责文字润色,语音识别继续使用已选服务;连接、额度或续期异常仍按五秒上限回退原文。独立的 macOS 开发预览版尚未包含此连接入口。
+Linux GTK 客户端也可将“润色服务”设为 **ChatGPT 套餐**。点击 **Continue with ChatGPT**,授权豆包说使用套餐,选择当前账号可用的模型后开启润色。同一面板提供账号切换、退出连接、模型刷新和“管理用量”。凭据保存在仅限当前用户读取的本机独立文件中,原有 API 地址、密钥和模型设置分别保留。它只负责文字润色,语音识别继续使用已选服务;连接、额度或续期异常仍按五秒上限回退原文。
+
+Mac 原生客户端也提供“ChatGPT 套餐”,听写润色、AI 整理词频和语音评测中的润色对比共用连接。模型通过下拉框选择,重新连接、添加/断开账号和刷新模型收在右侧“账号选项”中。凭据保存在本应用钥匙串中,原有 API 配置保留;使用方式见 [Mac 指南](macos/README.zh-CN.md)。
+
+ChatGPT 返回用量限制时,后续润色会暂停并使用原文。请打开“管理用量”查看套餐或应用限额,可用后点击“重试套餐用量”;仅因额度限制,无需重新登录。
默认提示词会结合整段语义纠正平翘舌、前后鼻音及 n/l、f/h 等口音造成的明确近音误识别;有歧义时保留原文,不凭近音猜改姓名、数字或否定表达。更新会升级旧默认提示词,保留自定义内容。
diff --git a/macos/PARITY.zh-CN.md b/macos/PARITY.zh-CN.md
index aed67cd..8973381 100644
--- a/macos/PARITY.zh-CN.md
+++ b/macos/PARITY.zh-CN.md
@@ -7,7 +7,7 @@
| 豆包网页登录与流式识别 | WKWebView 临时会话、钥匙串、WebSocket | 回环传输;之前真实 ASR 已返回两条合成转写 |
| 火山官方 API | API Key、内置资源、Seed 二进制协议、gzip、增量文字 | 回环握手、请求、音频和负序号结束帧 |
| Deepgram Nova-3 英语 | API Key、US English、标点、稳定段与临时段合并 | 回环音频、Finalize、累积转写 |
-| 润色配置 | 默认关闭,兼容接口、模型、钥匙串 Key、接口测试、双语可编辑提示词 | 提示词语言选择、服务商参数、请求与流式响应 |
+| 润色配置 | 默认关闭,可选兼容 API 或 ChatGPT 套餐;独立钥匙串凭据、账号和模型选择、双语提示词 | 提示词选择、Responses 完成事件、OIDC 签名、账号隔离与串行续期;真实授权另记 |
| 停顿预润色 | 稳定转写和低 RMS 1.2 秒;变化后旧结果失效 | 旧预览取消、同文缓存复用 |
| 结束润色与原文回退 | 五秒上限、流式预览、快捷键跳过、Esc 取消 | 错误、截断、超时、取消和跳过 |
| 触发手势 | 自定义组合、单修饰键、短按、长按、可选双击回车、预录音 | 时序、重复键、复位与阈值 |
diff --git a/macos/Package.swift b/macos/Package.swift
index ad7f8db..d38a473 100644
--- a/macos/Package.swift
+++ b/macos/Package.swift
@@ -1,6 +1,6 @@
// swift-tools-version: 5.9
import PackageDescription
let package = Package(name: "DoubaoSayCore", platforms: [.macOS(.v13)], targets: [
- .target(name: "DoubaoSayCore", path: "Sources", exclude: ["ApplicationPresence.swift", "APIASRClient.swift", "ASRParamsStore.swift", "AppState.swift", "AudioCaptureManager.swift", "AudioDevices.swift", "DoubaoASRClient.swift", "DoubaoSayApp.swift", "HotkeyManager.swift", "OverlayPanel.swift", "OverlayView.swift", "ListeningWaveform.swift", "PasteHelper.swift", "InputTargetCapture.swift", "SecretStore.swift", "SettingsWindow.swift", "StartupService.swift", "TranscriptionManager.swift", "UpdateInstaller.swift", "VibekeyReceiver.swift", "WebViewManager.swift", "WindowCapture.swift", "PersonalViews.swift", "SpeechEvaluationView.swift", "SpeechEvaluationModel.swift"], sources: ["InputLatency.swift", "SpeechEvaluation.swift", "VoiceMotion.swift", "HotkeyGesture.swift", "ASRResponse.swift", "FinalResultGate.swift", "ShortcutGesture.swift", "MacSettings.swift", "Strings.swift", "PolishDefaults.swift", "PolishClient.swift", "PolishCoordinator.swift", "SeedProtocol.swift", "VibekeyProtocol.swift", "UpdateRelease.swift", "UpdateChecker.swift", "PersonalData.swift", "PersonalCorrections.swift"]),
+ .target(name: "DoubaoSayCore", path: "Sources", exclude: ["ApplicationPresence.swift", "APIASRClient.swift", "ASRParamsStore.swift", "AppState.swift", "AudioCaptureManager.swift", "AudioDevices.swift", "DoubaoASRClient.swift", "DoubaoSayApp.swift", "HotkeyManager.swift", "OverlayPanel.swift", "OverlayView.swift", "ListeningWaveform.swift", "PasteHelper.swift", "InputTargetCapture.swift", "SecretStore.swift", "SettingsWindow.swift", "SettingsModel.swift", "ChatGPTSettings.swift", "DropdownControl.swift", "PolishingSettingsView.swift", "StartupService.swift", "TranscriptionManager.swift", "UpdateInstaller.swift", "VibekeyReceiver.swift", "WebViewManager.swift", "WindowCapture.swift", "PersonalViews.swift", "SpeechEvaluationView.swift", "SpeechEvaluationModel.swift"], sources: ["InputLatency.swift", "SpeechEvaluation.swift", "VoiceMotion.swift", "HotkeyGesture.swift", "ASRResponse.swift", "FinalResultGate.swift", "ShortcutGesture.swift", "MacSettings.swift", "Strings.swift", "PolishDefaults.swift", "PolishClient.swift", "ChatGPTVault.swift", "ChatGPTProtocol.swift", "ChatGPTOAuth.swift", "ChatGPTCallback.swift", "ChatGPTService.swift", "ChatGPTResponses.swift", "PolishCoordinator.swift", "SeedProtocol.swift", "VibekeyProtocol.swift", "UpdateRelease.swift", "UpdateChecker.swift", "PersonalData.swift", "PersonalCorrections.swift"]),
.testTarget(name: "DoubaoSayCoreTests", dependencies: ["DoubaoSayCore"], path: "Tests", exclude: ["Transport", "Live", "Network", "Settings", "Input"])
])
diff --git a/macos/README.zh-CN.md b/macos/README.zh-CN.md
index 909a8f8..57860ea 100644
--- a/macos/README.zh-CN.md
+++ b/macos/README.zh-CN.md
@@ -31,6 +31,12 @@ open 'build/macos/arm64/Doubao Say.app'
打开“语音润色”,填写 OpenAI 兼容的 Base URL、API Key 和模型,等待自动保存后使用“测试接口”验证。默认关闭。建议使用低延迟小模型,服务商思考开关策略与 Linux 版一致;没有通用的跨服务商关闭思考参数。
+也可以将“润色服务”切换为“ChatGPT 套餐”,点击 **Continue with ChatGPT**,在浏览器允许豆包说使用套餐,然后选择当前账号可用的模型。该连接同时用于听写润色、“AI 整理高频词”和语音评测中的润色对比。语音识别仍沿用已选服务;原有 API 地址、模型和密钥分别保留。
+
+模型可直接用下拉框切换,选择后自动保存;支持方向键、回车选择与 Esc 取消。重新连接、添加/断开账号、刷新模型和管理用量收在账号右侧的“账号选项”菜单中。有多个账号时,账号也通过下拉框切换。恢复默认提示词放在“提示词设置”中。
+
+ChatGPT 凭据使用本应用独立的 macOS 钥匙串条目,不借用 Codex 或其他产品的登录。账号改变会停止正在执行的套餐请求;续期由连接模块负责,保存新凭据后再交给各入口使用。遇到共享用量限制时,本次运行暂停后续套餐请求并保留原文,界面会显示“管理用量”和“重试套餐用量”;请检查套餐或应用限额,可用后主动重试。不会自动转用 API Key。
+
中文、英文提示词分别编辑,可恢复 Linux 版相同的默认值。按转写文字的主要语言选择提示词,与界面语言无关。默认提示词修正明确口误、重复、无意义语气词和有充分上下文的近音错误,整理必要标点、段落与明确列举的列表;不回答转写中的问题,不添加事实。个人词汇和你明确确认过的纠错会作为上下文参考,不做全局替换,也不额外注入固定产品示例。
转写稳定、低于语音阈值并静音 1.2 秒后启动预润色。音量变化只暂停计时,文字变化才使旧请求失效,避免背景噪声反复发请求。结束录音后可复用同一段文字的预润色结果或仍在运行的请求;不同文字重新请求,旧返回不能上屏。
diff --git a/macos/Sources/ChatGPTCallback.swift b/macos/Sources/ChatGPTCallback.swift
new file mode 100644
index 0000000..5c1ea0c
--- /dev/null
+++ b/macos/Sources/ChatGPTCallback.swift
@@ -0,0 +1,101 @@
+import Foundation
+import Network
+
+/// Loopback-only HTTP callback. Invalid state never consumes the pending authorization.
+final class ChatGPTCallback: @unchecked Sendable {
+ private let queue = DispatchQueue(label: "doubao.chatgpt.callback")
+ private var listener: NWListener?
+ private var ready: CheckedContinuation<UInt16, Error>?
+ private var callback: CheckedContinuation<(String, String), Error>?
+ private var result: Result<(String, String), Error>?
+ private var deadline: DispatchWorkItem?
+ private var connections: [NWConnection] = []
+ private let state: String
+ private let clientID: String?
+ private var port: UInt16 = 0
+
+ init(state: String, clientID: String?) { self.state = state; self.clientID = clientID }
+
+ func start() async throws -> UInt16 {
+ try await withTaskCancellationHandler(operation: {
+ try await withCheckedThrowingContinuation { continuation in
+ queue.async {
+ guard self.result == nil else { continuation.resume(throwing: ChatGPTError.cancelled); return }
+ self.ready = continuation
+ do {
+ let parameters = NWParameters.tcp
+ parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: .any)
+ let listener = try NWListener(using: parameters)
+ self.listener = listener
+ listener.stateUpdateHandler = { status in
+ switch status {
+ case .ready:
+ guard let port = listener.port?.rawValue else { self.finish(.failure(ChatGPTError.connection)); return }
+ self.port = port; self.ready?.resume(returning: port); self.ready = nil
+ case .failed: self.finish(.failure(ChatGPTError.connection))
+ default: break
+ }
+ }
+ listener.newConnectionHandler = { connection in
+ self.connections.append(connection); connection.start(queue: self.queue)
+ self.receive(connection, buffer: Data())
+ }
+ let deadline = DispatchWorkItem { self.finish(.failure(ChatGPTError.cancelled)) }
+ self.deadline = deadline
+ self.queue.asyncAfter(deadline: .now() + 300, execute: deadline)
+ listener.start(queue: self.queue)
+ } catch { self.finish(.failure(ChatGPTError.connection)) }
+ }
+ }
+ }, onCancel: { self.close() })
+ }
+ func wait() async throws -> (String, String) {
+ try await withTaskCancellationHandler(operation: {
+ try await withCheckedThrowingContinuation { continuation in
+ queue.async {
+ if let result = self.result { continuation.resume(with: result) }
+ else { self.callback = continuation }
+ }
+ }
+ }, onCancel: { self.close() })
+ }
+ func close() { queue.async { self.finish(.failure(ChatGPTError.cancelled)) } }
+
+ private func receive(_ connection: NWConnection, buffer: Data) {
+ connection.receive(minimumIncompleteLength: 1, maximumLength: 8192) { bytes, _, complete, error in
+ var data = buffer; data.append(bytes ?? Data())
+ guard data.count <= 8192, error == nil else { connection.cancel(); return }
+ if data.range(of: Data("\r\n\r\n".utf8)) != nil {
+ self.respond(connection, request: data)
+ } else if complete { connection.cancel() }
+ else { self.receive(connection, buffer: data) }
+ }
+ }
+ private func respond(_ connection: NWConnection, request: Data) {
+ let lines = String(data: request, encoding: .utf8)?.components(separatedBy: "\r\n") ?? []
+ let first = lines.first?.split(separator: " ").map(String.init) ?? []
+ let host = lines.dropFirst().first { $0.lowercased().hasPrefix("host:") }?.dropFirst(5).trimmingCharacters(in: .whitespaces)
+ var status = 400
+ var accepted: Result<(String, String), Error>?
+ if result == nil, first.count == 3, first[0] == "GET", host == "127.0.0.1:\(port)" {
+ do { accepted = .success(try ChatGPTProtocol.callback(first[1], state: state, clientID: clientID)); status = 200 }
+ catch ChatGPTError.cancelled { accepted = .failure(ChatGPTError.cancelled) }
+ catch { }
+ }
+ let body = status == 200 ? "Return to Doubao Say to finish connecting ChatGPT." : "Return to Doubao Say and try signing in again."
+ let response = "HTTP/1.1 \(status) \(status == 200 ? "OK" : "Bad Request")\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: \(body.utf8.count)\r\nCache-Control: no-store\r\nReferrer-Policy: no-referrer\r\nContent-Security-Policy: default-src 'none'\r\nConnection: close\r\n\r\n\(body)"
+ connection.send(content: Data(response.utf8), completion: .contentProcessed { _ in
+ connection.cancel()
+ if let accepted = accepted { self.finish(accepted) }
+ })
+ }
+ private func finish(_ next: Result<(String, String), Error>) {
+ guard result == nil else { return }
+ result = next
+ ready?.resume(throwing: ChatGPTError.cancelled); ready = nil
+ callback?.resume(with: next); callback = nil
+ deadline?.cancel(); deadline = nil
+ listener?.cancel(); listener = nil
+ connections.forEach { $0.cancel() }; connections.removeAll()
+ }
+}
diff --git a/macos/Sources/ChatGPTOAuth.swift b/macos/Sources/ChatGPTOAuth.swift
new file mode 100644
index 0000000..fda55c0
--- /dev/null
+++ b/macos/Sources/ChatGPTOAuth.swift
@@ -0,0 +1,80 @@
+import Foundation
+import AppKit
+
+class ChatGPTHTTP: NSObject, URLSessionTaskDelegate, @unchecked Sendable {
+ func json(_ url: URL, fields: [String: String]? = nil, access: String? = nil) async throws -> [String: Any] {
+ var request = URLRequest(url: url, timeoutInterval: 30)
+ request.setValue("application/json", forHTTPHeaderField: "Accept")
+ if let fields = fields {
+ request.httpMethod = "POST"; request.httpBody = ChatGPTProtocol.form(fields)
+ request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
+ }
+ if let access = access { request.setValue("Bearer " + access, forHTTPHeaderField: "Authorization") }
+ let config = URLSessionConfiguration.ephemeral
+ config.timeoutIntervalForRequest = 30; config.timeoutIntervalForResource = 30
+ config.urlCache = nil; config.httpCookieStorage = nil
+ let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
+ defer { session.invalidateAndCancel() }
+ let bytes: Data; let response: URLResponse
+ do { (bytes, response) = try await session.data(for: request) }
+ catch is CancellationError { throw ChatGPTError.cancelled }
+ catch { throw ChatGPTError.connection }
+ guard bytes.count <= 1_000_000, let http = response as? HTTPURLResponse else { throw ChatGPTError.response }
+ let value = bytes.isEmpty ? [:] : (try? JSONSerialization.jsonObject(with: bytes) as? [String: Any]) ?? [:]
+ guard (200...299).contains(http.statusCode) else {
+ let error = value["error"] as? [String: Any]
+ let code = value["error"] as? String ?? error?["code"] as? String
+ if ["invalid_grant", "invalid_refresh_token", "token_expired", "refresh_token_expired", "refresh_token_invalidated", "refresh_token_reused"].contains(code ?? "") { throw ChatGPTError.reconnect }
+ if code == "invalid_client" { throw ChatGPTError.invalidClient }
+ if code == "subscription_sharing_usage_limit_exceeded" { throw ChatGPTError.quota }
+ throw ChatGPTError.connection
+ }
+ return value
+ }
+ func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
+ newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { completionHandler(nil) }
+}
+
+struct ChatGPTOAuth {
+ let http: ChatGPTHTTP
+ var openBrowser: (URL) async throws -> Void = { url in
+ let opened = await MainActor.run { NSWorkspace.shared.open(url) }
+ if !opened { throw ChatGPTError.connection }
+ }
+ func token(_ fields: [String: String]) async throws -> [String: Any] {
+ try await http.json(URL(string: ChatGPTProtocol.issuer + "/api/accounts/oauth/token")!, fields: fields)
+ }
+ func identity(_ token: String, clientID: String, nonce: String? = nil) async throws -> [String: Any] {
+ let data = try await http.json(URL(string: ChatGPTProtocol.issuer + "/.well-known/jwks.json")!)
+ guard let keys = data["keys"] as? [[String: Any]] else { throw ChatGPTError.identity }
+ return try ChatGPTIdentity.verify(token, clientID: clientID, nonce: nonce, keys: keys)
+ }
+ func authorize(hostID: String, account: ChatGPTAccount?, saveRegistration: (String) async throws -> Void) async throws -> ChatGPTAccount {
+ let state = try ChatGPTProtocol.random(), nonce = try ChatGPTProtocol.random(), verifier = try ChatGPTProtocol.random()
+ let callback = ChatGPTCallback(state: state, clientID: account?.clientID)
+ defer { callback.close() }
+ let port = try await callback.start()
+ let redirect = "http://127.0.0.1:\(port)/auth/callback"
+ var fields = ["client_id": account?.clientID ?? "dynamic_agent_client", "ext_agent_host_id": hostID,
+ "response_type": "code", "redirect_uri": redirect, "resource": ChatGPTProtocol.resource,
+ "scope": "openid profile email offline_access resource.invoke " + ChatGPTProtocol.directScope,
+ "state": state, "nonce": nonce, "code_challenge": ChatGPTProtocol.challenge(verifier), "code_challenge_method": "S256"]
+ if account == nil { fields["agent_name_hint"] = "Doubao Say" }
+ fields["id_token_hint"] = account?.identity; fields["login_hint"] = account?.email
+ var url = URLComponents(string: ChatGPTProtocol.issuer + "/api/accounts/authorize")!
+ url.queryItems = fields.map { URLQueryItem(name: $0.key, value: $0.value) }
+ guard let address = url.url else { throw ChatGPTError.connection }
+ try await openBrowser(address)
+ let (issued, code) = try await callback.wait()
+ try Task.checkCancellation()
+ try await saveRegistration(issued)
+ let data = try await token(["grant_type": "authorization_code", "client_id": issued, "code": code,
+ "code_verifier": verifier, "redirect_uri": redirect, "resource": ChatGPTProtocol.resource])
+ guard let jwt = data["id_token"] as? String else { throw ChatGPTError.identity }
+ let claims = try await identity(jwt, clientID: issued, nonce: nonce)
+ guard account?.subject == nil || account?.subject == claims["sub"] as? String else { throw ChatGPTError.identity }
+ var next = try ChatGPTProtocol.tokenFields(data, previous: account ?? ChatGPTAccount(clientID: issued))
+ next.subject = claims["sub"] as? String; next.email = claims["email"] as? String; next.name = claims["name"] as? String
+ return next
+ }
+}
diff --git a/macos/Sources/ChatGPTProtocol.swift b/macos/Sources/ChatGPTProtocol.swift
new file mode 100644
index 0000000..8c506b7
--- /dev/null
+++ b/macos/Sources/ChatGPTProtocol.swift
@@ -0,0 +1,118 @@
+import Foundation
+import CryptoKit
+import Security
+
+enum ChatGPTError: Error, LocalizedError {
+ case connection, cancelled, storage, identity, invalidClient, response, reconnect, sharing, model, accountChanged, quota, refreshNotReady
+ var errorDescription: String? {
+ switch self {
+ case .cancelled: return L("ChatGPT sign-in cancelled.", "ChatGPT 登录已取消。")
+ case .storage: return L("ChatGPT credentials could not be saved securely.", "无法安全保存 ChatGPT 凭据。")
+ case .identity: return L("ChatGPT identity verification failed.", "ChatGPT 身份校验失败。")
+ case .invalidClient: return L("ChatGPT app registration could not be verified.", "无法校验 ChatGPT 应用注册。")
+ case .reconnect: return L("Reconnect your ChatGPT account.", "请重新连接 ChatGPT 账号。")
+ case .sharing: return L("Allow this app to use your ChatGPT plan.", "请允许本应用使用 ChatGPT 套餐。")
+ case .model: return L("Choose an available ChatGPT model in Voice polishing settings.", "请在语音润色设置中选择当前账号可用的 ChatGPT 模型。")
+ case .accountChanged: return L("ChatGPT account changed; the request stopped.", "ChatGPT 账号已改变,请求已停止。")
+ case .quota: return L("ChatGPT plan usage limit reached. Open Manage usage and retry when available; original text is retained.", "ChatGPT 套餐共享用量已达上限,请查看“管理用量”,可用后重试;原文保留。")
+ case .refreshNotReady: return L("ChatGPT renewal is not available yet; try later.", "ChatGPT 暂未允许续期,请稍后重试。")
+ case .response: return L("ChatGPT did not return a complete response; original text is retained.", "ChatGPT 未返回完整回复,原文保留。")
+ case .connection: return L("ChatGPT connection failed. Check connection and usage.", "ChatGPT 连接失败,请检查连接和用量。")
+ }
+ }
+}
+
+enum ChatGPTProtocol {
+ static let issuer = "https://auth.openai.com"
+ static let resource = "https://api.openai.com/v1"
+ static let directScope = "chatgpt.tokens.use.direct"
+ static let usageURL = URL(string: "https://chatgpt.com/settings/usage")!
+ static func base64(_ data: Data) -> String { data.base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") }
+ static func decode(_ value: String) -> Data? {
+ let base = value.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
+ return Data(base64Encoded: base + String(repeating: "=", count: (4 - base.count % 4) % 4))
+ }
+ static func random() throws -> String {
+ var bytes = [UInt8](repeating: 0, count: 32)
+ guard SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else { throw ChatGPTError.connection }
+ return base64(Data(bytes))
+ }
+ static func challenge(_ verifier: String) -> String { base64(Data(SHA256.hash(data: Data(verifier.utf8)))) }
+ static func sameState(_ actual: String, _ expected: String) -> Bool {
+ let a = Array(actual.utf8), b = Array(expected.utf8)
+ guard a.count == b.count, !a.isEmpty else { return false }
+ return zip(a, b).reduce(UInt8(0)) { $0 | ($1.0 ^ $1.1) } == 0
+ }
+ static func form(_ fields: [String: String]) -> Data {
+ var allowed = CharacterSet.alphanumerics; allowed.insert(charactersIn: "-._~")
+ return Data(fields.sorted { $0.key < $1.key }.map {
+ ($0.key.addingPercentEncoding(withAllowedCharacters: allowed) ?? "") + "=" + ($0.value.addingPercentEncoding(withAllowedCharacters: allowed) ?? "")
+ }.joined(separator: "&").utf8)
+ }
+ static func callback(_ target: String, state: String, clientID: String?) throws -> (String, String) {
+ guard let parts = URLComponents(string: "http://127.0.0.1" + target), parts.path == "/auth/callback" else { throw ChatGPTError.response }
+ let items = parts.queryItems ?? []
+ func value(_ name: String) -> String? { let values = items.filter { $0.name == name }; return values.count == 1 ? values[0].value : nil }
+ guard sameState(value("state") ?? "", state) else { throw ChatGPTError.response }
+ guard value("error") == nil else { throw ChatGPTError.cancelled }
+ guard let issued = value("client_id") ?? clientID, issued != "dynamic_agent_client",
+ clientID == nil || issued == clientID, let code = value("code"), !code.isEmpty else { throw ChatGPTError.invalidClient }
+ return (issued, code)
+ }
+ static func tokenFields(_ json: [String: Any], previous: ChatGPTAccount) throws -> ChatGPTAccount {
+ guard let access = json["access_token"] as? String, !access.isEmpty,
+ (json["token_type"] as? String)?.lowercased() == "bearer",
+ let secondsNumber = json["expires_in"] as? NSNumber,
+ CFGetTypeID(secondsNumber) != CFBooleanGetTypeID(),
+ secondsNumber.doubleValue.isFinite, secondsNumber.doubleValue > 0 else { throw ChatGPTError.response }
+ let seconds = secondsNumber.doubleValue
+ var account = previous
+ account.access = access; account.expires = Date().timeIntervalSince1970 + seconds
+ if let scope = json["scope"] { guard let value = scope as? String else { throw ChatGPTError.response }; account.scopes = value.split(whereSeparator: { $0.isWhitespace }).map(String.init) }
+ if let refresh = json["refresh_token"] { guard let value = refresh as? String, !value.isEmpty else { throw ChatGPTError.response }; account.refresh = value }
+ if let identity = json["id_token"] { guard let value = identity as? String else { throw ChatGPTError.response }; account.identity = value }
+ account.refreshAfter = nil
+ if let earliest = json["earliest_refresh_at"] {
+ if let number = earliest as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(), number.doubleValue.isFinite, number.doubleValue >= 0 { account.refreshAfter = number.doubleValue }
+ else if let value = earliest as? String, value.range(of: "(?:Z|[+-][0-9]{2}:[0-9]{2})$", options: .regularExpression) != nil {
+ let parser = ISO8601DateFormatter()
+ var date = parser.date(from: value)
+ if date == nil { parser.formatOptions.insert(.withFractionalSeconds); date = parser.date(from: value) }
+ guard let date = date else { throw ChatGPTError.response }; account.refreshAfter = date.timeIntervalSince1970
+ } else { throw ChatGPTError.response }
+ }
+ return account
+ }
+}
+
+/// Only the fixed OpenAI issuer and RS256 are trusted, not JWT-provided key URLs.
+enum ChatGPTIdentity {
+ static func verify(_ token: String, clientID: String, nonce: String?, keys: [[String: Any]], now: TimeInterval = Date().timeIntervalSince1970) throws -> [String: Any] {
+ let parts = token.split(separator: ".", omittingEmptySubsequences: false).map(String.init)
+ guard parts.count == 3, let headerData = ChatGPTProtocol.decode(parts[0]), let body = ChatGPTProtocol.decode(parts[1]),
+ let signature = ChatGPTProtocol.decode(parts[2]),
+ let header = try? JSONSerialization.jsonObject(with: headerData) as? [String: Any], header["alg"] as? String == "RS256",
+ let kid = header["kid"] as? String,
+ let jwk = keys.first(where: { $0["kid"] as? String == kid && $0["kty"] as? String == "RSA" }),
+ let n = jwk["n"] as? String, let e = jwk["e"] as? String,
+ let modulus = ChatGPTProtocol.decode(n), let exponent = ChatGPTProtocol.decode(e),
+ let claims = try? JSONSerialization.jsonObject(with: body) as? [String: Any] else { throw ChatGPTError.identity }
+ let bytes = der(0x30, derInteger(modulus) + derInteger(exponent))
+ let attributes: [String: Any] = [kSecAttrKeyType as String: kSecAttrKeyTypeRSA, kSecAttrKeyClass as String: kSecAttrKeyClassPublic]
+ guard let key = SecKeyCreateWithData(bytes as CFData, attributes as CFDictionary, nil),
+ SecKeyVerifySignature(key, .rsaSignatureMessagePKCS1v15SHA256, Data((parts[0] + "." + parts[1]).utf8) as CFData, signature as CFData, nil),
+ claims["iss"] as? String == ChatGPTProtocol.issuer,
+ let exp = claims["exp"] as? Double, exp.isFinite, exp > now,
+ let iat = claims["iat"] as? Double, iat.isFinite, iat <= now + 60,
+ let subject = claims["sub"] as? String, !subject.isEmpty,
+ claims["aud"] as? String == clientID || (claims["aud"] as? [String])?.contains(clientID) == true,
+ nonce == nil || claims["nonce"] as? String == nonce else { throw ChatGPTError.identity }
+ return claims
+ }
+ static func der(_ tag: UInt8, _ value: Data) -> Data {
+ var length = [UInt8](); var count = value.count
+ repeat { length.insert(UInt8(count & 255), at: 0); count >>= 8 } while count > 0
+ return Data([tag] + (value.count < 128 ? [UInt8(value.count)] : [0x80 | UInt8(length.count)] + length)) + value
+ }
+ private static func derInteger(_ bytes: Data) -> Data { der(0x02, bytes.first.map { $0 >= 128 } == true ? Data([0]) + bytes : bytes) }
+}
diff --git a/macos/Sources/ChatGPTResponses.swift b/macos/Sources/ChatGPTResponses.swift
new file mode 100644
index 0000000..b5135f1
--- /dev/null
+++ b/macos/Sources/ChatGPTResponses.swift
@@ -0,0 +1,46 @@
+import Foundation
+
+/// Responses SSE is distinct from Chat Completions; only response.completed commits output.
+struct ChatGPTResponses {
+ private var pending = Data()
+ private var frame: [String] = []
+ private var size = 0
+ private(set) var text = ""
+ private(set) var completed = false
+ mutating func append(_ bytes: Data) throws -> String? {
+ size += bytes.count
+ guard size <= 1_000_000 else { throw ChatGPTError.response }
+ pending.append(bytes)
+ let previous = text
+ while let newline = pending.firstIndex(of: 10) {
+ let line = pending.prefix(upTo: newline); pending.removeSubrange(...newline)
+ guard let value = String(data: line, encoding: .utf8) else { throw ChatGPTError.response }
+ try receive(value.trimmingCharacters(in: .newlines))
+ }
+ return text == previous ? nil : text
+ }
+ private mutating func receive(_ line: String) throws {
+ guard !completed else { return }
+ if line.hasPrefix("data:") { frame.append(line.dropFirst(5).trimmingCharacters(in: .whitespaces)); return }
+ guard line.isEmpty, !frame.isEmpty else { return }
+ let data = Data(frame.joined(separator: "\n").utf8); frame.removeAll()
+ guard let event = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let kind = event["type"] as? String else { throw ChatGPTError.response }
+ switch kind {
+ case "response.output_text.delta":
+ guard let delta = event["delta"] as? String else { throw ChatGPTError.response }; text += delta
+ case "response.completed":
+ if let response = event["response"] as? [String: Any], let status = response["status"] as? String, status != "completed" { throw ChatGPTError.response }
+ completed = true
+ case "response.failed", "response.incomplete", "error":
+ let error = event["error"] as? [String: Any] ?? (event["response"] as? [String: Any])?["error"] as? [String: Any] ?? event
+ if error["code"] as? String == "subscription_sharing_usage_limit_exceeded" { throw ChatGPTError.quota }
+ throw ChatGPTError.response
+ default: break
+ }
+ }
+ func result() throws -> String {
+ let value = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard completed, !value.isEmpty else { throw ChatGPTError.response }
+ return value
+ }
+}
diff --git a/macos/Sources/ChatGPTService.swift b/macos/Sources/ChatGPTService.swift
new file mode 100644
index 0000000..095631d
--- /dev/null
+++ b/macos/Sources/ChatGPTService.swift
@@ -0,0 +1,197 @@
+import Foundation
+import CryptoKit
+
+struct ChatGPTAccountView: Identifiable, Equatable {
+ let id: String
+ let label: String
+ let connected: Bool
+ let sharing: Bool
+}
+struct ChatGPTSnapshot: Equatable {
+ var activeID: String?
+ var accounts: [ChatGPTAccountView] = []
+ var signingIn = false
+ var usageLimited = false
+ var active: ChatGPTAccountView? { accounts.first { $0.id == activeID } }
+}
+struct ChatGPTModel: Identifiable, Equatable { let id: String; let label: String }
+struct ChatGPTLease {
+ let token: String
+ let accountID: String
+ let generation: Int
+ let revision: String
+}
+extension Notification.Name { static let chatGPTConnectionChanged = Notification.Name("doubao.chatgpt.connection.changed") }
+
+/// Every Mac AI consumer uses this one application-owned connection and renewal owner.
+actor ChatGPTService {
+ static let shared = ChatGPTService()
+ private let vault: ChatGPTVault
+ private let oauth: ChatGPTOAuth
+ private var signInTask: Task<ChatGPTAccount, Error>?
+ private var renewal: (id: String, ticket: UUID, task: Task<ChatGPTLease, Error>)?
+ private var generation = 0
+ private var limitedAccounts = Set<String>()
+
+ init(vault: ChatGPTVault = ChatGPTVault(), oauth: ChatGPTOAuth = ChatGPTOAuth(http: ChatGPTHTTP())) {
+ self.vault = vault; self.oauth = oauth
+ }
+ func state() async throws -> ChatGPTSnapshot {
+ let stored = try await vault.transact { $0 }
+ return ChatGPTSnapshot(activeID: stored.activeID, accounts: stored.accounts.map {
+ ChatGPTAccountView(id: $0.id, label: $0.email ?? $0.name ?? "ChatGPT", connected: $0.subject != nil && $0.access != nil, sharing: $0.sharing)
+ }, signingIn: signInTask != nil, usageLimited: stored.activeID.map { limitedAccounts.contains($0) } ?? false)
+ }
+ func signIn(newAccount: Bool = false) async throws {
+ guard signInTask == nil else { throw ChatGPTError.connection }
+ let stored = try await vault.transact { $0 }
+ let account = newAccount ? nil : stored.activeIndex.map { stored.accounts[$0] }
+ let profileID = account?.id ?? UUID().uuidString
+ let task = Task { [vault, oauth] in
+ try await oauth.authorize(hostID: stored.hostID, account: account) { issued in
+ try await vault.transact { state in
+ if !state.accounts.contains(where: { $0.id == profileID }) {
+ var registration = ChatGPTAccount(clientID: issued); registration.id = profileID
+ state.accounts.append(registration)
+ }
+ if state.activeID == nil { state.activeID = profileID }
+ }
+ }
+ }
+ signInTask = task
+ defer { signInTask = nil }
+ var next = try await task.value
+ try Task.checkCancellation(); next.id = profileID
+ try await vault.transact { state in
+ if let index = state.accounts.firstIndex(where: { $0.id == profileID }) { state.accounts[index] = next }
+ else { state.accounts.append(next) }
+ state.activeID = profileID
+ }
+ changed()
+ }
+ func cancelSignIn() { signInTask?.cancel() }
+ func select(_ id: String) async throws {
+ guard signInTask == nil else { throw ChatGPTError.connection }
+ try await vault.transact { state in
+ guard state.accounts.contains(where: { $0.id == id }) else { throw ChatGPTError.accountChanged }
+ state.activeID = id
+ }
+ changed()
+ }
+ func signOut() async throws -> Bool {
+ cancelSignIn()
+ let revoked = try await vault.transact { [oauth] state in
+ guard let index = state.activeIndex else { return true }
+ let account = state.accounts[index]
+ var revoked = true
+ if let token = account.refresh {
+ do {
+ let discovery = try await oauth.http.json(URL(string: ChatGPTProtocol.issuer + "/.well-known/openid-configuration")!)
+ guard let address = discovery["revocation_endpoint"] as? String, let url = URL(string: address),
+ url.scheme == "https", url.host == "auth.openai.com", url.user == nil, url.password == nil,
+ url.port == nil || url.port == 443 else { throw ChatGPTError.response }
+ _ = try await oauth.http.json(url, fields: ["token": token, "token_type_hint": "refresh_token", "client_id": account.clientID])
+ } catch { revoked = false }
+ }
+ state.accounts[index].clearTokens()
+ return revoked
+ }
+ changed(); return revoked
+ }
+ private func changed() {
+ generation += 1; limitedAccounts.removeAll()
+ NotificationCenter.default.post(name: .chatGPTConnectionChanged, object: nil, userInfo: ["reason": "account"])
+ }
+ func resumeUsage() {
+ limitedAccounts.removeAll()
+ NotificationCenter.default.post(name: .chatGPTConnectionChanged, object: nil, userInfo: ["reason": "retry"])
+ }
+ func pauseUsage(_ lease: ChatGPTLease) {
+ guard lease.generation == generation else { return }
+ limitedAccounts.insert(lease.accountID)
+ NotificationCenter.default.post(name: .chatGPTConnectionChanged, object: nil, userInfo: ["reason": "quota"])
+ }
+ func isCurrent(_ lease: ChatGPTLease) async -> Bool {
+ guard lease.generation == generation else { return false }
+ guard let stored = try? await vault.transact({ $0 }), let index = stored.activeIndex,
+ stored.activeID == lease.accountID, let token = stored.accounts[index].access else { return false }
+ return Self.revision(token) == lease.revision
+ }
+ private static func revision(_ token: String) -> String { ChatGPTProtocol.base64(Data(SHA256.hash(data: Data(token.utf8)))) }
+ private func lease(_ account: ChatGPTAccount) throws -> ChatGPTLease {
+ guard let token = account.access else { throw ChatGPTError.reconnect }
+ return ChatGPTLease(token: token, accountID: account.id, generation: generation, revision: Self.revision(token))
+ }
+ func access(forCatalog: Bool = false) async throws -> ChatGPTLease {
+ let expected = generation
+ let stored = try await vault.transact { $0 }
+ guard let index = stored.activeIndex, stored.accounts[index].subject != nil,
+ stored.accounts[index].access != nil else { throw ChatGPTError.reconnect }
+ let account = stored.accounts[index]
+ guard account.sharing else { throw ChatGPTError.sharing }
+ guard forCatalog || !limitedAccounts.contains(account.id) else { throw ChatGPTError.quota }
+ if (account.expires ?? 0) > Date().timeIntervalSince1970 + 120 {
+ guard expected == generation else { throw ChatGPTError.accountChanged }; return try lease(account)
+ }
+ let owner: (id: String, ticket: UUID, task: Task<ChatGPTLease, Error>)
+ if let pending = renewal, pending.id == account.id { owner = pending }
+ else {
+ // An unstructured connection-owned task survives cancellation of a five-second caller.
+ let job = Task { try await self.renew(account.id) }
+ owner = (account.id, UUID(), job); renewal = owner
+ }
+ defer { if renewal?.ticket == owner.ticket { renewal = nil } }
+ let result = try await owner.task.value
+ try Task.checkCancellation()
+ guard expected == generation else { throw ChatGPTError.accountChanged }
+ return result
+ }
+ private func renew(_ id: String) async throws -> ChatGPTLease {
+ let outcome: Result<ChatGPTAccount, ChatGPTError> = try await vault.transact { [oauth] state in
+ guard let index = state.activeIndex, state.accounts[index].id == id else { return .failure(.accountChanged) }
+ var account = state.accounts[index]
+ guard account.subject != nil, account.access != nil else { return .failure(.reconnect) }
+ let now = Date().timeIntervalSince1970
+ if (account.expires ?? 0) > now + 120 { return .success(account) }
+ if (account.refreshAfter ?? 0) > now { return (account.expires ?? 0) > now ? .success(account) : .failure(.refreshNotReady) }
+ guard let refresh = account.refresh else { return .failure(.reconnect) }
+ do {
+ let data = try await oauth.token(["grant_type": "refresh_token", "client_id": account.clientID,
+ "refresh_token": refresh, "resource": ChatGPTProtocol.resource])
+ do {
+ if let token = data["id_token"] as? String {
+ let claims = try await oauth.identity(token, clientID: account.clientID)
+ guard claims["sub"] as? String == account.subject else { throw ChatGPTError.identity }
+ }
+ account = try ChatGPTProtocol.tokenFields(data, previous: account)
+ }
+ catch {
+ // A successful token exchange may already have rotated the grant.
+ // Failed identity validation or replacement fields must not roll back to it.
+ state.accounts[index].clearTokens(); return .failure(.reconnect)
+ }
+ state.accounts[index] = account
+ return .success(account)
+ } catch ChatGPTError.reconnect {
+ state.accounts[index].clearTokens(); return .failure(.reconnect)
+ } catch ChatGPTError.identity {
+ state.accounts[index].clearTokens(); return .failure(.reconnect)
+ }
+ }
+ switch outcome {
+ case .success(let account): guard account.sharing else { throw ChatGPTError.sharing }; return try lease(account)
+ case .failure(let error): if case .reconnect = error { changed() }; throw error
+ }
+ }
+ func models() async throws -> [ChatGPTModel] {
+ // A directory remains available while inference is locally paused for quota.
+ let connection = try await access(forCatalog: true)
+ let data = try await oauth.http.json(URL(string: ChatGPTProtocol.resource + "/models")!, access: connection.token)
+ guard await isCurrent(connection) else { throw ChatGPTError.accountChanged }
+ guard let models = data["models"] as? [[String: Any]] else { throw ChatGPTError.response }
+ return models.compactMap { item in
+ guard item["visibility"] as? String == "list", let id = item["slug"] as? String, let label = item["display_name"] as? String else { return nil }
+ return ChatGPTModel(id: id, label: label)
+ }
+ }
+}
diff --git a/macos/Sources/ChatGPTSettings.swift b/macos/Sources/ChatGPTSettings.swift
new file mode 100644
index 0000000..7d9cbda
--- /dev/null
+++ b/macos/Sources/ChatGPTSettings.swift
@@ -0,0 +1,143 @@
+import SwiftUI
+import AppKit
+
+@MainActor
+final class ChatGPTConnectionModel: ObservableObject {
+ static let shared = ChatGPTConnectionModel()
+ @Published var snapshot = ChatGPTSnapshot()
+ @Published var models: [ChatGPTModel] = []
+ @Published var busy = false
+ @Published var message = ""
+ private let service: ChatGPTService
+ private var job: Task<Void, Never>?
+ private var observer: NSObjectProtocol?
+
+ init(service: ChatGPTService = .shared, refreshInitially: Bool = true) {
+ self.service = service
+ if refreshInitially {
+ observer = NotificationCenter.default.addObserver(forName: .chatGPTConnectionChanged, object: nil, queue: .main) { [weak self] _ in
+ Task { @MainActor in
+ guard let self = self else { return }
+ if let state = try? await self.service.state() { self.snapshot = state }
+ }
+ }
+ refresh()
+ }
+ }
+ deinit { if let observer = observer { NotificationCenter.default.removeObserver(observer) } }
+ func refresh() { perform { } }
+ func signIn(newAccount: Bool = false) { perform { try await self.service.signIn(newAccount: newAccount) } }
+ func select(_ id: String) { guard !busy else { return }; models = []; perform { try await self.service.select(id) } }
+ func signOut() {
+ perform {
+ let revoked = try await self.service.signOut()
+ if !revoked { self.message = L("Local connection cleared; remote revocation was not confirmed. Review app access in ChatGPT settings.", "本机连接已清除,远端撤销未确认,请在 ChatGPT 设置检查应用授权。") }
+ }
+ }
+ func retryUsage() { perform { await self.service.resumeUsage() } }
+ func cancelSignIn() { Task { await service.cancelSignIn() }; job?.cancel() }
+ private func perform(_ operation: @escaping () async throws -> Void) {
+ guard !busy else { return }
+ busy = true; message = ""
+ job = Task {
+ defer { busy = false; job = nil }
+ do {
+ try await operation()
+ snapshot = try await service.state()
+ models = snapshot.active?.sharing == true ? try await service.models() : []
+ try Task.checkCancellation()
+ } catch {
+ if let state = try? await service.state() { snapshot = state }
+ if snapshot.active?.sharing != true { models = [] }
+ message = (error as? ChatGPTError)?.localizedDescription ?? (error is CancellationError ? ChatGPTError.cancelled.localizedDescription : ChatGPTError.connection.localizedDescription)
+ }
+ }
+ }
+}
+
+struct ChatGPTSettingsView: View {
+ @ObservedObject var connection: ChatGPTConnectionModel
+ @Binding var model: String
+ @State private var previousAccount: String?
+ var disabled = false
+ var body: some View {
+ GroupBox {
+ VStack(alignment: .leading, spacing: 12) {
+ Text(L("Use your ChatGPT plan for text polishing, vocabulary suggestions and polishing comparisons. Recognition still uses your selected speech service.", "使用 ChatGPT 套餐润色文字、整理词频和对比润色结果。语音识别仍由已选语音服务提供。"))
+ .font(.callout).foregroundColor(.secondary)
+ if connection.busy { HStack { ProgressView().controlSize(.small); Text(L("Connecting…", "正在连接…")) } }
+ if !connection.snapshot.accounts.isEmpty {
+ HStack {
+ if connection.snapshot.accounts.count > 1 {
+ DropdownControl(label: L("ChatGPT account", "ChatGPT 账号"),
+ title: connection.snapshot.active?.label ?? L("Choose account", "选择账号"),
+ identifier: "chatgpt-account", choices: connection.snapshot.accounts.map { DropdownChoice(id: $0.id, title: $0.label) },
+ selectedID: connection.snapshot.activeID, disabled: disabled || connection.busy,
+ select: connection.select)
+ } else if let account = connection.snapshot.active { Text(account.label).font(.headline) }
+ Spacer(minLength: 12)
+ DropdownControl(label: L("Account options", "账号选项"), title: "", identifier: "chatgpt-options",
+ choices: accountOptions, compact: true, disabled: disabled || connection.busy, select: accountAction)
+ }
+ }
+ Text(status).font(.callout).foregroundColor(connection.snapshot.usageLimited ? .orange : .secondary)
+ if connection.snapshot.active?.sharing != true {
+ Button("Continue with ChatGPT") { connection.signIn() }.disabled(disabled || connection.busy)
+ }
+ if connection.snapshot.active?.sharing == true {
+ HStack {
+ Text(L("Model", "模型"))
+ DropdownControl(label: L("ChatGPT model", "ChatGPT 模型"),
+ title: connection.models.first { $0.id == model }?.label ?? L("Choose a model", "请选择模型"),
+ identifier: "chatgpt-model", choices: connection.models.map { DropdownChoice(id: $0.id, title: $0.label) },
+ selectedID: model, disabled: disabled || connection.busy, select: { model = $0 })
+ }
+ }
+ if connection.snapshot.usageLimited {
+ HStack {
+ Button(L("Manage usage", "管理用量")) { NSWorkspace.shared.open(ChatGPTProtocol.usageURL) }
+ Button(L("Retry plan usage", "重试套餐用量")) { connection.retryUsage() }.disabled(disabled || connection.busy)
+ }
+ }
+ if connection.busy { Button(L("Cancel", "取消")) { connection.cancelSignIn() } }
+ if !connection.message.isEmpty { Text(connection.message).font(.callout).foregroundColor(.orange).accessibilityLabel(connection.message) }
+ Text(L("Credentials stay in this app's macOS Keychain. Requests count toward your ChatGPT usage; dictation still falls back to the original after five seconds.", "凭据保存在本应用的 macOS 钥匙串中。请求计入 ChatGPT 用量;听写润色超过五秒仍回退原文。"))
+ .font(.caption).foregroundColor(.secondary)
+ }.frame(maxWidth: .infinity, alignment: .leading).padding(8)
+ } label: { Label(L("ChatGPT plan", "ChatGPT 套餐"), systemImage: "person.crop.circle") }
+ .onAppear { previousAccount = connection.snapshot.activeID }
+ .onChange(of: connection.snapshot.activeID) { active in
+ if let previous = previousAccount, previous != active { model = "" }
+ previousAccount = active
+ }
+ .onChange(of: connection.models) { catalog in
+ if !catalog.isEmpty, !catalog.contains(where: { $0.id == model }) { model = "" }
+ }
+ }
+ private var status: String {
+ if connection.snapshot.usageLimited { return ChatGPTError.quota.localizedDescription }
+ if connection.snapshot.active?.sharing == true { return L("Connected · ChatGPT plan usage allowed", "已连接 · 已允许使用 ChatGPT 套餐") }
+ if connection.snapshot.active?.connected == true { return L("Signed in · plan usage not allowed yet", "已登录 · 尚未允许使用套餐") }
+ return L("Connect ChatGPT and allow plan usage to choose a model.", "连接 ChatGPT 并允许套餐使用后,即可选择模型。")
+ }
+ private var accountOptions: [DropdownChoice] {
+ var items = [DropdownChoice(id: "add", title: L("Add account", "添加账号"))]
+ if connection.snapshot.active?.connected == true {
+ items += [DropdownChoice(id: "reconnect", title: L("Reconnect", "重新连接")),
+ DropdownChoice(id: "refresh", title: L("Refresh models", "刷新模型")),
+ DropdownChoice(id: "usage", title: L("Manage usage", "管理用量")),
+ DropdownChoice(id: "disconnect", title: L("Disconnect", "断开连接"), destructive: true)]
+ }
+ return items
+ }
+ private func accountAction(_ action: String) {
+ switch action {
+ case "add": connection.signIn(newAccount: true)
+ case "reconnect": connection.signIn()
+ case "refresh": connection.refresh()
+ case "usage": NSWorkspace.shared.open(ChatGPTProtocol.usageURL)
+ case "disconnect": connection.signOut()
+ default: break
+ }
+ }
+}
diff --git a/macos/Sources/ChatGPTVault.swift b/macos/Sources/ChatGPTVault.swift
new file mode 100644
index 0000000..880ea57
--- /dev/null
+++ b/macos/Sources/ChatGPTVault.swift
@@ -0,0 +1,95 @@
+import Foundation
+import Security
+import Darwin
+
+@_silgen_name("flock") private func chatGPTFileLock(_ fd: Int32, _ operation: Int32) -> Int32
+
+struct ChatGPTAccount: Codable {
+ var id = UUID().uuidString
+ var clientID: String
+ var subject: String?
+ var email: String?
+ var name: String?
+ var access: String?
+ var refresh: String?
+ var identity: String?
+ var expires: TimeInterval?
+ var refreshAfter: TimeInterval?
+ var scopes: [String] = []
+ var sharing: Bool { subject != nil && access != nil && scopes.contains(ChatGPTProtocol.directScope) }
+ mutating func clearTokens() { access = nil; refresh = nil; identity = nil; expires = nil; refreshAfter = nil; scopes = [] }
+}
+
+struct ChatGPTStored: Codable {
+ var version = 1
+ var hostID = "urn:uuid:" + UUID().uuidString.lowercased()
+ var activeID: String?
+ var accounts: [ChatGPTAccount] = []
+ var activeIndex: Int? { accounts.firstIndex { $0.id == activeID } }
+}
+
+/// The Keychain owns secrets. An owner-only lock serializes rotating tokens across processes.
+final class ChatGPTVault: @unchecked Sendable {
+ private let directory: URL
+ private let read: () throws -> Data?
+ private let write: (Data) throws -> Void
+
+ init(directory: URL? = nil, read: (() throws -> Data?)? = nil, write: ((Data) throws -> Void)? = nil) {
+ let service = Bundle.main.bundleIdentifier ?? "md.lifeos.doubao-say.macos"
+ self.directory = directory ?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
+ .appendingPathComponent(service).appendingPathComponent("chatgpt")
+ self.read = read ?? { try Self.load(service) }
+ self.write = write ?? { try Self.save($0, service: service) }
+ }
+
+ func transact<T>(_ work: (inout ChatGPTStored) async throws -> T) async throws -> T {
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true,
+ attributes: [.posixPermissions: 0o700])
+ let info = try FileManager.default.attributesOfItem(atPath: directory.path)
+ guard info[.type] as? FileAttributeType == .typeDirectory else { throw ChatGPTError.storage }
+ guard chmod(directory.path, 0o700) == 0 else { throw ChatGPTError.storage }
+ let descriptor = open(directory.appendingPathComponent("connection.lock").path, O_CREAT | O_RDWR | O_NOFOLLOW, 0o600)
+ guard descriptor >= 0 else { throw ChatGPTError.storage }
+ defer { _ = chatGPTFileLock(descriptor, LOCK_UN); close(descriptor) }
+ let deadline = ProcessInfo.processInfo.systemUptime + 35
+ while chatGPTFileLock(descriptor, LOCK_EX | LOCK_NB) != 0 {
+ guard errno == EWOULDBLOCK, ProcessInfo.processInfo.systemUptime < deadline else { throw ChatGPTError.storage }
+ try await Task.sleep(nanoseconds: 20_000_000)
+ }
+ var state = ChatGPTStored()
+ if let bytes = try read() {
+ guard bytes.count <= 1_000_000, let saved = try? JSONDecoder().decode(ChatGPTStored.self, from: bytes),
+ saved.version == 1, saved.hostID.hasPrefix("urn:uuid:"),
+ UUID(uuidString: String(saved.hostID.dropFirst(9))) != nil else { throw ChatGPTError.storage }
+ state = saved
+ }
+ let value = try await work(&state)
+ try write(JSONEncoder().encode(state))
+ return value
+ }
+
+ private static func query(_ service: String) -> [String: Any] {
+ [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service,
+ kSecAttrAccount as String: "chatgpt-connection"]
+ }
+ private static func load(_ service: String) throws -> Data? {
+ var attributes = query(service)
+ attributes[kSecReturnData as String] = true; attributes[kSecMatchLimit as String] = kSecMatchLimitOne
+ var result: CFTypeRef?
+ let status = SecItemCopyMatching(attributes as CFDictionary, &result)
+ if status == errSecItemNotFound { return nil }
+ guard status == errSecSuccess, let bytes = result as? Data else { throw ChatGPTError.storage }
+ return bytes
+ }
+ private static func save(_ bytes: Data, service: String) throws {
+ guard bytes.count <= 1_000_000 else { throw ChatGPTError.storage }
+ let value = [kSecValueData as String: bytes]
+ let status = SecItemUpdate(query(service) as CFDictionary, value as CFDictionary)
+ if status == errSecSuccess { return }
+ guard status == errSecItemNotFound else { throw ChatGPTError.storage }
+ var attributes = query(service)
+ attributes.merge(value) { _, next in next }
+ attributes[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly
+ guard SecItemAdd(attributes as CFDictionary, nil) == errSecSuccess else { throw ChatGPTError.storage }
+ }
+}
diff --git a/macos/Sources/DropdownControl.swift b/macos/Sources/DropdownControl.swift
new file mode 100644
index 0000000..10d2812
--- /dev/null
+++ b/macos/Sources/DropdownControl.swift
@@ -0,0 +1,116 @@
+import SwiftUI
+import AppKit
+
+struct DropdownChoice: Identifiable {
+ let id: String
+ let title: String
+ var destructive = false
+}
+
+/// An application-drawn dropdown shared by settings selectors and action menus.
+struct DropdownControl: View {
+ let label: String
+ let title: String
+ let identifier: String
+ let choices: [DropdownChoice]
+ var selectedID: String?
+ var compact = false
+ var disabled = false
+ let select: (String) -> Void
+ @State private var presented = false
+
+ var body: some View {
+ Button { presented.toggle() } label: {
+ HStack(spacing: 8) {
+ if compact { Image(systemName: "ellipsis").frame(width: 18) }
+ else {
+ Text(title).lineLimit(1).truncationMode(.middle)
+ Spacer(minLength: 12)
+ Image(systemName: "chevron.down").font(.caption.weight(.semibold))
+ }
+ }
+ .padding(.horizontal, 10).padding(.vertical, 7)
+ .background(RoundedRectangle(cornerRadius: 6).fill(Color(nsColor: .controlBackgroundColor)))
+ .overlay(RoundedRectangle(cornerRadius: 6).stroke(Color.secondary.opacity(0.3)))
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain).disabled(disabled || choices.isEmpty)
+ .accessibilityLabel(label).accessibilityValue(compact ? "" : title)
+ .accessibilityIdentifier(identifier).help(compact ? label : title)
+ .popover(isPresented: $presented, arrowEdge: .bottom) {
+ DropdownList(choices: choices, selectedID: selectedID, identifier: identifier) { value in
+ presented = false
+ if let value = value { select(value) }
+ }
+ }
+ .onChange(of: disabled) { if $0 { presented = false } }
+ }
+}
+
+private struct DropdownList: View {
+ let choices: [DropdownChoice]
+ let selectedID: String?
+ let identifier: String
+ let finish: (String?) -> Void
+ @State private var highlighted: String?
+ @State private var keyMonitor: Any?
+
+ var body: some View {
+ ScrollViewReader { proxy in
+ ScrollView {
+ VStack(spacing: 2) {
+ ForEach(choices) { choice in
+ Button { finish(choice.id) } label: {
+ HStack(spacing: 8) {
+ Image(systemName: "checkmark").opacity(choice.id == selectedID ? 1 : 0)
+ .frame(width: 14)
+ Text(choice.title).lineLimit(1)
+ Spacer(minLength: 8)
+ }
+ .foregroundColor(choice.destructive ? .red : .primary)
+ .padding(.horizontal, 10).frame(height: 30)
+ .background(RoundedRectangle(cornerRadius: 4)
+ .fill(highlighted == choice.id ? Color.accentColor.opacity(0.18) : .clear))
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain).id(choice.id)
+ .accessibilityIdentifier(identifier + "." + choice.id)
+ .accessibilityLabel(choice.title)
+ .accessibilityValue(choice.id == selectedID ? L("Selected", "已选") : "")
+ .onHover { if $0 { highlighted = choice.id } }
+ }
+ }.padding(6)
+ }
+ .frame(width: 280, height: CGFloat(min(choices.count, 8) * 32 + 10))
+ .onChange(of: highlighted) { if let value = $0 { proxy.scrollTo(value) } }
+ }
+ .onAppear {
+ highlighted = choices.contains { $0.id == selectedID } ? selectedID : choices.first?.id
+ keyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in
+ guard let window = event.window, NSApp.windows.contains(where: { $0 === window }),
+ event.modifierFlags.intersection([.command, .control, .option]).isEmpty else { return event }
+ switch event.keyCode {
+ case 125: move(1)
+ case 126: move(-1)
+ case 115: highlighted = choices.first?.id
+ case 119: highlighted = choices.last?.id
+ case 36, 49, 76: if let value = highlighted { finish(value) }
+ case 53: finish(nil)
+ case 48: finish(nil); return event
+ default: return event
+ }
+ return nil
+ }
+ }
+ .onDisappear {
+ if let monitor = keyMonitor { NSEvent.removeMonitor(monitor) }
+ keyMonitor = nil
+ }
+ }
+
+ private func move(_ offset: Int) {
+ guard !choices.isEmpty else { return }
+ let index = choices.firstIndex { $0.id == highlighted } ?? 0
+ highlighted = choices[max(0, min(choices.count - 1, index + offset))].id
+ }
+}
diff --git a/macos/Sources/MacSettings.swift b/macos/Sources/MacSettings.swift
index c7a5623..8cc181e 100644
--- a/macos/Sources/MacSettings.swift
+++ b/macos/Sources/MacSettings.swift
@@ -40,6 +40,8 @@ struct MacSettings: Codable, Equatable {
var reducedMotion = false
var autostart = false
var polishEnabled = false
+ var polishProvider = "api"
+ var polishChatGPTModel = ""
var polishBaseURL = "https://api.openai.com/v1"
var polishModel = "gpt-4o-mini"
var polishPromptZH = PolishDefaults.chinese
@@ -53,7 +55,9 @@ struct MacSettings: Codable, Equatable {
var dialPress = Shortcut(keyCode: 51, modifiers: 4)
func validate() throws {
- guard version == 1, (200...1500).contains(holdMilliseconds), (150...600).contains(doubleMilliseconds),
+ guard version == 1, ["api", "chatgpt"].contains(polishProvider), polishChatGPTModel.count <= 256,
+ !polishChatGPTModel.contains(where: { $0.isNewline || $0 == "\0" }),
+ (200...1500).contains(holdMilliseconds), (150...600).contains(doubleMilliseconds),
["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 ?? ""),
diff --git a/macos/Sources/PersonalViews.swift b/macos/Sources/PersonalViews.swift
index 360fe25..ce2b423 100644
--- a/macos/Sources/PersonalViews.swift
+++ b/macos/Sources/PersonalViews.swift
@@ -136,7 +136,8 @@ final class PersonalModel: ObservableObject {
guard !busy, flush() else { return }
statistics()
guard !candidates.isEmpty else { return }
- guard let key = SecretStore.load("polish-api-key"), !key.isEmpty else { feedback = L("Configure your polishing API key first.", "请先配置润色 API Key。"); return }
+ let key = PolishPolicy.credential(settings: SettingsStore.shared.value, apiKey: SecretStore.load("polish-api-key"))
+ guard !key.isEmpty else { feedback = L("Configure your polishing service first.", "请先配置润色服务。"); return }
let snapshot = candidates
let payload = snapshot.map { ["term": $0.term, "count": $0.count] as [String: Any] }
guard let json = try? JSONSerialization.data(withJSONObject: payload), let input = String(data: json, encoding: .utf8) else { return }
diff --git a/macos/Sources/PolishClient.swift b/macos/Sources/PolishClient.swift
index 7333571..77b64d2 100644
--- a/macos/Sources/PolishClient.swift
+++ b/macos/Sources/PolishClient.swift
@@ -1,6 +1,10 @@
import Foundation
enum PolishPolicy {
+ /// This internal readiness marker is never sent as a bearer token.
+ static func credential(settings: MacSettings, apiKey: @autoclosure () -> String?) -> String {
+ settings.polishProvider == "chatgpt" ? "chatgpt-plan" : apiKey() ?? ""
+ }
static func prompt(text: String, chinese: String, english: String) -> String {
let han = text.unicodeScalars.filter { (0x3400...0x4DBF).contains($0.value) || (0x4E00...0x9FFF).contains($0.value) || (0xF900...0xFAFF).contains($0.value) }.count
let words = text.split(whereSeparator: { !$0.isASCII || !$0.isLetter }).count
@@ -72,44 +76,84 @@ struct PolishStream {
/// One request owns its session and five-second deadline. No redirects or response bodies in errors.
final class PolishClient: NSObject, URLSessionDataDelegate {
+ private let planService: ChatGPTService
+ private let configuration: URLSessionConfiguration?
private var session: URLSession?
private var task: URLSessionDataTask?
private var deadline: DispatchWorkItem?
private var parser = PolishStream()
+ private var planParser = ChatGPTResponses()
+ private var planLease: ChatGPTLease?
+ private var failedHTTP = false
+ private var errorBody = Data()
+ private var credentialTask: Task<Void, Never>?
+ private var connectionObserver: NSObjectProtocol?
+ private var usingPlan = false
private var stopped = false
private var startedAt: TimeInterval = 0
private var timeout: TimeInterval = 5
var progress: ((String) -> Void)?
var completion: ((String?, String?) -> Void)?
+ init(planService: ChatGPTService = .shared, configuration: URLSessionConfiguration? = nil) {
+ self.planService = planService; self.configuration = configuration
+ super.init()
+ }
+
func start(text: String, settings: MacSettings, apiKey: String, timeout: TimeInterval = 5, personalize: Bool = true) {
self.timeout = min(30, max(1, timeout))
startedAt = ProcessInfo.processInfo.systemUptime
- guard let url = PolishPolicy.endpoint(settings.polishBaseURL) else { finish(nil, "endpoint"); return }
- var request = URLRequest(url: url, timeoutInterval: self.timeout)
- request.httpMethod = "POST"
- request.setValue("Bearer " + apiKey, forHTTPHeaderField: "Authorization")
- request.setValue("application/json", forHTTPHeaderField: "Content-Type")
- request.setValue("text/event-stream", forHTTPHeaderField: "Accept")
+ usingPlan = settings.polishProvider == "chatgpt"
let basePrompt = PolishPolicy.prompt(text: text, chinese: settings.polishPromptZH, english: settings.polishPromptEN)
let prompt = personalize ? PersonalVocabulary.prompt(basePrompt, words: (try? PersonalDataStore.shared.words()) ?? []) : basePrompt
let contextualPrompt = personalize ? PersonalCorrections.prompt(prompt, text: text, corrections: (try? PersonalDataStore.shared.corrections()) ?? []) : prompt
+ let expiry = DispatchWorkItem { [weak self] in self?.finish(nil, "timeout") }
+ deadline = expiry
+ DispatchQueue.main.asyncAfter(deadline: .now() + self.timeout, execute: expiry)
+ if usingPlan {
+ guard !settings.polishChatGPTModel.isEmpty else { finish(nil, ChatGPTError.model.localizedDescription); return }
+ connectionObserver = NotificationCenter.default.addObserver(forName: .chatGPTConnectionChanged, object: nil, queue: .main) { [weak self] notice in
+ if notice.userInfo?["reason"] as? String == "account" { self?.finish(nil, ChatGPTError.accountChanged.localizedDescription) }
+ if notice.userInfo?["reason"] as? String == "quota" { self?.finish(nil, ChatGPTError.quota.localizedDescription) }
+ }
+ credentialTask = Task { @MainActor [weak self] in
+ do {
+ let lease = try await self?.planService.access()
+ try Task.checkCancellation()
+ guard let self = self, let lease = lease, !self.stopped else { return }
+ self.planLease = lease
+ self.send(text: text, settings: settings, prompt: contextualPrompt, credential: lease.token)
+ } catch { self?.finish(nil, (error as? ChatGPTError)?.localizedDescription ?? ChatGPTError.connection.localizedDescription) }
+ }
+ } else { send(text: text, settings: settings, prompt: contextualPrompt, credential: apiKey) }
+ }
+ private func send(text: String, settings: MacSettings, prompt: String, credential: String) {
+ let elapsed = ProcessInfo.processInfo.systemUptime - startedAt
+ guard !stopped, elapsed < timeout else { finish(nil, "timeout"); return }
+ guard let url = usingPlan ? URL(string: ChatGPTProtocol.resource + "/responses") : PolishPolicy.endpoint(settings.polishBaseURL) else { finish(nil, "endpoint"); return }
+ var request = URLRequest(url: url, timeoutInterval: timeout - elapsed)
+ request.httpMethod = "POST"
+ request.setValue("Bearer " + credential, forHTTPHeaderField: "Authorization")
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ request.setValue("text/event-stream", forHTTPHeaderField: "Accept")
var body: [String: Any] = ["model": settings.polishModel, "temperature": 0.2, "stream": true,
- "messages": [["role": "system", "content": contextualPrompt], ["role": "user", "content": text]]]
- body.merge(PolishPolicy.reasoning(baseURL: settings.polishBaseURL, model: settings.polishModel)) { _, new in new }
+ "messages": [["role": "system", "content": prompt], ["role": "user", "content": text]]]
+ if usingPlan {
+ body = ["model": settings.polishChatGPTModel, "store": false, "stream": true,
+ "input": [["role": "developer", "content": prompt], ["role": "user", "content": text]]]
+ } else { body.merge(PolishPolicy.reasoning(baseURL: settings.polishBaseURL, model: settings.polishModel)) { _, new in new } }
guard let data = try? JSONSerialization.data(withJSONObject: body) else { finish(nil, "request"); return }
request.httpBody = data
- let config = URLSessionConfiguration.ephemeral
+ let config = (configuration?.copy() as? URLSessionConfiguration) ?? URLSessionConfiguration.ephemeral
config.urlCache = nil; config.httpCookieStorage = nil
- config.timeoutIntervalForRequest = self.timeout; config.timeoutIntervalForResource = self.timeout
+ config.timeoutIntervalForRequest = timeout - elapsed; config.timeoutIntervalForResource = timeout - elapsed
session = URLSession(configuration: config, delegate: self, delegateQueue: .main)
- let expiry = DispatchWorkItem { [weak self] in self?.finish(nil, "timeout") }
- deadline = expiry
- DispatchQueue.main.asyncAfter(deadline: .now() + self.timeout, execute: expiry)
task = session?.dataTask(with: request); task?.resume()
}
func cancel() {
stopped = true; deadline?.cancel(); deadline = nil
+ credentialTask?.cancel(); credentialTask = nil
+ if let observer = connectionObserver { NotificationCenter.default.removeObserver(observer) }; connectionObserver = nil
task?.cancel(); session?.invalidateAndCancel(); session = nil
completion = nil; progress = nil
}
@@ -123,20 +167,46 @@ final class PolishClient: NSObject, URLSessionDataDelegate {
newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { completionHandler(nil) }
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
- guard let http = response as? HTTPURLResponse, (200...299).contains(http.statusCode) else {
- completionHandler(.cancel); finish(nil, "service"); return
+ guard let http = response as? HTTPURLResponse else { completionHandler(.cancel); finish(nil, "service"); return }
+ if !(200...299).contains(http.statusCode) {
+ if usingPlan { failedHTTP = true; completionHandler(.allow) }
+ else { completionHandler(.cancel); finish(nil, "service") }
+ return
}
completionHandler(.allow)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
guard !stopped else { return }
guard ProcessInfo.processInfo.systemUptime - startedAt < timeout else { finish(nil, "timeout"); return }
- do { if let text = try parser.append(data) { progress?(text) } }
+ if failedHTTP {
+ guard errorBody.count + data.count <= 65_536 else { finish(nil, "service"); return }
+ errorBody.append(data); return
+ }
+ do { if let text = try (usingPlan ? planParser.append(data) : parser.append(data)) { progress?(text) } }
+ catch let error as ChatGPTError { planFailure(error) }
catch { finish(nil, "response") }
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
guard !stopped else { return }
guard error == nil else { finish(nil, "network"); return }
- do { finish(try parser.result(), nil) } catch { finish(nil, "response") }
+ if failedHTTP {
+ let body = (try? JSONSerialization.jsonObject(with: errorBody)) as? [String: Any]
+ let failure = body?["error"] as? [String: Any]
+ let code = failure?["code"] as? String ?? body?["code"] as? String
+ if code == "subscription_sharing_usage_limit_exceeded" { planFailure(.quota) }
+ else { finish(nil, "service") }
+ return
+ }
+ if usingPlan, let lease = planLease {
+ Task { @MainActor [weak self] in
+ guard let self = self, !self.stopped else { return }
+ guard await self.planService.isCurrent(lease) else { self.finish(nil, ChatGPTError.accountChanged.localizedDescription); return }
+ do { self.finish(try self.planParser.result(), nil) } catch { self.finish(nil, ChatGPTError.response.localizedDescription) }
+ }
+ } else { do { finish(try parser.result(), nil) } catch { finish(nil, "response") } }
+ }
+ private func planFailure(_ error: ChatGPTError) {
+ if case .quota = error, let lease = planLease { Task { await planService.pauseUsage(lease) } }
+ finish(nil, error.localizedDescription)
}
}
diff --git a/macos/Sources/PolishingSettingsView.swift b/macos/Sources/PolishingSettingsView.swift
new file mode 100644
index 0000000..e5db7f1
--- /dev/null
+++ b/macos/Sources/PolishingSettingsView.swift
@@ -0,0 +1,43 @@
+import SwiftUI
+
+struct PolishingSettingsView: View {
+ @ObservedObject var model: SettingsModel
+ @ObservedObject var connection = ChatGPTConnectionModel.shared
+ var body: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 14) {
+ Toggle(L("Voice polishing · experimental", "语音润色 · 实验特性"), isOn: $model.draft.polishEnabled)
+ Text(L("Text and pause previews are sent to the selected polishing service. Dictation has a five-second limit; failures retain the original text.", "文字和停顿预览会发送到已选润色服务。听写润色最多等待五秒,失败时保留原文。"))
+ .font(.callout).foregroundColor(.secondary)
+ Picker(L("Polishing service", "润色服务"), selection: $model.draft.polishProvider) {
+ Text(L("API key", "API Key")).tag("api")
+ Text(L("ChatGPT plan", "ChatGPT 套餐")).tag("chatgpt")
+ }.pickerStyle(.radioGroup).disabled(model.testing || model.state.recordingState != .idle)
+ if model.draft.polishProvider == "chatgpt" {
+ ChatGPTSettingsView(connection: connection, model: $model.draft.polishChatGPTModel,
+ disabled: model.testing || model.state.recordingState != .idle || model.state.evaluationBusy)
+ } else {
+ Text(L("API endpoint", "接口地址")).font(.headline)
+ TextField("Base URL", text: $model.draft.polishBaseURL)
+ Text(L("Model", "模型")).font(.headline)
+ TextField(L("Model", "模型"), text: $model.draft.polishModel)
+ Text("API Key").font(.headline)
+ SecureField(model.polishKeySaved ? L("API key saved · blank keeps it", "API Key 已保存 · 留空保留") : "API Key", text: $model.polishKey)
+ Text(L("Prefer a fast model with thinking disabled.", "建议选择低延迟、关闭思考的模型。"))
+ }
+ HStack {
+ Button(L("Test polishing", "测试润色")) { model.testPolish() }.disabled(model.testing)
+ if model.draft.polishProvider == "api" { Button(L("Clear saved key", "清除已存 Key")) { model.clearKey("polish-api-key") }.disabled(model.testing || model.state.recordingState != .idle) }
+ }
+ DisclosureGroup(L("Prompt settings", "提示词设置")) {
+ Button(L("Restore default prompts", "恢复默认提示词")) { model.draft.polishPromptZH = PolishDefaults.chinese; model.draft.polishPromptEN = PolishDefaults.english }
+ Text(L("Chinese prompt", "中文提示词")).font(.headline)
+ TextEditor(text: $model.draft.polishPromptZH).font(.system(size: 12)).frame(height: 150).border(Color.secondary.opacity(0.25))
+ Text(L("English prompt", "英文提示词")).font(.headline)
+ TextEditor(text: $model.draft.polishPromptEN).font(.system(size: 12)).frame(height: 150).border(Color.secondary.opacity(0.25))
+ Text(L("The transcript's main language selects the prompt. Your personal vocabulary and confirmed corrections are contextual references.", "按转写的主要语言选择提示词;个人词汇和已确认的纠错作为上下文参考。"))
+ }
+ }.padding(16)
+ }
+ }
+}
diff --git a/macos/Sources/SettingsModel.swift b/macos/Sources/SettingsModel.swift
new file mode 100644
index 0000000..adb860f
--- /dev/null
+++ b/macos/Sources/SettingsModel.swift
@@ -0,0 +1,303 @@
+import SwiftUI
+import AVFoundation
+import Combine
+
+@MainActor
+final class SettingsModel: ObservableObject {
+ @Published var draft = SettingsStore.shared.value {
+ didSet {
+ guard !suppressAutosave, draft != oldValue else { return }
+ if draft.microphoneID != oldValue.microphoneID { state.microphoneChecked = false; state.voiceChecked = false }
+ if draft.provider != oldValue.provider {
+ state.voiceChecked = false
+ suppressAutosave = true
+ recognitionKey = ""; savedRecognitionKey = ""
+ suppressAutosave = false
+ asrKeySaved = false
+ }
+ scheduleAutosave()
+ }
+ }
+ @Published var recognitionKey = "" { didSet { if recognitionKey != oldValue { scheduleAutosave() } } }
+ @Published var polishKey = "" { didSet { if polishKey != oldValue { scheduleAutosave() } } }
+ @Published var feedback = ""
+ @Published var selectedTab = "setup"
+ @Published var setupStep = 0
+ @Published var shortcutAvailable = false
+ @Published var capturing = false { didSet { if !capturing { resumeAutosave() } } }
+ @Published var testing = false { didSet { if !testing { resumeAutosave() } } }
+ @Published var microphones: [AudioInputDevice] = []
+ @Published var asrKeySaved = false
+ @Published var doubaoSessionSaved = false
+ @Published var polishKeySaved = false
+ let state: AppState
+ var apply: ((MacSettings, String?, String?) throws -> Void)?
+ var signIn: (() -> Void)?
+ var enableShortcut: (() -> Void)?
+ var captureShortcut: ((@escaping (Shortcut?) -> Void) -> Void)?
+ var voiceTest: (() -> Void)?
+ var stopVoiceTest: (() -> Void)?
+ var flushPersonal: (() -> Bool)?
+ var retry: (() -> Void)?
+ var clear: (() -> Void)?
+ var shortcutReady: (() -> Bool)?
+ var onFinishSetup: (() -> Void)?
+ var checkUpdates: (() -> Void)?
+ var canEvaluate: (() -> Bool)?
+ var cancelEvaluation: (() -> Void)?
+ var cancelUpdate: (() -> Void)?
+ var installUpdate: (() -> Void)?
+ var releaseNotes: (() -> Void)?
+ var languageChanged: (() -> Void)?
+ var clearNavigationFocus: (() -> Void)?
+ private var testASRClient: APIASRClient?
+ var cancelCapture: (() -> Void)?
+ private var testClient: PolishClient?
+ private var mic = AudioCaptureManager()
+ private var peak: Double = 0
+ private var testTimer: DispatchWorkItem?
+ @Published private(set) var saveStatus = ""
+ private var suppressAutosave = false
+ private var hasPendingAutosave = false
+ private var autosaveTimer: DispatchWorkItem?
+ private var recordingObserver: AnyCancellable?
+ private var savedRecognitionKey = ""
+ private var savedPolishKey = ""
+ 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.
+ DispatchQueue.main.async { self?.resumeAutosave() }
+ }
+ }
+ private func scheduleAutosave() {
+ guard !suppressAutosave, apply != nil else { return }
+ hasPendingAutosave = true
+ saveStatus = L("Saving automatically…", "正在自动保存…")
+ autosaveTimer?.cancel()
+ let work = DispatchWorkItem { [weak self] in _ = self?.save() }
+ autosaveTimer = work
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.6, execute: work)
+ }
+ private func resumeAutosave() {
+ if !suppressAutosave && hasPendingAutosave && !testing && !capturing && state.recordingState == .idle { scheduleAutosave() }
+ }
+ @discardableResult func saveIfNeeded() -> Bool { (!hasPendingAutosave || save()) && (flushPersonal?() ?? true) }
+ func closeEditor() {
+ cancelEvaluation?(); stopTests(); cancelCapture?(); capturing = false
+ if saveIfNeeded() {
+ suppressAutosave = true
+ recognitionKey = ""; polishKey = ""; savedRecognitionKey = ""; savedPolishKey = ""
+ suppressAutosave = false
+ }
+ }
+ var isDoubaoSignedIn: Bool {
+ SettingsStore.shared.value.provider == .doubao ? state.loginStatus == .loggedIn : doubaoSessionSaved
+ }
+ var effectiveMicrophone: AudioInputDevice? {
+ AudioDevices.resolve(preferred: draft.microphoneID, inputs: microphones, defaultUID: currentDefaultMicrophoneID)
+ }
+ var microphoneStatus: String {
+ guard let device = effectiveMicrophone else { return L("No microphone available", "没有可用的麦克风") }
+ if !draft.microphoneID.isEmpty && device.id != draft.microphoneID {
+ return L("Saved microphone disconnected. Using: ", "所选麦克风已断开,自动使用:") + device.name
+ }
+ return L("Using: ", "当前使用:") + device.name
+ }
+ func refreshMicrophones() {
+ let previous = effectiveMicrophone
+ microphones = microphoneInputs(); currentDefaultMicrophoneID = defaultMicrophoneID()
+ if previous != effectiveMicrophone {
+ state.microphoneChecked = false; state.voiceChecked = false
+ }
+ }
+ func refresh() {
+ guard !testing, !capturing, !hasPendingAutosave else { return }
+ suppressAutosave = true
+ defer { suppressAutosave = false }
+ draft = SettingsStore.shared.value
+ refreshMicrophones()
+ doubaoSessionSaved = ASRParamsStore.hasSavedParams
+ asrKeySaved = draft.provider == .doubao ? doubaoSessionSaved : SecretStore.load(draft.provider.rawValue + "-api-key") != nil
+ polishKeySaved = SecretStore.load("polish-api-key") != nil
+ recognitionKey = ""; polishKey = ""; savedRecognitionKey = ""; savedPolishKey = ""
+ }
+ @discardableResult func save() -> Bool {
+ autosaveTimer?.cancel(); autosaveTimer = nil
+ guard let apply = apply else { return false }
+ guard !testing, !capturing, state.recordingState == .idle else {
+ saveStatus = L("Changes will be saved when the current operation finishes.", "当前操作结束后自动保存修改。")
+ return false
+ }
+ suppressAutosave = true
+ defer { suppressAutosave = false }
+ do {
+ try draft.validate()
+ let recognition = recognitionKey.isEmpty || recognitionKey == savedRecognitionKey ? nil : recognitionKey
+ let polish = polishKey.isEmpty || polishKey == savedPolishKey ? nil : polishKey
+ try apply(draft, recognition, polish)
+ hasPendingAutosave = false
+ if recognition != nil { savedRecognitionKey = recognitionKey; asrKeySaved = true }
+ if polish != nil { savedPolishKey = polishKey; polishKeySaved = true }
+ saveStatus = draft.autostart && StartupService.needsApproval
+ ? L("Saved. Allow Doubao Say in System Settings → General → Login Items.", "已保存,请在系统设置 → 通用 → 登录项允许豆包说自启动。")
+ : L("Automatically saved", "已自动保存")
+ return true
+ } catch {
+ saveStatus = L("Changes could not be saved. Check values and system permissions.", "修改尚未保存,请检查填写内容和系统权限。")
+ return false
+ }
+ }
+ var setupBusy: Bool { testing || capturing || state.recordingState != .idle }
+ func setupComplete(_ step: Int) -> Bool {
+ switch step {
+ case 0: return draft.provider == .doubao ? isDoubaoSignedIn : (draft.provider == SettingsStore.shared.value.provider && state.loginStatus == .loggedIn)
+ case 1: return state.microphoneChecked
+ case 2: return shortcutAvailable
+ case 3: return state.voiceChecked
+ default: return false
+ }
+ }
+ 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 = ""
+ }
+ func previousSetupStep() {
+ guard !setupBusy else { return }
+ setupStep = max(0, setupStep - 1); feedback = ""
+ }
+ func finishSetup() {
+ guard setupStep == 3, canAdvanceSetup, saveIfNeeded() else { return }
+ let saved = SettingsStore.shared.value
+ guard state.loginStatus == .loggedIn, state.microphoneChecked, state.voiceChecked,
+ shortcutReady?() == true, draft.provider == saved.provider, draft.microphoneID == saved.microphoneID else {
+ feedback = L("Complete recognition, microphone, shortcut and voice checks first.", "请先完成识别服务、麦克风、快捷键和语音检查。")
+ return
+ }
+ var completed = draft; completed.onboardingComplete = true
+ do { try apply?(completed, nil, nil); draft = completed; onFinishSetup?() }
+ catch { feedback = L("Could not complete setup.", "无法完成使用准备。") }
+ }
+ func chooseShortcut(_ destination: String = "record") {
+ capturing = true; feedback = L("Press a shortcut. Esc cancels; selection does not use the microphone.", "请按下快捷键,Esc 取消。选键时不使用麦克风。")
+ captureShortcut? { [weak self] value in
+ guard let self = self else { return }; self.capturing = false
+ if let value = value {
+ switch destination {
+ case "vibekeyRecord": self.draft.vibekeyRecord = value
+ case "vibekeyEnter": self.draft.vibekeyEnter = value
+ case "vibekeyCancel": self.draft.vibekeyCancel = value
+ case "clockwise": self.draft.dialClockwise = value
+ case "counterclockwise": self.draft.dialCounterclockwise = value
+ case "press": self.draft.dialPress = value
+ default: self.draft.shortcut = value
+ }
+ self.feedback = L("Selected: ", "已选择:") + value.label
+ } else { self.feedback = L("Shortcut selection cancelled or unavailable", "选键已取消或当前不可用") }
+ }
+ }
+ func testPolish() {
+ guard saveIfNeeded() else { return }
+ guard !testing else { return }
+ do { try draft.validate() } catch { feedback = L("Check the endpoint, model and prompts.", "请检查接口、模型和提示词。"); return }
+ let key = PolishPolicy.credential(settings: draft, apiKey: polishKey.isEmpty ? SecretStore.load("polish-api-key") : polishKey)
+ guard !key.isEmpty else { feedback = L("Add a polishing API key first.", "请先填写润色 API Key。"); return }
+ testing = true; feedback = L("Testing with synthetic text…", "正在用合成文字测试…")
+ let usingPlan = draft.polishProvider == "chatgpt"
+ let client = PolishClient(); testClient = client
+ client.completion = { [weak self] text, error in
+ self?.testing = false; self?.testClient = nil
+ let detail = usingPlan && (error?.count ?? 0) > 12 ? error : nil
+ self?.feedback = text.map { L("Polishing test: ", "润色测试:") + $0 } ?? detail ?? L("Polishing failed or exceeded five seconds.", "润色失败或超过五秒。")
+ }
+ client.start(text: "周三上线,不对,周四上线。", settings: draft, apiKey: key)
+ }
+ func clearKey(_ account: String) {
+ guard !testing, !state.evaluationBusy, state.recordingState == .idle else { return }
+ do {
+ try SecretStore.clear(account)
+ if account == "polish-api-key" { savedPolishKey = ""; polishKey = ""; polishKeySaved = false }
+ else {
+ savedRecognitionKey = ""; recognitionKey = ""; asrKeySaved = false
+ if account == SettingsStore.shared.value.provider.rawValue + "-api-key" { state.loginStatus = .notLoggedIn }
+ }
+ feedback = L("Saved key removed", "已移除保存的 Key")
+ } catch { feedback = L("Could not remove the saved key.", "无法移除已存 Key。") }
+ }
+ func testRecognition() {
+ guard saveIfNeeded() else { return }
+ guard !testing, state.recordingState == .idle, draft.provider != .doubao else { return }
+ let key = recognitionKey.isEmpty ? (SecretStore.load(draft.provider.rawValue + "-api-key") ?? "") : recognitionKey
+ guard !key.isEmpty, !key.contains(where: { $0.isNewline || $0 == "\0" }) else { feedback = L("Add a valid API key first.", "请先填写有效的 API Key。"); return }
+ testing = true; feedback = L("Checking recognition connection…", "正在检查识别连接…")
+ let client = APIASRClient(provider: draft.provider); testASRClient = client
+ client.onOpen = { [weak self] in Task { @MainActor in
+ self?.stopTests(); self?.feedback = L("Recognition connection ready. Try a voice test next.", "识别连接已准备好,请继续语音测试。")
+ } }
+ let rejected: () -> Void = { [weak self] in Task { @MainActor in
+ self?.stopTests(); self?.feedback = L("Recognition connection failed. Check the key, service access and network.", "识别连接失败,请检查凭证、服务权限和网络。")
+ } }
+ client.onError = rejected; client.onAuthError = rejected
+ client.connect(apiKey: key)
+ let timer = DispatchWorkItem { [weak self] in
+ self?.stopTests(); self?.feedback = L("Recognition check timed out.", "识别连接检查超时。")
+ }
+ testTimer = timer; DispatchQueue.main.asyncAfter(deadline: .now() + 8, execute: timer)
+ }
+ func checkMicrophone() {
+ guard saveIfNeeded() else { return }
+ guard !testing, !state.evaluationBusy, state.recordingState == .idle else { return }
+ guard AVCaptureDevice.authorizationStatus(for: .audio) == .authorized else {
+ AVCaptureDevice.requestAccess(for: .audio) { _ in }
+ feedback = L("Allow microphone access, then retry.", "允许麦克风访问后,请重试。"); return
+ }
+ testing = true; peak = 0; state.microphoneChecked = false
+ feedback = L("Speak normally for three seconds. Audio stays on this device.", "请正常说话三秒,音频仅在本机检查。")
+ mic.onRMS = { [weak self] rms in Task { @MainActor in
+ guard let self = self, self.testing else { return }
+ self.peak = max(self.peak, rms); self.state.rms = rms
+ } }
+ mic.onError = { [weak self] in
+ self?.stopTests(); self?.feedback = L("Microphone input changed or disconnected. Retry the check.", "麦克风输入变化或断开,请重新检查。")
+ }
+ do { try mic.startCapture(deviceID: draft.microphoneID) }
+ catch { stopTests(); feedback = L("Microphone could not start.", "麦克风启动失败。"); return }
+ let timer = DispatchWorkItem { [weak self] in
+ guard let self = self else { return }
+ let audible = self.peak >= 0.012
+ self.stopTests(); self.state.microphoneChecked = audible
+ self.feedback = audible ? L("Microphone signal detected", "已检测到麦克风声音") : L("No clear signal. Check input and volume.", "没有明显声音,请检查输入设备和音量。")
+ }
+ testTimer = timer; DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: timer)
+ }
+ func stopTests() {
+ testTimer?.cancel(); testTimer = nil; mic.stopCapture(); mic.onRMS = nil; mic.onError = nil
+ testClient?.cancel(); testClient = nil; testASRClient?.disconnect(); testASRClient = nil; testing = false; state.rms = 0
+ }
+}
diff --git a/macos/Sources/SettingsWindow.swift b/macos/Sources/SettingsWindow.swift
index 96fedcf..ee1ea2c 100644
--- a/macos/Sources/SettingsWindow.swift
+++ b/macos/Sources/SettingsWindow.swift
@@ -2,304 +2,6 @@ import SwiftUI
import AVFoundation
import Combine
-@MainActor
-final class SettingsModel: ObservableObject {
- @Published var draft = SettingsStore.shared.value {
- didSet {
- guard !suppressAutosave, draft != oldValue else { return }
- if draft.microphoneID != oldValue.microphoneID { state.microphoneChecked = false; state.voiceChecked = false }
- if draft.provider != oldValue.provider {
- state.voiceChecked = false
- suppressAutosave = true
- recognitionKey = ""; savedRecognitionKey = ""
- suppressAutosave = false
- asrKeySaved = false
- }
- scheduleAutosave()
- }
- }
- @Published var recognitionKey = "" { didSet { if recognitionKey != oldValue { scheduleAutosave() } } }
- @Published var polishKey = "" { didSet { if polishKey != oldValue { scheduleAutosave() } } }
- @Published var feedback = ""
- @Published var selectedTab = "setup"
- @Published var setupStep = 0
- @Published var shortcutAvailable = false
- @Published var capturing = false { didSet { if !capturing { resumeAutosave() } } }
- @Published var testing = false { didSet { if !testing { resumeAutosave() } } }
- @Published var microphones: [AudioInputDevice] = []
- @Published var asrKeySaved = false
- @Published var doubaoSessionSaved = false
- @Published var polishKeySaved = false
- let state: AppState
- var apply: ((MacSettings, String?, String?) throws -> Void)?
- var signIn: (() -> Void)?
- var enableShortcut: (() -> Void)?
- var captureShortcut: ((@escaping (Shortcut?) -> Void) -> Void)?
- var voiceTest: (() -> Void)?
- var stopVoiceTest: (() -> Void)?
- var flushPersonal: (() -> Bool)?
- var retry: (() -> Void)?
- var clear: (() -> Void)?
- var shortcutReady: (() -> Bool)?
- var onFinishSetup: (() -> Void)?
- var checkUpdates: (() -> Void)?
- var canEvaluate: (() -> Bool)?
- var cancelEvaluation: (() -> Void)?
- var cancelUpdate: (() -> Void)?
- var installUpdate: (() -> Void)?
- var releaseNotes: (() -> Void)?
- var languageChanged: (() -> Void)?
- var clearNavigationFocus: (() -> Void)?
- private var testASRClient: APIASRClient?
- var cancelCapture: (() -> Void)?
- private var testClient: PolishClient?
- private var mic = AudioCaptureManager()
- private var peak: Double = 0
- private var testTimer: DispatchWorkItem?
- @Published private(set) var saveStatus = ""
- private var suppressAutosave = false
- private var hasPendingAutosave = false
- private var autosaveTimer: DispatchWorkItem?
- private var recordingObserver: AnyCancellable?
- private var savedRecognitionKey = ""
- private var savedPolishKey = ""
- 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.
- DispatchQueue.main.async { self?.resumeAutosave() }
- }
- }
- private func scheduleAutosave() {
- guard !suppressAutosave, apply != nil else { return }
- hasPendingAutosave = true
- saveStatus = L("Saving automatically…", "正在自动保存…")
- autosaveTimer?.cancel()
- let work = DispatchWorkItem { [weak self] in _ = self?.save() }
- autosaveTimer = work
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.6, execute: work)
- }
- private func resumeAutosave() {
- if !suppressAutosave && hasPendingAutosave && !testing && !capturing && state.recordingState == .idle { scheduleAutosave() }
- }
- @discardableResult func saveIfNeeded() -> Bool { (!hasPendingAutosave || save()) && (flushPersonal?() ?? true) }
- func closeEditor() {
- cancelEvaluation?(); stopTests(); cancelCapture?(); capturing = false
- if saveIfNeeded() {
- suppressAutosave = true
- recognitionKey = ""; polishKey = ""; savedRecognitionKey = ""; savedPolishKey = ""
- suppressAutosave = false
- }
- }
- var isDoubaoSignedIn: Bool {
- SettingsStore.shared.value.provider == .doubao ? state.loginStatus == .loggedIn : doubaoSessionSaved
- }
- var effectiveMicrophone: AudioInputDevice? {
- AudioDevices.resolve(preferred: draft.microphoneID, inputs: microphones, defaultUID: currentDefaultMicrophoneID)
- }
- var microphoneStatus: String {
- guard let device = effectiveMicrophone else { return L("No microphone available", "没有可用的麦克风") }
- if !draft.microphoneID.isEmpty && device.id != draft.microphoneID {
- return L("Saved microphone disconnected. Using: ", "所选麦克风已断开,自动使用:") + device.name
- }
- return L("Using: ", "当前使用:") + device.name
- }
- func refreshMicrophones() {
- let previous = effectiveMicrophone
- microphones = microphoneInputs(); currentDefaultMicrophoneID = defaultMicrophoneID()
- if previous != effectiveMicrophone {
- state.microphoneChecked = false; state.voiceChecked = false
- }
- }
- func refresh() {
- guard !testing, !capturing, !hasPendingAutosave else { return }
- suppressAutosave = true
- defer { suppressAutosave = false }
- draft = SettingsStore.shared.value
- refreshMicrophones()
- doubaoSessionSaved = ASRParamsStore.hasSavedParams
- asrKeySaved = draft.provider == .doubao ? doubaoSessionSaved : SecretStore.load(draft.provider.rawValue + "-api-key") != nil
- polishKeySaved = SecretStore.load("polish-api-key") != nil
- recognitionKey = ""; polishKey = ""; savedRecognitionKey = ""; savedPolishKey = ""
- }
- @discardableResult func save() -> Bool {
- autosaveTimer?.cancel(); autosaveTimer = nil
- guard let apply = apply else { return false }
- guard !testing, !capturing, state.recordingState == .idle else {
- saveStatus = L("Changes will be saved when the current operation finishes.", "当前操作结束后自动保存修改。")
- return false
- }
- suppressAutosave = true
- defer { suppressAutosave = false }
- do {
- try draft.validate()
- let recognition = recognitionKey.isEmpty || recognitionKey == savedRecognitionKey ? nil : recognitionKey
- let polish = polishKey.isEmpty || polishKey == savedPolishKey ? nil : polishKey
- try apply(draft, recognition, polish)
- hasPendingAutosave = false
- if recognition != nil { savedRecognitionKey = recognitionKey; asrKeySaved = true }
- if polish != nil { savedPolishKey = polishKey; polishKeySaved = true }
- saveStatus = draft.autostart && StartupService.needsApproval
- ? L("Saved. Allow Doubao Say in System Settings → General → Login Items.", "已保存,请在系统设置 → 通用 → 登录项允许豆包说自启动。")
- : L("Automatically saved", "已自动保存")
- return true
- } catch {
- saveStatus = L("Changes could not be saved. Check values and system permissions.", "修改尚未保存,请检查填写内容和系统权限。")
- return false
- }
- }
- var setupBusy: Bool { testing || capturing || state.recordingState != .idle }
- func setupComplete(_ step: Int) -> Bool {
- switch step {
- case 0: return draft.provider == .doubao ? isDoubaoSignedIn : (draft.provider == SettingsStore.shared.value.provider && state.loginStatus == .loggedIn)
- case 1: return state.microphoneChecked
- case 2: return shortcutAvailable
- case 3: return state.voiceChecked
- default: return false
- }
- }
- 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 = ""
- }
- func previousSetupStep() {
- guard !setupBusy else { return }
- setupStep = max(0, setupStep - 1); feedback = ""
- }
- func finishSetup() {
- guard setupStep == 3, canAdvanceSetup, saveIfNeeded() else { return }
- let saved = SettingsStore.shared.value
- guard state.loginStatus == .loggedIn, state.microphoneChecked, state.voiceChecked,
- shortcutReady?() == true, draft.provider == saved.provider, draft.microphoneID == saved.microphoneID else {
- feedback = L("Complete recognition, microphone, shortcut and voice checks first.", "请先完成识别服务、麦克风、快捷键和语音检查。")
- return
- }
- var completed = draft; completed.onboardingComplete = true
- do { try apply?(completed, nil, nil); draft = completed; onFinishSetup?() }
- catch { feedback = L("Could not complete setup.", "无法完成使用准备。") }
- }
- func chooseShortcut(_ destination: String = "record") {
- capturing = true; feedback = L("Press a shortcut. Esc cancels; selection does not use the microphone.", "请按下快捷键,Esc 取消。选键时不使用麦克风。")
- captureShortcut? { [weak self] value in
- guard let self = self else { return }; self.capturing = false
- if let value = value {
- switch destination {
- case "vibekeyRecord": self.draft.vibekeyRecord = value
- case "vibekeyEnter": self.draft.vibekeyEnter = value
- case "vibekeyCancel": self.draft.vibekeyCancel = value
- case "clockwise": self.draft.dialClockwise = value
- case "counterclockwise": self.draft.dialCounterclockwise = value
- case "press": self.draft.dialPress = value
- default: self.draft.shortcut = value
- }
- self.feedback = L("Selected: ", "已选择:") + value.label
- } else { self.feedback = L("Shortcut selection cancelled or unavailable", "选键已取消或当前不可用") }
- }
- }
- func testPolish() {
- guard saveIfNeeded() else { return }
- guard !testing else { return }
- do { try draft.validate() } catch { feedback = L("Check the endpoint, model and prompts.", "请检查接口、模型和提示词。"); return }
- let key = polishKey.isEmpty ? (SecretStore.load("polish-api-key") ?? "") : polishKey
- guard !key.isEmpty else { feedback = L("Add a polishing API key first.", "请先填写润色 API Key。"); return }
- testing = true; feedback = L("Testing with synthetic text…", "正在用合成文字测试…")
- let client = PolishClient(); testClient = client
- client.completion = { [weak self] text, _ in
- self?.testing = false; self?.testClient = nil
- self?.feedback = text.map { L("Polishing test: ", "润色测试:") + $0 } ?? L("Polishing failed or exceeded five seconds.", "润色失败或超过五秒。")
- }
- client.start(text: "周三上线,不对,周四上线。", settings: draft, apiKey: key)
- }
- func clearKey(_ account: String) {
- guard !testing, !state.evaluationBusy, state.recordingState == .idle else { return }
- do {
- try SecretStore.clear(account)
- if account == "polish-api-key" { savedPolishKey = ""; polishKey = ""; polishKeySaved = false }
- else {
- savedRecognitionKey = ""; recognitionKey = ""; asrKeySaved = false
- if account == SettingsStore.shared.value.provider.rawValue + "-api-key" { state.loginStatus = .notLoggedIn }
- }
- feedback = L("Saved key removed", "已移除保存的 Key")
- } catch { feedback = L("Could not remove the saved key.", "无法移除已存 Key。") }
- }
- func testRecognition() {
- guard saveIfNeeded() else { return }
- guard !testing, state.recordingState == .idle, draft.provider != .doubao else { return }
- let key = recognitionKey.isEmpty ? (SecretStore.load(draft.provider.rawValue + "-api-key") ?? "") : recognitionKey
- guard !key.isEmpty, !key.contains(where: { $0.isNewline || $0 == "\0" }) else { feedback = L("Add a valid API key first.", "请先填写有效的 API Key。"); return }
- testing = true; feedback = L("Checking recognition connection…", "正在检查识别连接…")
- let client = APIASRClient(provider: draft.provider); testASRClient = client
- client.onOpen = { [weak self] in Task { @MainActor in
- self?.stopTests(); self?.feedback = L("Recognition connection ready. Try a voice test next.", "识别连接已准备好,请继续语音测试。")
- } }
- let rejected: () -> Void = { [weak self] in Task { @MainActor in
- self?.stopTests(); self?.feedback = L("Recognition connection failed. Check the key, service access and network.", "识别连接失败,请检查凭证、服务权限和网络。")
- } }
- client.onError = rejected; client.onAuthError = rejected
- client.connect(apiKey: key)
- let timer = DispatchWorkItem { [weak self] in
- self?.stopTests(); self?.feedback = L("Recognition check timed out.", "识别连接检查超时。")
- }
- testTimer = timer; DispatchQueue.main.asyncAfter(deadline: .now() + 8, execute: timer)
- }
- func checkMicrophone() {
- guard saveIfNeeded() else { return }
- guard !testing, !state.evaluationBusy, state.recordingState == .idle else { return }
- guard AVCaptureDevice.authorizationStatus(for: .audio) == .authorized else {
- AVCaptureDevice.requestAccess(for: .audio) { _ in }
- feedback = L("Allow microphone access, then retry.", "允许麦克风访问后,请重试。"); return
- }
- testing = true; peak = 0; state.microphoneChecked = false
- feedback = L("Speak normally for three seconds. Audio stays on this device.", "请正常说话三秒,音频仅在本机检查。")
- mic.onRMS = { [weak self] rms in Task { @MainActor in
- guard let self = self, self.testing else { return }
- self.peak = max(self.peak, rms); self.state.rms = rms
- } }
- mic.onError = { [weak self] in
- self?.stopTests(); self?.feedback = L("Microphone input changed or disconnected. Retry the check.", "麦克风输入变化或断开,请重新检查。")
- }
- do { try mic.startCapture(deviceID: draft.microphoneID) }
- catch { stopTests(); feedback = L("Microphone could not start.", "麦克风启动失败。"); return }
- let timer = DispatchWorkItem { [weak self] in
- guard let self = self else { return }
- let audible = self.peak >= 0.012
- self.stopTests(); self.state.microphoneChecked = audible
- self.feedback = audible ? L("Microphone signal detected", "已检测到麦克风声音") : L("No clear signal. Check input and volume.", "没有明显声音,请检查输入设备和音量。")
- }
- testTimer = timer; DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: timer)
- }
- func stopTests() {
- testTimer?.cancel(); testTimer = nil; mic.stopCapture(); mic.onRMS = nil; mic.onError = nil
- testClient?.cancel(); testClient = nil; testASRClient?.disconnect(); testASRClient = nil; testing = false; state.rms = 0
- }
-}
-
struct SettingsView: View {
@ObservedObject var model: SettingsModel
@ObservedObject var state: AppState
@@ -531,31 +233,7 @@ struct SettingsView: View {
}
}
}
- private var polishing: some View {
- ScrollView {
- VStack(alignment: .leading, spacing: 12) {
- Toggle(L("Voice polishing · experimental", "语音润色 · 实验特性"), isOn: $model.draft.polishEnabled)
- Text(L("Transcripts and pause previews go to this endpoint. Five-second limit; failures use original text. Press the dictation shortcut during final polishing to skip.", "转写和停顿预览会发送到下方接口。最多等待五秒,失败时使用原文;最终润色期间再按听写快捷键可跳过。"))
- Text(L("API endpoint", "接口地址")).font(.headline)
- TextField("Base URL", text: $model.draft.polishBaseURL)
- Text(L("Model", "模型")).font(.headline)
- TextField(L("Model", "模型"), text: $model.draft.polishModel)
- Text("API Key").font(.headline)
- SecureField(model.polishKeySaved ? L("API key saved · blank keeps it", "API Key 已保存 · 留空保留") : "API Key", text: $model.polishKey)
- Text(L("Prefer a fast model with thinking disabled.", "建议选择低延迟、关闭思考的模型。"))
- HStack {
- Button(L("Test endpoint", "测试接口")) { model.testPolish() }.disabled(model.testing)
- Button(L("Clear saved key", "清除已存 Key")) { model.clearKey("polish-api-key") }.disabled(model.testing || state.recordingState != .idle)
- Button(L("Restore default prompts", "恢复默认提示词")) { model.draft.polishPromptZH = PolishDefaults.chinese; model.draft.polishPromptEN = PolishDefaults.english }
- }
- Text(L("Chinese prompt", "中文提示词")).font(.headline)
- TextEditor(text: $model.draft.polishPromptZH).font(.system(size: 12)).frame(height: 150).border(Color.secondary.opacity(0.25))
- Text(L("English prompt", "英文提示词")).font(.headline)
- TextEditor(text: $model.draft.polishPromptEN).font(.system(size: 12)).frame(height: 150).border(Color.secondary.opacity(0.25))
- Text(L("The transcript's main language selects the prompt. Your personal vocabulary and confirmed corrections are added as contextual references.", "按转写的主要语言选择提示词;个人词汇和你确认过的纠错会作为上下文参考。"))
- }.padding(16)
- }
- }
+ private var polishing: some View { PolishingSettingsView(model: model) }
private var shortcuts: some View {
ScrollView {
VStack(alignment: .leading, spacing: 14) {
diff --git a/macos/Sources/SpeechEvaluationModel.swift b/macos/Sources/SpeechEvaluationModel.swift
index 356e243..beee935 100644
--- a/macos/Sources/SpeechEvaluationModel.swift
+++ b/macos/Sources/SpeechEvaluationModel.swift
@@ -125,7 +125,7 @@ import Combine
guard ready, !busy, !recording else { return }
guard state.recordingState == .idle, !state.evaluationBusy, canStart() else { feedback = L("Finish dictation or microphone checks first.", "请先结束日常听写或麦克风检查。"); return }
guard let key = SecretStore.load("volcengine-api-key"), !key.isEmpty else { feedback = L("Configure an official Volcengine ASR key first.", "请先配置官方火山引擎 ASR Key。") ; return }
- let polishKey = includePolish ? SecretStore.load("polish-api-key") : nil
+ let polishKey = includePolish ? PolishPolicy.credential(settings: SettingsStore.shared.value, apiKey: SecretStore.load("polish-api-key")) : nil
guard !includePolish || !(polishKey ?? "").isEmpty else { feedback = L("Configure polishing credentials or turn off polishing comparison.", "请配置润色凭证,或关闭润色对比。") ; return }
let words = (try? PersonalDataStore.shared.recognitionWords()) ?? []
let settings = SettingsStore.shared.value
diff --git a/macos/Sources/TranscriptionManager.swift b/macos/Sources/TranscriptionManager.swift
index ab24b9a..1ddfbe3 100644
--- a/macos/Sources/TranscriptionManager.swift
+++ b/macos/Sources/TranscriptionManager.swift
@@ -85,7 +85,7 @@ final class TranscriptionManager {
latency = InputLatency()
rawText = ""; speaking = false; finalGate = FinalResultGate()
state.transcriptionText = ""; state.errorMessage = nil; state.overlayStatus = ""
- let polishKey = settings.polishEnabled ? (SecretStore.load("polish-api-key") ?? "") : ""
+ let polishKey = settings.polishEnabled ? PolishPolicy.credential(settings: settings, apiKey: SecretStore.load("polish-api-key")) : ""
polishAvailable = !polishKey.isEmpty
polisher.begin(settings: settings, key: polishKey)
setState(.starting); overlay.showOverlay()
diff --git a/macos/Tests/ChatGPTPolishTests.swift b/macos/Tests/ChatGPTPolishTests.swift
new file mode 100644
index 0000000..3aa53f9
--- /dev/null
+++ b/macos/Tests/ChatGPTPolishTests.swift
@@ -0,0 +1,94 @@
+import XCTest
+@testable import DoubaoSayCore
+
+private final class PlanRequestFixture: URLProtocol {
+ static var mode = "success"
+ static var requests = 0
+ override class func canInit(with request: URLRequest) -> Bool { true }
+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
+ override func startLoading() {
+ Self.requests += 1
+ XCTAssertEqual(request.url?.absoluteString, ChatGPTProtocol.resource + "/responses")
+ XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), "Bearer synthetic-plan-token")
+ var data = request.httpBody ?? Data()
+ if data.isEmpty, let stream = request.httpBodyStream {
+ stream.open(); defer { stream.close() }
+ var bytes = [UInt8](repeating: 0, count: 1024)
+ while stream.hasBytesAvailable, data.count < 100_000 {
+ let count = stream.read(&bytes, maxLength: bytes.count)
+ if count <= 0 { break }; data.append(contentsOf: bytes.prefix(count))
+ }
+ }
+ if let payload = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
+ XCTAssertEqual(payload["model"] as? String, "synthetic-fast")
+ XCTAssertEqual(payload["store"] as? Bool, false); XCTAssertEqual(payload["stream"] as? Bool, true)
+ XCTAssertNil(payload["messages"]); XCTAssertNil(payload["temperature"])
+ XCTAssertEqual((payload["input"] as? [[String: Any]])?.first?["role"] as? String, "developer")
+ } else { XCTFail("Responses body must be JSON") }
+ let response = HTTPURLResponse(url: request.url!, statusCode: Self.mode.hasPrefix("http") ? 429 : 200,
+ httpVersion: nil, headerFields: ["Content-Type": "text/event-stream"])!
+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
+ let body: String
+ if Self.mode == "httpQuota" { body = "{\"error\":{\"code\":\"subscription_sharing_usage_limit_exceeded\"}}" }
+ else if Self.mode == "httpRateLimit" { body = "{\"error\":{\"code\":\"rate_limit_exceeded\"}}" }
+ else if Self.mode == "quota" { body = "data: {\"type\":\"error\",\"code\":\"subscription_sharing_usage_limit_exceeded\"}\n\n" }
+ else {
+ body = "data: {\"type\":\"response.output_text.delta\",\"delta\":\"done\"}\n\n"
+ + (Self.mode == "success" ? "data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\"}}\n\n" : "")
+ }
+ for byte in Data(body.utf8) { client?.urlProtocol(self, didLoad: Data([byte])) }
+ client?.urlProtocolDidFinishLoading(self)
+ }
+ override func stopLoading() { }
+}
+
+final class ChatGPTPolishTests: XCTestCase {
+ @MainActor
+ func testSharedPolisherUsesPlanWithoutAPIKeyRequiresCompletionAndPausesQuota() async throws {
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ var data: Data?
+ let vault = ChatGPTVault(directory: directory, read: { data }, write: { data = $0 })
+ try await vault.transact { stored in
+ var account = ChatGPTAccount(clientID: "synthetic-issued")
+ account.id = "synthetic"; account.subject = "subject"; account.access = "synthetic-plan-token"
+ account.expires = Date().timeIntervalSince1970 + 3600; account.scopes = [ChatGPTProtocol.directScope]
+ stored.accounts = [account]; stored.activeID = account.id
+ }
+ let service = ChatGPTService(vault: vault)
+ let config = URLSessionConfiguration.ephemeral; config.protocolClasses = [PlanRequestFixture.self]
+ var settings = MacSettings(); settings.polishProvider = "chatgpt"; settings.polishChatGPTModel = "synthetic-fast"
+ func request() async -> (String?, String?) {
+ let client = PolishClient(planService: service, configuration: config)
+ defer { client.cancel() }
+ return await withCheckedContinuation { continuation in
+ client.completion = { value, error in continuation.resume(returning: (value, error)) }
+ client.start(text: "synthetic text", settings: settings, apiKey: "", personalize: false)
+ }
+ }
+ PlanRequestFixture.requests = 0; PlanRequestFixture.mode = "success"
+ let completed = await request(); XCTAssertEqual(completed.0, "done"); XCTAssertNil(completed.1)
+ PlanRequestFixture.mode = "incomplete"
+ let incomplete = await request(); XCTAssertNil(incomplete.0); XCTAssertNotNil(incomplete.1)
+ PlanRequestFixture.mode = "httpRateLimit"
+ let transient = await request(); XCTAssertNil(transient.0)
+ let transientState = try await service.state(); XCTAssertFalse(transientState.usageLimited)
+ PlanRequestFixture.mode = "httpQuota"
+ let httpLimited = await request(); XCTAssertNil(httpLimited.0)
+ let httpDeadline = Date().addingTimeInterval(1)
+ while !(try await service.state()).usageLimited && Date() < httpDeadline { await Task.yield() }
+ let httpState = try await service.state(); XCTAssertTrue(httpState.usageLimited)
+ await service.resumeUsage()
+ PlanRequestFixture.mode = "quota"
+ let limited = await request(); XCTAssertNil(limited.0)
+ // Await the connection-owned pause, not a sleep or copied mock state.
+ let deadline = Date().addingTimeInterval(1)
+ while !(try await service.state()).usageLimited && Date() < deadline { await Task.yield() }
+ let calls = PlanRequestFixture.requests
+ let paused = await request(); XCTAssertNil(paused.0)
+ XCTAssertEqual(PlanRequestFixture.requests, calls)
+ let state = try await service.state(); XCTAssertEqual(state.active?.connected, true)
+ await service.resumeUsage(); PlanRequestFixture.mode = "success"
+ let retried = await request(); XCTAssertEqual(retried.0, "done")
+ }
+}
diff --git a/macos/Tests/ChatGPTServiceTests.swift b/macos/Tests/ChatGPTServiceTests.swift
new file mode 100644
index 0000000..628b577
--- /dev/null
+++ b/macos/Tests/ChatGPTServiceTests.swift
@@ -0,0 +1,134 @@
+import XCTest
+@testable import DoubaoSayCore
+
+private final class MemoryCredentials: @unchecked Sendable {
+ private let lock = NSLock()
+ private var bytes: Data?
+ func read() -> Data? { lock.lock(); defer { lock.unlock() }; return bytes }
+ func write(_ value: Data) { lock.lock(); defer { lock.unlock() }; bytes = value }
+}
+private final class TokenFixture: ChatGPTHTTP, @unchecked Sendable {
+ private let lock = NSLock()
+ private var calls = 0
+ var failure: ChatGPTError?
+ var identityUnavailable = false
+ var delay: UInt64 = 40_000_000
+ var tokenCalls: Int { lock.lock(); defer { lock.unlock() }; return calls }
+ private func count() { lock.lock(); defer { lock.unlock() }; calls += 1 }
+ override func json(_ url: URL, fields: [String: String]? = nil, access: String? = nil) async throws -> [String: Any] {
+ if url.path.hasSuffix("/token") {
+ XCTAssertEqual(fields?["grant_type"], "refresh_token")
+ XCTAssertEqual(fields?["client_id"], "issued")
+ XCTAssertEqual(fields?["refresh_token"], "synthetic-old-refresh")
+ XCTAssertNil(fields?["scope"])
+ count(); try await Task.sleep(nanoseconds: delay)
+ if let failure = failure { throw failure }
+ var result: [String: Any] = ["access_token": "synthetic-new-access", "refresh_token": "synthetic-rotated-refresh", "token_type": "Bearer", "expires_in": 3600]
+ if identityUnavailable { result["id_token"] = "synthetic-unverified-identity" }
+ return result
+ }
+ if url.path.hasSuffix("/jwks.json") { throw ChatGPTError.connection }
+ XCTAssertEqual(url.path, "/v1/models")
+ try await Task.sleep(nanoseconds: 20_000_000)
+ return ["models": [["slug": "synthetic-fast", "display_name": "Synthetic Fast", "visibility": "list"]]]
+ }
+}
+
+final class ChatGPTServiceTests: XCTestCase {
+ private func fixture() async throws -> (ChatGPTVault, TokenFixture, URL, MemoryCredentials) {
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent("doubao-chatgpt-" + UUID().uuidString)
+ let memory = MemoryCredentials()
+ let vault = ChatGPTVault(directory: directory, read: { memory.read() }, write: { memory.write($0) })
+ try await vault.transact { stored in
+ var account = ChatGPTAccount(clientID: "issued")
+ account.id = "synthetic"; account.subject = "synthetic-subject"
+ account.access = "synthetic-old-access"; account.refresh = "synthetic-old-refresh"
+ account.expires = 1; account.scopes = [ChatGPTProtocol.directScope]
+ stored.accounts = [account]; stored.activeID = account.id
+ }
+ addTeardownBlock { try? FileManager.default.removeItem(at: directory) }
+ return (vault, TokenFixture(), directory, memory)
+ }
+ func testTwoInstancesSerializeRotationAcrossTheirCredentialVaults() async throws {
+ let (vault, network, directory, memory) = try await fixture()
+ let second = ChatGPTVault(directory: directory, read: { memory.read() }, write: { memory.write($0) })
+ let firstClient = ChatGPTService(vault: vault, oauth: ChatGPTOAuth(http: network))
+ let secondClient = ChatGPTService(vault: second, oauth: ChatGPTOAuth(http: network))
+ async let first = firstClient.access()
+ async let other = secondClient.access()
+ let values = try await [first, other]
+ XCTAssertTrue(values.allSatisfy { $0.token == "synthetic-new-access" })
+ XCTAssertEqual(network.tokenCalls, 1)
+ let stored = try await vault.transact { $0 }
+ XCTAssertEqual(stored.accounts[0].refresh, "synthetic-rotated-refresh")
+ let snapshot = try await firstClient.state()
+ XCTAssertFalse(String(describing: snapshot).contains("synthetic-new-access"))
+ }
+ func testCallerCancellationStillPersistsConnectionOwnedRotation() async throws {
+ let (vault, network, _, _) = try await fixture()
+ network.delay = 100_000_000
+ let service = ChatGPTService(vault: vault, oauth: ChatGPTOAuth(http: network))
+ let caller = Task { try await service.access() }
+ try await Task.sleep(nanoseconds: 25_000_000); caller.cancel()
+ do { _ = try await caller.value; XCTFail("Cancelled caller must not get a lease") } catch { }
+ let stored = try await vault.transact { $0 }
+ XCTAssertEqual(stored.accounts[0].refresh, "synthetic-rotated-refresh")
+ XCTAssertEqual(network.tokenCalls, 1)
+ }
+ func testTerminalRefreshErrorClearsCredentialsAndRetainsRegistration() async throws {
+ let (vault, network, _, _) = try await fixture()
+ network.failure = .reconnect
+ let service = ChatGPTService(vault: vault, oauth: ChatGPTOAuth(http: network))
+ do { _ = try await service.access(); XCTFail("Expired grant must be rejected") }
+ catch { guard case ChatGPTError.reconnect = error else { return XCTFail("Expected reconnect") } }
+ let stored = try await vault.transact { $0 }
+ XCTAssertNil(stored.accounts[0].access); XCTAssertNil(stored.accounts[0].refresh)
+ XCTAssertEqual(stored.accounts[0].clientID, "issued")
+ }
+ func testIdentityFailureAfterRotationNeverRestoresTheConsumedRefreshToken() async throws {
+ let (vault, network, _, _) = try await fixture()
+ network.identityUnavailable = true
+ let service = ChatGPTService(vault: vault, oauth: ChatGPTOAuth(http: network))
+ for _ in 0..<2 {
+ do { _ = try await service.access(); XCTFail("Unverified replacement must require reconnect") }
+ catch { guard case ChatGPTError.reconnect = error else { return XCTFail("Expected reconnect") } }
+ }
+ let stored = try await vault.transact { $0 }
+ XCTAssertNil(stored.accounts[0].refresh); XCTAssertNil(stored.accounts[0].access)
+ XCTAssertEqual(stored.accounts[0].clientID, "issued")
+ XCTAssertEqual(network.tokenCalls, 1)
+ }
+ func testQuotaDoesNotBypassDuringCatalogFetchAndExplicitRetryOrAccountSwitchClearsPause() async throws {
+ let (vault, network, _, _) = try await fixture()
+ let service = ChatGPTService(vault: vault, oauth: ChatGPTOAuth(http: network))
+ let lease = try await service.access()
+ await service.pauseUsage(lease)
+ let catalog = Task { try await service.models() }
+ do { _ = try await service.access(); XCTFail("Quota must still pause inference while the directory is read") }
+ catch { guard case ChatGPTError.quota = error else { return XCTFail("Expected quota") } }
+ let models = try await catalog.value
+ XCTAssertEqual(models.count, 1)
+ let paused = try await service.state()
+ XCTAssertTrue(paused.usageLimited); XCTAssertEqual(paused.active?.connected, true)
+ await service.resumeUsage()
+ _ = try await service.access()
+ await service.pauseUsage(lease)
+ try await service.select("synthetic")
+ let selected = try await service.state()
+ XCTAssertFalse(selected.usageLimited)
+ let current = await service.isCurrent(lease)
+ XCTAssertFalse(current)
+ }
+ func testEarliestRefreshIsRespectedAndFailedVaultUpdatesRollback() async throws {
+ let (vault, network, _, _) = try await fixture()
+ try await vault.transact { state in state.accounts[0].refreshAfter = Date().timeIntervalSince1970 + 60 }
+ let service = ChatGPTService(vault: vault, oauth: ChatGPTOAuth(http: network))
+ do { _ = try await service.access(); XCTFail("Must not refresh early") }
+ catch { guard case ChatGPTError.refreshNotReady = error else { return XCTFail("Expected refresh window") } }
+ XCTAssertEqual(network.tokenCalls, 0)
+ do { try await vault.transact { state in state.accounts[0].clientID = "wrong"; throw ChatGPTError.storage } }
+ catch { }
+ let stored = try await vault.transact { $0 }
+ XCTAssertEqual(stored.accounts[0].clientID, "issued")
+ }
+}
diff --git a/macos/Tests/ChatGPTTests.swift b/macos/Tests/ChatGPTTests.swift
new file mode 100644
index 0000000..741b47e
--- /dev/null
+++ b/macos/Tests/ChatGPTTests.swift
@@ -0,0 +1,109 @@
+import XCTest
+import Security
+@testable import DoubaoSayCore
+
+final class ChatGPTTests: XCTestCase {
+ func testPKCEAndCallbackPinsStateAndIssuedClient() throws {
+ XCTAssertEqual(ChatGPTProtocol.challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"), "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM")
+ let target = "/auth/callback?state=expected&code=synthetic&client_id=issued"
+ let pair = try ChatGPTProtocol.callback(target, state: "expected", clientID: nil)
+ XCTAssertEqual(pair.0, "issued")
+ XCTAssertThrowsError(try ChatGPTProtocol.callback(target, state: "wrong", clientID: nil))
+ XCTAssertThrowsError(try ChatGPTProtocol.callback(target, state: "expected", clientID: "other"))
+ XCTAssertThrowsError(try ChatGPTProtocol.callback(target + "&state=expected", state: "expected", clientID: nil))
+ }
+ func testTokenRotationRefreshWindowAndScopeReduction() throws {
+ var previous = ChatGPTAccount(clientID: "issued")
+ previous.refresh = "synthetic-old"; previous.scopes = [ChatGPTProtocol.directScope]
+ var data: [String: Any] = ["access_token": "synthetic", "token_type": "Bearer", "expires_in": 3600,
+ "earliest_refresh_at": "2026-10-14T12:00:00Z"]
+ var next = try ChatGPTProtocol.tokenFields(data, previous: previous)
+ XCTAssertEqual(next.refresh, previous.refresh); XCTAssertEqual(next.scopes, previous.scopes)
+ XCTAssertEqual(next.refreshAfter, ISO8601DateFormatter().date(from: "2026-10-14T12:00:00Z")!.timeIntervalSince1970)
+ data["scope"] = ""; data["refresh_token"] = "synthetic-rotated"
+ next = try ChatGPTProtocol.tokenFields(data, previous: previous)
+ XCTAssertTrue(next.scopes.isEmpty); XCTAssertEqual(next.refresh, "synthetic-rotated")
+ data["earliest_refresh_at"] = "2026-10-14T12:00:00"
+ XCTAssertThrowsError(try ChatGPTProtocol.tokenFields(data, previous: previous))
+ }
+ func testResponsesRequiresCompletionAndPreservesFragmentedUnicode() throws {
+ let delta = "data: {\"type\":\"response.output_text.delta\",\"delta\":\"你好😊\"}\n\n"
+ let end = "data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\"}}\n\n"
+ var stream = ChatGPTResponses()
+ for byte in Data((delta + end).utf8) { _ = try stream.append(Data([byte])) }
+ XCTAssertEqual(try stream.result(), "你好😊")
+ for final in ["", "data: {\"type\":\"response.incomplete\"}\n\n", "data: {\"type\":\"response.failed\"}\n\n"] {
+ var stream = ChatGPTResponses()
+ XCTAssertThrowsError(try { _ = try stream.append(Data((delta + final).utf8)); return try stream.result() }())
+ }
+ var limited = ChatGPTResponses()
+ XCTAssertThrowsError(try limited.append(Data("data: {\"type\":\"error\",\"code\":\"subscription_sharing_usage_limit_exceeded\"}\n\n".utf8))) { error in
+ guard case ChatGPTError.quota = error else { return XCTFail("Expected private-safe quota error") }
+ }
+ }
+ func testIdentityUsesRealRSASignatureAndRejectsClaimsOrSignatureTampering() throws {
+ let privateKey = try XCTUnwrap(SecKeyCreateRandomKey([kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
+ kSecAttrKeySizeInBits as String: 2048] as CFDictionary, nil))
+ let publicKey = try XCTUnwrap(SecKeyCopyPublicKey(privateKey))
+ let publicData = try XCTUnwrap(SecKeyCopyExternalRepresentation(publicKey, nil) as Data?)
+ var offset = 0
+ func node() throws -> Data {
+ guard offset + 2 <= publicData.count else { throw ChatGPTError.identity }
+ offset += 1; var length = Int(publicData[offset]); offset += 1
+ if length & 128 != 0 {
+ let bytes = length & 127; length = 0
+ for _ in 0..<bytes { length = length << 8 | Int(publicData[offset]); offset += 1 }
+ }
+ let result = publicData.subdata(in: offset..<offset + length)
+ offset += length; return result
+ }
+ _ = try node(); offset = publicData.count - (try { () -> Int in
+ var pos = 1; let length = Int(publicData[pos]); pos += 1
+ if length & 128 != 0 { pos += length & 127 }; return publicData.count - pos
+ }())
+ let modulus = try node(), exponent = try node()
+ let keys: [[String: Any]] = [["kid": "synthetic", "kty": "RSA", "n": ChatGPTProtocol.base64(modulus), "e": ChatGPTProtocol.base64(exponent)]]
+ let now = Date().timeIntervalSince1970
+ let base: [String: Any] = ["iss": ChatGPTProtocol.issuer, "sub": "synthetic-subject", "aud": "issued", "nonce": "expected", "iat": now, "exp": now + 60]
+ func signed(_ claims: [String: Any]) throws -> String {
+ let header = ChatGPTProtocol.base64(try JSONSerialization.data(withJSONObject: ["alg": "RS256", "kid": "synthetic"]))
+ let body = ChatGPTProtocol.base64(try JSONSerialization.data(withJSONObject: claims))
+ let message = header + "." + body
+ let signature = try XCTUnwrap(SecKeyCreateSignature(privateKey, .rsaSignatureMessagePKCS1v15SHA256, Data(message.utf8) as CFData, nil) as Data?)
+ return message + "." + ChatGPTProtocol.base64(signature)
+ }
+ let jwt = try signed(base)
+ XCTAssertEqual(try ChatGPTIdentity.verify(jwt, clientID: "issued", nonce: "expected", keys: keys)["sub"] as? String, "synthetic-subject")
+ let overrides: [[String: Any]] = [["aud": "other"], ["iss": "https://example.invalid"], ["nonce": "other"], ["exp": now - 1]]
+ for override in overrides {
+ var claims = base; claims.merge(override) { _, new in new }
+ XCTAssertThrowsError(try ChatGPTIdentity.verify(signed(claims), clientID: "issued", nonce: "expected", keys: keys))
+ }
+ var parts = jwt.split(separator: ".").map(String.init)
+ var signature = try XCTUnwrap(ChatGPTProtocol.decode(parts[2])); signature[0] ^= 1; parts[2] = ChatGPTProtocol.base64(signature)
+ XCTAssertThrowsError(try ChatGPTIdentity.verify(parts.joined(separator: "."), clientID: "issued", nonce: "expected", keys: keys))
+ }
+ func testProviderMigrationPreservesAPIConfigurationAndDoesNotReadKeyForPlan() throws {
+ var settings = MacSettings(); settings.polishProvider = "chatgpt"; settings.polishChatGPTModel = "synthetic-model"
+ var reads = 0
+ func key() -> String? { reads += 1; return "synthetic-api-key" }
+ XCTAssertEqual(PolishPolicy.credential(settings: settings, apiKey: key()), "chatgpt-plan")
+ XCTAssertEqual(reads, 0)
+ settings.polishProvider = "api"
+ XCTAssertEqual(PolishPolicy.credential(settings: settings, apiKey: key()), "synthetic-api-key")
+ XCTAssertEqual(reads, 1)
+ }
+ func testLoopbackCallbackRejectsWrongStateThenAcceptsValidState() async throws {
+ let callback = ChatGPTCallback(state: "expected", clientID: "issued")
+ defer { callback.close() }
+ let port = try await callback.start()
+ let bad = URL(string: "http://127.0.0.1:\(port)/auth/callback?state=wrong&code=synthetic&client_id=issued")!
+ let (_, rejected) = try await URLSession.shared.data(from: bad)
+ XCTAssertEqual((rejected as? HTTPURLResponse)?.statusCode, 400)
+ let good = URL(string: "http://127.0.0.1:\(port)/auth/callback?state=expected&code=synthetic&client_id=issued")!
+ let (_, accepted) = try await URLSession.shared.data(from: good)
+ XCTAssertEqual((accepted as? HTTPURLResponse)?.statusCode, 200)
+ let result = try await callback.wait()
+ XCTAssertEqual(result.0, "issued"); XCTAssertEqual(result.1, "synthetic")
+ }
+}
diff --git a/macos/Tests/Input/RetryCheck.swift b/macos/Tests/Input/RetryCheck.swift
index 8dfe187..24fcacf 100644
--- a/macos/Tests/Input/RetryCheck.swift
+++ b/macos/Tests/Input/RetryCheck.swift
@@ -5,6 +5,7 @@ import AVFoundation
enum RecognitionProvider { case doubao, volcengine, deepgram; var rawValue: String { "synthetic" } }
struct MacSettings { var provider: RecognitionProvider = .doubao; var polishEnabled = false; var inputMethod = "clipboard"; var microphoneID = "" }
@MainActor final class SettingsStore { static let shared = SettingsStore(); var value = MacSettings() }
+enum PolishPolicy { static func credential(settings: MacSettings, apiKey: @autoclosure () -> String?) -> String { apiKey() ?? "" } }
enum SecretStore { static func load(_ key: String) -> String? { nil } }
enum ASRParamsStore { static var available = false; static func load() -> Int? { available ? 1 : nil }; static func clear() {} }
enum AVCaptureDevice {
diff --git a/macos/Tests/Live/ChatGPTCheck.swift b/macos/Tests/Live/ChatGPTCheck.swift
new file mode 100644
index 0000000..cb9e5a6
--- /dev/null
+++ b/macos/Tests/Live/ChatGPTCheck.swift
@@ -0,0 +1,64 @@
+import Foundation
+
+/// An opt-in real native connection check. It never records audio or copies another app's tokens.
+@main
+struct ChatGPTCheck {
+ @MainActor
+ static func main() async {
+ let output = URL(fileURLWithPath: ProcessInfo.processInfo.environment["SIWC_LIVE_OUTPUT"] ?? "artifacts/verification/siwc/2026-10-14/mac-live", isDirectory: true)
+ try? FileManager.default.createDirectory(at: output, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
+ var result: [String: Any] = ["signedIn": false, "sharing": false, "models": 0, "completed": false]
+ do {
+ guard Bundle.main.bundleIdentifier?.hasPrefix("md.lifeos.doubao-say.macos.siwc-live.") == true else {
+ throw ChatGPTError.storage
+ }
+ let vault = ChatGPTVault()
+ let oauth = ChatGPTOAuth(http: ChatGPTHTTP(), openBrowser: { address in
+ let bytes = try JSONSerialization.data(withJSONObject: ["url": address.absoluteString])
+ let path = output.appendingPathComponent("browser.json")
+ try bytes.write(to: path, options: .atomic)
+ try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: path.path)
+ print("Native OAuth browser request ready."); fflush(stdout)
+ })
+ let service = ChatGPTService(vault: vault, oauth: oauth)
+ if CommandLine.arguments.contains("--sign-in") { try await service.signIn() }
+ let state = try await service.state()
+ result["signedIn"] = state.active?.connected == true
+ result["sharing"] = state.active?.sharing == true
+ let models = try await service.models()
+ result["models"] = models.count
+ result["modelDirectory"] = models.map { $0.id }
+ let preferred = ProcessInfo.processInfo.environment["SIWC_LIVE_MODEL"]
+ let selected = models.first(where: { $0.id == preferred })
+ ?? models.first(where: { $0.id.contains("mini") || $0.id.contains("nano") })
+ ?? models.first(where: { $0.id.contains("luna") }) ?? models.first
+ if CommandLine.arguments.contains("--request"), let selected = selected {
+ result["selectedModel"] = selected.id
+ var settings = MacSettings()
+ settings.polishProvider = "chatgpt"; settings.polishChatGPTModel = selected.id
+ settings.polishPromptEN = "Correct capitalization and punctuation. Return only the corrected text."
+ let client = PolishClient()
+ defer { client.cancel() }
+ let started = ProcessInfo.processInfo.systemUptime
+ let reply: (String?, String?) = await withCheckedContinuation { continuation in
+ client.completion = { text, error in continuation.resume(returning: (text, error)) }
+ client.start(text: "hello world", settings: settings, apiKey: "",
+ timeout: CommandLine.arguments.contains("--comparison") ? 25 : 5, personalize: false)
+ }
+ result["completed"] = reply.0?.isEmpty == false
+ result["elapsedSeconds"] = ProcessInfo.processInfo.systemUptime - started
+ result["usageLimited"] = try await ChatGPTService.shared.state().usageLimited
+ result["safeError"] = reply.1
+ }
+ let stored = try await vault.transact { $0 }
+ if let index = stored.activeIndex, let expiry = stored.accounts[index].expires {
+ result["expiresAt"] = ISO8601DateFormatter().string(from: Date(timeIntervalSince1970: expiry))
+ result["refreshAfter"] = stored.accounts[index].refreshAfter
+ }
+ } catch { result["safeError"] = (error as? ChatGPTError)?.localizedDescription ?? "Native ChatGPT check did not finish." }
+ if let bytes = try? JSONSerialization.data(withJSONObject: result, options: [.prettyPrinted, .sortedKeys]) {
+ try? bytes.write(to: output.appendingPathComponent("result.json"), options: .atomic)
+ print(String(data: bytes, encoding: .utf8) ?? "Native check ended.")
+ }
+ }
+}
diff --git a/macos/Tests/Live/README.md b/macos/Tests/Live/README.md
new file mode 100644
index 0000000..e8a01c4
--- /dev/null
+++ b/macos/Tests/Live/README.md
@@ -0,0 +1,38 @@
+# Opt-in native ChatGPT connection check
+
+Build `bash macos/Tests/Live/build-chatgpt.sh` under a heavy resource slot.
+After compilation exits, run the prebuilt helper under a runtime slot:
+
+```sh
+python3 macos/Tests/Live/chatgpt_check.py build/macos/tests/chatgpt-live-check \
+ artifacts/verification/siwc/mac-live --sign-in --request
+```
+
+The helper creates a unique ad-hoc signed bundle and app-owned Keychain item.
+The output directory retains its bundle identifier so a later invocation without
+`--sign-in` checks actual restart restoration and expiry renewal. Never use a
+production bundle identifier or copy another application's credentials.
+Use the exact same probe binary and signer for later invocations. The runner
+refuses to replace them in an existing profile: rebuilding an ad-hoc signed app
+changes its Keychain identity and can prompt for user authentication. Set
+`DOUBAO_SIWC_CODESIGN_IDENTITY` to the app's Developer ID signing identity when
+verifying the distribution signing configuration; it does not publish a build.
+The original executable remains in the output bundle. Pass
+`PRIVATE_OUTPUT/NativeSIWCCheck.app/Contents/MacOS/NativeSIWCCheck` as the binary
+for later expiry checks when the repository's build output has been rebuilt.
+
+During sign-in, `browser.json` is an owner-only browser handoff file. Open its
+URL in the verification browser session without logging the URL or callback
+query. It can contain identity hints on a later sign-in. A pending authorization
+expires after five minutes; the runner terminates its own process after six.
+Do not publish this file, Keychain data, or screenshots with personal account
+details. `result.json` contains only safe status, counts and request timing.
+
+`--request` sends synthetic text (`hello world`) through the actual shared
+`PolishClient`, fixed Responses endpoint and five-second deadline without an API
+key. The real server may reject a request for plan or application usage limits;
+record that result separately from successful sign-in and model access. This
+check does not record audio, install an app, inject input or release a build.
+`--comparison` uses the existing 25-second comparison/vocabulary deadline instead
+of the five-second dictation deadline. Record which mode was used; a completed
+comparison request does not prove five-second dictation success.
diff --git a/macos/Tests/Live/build-chatgpt.sh b/macos/Tests/Live/build-chatgpt.sh
new file mode 100644
index 0000000..5881622
--- /dev/null
+++ b/macos/Tests/Live/build-chatgpt.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+set -euo pipefail
+cd "$(dirname "$0")/../../.."
+mkdir -p build/macos/tests
+xcrun swiftc -swift-version 5 -target "$(uname -m)-apple-macos13.0" \
+ -module-cache-path build/macos/module-cache \
+ macos/Sources/Strings.swift macos/Sources/MacSettings.swift macos/Sources/PolishDefaults.swift \
+ macos/Sources/PersonalData.swift macos/Sources/PersonalCorrections.swift macos/Sources/PolishClient.swift \
+ macos/Sources/ChatGPTVault.swift macos/Sources/ChatGPTProtocol.swift macos/Sources/ChatGPTOAuth.swift \
+ macos/Sources/ChatGPTCallback.swift macos/Sources/ChatGPTService.swift macos/Sources/ChatGPTResponses.swift \
+ macos/Tests/Live/ChatGPTCheck.swift -o build/macos/tests/chatgpt-live-check
diff --git a/macos/Tests/Live/chatgpt_check.py b/macos/Tests/Live/chatgpt_check.py
new file mode 100644
index 0000000..1057f18
--- /dev/null
+++ b/macos/Tests/Live/chatgpt_check.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python3
+"""Run a prebuilt native SIWC probe with an isolated, restartable Keychain namespace."""
+
+import json
+import hashlib
+import os
+from pathlib import Path
+import plistlib
+import shutil
+import subprocess
+import sys
+import uuid
+
+
+def main():
+ if len(sys.argv) < 3:
+ raise SystemExit("Usage: chatgpt_check.py PREBUILT_BINARY PRIVATE_OUTPUT [--sign-in] [--request]")
+ executable, output = Path(sys.argv[1]).resolve(), Path(sys.argv[2]).resolve()
+ options = sys.argv[3:]
+ if any(value not in ("--sign-in", "--request", "--comparison") for value in options):
+ raise SystemExit("Only --sign-in, --request and --comparison are supported.")
+ output.mkdir(parents=True, exist_ok=True, mode=0o700)
+ output.chmod(0o700)
+ fingerprint = hashlib.sha256(executable.read_bytes()).hexdigest()
+ signer = os.environ.get("DOUBAO_SIWC_CODESIGN_IDENTITY", "-")
+ metadata = output / "bundle.json"
+ if metadata.exists():
+ saved = json.loads(metadata.read_text())
+ identifier = saved["bundleIdentifier"]
+ if not identifier.startswith("md.lifeos.doubao-say.macos.siwc-live."):
+ raise SystemExit("Refusing a production or unrelated Keychain namespace.")
+ if saved.get("binarySha256") != fingerprint or saved.get("signer") != signer:
+ raise SystemExit("Use the original probe binary and signer for restoration; a rebuilt ad-hoc probe changes Keychain identity.")
+ else:
+ identifier = "md.lifeos.doubao-say.macos.siwc-live." + uuid.uuid4().hex
+ metadata.write_text(json.dumps({"bundleIdentifier": identifier, "binarySha256": fingerprint, "signer": signer}))
+ metadata.chmod(0o600)
+ bundle = output / "NativeSIWCCheck.app"
+ binary = bundle / "Contents/MacOS/NativeSIWCCheck"
+ binary.parent.mkdir(parents=True, exist_ok=True)
+ if executable != binary:
+ shutil.copy2(executable, binary)
+ (bundle / "Contents/Info.plist").write_bytes(plistlib.dumps({
+ "CFBundleIdentifier": identifier, "CFBundleExecutable": binary.name,
+ "CFBundleName": "Doubao Say SIWC check", "CFBundlePackageType": "APPL",
+ "LSMinimumSystemVersion": "13.0", "LSUIElement": True,
+ }))
+ subprocess.run(["codesign", "--force", "--sign", signer, "--timestamp=none", str(bundle)], check=True, timeout=20)
+ subprocess.run(["codesign", "--verify", "--strict", str(bundle)], check=True, timeout=20)
+ # A previous authorization URL must never be mistaken for the next browser request.
+ (output / "browser.json").unlink(missing_ok=True)
+ environment = dict(os.environ, SIWC_LIVE_OUTPUT=str(output))
+ process = subprocess.Popen([str(binary), *options], env=environment)
+ try:
+ return process.wait(timeout=360)
+ finally:
+ if process.poll() is None:
+ process.terminate()
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=5)
+ (output / "browser.json").unlink(missing_ok=True)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/macos/Tests/Settings/ChatGPTUICheck.swift b/macos/Tests/Settings/ChatGPTUICheck.swift
new file mode 100644
index 0000000..883a9b0
--- /dev/null
+++ b/macos/Tests/Settings/ChatGPTUICheck.swift
@@ -0,0 +1,125 @@
+import AppKit
+import SwiftUI
+
+/// Native controls with synthetic accounts; no Keychain, login, microphone or network.
+@main
+struct ChatGPTUICheck {
+ static func main() {
+ let application = NSApplication.shared
+ let delegate = ChatGPTUIDelegate()
+ application.delegate = delegate
+ application.run()
+ }
+}
+@MainActor
+final class ChatGPTUIDelegate: NSObject, NSApplicationDelegate {
+ private var window: NSWindow?
+ private var settings: SettingsModel?
+ private var connection: ChatGPTConnectionModel?
+ private var savedModel: String?
+ func applicationDidFinishLaunching(_ notification: Notification) {
+ NSApp.setActivationPolicy(.regular)
+ let environment = ProcessInfo.processInfo.environment
+ let mode = environment["SIWC_UI_CASE"] ?? "disconnected"
+ if environment["SIWC_UI_DARK"] == "1" { NSApp.appearance = NSAppearance(named: .darkAqua) }
+ let settings = SettingsModel(state: AppState())
+ settings.apply = { [weak self] state, _, _ in
+ precondition(state.polishBaseURL == "https://example.invalid/v1" && state.polishModel == "legacy-api-model")
+ self?.savedModel = state.polishChatGPTModel
+ }
+ settings.draft.polishBaseURL = "https://example.invalid/v1"
+ settings.draft.polishModel = "legacy-api-model"
+ settings.draft.polishProvider = "chatgpt"
+ let connection = ChatGPTConnectionModel(refreshInitially: false)
+ if mode != "disconnected" {
+ connection.snapshot = ChatGPTSnapshot(activeID: "synthetic", accounts: [
+ ChatGPTAccountView(id: "synthetic", label: "[email protected]", connected: true, sharing: true)
+ ], usageLimited: mode == "quota")
+ connection.models = [ChatGPTModel(id: "synthetic-fast", label: "Synthetic Fast"), ChatGPTModel(id: "synthetic-standard", label: "Synthetic Standard")]
+ settings.draft.polishChatGPTModel = "synthetic-fast"
+ }
+ self.settings = settings; self.connection = connection
+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 690, height: 740),
+ styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)
+ window.title = "Doubao Say · " + L("Voice polishing", "语音润色")
+ window.contentView = NSHostingView(rootView: PolishingSettingsView(model: settings, connection: connection))
+ self.window = window; window.center(); window.makeKeyAndOrderFront(nil)
+ NSApp.activate(ignoringOtherApps: true)
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.3) {
+ if ["model-menu", "model-select", "model-keyboard", "model-cancel", "account-menu"].contains(mode) {
+ self.openMenu(mode, window: window, deadline: Date().addingTimeInterval(3))
+ } else { self.capture(window) }
+ }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 12) { fatalError("UI fixture deadline exceeded") }
+ }
+
+ private func openMenu(_ mode: String, window: NSWindow, deadline: Date) {
+ guard Date() < deadline else { fatalError("Fixture window did not activate") }
+ NSApp.activate(ignoringOtherApps: true); window.makeKeyAndOrderFront(nil)
+ guard NSApp.isActive && window.isKeyWindow else {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.openMenu(mode, window: window, deadline: deadline) }
+ return
+ }
+ // Coordinates are grounded in native captures for this fixed-size fixture.
+ // Events stay in this NSApplication and never reach the user's desktop.
+ let chinese = L("en", "zh") == "zh"
+ let fromTop: CGFloat = mode == "account-menu" ? (chinese ? 227 : 257) : (chinese ? 290 : 320)
+ click(NSPoint(x: mode == "account-menu" ? 642 : 350, y: window.frame.height - fromTop), in: window)
+ awaitMenu(mode, window: window, deadline: Date().addingTimeInterval(3))
+ }
+ private func awaitMenu(_ mode: String, window: NSWindow, deadline: Date) {
+ if menuWindow() != nil {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { self.exerciseMenu(mode, window: window) }
+ } else {
+ guard Date() < deadline else { fatalError("Dropdown rows did not appear") }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.awaitMenu(mode, window: window, deadline: deadline) }
+ }
+ }
+
+ private func click(_ point: NSPoint, in window: NSWindow) {
+ for type: NSEvent.EventType in [.leftMouseDown, .leftMouseUp] {
+ if let event = NSEvent.mouseEvent(with: type, location: point, modifierFlags: [],
+ timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: window.windowNumber, context: nil,
+ eventNumber: 0, clickCount: 1, pressure: 1) { NSApp.postEvent(event, atStart: false) }
+ }
+ }
+ private func menuWindow() -> NSWindow? {
+ NSApp.windows.first { $0 !== window && $0.isVisible }
+ }
+ private func key(_ code: UInt16, in window: NSWindow) {
+ if let event = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [],
+ timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: window.windowNumber, context: nil,
+ characters: "", charactersIgnoringModifiers: "", isARepeat: false, keyCode: code) { NSApp.postEvent(event, atStart: false) }
+ }
+ private func exerciseMenu(_ mode: String, window: NSWindow) {
+ guard let popup = menuWindow() else { fatalError("Dropdown rows did not appear") }
+ if ["model-menu", "account-menu"].contains(mode) {
+ print("CAPTURE_MENU:\(popup.windowNumber)"); fflush(stdout)
+ capture(window); return
+ }
+ if mode == "model-select" {
+ click(NSPoint(x: popup.frame.width / 2, y: popup.frame.height / 2 - 16), in: popup)
+ } else {
+ key(125, in: popup)
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) { self.key(mode == "model-cancel" ? 53 : 36, in: popup) }
+ }
+ awaitSelection(mode, window: window, deadline: Date().addingTimeInterval(4))
+ }
+ private func awaitSelection(_ mode: String, window: NSWindow, deadline: Date) {
+ let expected = mode == "model-cancel" ? "synthetic-fast" : "synthetic-standard"
+ if settings?.draft.polishChatGPTModel == expected, savedModel == expected, menuWindow() == nil {
+ print("PASS_INTERACTION:\(mode)"); fflush(stdout)
+ capture(window)
+ } else {
+ guard Date() < deadline else { fatalError("Dropdown selection, autosave or popup closure did not finish") }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.awaitSelection(mode, window: window, deadline: deadline) }
+ }
+ }
+ private func capture(_ window: NSWindow) {
+ guard let settings = settings else { exit(1) }
+ precondition(settings.draft.polishProvider == "chatgpt")
+ precondition(settings.draft.polishBaseURL == "https://example.invalid/v1" && settings.draft.polishModel == "legacy-api-model")
+ print("CAPTURE_WINDOW:\(window.windowNumber)"); fflush(stdout)
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { window.close(); NSApp.terminate(nil) }
+ }
+}
diff --git a/macos/Tests/Settings/README.md b/macos/Tests/Settings/README.md
index d089cc1..2aa323a 100644
--- a/macos/Tests/Settings/README.md
+++ b/macos/Tests/Settings/README.md
@@ -1,5 +1,23 @@
# Native sidebar focus regression probe
+## ChatGPT connection controls
+
+`build-chatgpt-ui.sh` builds `ChatGPTUICheck.swift` against the actual settings
+components. `chatgpt_ui_check.py` captures disconnected, connected and quota
+states in English/Chinese, light/dark, in a unique signed test bundle. Build
+under the heavy resource gate and run the prebuilt probe under a runtime slot.
+Credentials and models are synthetic; the probe never connects to OpenAI,
+records audio or posts input to another application. It checks preservation of
+the existing API configuration. Real OAuth, expiry, model access and speech
+delivery require separate verification.
+
+The same fixture exercises the application-drawn model dropdown and account
+options. It uses in-process mouse and keyboard events addressed
+only to the fixture's own window. Checks cover selecting and autosaving a model,
+Arrow Down/Return, Escape without changing the choice, popup closure and retained
+API settings. Separate popup captures use only the owned menu window, never the
+user's desktop. Each process remains bounded to 15 seconds.
+
`SidebarFocusCheck.swift` opens the real SettingsWindow with synthetic state in a
SwiftUI application. It never signs in, records audio, saves credentials or
posts events to another application. Its only key/mouse events go through its own
diff --git a/macos/Tests/Settings/build-chatgpt-ui.sh b/macos/Tests/Settings/build-chatgpt-ui.sh
new file mode 100644
index 0000000..c784610
--- /dev/null
+++ b/macos/Tests/Settings/build-chatgpt-ui.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+set -euo pipefail
+cd "$(dirname "$0")/../../.."
+mkdir -p build/macos/tests
+sources=()
+for source in macos/Sources/*.swift; do
+ [[ "$source" == *DoubaoSayApp.swift ]] || sources+=("$source")
+done
+xcrun swiftc -swift-version 5 -target "$(uname -m)-apple-macos13.0" \
+ -module-cache-path build/macos/module-cache \
+ "${sources[@]}" macos/Tests/Settings/ChatGPTUICheck.swift -o build/macos/tests/chatgpt-ui-check
diff --git a/macos/Tests/Settings/chatgpt_ui_check.py b/macos/Tests/Settings/chatgpt_ui_check.py
new file mode 100644
index 0000000..5752f18
--- /dev/null
+++ b/macos/Tests/Settings/chatgpt_ui_check.py
@@ -0,0 +1,60 @@
+"""Capture actual SwiftUI controls with synthetic accounts in an isolated bundle."""
+import os
+from pathlib import Path
+import plistlib
+import subprocess
+import sys
+import threading
+import uuid
+
+binary = Path(sys.argv[1]).resolve()
+output = Path(sys.argv[2]).resolve()
+output.mkdir(parents=True, exist_ok=True)
+bundle = output / "Doubao SIWC UI Verify.app"
+executable = bundle / "Contents/MacOS/ChatGPTUICheck"
+executable.parent.mkdir(parents=True, exist_ok=True)
+subprocess.run(["ditto", str(binary), str(executable)], check=True)
+(bundle / "Contents/Info.plist").write_bytes(plistlib.dumps({
+ "CFBundleIdentifier": "md.lifeos.doubao-say.siwc-ui." + uuid.uuid4().hex,
+ "CFBundleName": "Doubao SIWC UI Verify", "CFBundleExecutable": "ChatGPTUICheck",
+ "CFBundlePackageType": "APPL", "LSMinimumSystemVersion": "13.0", "LSUIElement": True,
+}))
+subprocess.run(["codesign", "--force", "--sign", "-", str(bundle)], check=True)
+modes = os.environ.get("SIWC_UI_MODES", "disconnected,connected,quota,model-menu,model-select,model-keyboard,model-cancel,account-menu").split(",")
+for language in ["en", "zh"]:
+ for mode in modes:
+ for theme in ["light", "dark"]:
+ name = mode + "-" + language + "-" + theme
+ image = output / (name + ".png")
+ environment = dict(os.environ, SIWC_UI_CASE=mode, SIWC_UI_DARK="1" if theme == "dark" else "0")
+ process = subprocess.Popen([str(executable), "-language", language], env=environment,
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
+ timer = threading.Timer(15, process.kill)
+ timer.start()
+ lines = []
+ captured = False
+ try:
+ for line in process.stdout:
+ lines.append(line)
+ if line.startswith("CAPTURE_WINDOW:"):
+ window = line.strip().split(":", 1)[1]
+ capture = subprocess.run(["/usr/sbin/screencapture", "-x", "-o", "-l", window, str(image)],
+ timeout=5, capture_output=True)
+ captured = capture.returncode == 0 and image.is_file()
+ elif line.startswith("CAPTURE_MENU:"):
+ window = line.strip().split(":", 1)[1]
+ menu_image = output / (name + ".menu.png")
+ capture = subprocess.run(["/usr/sbin/screencapture", "-x", "-o", "-l", window, str(menu_image)],
+ timeout=5, capture_output=True)
+ if capture.returncode or not menu_image.is_file():
+ raise RuntimeError("Dropdown screenshot failed")
+ code = process.wait(timeout=2)
+ finally:
+ timer.cancel()
+ if process.poll() is None:
+ process.kill()
+ process.wait(timeout=2)
+ (output / (name + ".log")).write_text("".join(lines))
+ if code or not captured:
+ raise SystemExit(code or 1)
+ print(name + ": native window captured, isolated process exited")
diff --git a/macos/check.sh b/macos/check.sh
index 52e6264..2921c85 100755
--- a/macos/check.sh
+++ b/macos/check.sh
@@ -3,6 +3,7 @@ set -euo pipefail
cd "$(dirname "$0")/.."
swift test --package-path macos --jobs 2
mkdir -p build/macos/tests
+chatgpt_core=(macos/Sources/ChatGPTVault.swift macos/Sources/ChatGPTProtocol.swift macos/Sources/ChatGPTOAuth.swift macos/Sources/ChatGPTCallback.swift macos/Sources/ChatGPTService.swift macos/Sources/ChatGPTResponses.swift)
xcrun swiftc -swift-version 5 -target "$(uname -m)-apple-macos13.0" \
-module-cache-path build/macos/module-cache \
macos/Sources/ASRResponse.swift macos/Sources/DoubaoASRClient.swift \
@@ -13,7 +14,7 @@ xcrun swiftc -swift-version 5 -target "$(uname -m)-apple-macos13.0" \
-module-cache-path build/macos/module-cache \
macos/Sources/Strings.swift macos/Sources/MacSettings.swift macos/Sources/PolishDefaults.swift \
macos/Sources/PersonalData.swift macos/Sources/PersonalCorrections.swift macos/Sources/PolishClient.swift macos/Sources/PolishCoordinator.swift \
- macos/Tests/Network/PolishCheck.swift -o build/macos/tests/polish-check
+ "${chatgpt_core[@]}" macos/Tests/Network/PolishCheck.swift -o build/macos/tests/polish-check
python3 macos/Tests/Network/check.py build/macos/tests/polish-check
xcrun swiftc -swift-version 5 -target "$(uname -m)-apple-macos13.0" \
diff --git a/src/doubao_input/chatgpt.py b/src/doubao_input/chatgpt.py
index 6cf88e5..6e54267 100644
--- a/src/doubao_input/chatgpt.py
+++ b/src/doubao_input/chatgpt.py
@@ -9,6 +9,7 @@ import webbrowser
from doubao_input import chatgpt_auth as auth
from doubao_input.chatgpt_store import ChatGPTStore, active_account
+from doubao_input.i18n import tr
from doubao_input.polish_transport import open_request, RequestCancellation
@@ -21,10 +22,12 @@ class ChatGPTClient:
self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="chatgpt-renewal")
self._requests = set()
self._generation = 0
+ self._usage_limited = False
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,
+ "usage_limited": self._usage_limited,
"accounts": [{"id": account["id"],
"label": account.get("email") or account.get("name") or "ChatGPT",
"connected": bool(account.get("subject") and account.get("access")),
@@ -42,6 +45,7 @@ class ChatGPTClient:
def _invalidate(self):
with self._lock:
self._generation += 1
+ self._usage_limited = False
for cancellation in self._requests:
cancellation.set()
@@ -188,11 +192,18 @@ class ChatGPTClient:
if isinstance(item, dict) and item.get("visibility") == "list"
and isinstance(item.get("slug"), str) and isinstance(item.get("display_name"), str)]
+ def resume_usage(self):
+ """An explicit user retry; the next inference still verifies its limit."""
+ with self._lock:
+ self._usage_limited = False
+
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
+ if self._usage_limited:
+ raise usage_limit_error()
token = self.access(timeout=max(0.01, timeout - (time.monotonic() - started)))
if generation != self._generation:
raise auth.ChatGPTError("account_changed", "ChatGPT account changed")
@@ -217,6 +228,10 @@ class ChatGPTClient:
return result
except (OSError, ValueError) as exc:
if isinstance(exc, auth.ChatGPTError):
+ if exc.code == "usage_limit_exceeded":
+ with self._lock:
+ if generation == self._generation:
+ self._usage_limited = True
raise
raise ValueError("ChatGPT polishing did not complete; using original text") from None
finally:
@@ -229,6 +244,12 @@ class ChatGPTClient:
self._executor.shutdown(wait=False, cancel_futures=False)
+def usage_limit_error():
+ return auth.ChatGPTError("usage_limit_exceeded", tr(
+ "ChatGPT plan usage limit reached. Open Manage usage, then retry when available; using original text.",
+ "ChatGPT 套餐共享用量已达上限,请查看“管理用量”,可用后再重试;本次使用原文。"))
+
+
def completed_text(response, progress=None):
text, frame, count, completed = "", [], 0, False
for raw in response:
@@ -250,6 +271,9 @@ def completed_text(response, progress=None):
completed = True
break
elif kind in {"response.failed", "response.incomplete", "error"}:
+ failure = event.get("error") or (event.get("response") or {}).get("error") or event
+ if isinstance(failure, dict) and failure.get("code") == "subscription_sharing_usage_limit_exceeded":
+ raise usage_limit_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")
diff --git a/src/doubao_input/ui/chatgpt_settings.py b/src/doubao_input/ui/chatgpt_settings.py
index f2e3958..c5f34e5 100644
--- a/src/doubao_input/ui/chatgpt_settings.py
+++ b/src/doubao_input/ui/chatgpt_settings.py
@@ -58,6 +58,9 @@ class ChatGPTSettings(Gtk.Box):
refresh = Gtk.Button(label=tr("Refresh models", "刷新模型"))
refresh.connect("clicked", lambda *_: self._run(lambda: None))
self.append(refresh)
+ self.retry_usage_button = Gtk.Button(label=tr("Retry plan usage", "重试套餐用量"))
+ self.retry_usage_button.connect("clicked", lambda *_: self._run(self.client.resume_usage))
+ self.append(self.retry_usage_button)
self.connect("unmap", self._close)
self.connect("map", self._mapped)
self._run(lambda: None)
@@ -119,8 +122,12 @@ class ChatGPTSettings(Gtk.Box):
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 套餐"))
+ limited = bool(state and state.get("usage_limited"))
+ self.status.set_text(message or (tr(
+ "ChatGPT plan usage limit reached. Open Manage usage; retry plan usage when available.",
+ "ChatGPT 套餐共享用量已达上限,请查看“管理用量”,可用后重试套餐用量。") if limited else tr(
+ "ChatGPT plan connected" if models else "ChatGPT is not connected for plan usage",
+ "ChatGPT 套餐已连接" if models else "尚未连接 ChatGPT 套餐")))
return False
def _selected(self, *_):
diff --git a/tests/README.md b/tests/README.md
index 5232ad0..2620f87 100644
--- a/tests/README.md
+++ b/tests/README.md
@@ -146,14 +146,27 @@ GTK_A11Y=none SIWC_UI_SCREENSHOTS=artifacts/verification/siwc/native \
dbus-run-session -- .venv/bin/python tests/manual/chatgpt_ui.py
```
-Repeat with `SIWC_UI_LANGUAGE=zh` for Chinese. This fixture exercises real GTK
+Repeat with `SIWC_UI_LANGUAGE=zh_CN` 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.
+settings, and hiding/reopening the connection card. It also checks a connected
+account's quota message and explicit usage retry; a quota error must retain the
+account connection. 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.
+from Codex or another product.
+
+The native Mac client has a separate Swift connection. `make macos-check`
+includes signed-identity, loopback callback, credential rotation and cancellation
+tests alongside existing polishing checks. Build its isolated native UI probe
+with `bash macos/Tests/Settings/build-chatgpt-ui.sh` under a heavy slot, then run
+`python3 macos/Tests/Settings/chatgpt_ui_check.py
+build/macos/tests/chatgpt-ui-check artifacts/verification/siwc/mac-native` under
+a runtime slot. It captures real SwiftUI controls with synthetic accounts in
+English/Chinese and both appearances; no live login, microphone or paste occurs.
+The opt-in `macos/Tests/Live/ChatGPTCheck.swift` uses this app's own Keychain
+registration for real OAuth/catalog/inference verification. Never copy a token
+from the Python client or any other product into that check.
## Personal speech and correction checks
diff --git a/tests/manual/chatgpt_ui.py b/tests/manual/chatgpt_ui.py
index ce93e92..7d3f0fd 100644
--- a/tests/manual/chatgpt_ui.py
+++ b/tests/manual/chatgpt_ui.py
@@ -20,10 +20,12 @@ from doubao_input.ui.polish_settings import PolishSettings
class Connection:
connected = False
active = "synthetic-one"
+ usage_limited = False
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}
+ return {"accounts": accounts if self.connected else [], "active_id": self.active if self.connected else None,
+ "usage_limited": self.usage_limited}
def ready(self):
return self.connected
@@ -35,6 +37,9 @@ class Connection:
def cancel_sign_in(self):
pass
+ def resume_usage(self):
+ self.usage_limited = False
+
def sign_out(self):
self.connected = False
return True
@@ -101,6 +106,15 @@ def main():
assert saves[-1][0].polish_chatgpt_model == "synthetic-fast"
assert saves[-1][1] is None
capture("connected")
+ connection.usage_limited = True
+ box.chatgpt._run(lambda: None)
+ pump(0.8)
+ assert "Manage usage" in box.chatgpt.status.get_text() or "管理用量" in box.chatgpt.status.get_text()
+ assert box.chatgpt.ready(), "A quota limit must not discard a valid account connection"
+ capture("usage-limited")
+ box.chatgpt.retry_usage_button.emit("clicked")
+ pump(0.8)
+ assert not connection.usage_limited
box.provider.set_active_id("api")
pump()
box.provider.set_active_id("chatgpt")
diff --git a/tests/unit/test_chatgpt.py b/tests/unit/test_chatgpt.py
index 71d347e..2483ae8 100644
--- a/tests/unit/test_chatgpt.py
+++ b/tests/unit/test_chatgpt.py
@@ -3,6 +3,7 @@ from concurrent.futures import ThreadPoolExecutor
import io
import json
from pathlib import Path
+from queue import Queue
from tempfile import TemporaryDirectory
import time
from types import SimpleNamespace
@@ -11,9 +12,12 @@ from threading import Thread
import unittest
from unittest.mock import patch
-from doubao_input import chatgpt_auth as auth
+from doubao_input import chatgpt as connection, chatgpt_auth as auth
from doubao_input.chatgpt import ChatGPTClient, completed_text
from doubao_input.chatgpt_store import ChatGPTStore
+from doubao_input.i18n import set_language
+from doubao_input.polish import PolishClient, PolishManager
+from doubao_input.settings import Settings
class ChatGPTTest(unittest.TestCase):
@@ -120,6 +124,57 @@ class ChatGPTTest(unittest.TestCase):
complete = 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
self.assertEqual(completed_text(io.BytesIO((text + complete).encode())), "Synthetic 😊")
+ def test_real_quota_error_reaches_original_text_fallback_without_api_request(self):
+ partial = 'data: {"type":"response.output_text.delta","delta":"partial"}\n\n'
+ failure = {"code": "subscription_sharing_usage_limit_exceeded", "message": "private server detail"}
+ for language, expected in (("en", "usage limit reached"), ("zh_CN", "共享用量已达上限")):
+ set_language(language)
+ self.addCleanup(set_language, "en")
+ for event in ({"type": "error", "error": failure},
+ {"type": "response.failed", "response": {"error": failure}},
+ {"type": "error", **failure}):
+ payload = (partial + 'data: ' + json.dumps(event) + '\n\n').encode()
+ callbacks = Queue()
+ outcome = []
+ settings = Settings(polish_enabled=True, polish_provider="chatgpt",
+ polish_chatgpt_model="synthetic-fast")
+ client = PolishClient()
+ with patch.object(client, "polish") as api, patch.object(client, "polish_chatgpt",
+ side_effect=lambda *_, **__: completed_text(io.BytesIO(payload))):
+ manager = PolishManager(callbacks.put, client)
+ try:
+ manager.start("original transcript", settings, "", lambda text, error: outcome.append((text, error)))
+ callbacks.get(timeout=2)()
+ self.assertEqual(len(outcome), 1)
+ self.assertIsNone(outcome[0][0])
+ self.assertIn(expected, outcome[0][1])
+ self.assertNotIn("private server detail", outcome[0][1])
+ self.assertFalse(manager.busy)
+ api.assert_not_called()
+ finally:
+ manager.close()
+
+ def test_quota_pauses_inference_until_explicit_retry_without_losing_connection(self):
+ with TemporaryDirectory() as directory:
+ client = self.fixture(directory)
+ with client.store.transaction() as data:
+ data["accounts"][0]["expires"] = time.time() + 3600
+ error = b'data: {"type":"error","code":"subscription_sharing_usage_limit_exceeded"}\n\n'
+ complete = (b'data: {"type":"response.output_text.delta","delta":"done"}\n\n'
+ b'data: {"type":"response.completed"}\n\n')
+ with patch.object(connection, "open_request", side_effect=[io.BytesIO(error), io.BytesIO(complete)]) as network:
+ for _ in range(2):
+ with self.assertRaises(auth.ChatGPTError) as limited:
+ client.polish("synthetic", model="synthetic-fast", prompt="Correct text")
+ self.assertEqual(limited.exception.code, "usage_limit_exceeded")
+ self.assertEqual(network.call_count, 1)
+ self.assertTrue(client.ready())
+ self.assertTrue(client.state()["usage_limited"])
+ client.resume_usage()
+ self.assertFalse(client.state()["usage_limited"])
+ self.assertEqual(client.polish("synthetic", model="synthetic-fast", prompt="Correct text"), "done")
+ self.assertEqual(network.call_count, 2)
+
def test_store_rolls_back_failed_update_and_refuses_symlinks(self):
with TemporaryDirectory() as directory:
store = ChatGPTStore(Path(directory) / "safe")