Doubao-powered voice input for Linux, Wayland and Omarchy
fix(siwc): handle HTTP quota and empty model catalogs
quanruebc33d2f04cb
diff --git a/macos/Sources/ChatGPTSettings.swift b/macos/Sources/ChatGPTSettings.swiftindex 7d9cbda..55af0bf 100644--- a/macos/Sources/ChatGPTSettings.swift+++ b/macos/Sources/ChatGPTSettings.swift@@ -6,6 +6,7 @@ final class ChatGPTConnectionModel: ObservableObject {static let shared = ChatGPTConnectionModel()@Published var snapshot = ChatGPTSnapshot()@Published var models: [ChatGPTModel] = []+ @Published var catalogLoaded = false@Published var busy = false@Published var message = ""private let service: ChatGPTService@@ -27,7 +28,7 @@ final class ChatGPTConnectionModel: ObservableObject {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 select(_ id: String) { guard !busy else { return }; catalogLoaded = false; models = []; perform { try await self.service.select(id) } }func signOut() {perform {let revoked = try await self.service.signOut()@@ -38,7 +39,7 @@ final class ChatGPTConnectionModel: ObservableObject {func cancelSignIn() { Task { await service.cancelSignIn() }; job?.cancel() }private func perform(_ operation: @escaping () async throws -> Void) {guard !busy else { return }- busy = true; message = ""+ busy = true; message = ""; catalogLoaded = falsejob = Task {defer { busy = false; job = nil }do {@@ -46,6 +47,7 @@ final class ChatGPTConnectionModel: ObservableObject {snapshot = try await service.state()models = snapshot.active?.sharing == true ? try await service.models() : []try Task.checkCancellation()+ catalogLoaded = snapshot.active?.sharing == true} catch {if let state = try? await service.state() { snapshot = state }if snapshot.active?.sharing != true { models = [] }@@ -105,14 +107,17 @@ struct ChatGPTSettingsView: View {.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 }+ .onAppear { previousAccount = connection.snapshot.activeID; validateModel() }.onChange(of: connection.snapshot.activeID) { active inif let previous = previousAccount, previous != active { model = "" }previousAccount = active}- .onChange(of: connection.models) { catalog in- if !catalog.isEmpty, !catalog.contains(where: { $0.id == model }) { model = "" }- }+ .onChange(of: connection.models) { _ in validateModel() }+ .onChange(of: connection.catalogLoaded) { _ in validateModel() }+ }+ private func validateModel() {+ guard connection.catalogLoaded, connection.snapshot.active?.sharing == true else { return }+ if !connection.models.contains(where: { $0.id == model }) { model = "" }}private var status: String {if connection.snapshot.usageLimited { return ChatGPTError.quota.localizedDescription }diff --git a/macos/Tests/Settings/ChatGPTUICheck.swift b/macos/Tests/Settings/ChatGPTUICheck.swiftindex 883a9b0..050dddb 100644--- a/macos/Tests/Settings/ChatGPTUICheck.swift+++ b/macos/Tests/Settings/ChatGPTUICheck.swift@@ -36,7 +36,9 @@ final class ChatGPTUIDelegate: NSObject, NSApplicationDelegate {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")]+ connection.catalogLoaded = truesettings.draft.polishChatGPTModel = "synthetic-fast"+ if ["empty-models", "models-loading"].contains(mode) { connection.catalogLoaded = false; connection.models = [] }}self.settings = settings; self.connection = connectionlet window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 690, height: 740),@@ -45,6 +47,9 @@ final class ChatGPTUIDelegate: NSObject, NSApplicationDelegate {window.contentView = NSHostingView(rootView: PolishingSettingsView(model: settings, connection: connection))self.window = window; window.center(); window.makeKeyAndOrderFront(nil)NSApp.activate(ignoringOtherApps: true)+ if mode == "empty-models" {+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { connection.catalogLoaded = 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))@@ -119,6 +124,19 @@ final class ChatGPTUIDelegate: NSObject, NSApplicationDelegate {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")+ let mode = ProcessInfo.processInfo.environment["SIWC_UI_CASE"] ?? "disconnected"+ if mode == "empty-models" {+ precondition(connection?.catalogLoaded == true && settings.draft.polishChatGPTModel.isEmpty && savedModel == "")+ let client = PolishClient()+ var blocked = false+ client.completion = { text, error in blocked = text == nil && error == ChatGPTError.model.localizedDescription }+ client.start(text: "synthetic", settings: settings.draft, apiKey: "", personalize: false)+ precondition(blocked)+ print("PASS_INTERACTION:empty-models"); fflush(stdout)+ } else if mode == "models-loading" {+ precondition(connection?.catalogLoaded == false && settings.draft.polishChatGPTModel == "synthetic-fast" && savedModel == "synthetic-fast")+ print("PASS_INTERACTION:models-loading"); fflush(stdout)+ }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.mdindex 2aa323a..731086e 100644--- a/macos/Tests/Settings/README.md+++ b/macos/Tests/Settings/README.md@@ -17,6 +17,9 @@ 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 retainedAPI settings. Separate popup captures use only the owned menu window, never theuser's desktop. Each process remains bounded to 15 seconds.+The empty-catalog case checks that a successfully loaded empty model list clears+and autosaves the stale selection, blocking inference before credential access.+The loading case preserves the selection until a catalog succeeds.`SidebarFocusCheck.swift` opens the real SettingsWindow with synthetic state in aSwiftUI application. It never signs in, records audio, saves credentials ordiff --git a/macos/Tests/Settings/chatgpt_ui_check.py b/macos/Tests/Settings/chatgpt_ui_check.pyindex 5752f18..4c29919 100644--- a/macos/Tests/Settings/chatgpt_ui_check.py+++ b/macos/Tests/Settings/chatgpt_ui_check.py@@ -20,7 +20,7 @@ subprocess.run(["ditto", str(binary), str(executable)], check=True)"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(",")+modes = os.environ.get("SIWC_UI_MODES", "disconnected,connected,quota,model-menu,model-select,model-keyboard,model-cancel,account-menu,empty-models,models-loading").split(",")for language in ["en", "zh"]:for mode in modes:for theme in ["light", "dark"]:diff --git a/src/doubao_input/chatgpt.py b/src/doubao_input/chatgpt.pyindex 6e54267..d118877 100644--- a/src/doubao_input/chatgpt.py+++ b/src/doubao_input/chatgpt.py@@ -220,7 +220,8 @@ class ChatGPTClient:raise auth.ChatGPTError("account_changed", "ChatGPT account changed")self._requests.add(cancellation)try:- with open_request(req, timeout=remaining, cancellation=cancellation) as response:+ with open_request(req, timeout=remaining, cancellation=cancellation,+ on_error=classify_usage_error) as response:result = completed_text(response, on_progress)cancellation.check()if generation != self._generation:@@ -250,6 +251,20 @@ def usage_limit_error():"ChatGPT 套餐共享用量已达上限,请查看“管理用量”,可用后再重试;本次使用原文。"))+def classify_usage_error(response):+ """Inspect a bounded HTTP error body before the transport closes it."""+ try:+ raw = response.read(64_001)+ if len(raw) > 64_000:+ return+ data = json.loads(raw)+ except (OSError, ValueError):+ return+ failure = (data.get("error") or data) if isinstance(data, dict) else None+ if isinstance(failure, dict) and failure.get("code") == "subscription_sharing_usage_limit_exceeded":+ raise usage_limit_error()++def completed_text(response, progress=None):text, frame, count, completed = "", [], 0, Falsefor raw in response:diff --git a/tests/README.md b/tests/README.mdindex 2620f87..07ac105 100644--- a/tests/README.md+++ b/tests/README.md@@ -153,6 +153,9 @@ settings, and hiding/reopening the connection card. It also checks a connectedaccount's quota message and explicit usage retry; a quota error must retain theaccount connection. It does not verify live OAuth, actual plan inference, tokenexpiry, audio capture or paste delivery.+Unit regressions also exercise bounded HTTP error bodies: an exact plan quota+code pauses inference until explicit retry, while ordinary HTTP throttling,+malformed errors and oversized bodies leave the connection available.Live sign-in must use a separate app-owned account store; never copy credentialsfrom Codex or another product.diff --git a/tests/unit/test_chatgpt.py b/tests/unit/test_chatgpt.pyindex 2483ae8..134890c 100644--- a/tests/unit/test_chatgpt.py+++ b/tests/unit/test_chatgpt.py@@ -9,6 +9,7 @@ import timefrom types import SimpleNamespacefrom http.server import BaseHTTPRequestHandler, HTTPServerfrom threading import Thread+from urllib.error import HTTPErrorimport unittestfrom unittest.mock import patch@@ -175,6 +176,47 @@ class ChatGPTTest(unittest.TestCase):self.assertEqual(client.polish("synthetic", model="synthetic-fast", prompt="Correct text"), "done")self.assertEqual(network.call_count, 2)+ def test_http_usage_limit_pauses_until_retry_and_closes_error_body(self):+ with TemporaryDirectory() as directory:+ client = self.fixture(directory)+ with client.store.transaction() as data:+ data["accounts"][0]["expires"] = time.time() + 3600+ body = io.BytesIO(json.dumps({"error": {"code": "subscription_sharing_usage_limit_exceeded"}}).encode())+ failure = HTTPError("https://example.invalid", 429, "Synthetic limit", {}, body)+ complete = io.BytesIO(b'data: {"type":"response.output_text.delta","delta":"done"}\n\n'+ b'data: {"type":"response.completed"}\n\n')+ opener = SimpleNamespace(open=unittest.mock.Mock(side_effect=[failure, complete]))+ with patch("doubao_input.polish_transport.request.build_opener", return_value=opener):+ 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.assertTrue(body.closed)+ self.assertTrue(client.ready())+ self.assertTrue(client.state()["usage_limited"])+ self.assertEqual(opener.open.call_count, 1)+ client.resume_usage()+ self.assertEqual(client.polish("synthetic", model="synthetic-fast", prompt="Correct text"), "done")+ self.assertEqual(opener.open.call_count, 2)++ def test_other_http_errors_and_oversized_bodies_do_not_pause_plan_usage(self):+ for payload in ({"error": {"code": "rate_limit_exceeded"}},+ {"error": {"code": "subscription_sharing_usage_limit_exceeded", "message": "x" * 70_000}},+ ["malformed error"]):+ with self.subTest(payload_type=type(payload).__name__), TemporaryDirectory() as directory:+ client = self.fixture(directory)+ with client.store.transaction() as data:+ data["accounts"][0]["expires"] = time.time() + 3600+ body = io.BytesIO(json.dumps(payload).encode())+ failure = HTTPError("https://example.invalid", 429, "Synthetic error", {}, body)+ opener = SimpleNamespace(open=unittest.mock.Mock(side_effect=failure))+ with patch("doubao_input.polish_transport.request.build_opener", return_value=opener):+ with self.assertRaises(ValueError):+ client.polish("synthetic", model="synthetic-fast", prompt="Correct text")+ self.assertTrue(body.closed)+ self.assertTrue(client.ready())+ self.assertFalse(client.state()["usage_limited"])+def test_store_rolls_back_failed_update_and_refuses_symlinks(self):with TemporaryDirectory() as directory:store = ChatGPTStore(Path(directory) / "safe")