A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.
Swift ai-agentsanthropicantigravityclaudeclaude-codecodexcursordynamic-islandgemini-cliiosiphonlinuxmacosmacos-appmenubar-appnotchopen-sourceswiftswiftuiwindows
Mac chat: DeepSeek, Qwen and Moonshot send the user's key when streaming
Claude6e990d7068be
diff --git a/NotchBuddy/Sources/App/ClaudeService.swift b/NotchBuddy/Sources/App/ClaudeService.swiftindex bf32ae4e..a9cbb06a 100644--- a/NotchBuddy/Sources/App/ClaudeService.swift+++ b/NotchBuddy/Sources/App/ClaudeService.swift@@ -330,14 +330,17 @@ final class ClaudeService {// Auth headerlet authHeader: String+ let cloudKey: String? // the provider's own key, sent when streaming tooif provider.isLocal {authHeader = "Bearer ollama"+ cloudKey = nil} else {guard let key = KeychainStore.shared.get(provider.keychainKey), !key.isEmpty else {await showError("\(provider.displayName) API key missing. Configure it in Settings.", state: state)return}authHeader = "Bearer \(key)"+ cloudKey = key}// Build messages@@ -411,7 +414,8 @@ final class ClaudeService {let final = try await LocalChat.streamChat(baseURL: baseURL,encodedBody: encodedBody,- model: modelCopy+ model: modelCopy,+ apiKey: cloudKey) { [state, msgId] visible inif !visible.isEmpty, state.stateOverride == .thinking {state.stateOverride = nil // hide typing dots on first visible textdiff --git a/NotchBuddy/Sources/App/LocalChat.swift b/NotchBuddy/Sources/App/LocalChat.swiftindex 0bb3e0ab..4212777b 100644--- a/NotchBuddy/Sources/App/LocalChat.swift+++ b/NotchBuddy/Sources/App/LocalChat.swift@@ -128,6 +128,7 @@ enum LocalChat {baseURL: String,model: String,messages: [[String: Any]],+ apiKey: String? = nil,onToken: @MainActor @escaping (String) -> Void) async throws -> String {let body: [String: Any] = [@@ -137,23 +138,39 @@ enum LocalChat {"max_tokens": 4096,]let bodyData = (try? JSONSerialization.data(withJSONObject: body)) ?? Data()- return try await streamChat(baseURL: baseURL, encodedBody: bodyData, model: model, onToken: onToken)+ return try await streamChat(baseURL: baseURL, encodedBody: bodyData, model: model, apiKey: apiKey, onToken: onToken)}+ /// Where a streamed chat goes and the bearer token it carries.+ /// A cloud provider (DeepSeek, Qwen, Moonshot) passes its key: its base URL+ /// already ends with its version (`https://api.deepseek.com/v1`), so only+ /// `/chat/completions` is added, and the key is the bearer token. A local+ /// server (Ollama, LM Studio) passes nil: `/v1` is added, with `Bearer ollama`.+ static func streamEndpoint(baseURL: String, apiKey: String?) -> (url: String, authorization: String) {+ if let key = apiKey, !key.isEmpty {+ return ("\(baseURL)/chat/completions", "Bearer \(key)")+ }+ return ("\(baseURL)/v1/chat/completions", "Bearer ollama")+ }++ /// - Parameters:+ /// - apiKey: A cloud provider's key from the Keychain; nil for a local server.static func streamChat(baseURL: String,encodedBody: Data,model: String,+ apiKey: String? = nil,onToken: @MainActor @escaping (String) -> Void) async throws -> String {- guard let url = URL(string: "\(baseURL)/v1/chat/completions") else {+ let endpoint = streamEndpoint(baseURL: baseURL, apiKey: apiKey)+ guard let url = URL(string: endpoint.url) else {throw LocalChatError.serverUnreachable(baseURL)}var req = URLRequest(url: url, timeoutInterval: 300)req.httpMethod = "POST"req.setValue("application/json", forHTTPHeaderField: "Content-Type")- req.setValue("Bearer ollama", forHTTPHeaderField: "Authorization")+ req.setValue(endpoint.authorization, forHTTPHeaderField: "Authorization")req.httpBody = encodedBodylet bytes: URLSession.AsyncBytesdiff --git a/tests/ChatParsingTests.swift b/tests/ChatParsingTests.swiftindex 8e3da271..217641db 100644--- a/tests/ChatParsingTests.swift+++ b/tests/ChatParsingTests.swift@@ -36,6 +36,19 @@ enum ChatParsingTests {check("no-op clean URL", LocalChat.normaliseURL("http://localhost:11434"), "http://localhost:11434")check("trims whitespace", LocalChat.normaliseURL(" http://localhost:11434 "), "http://localhost:11434")+ print("LocalChat.streamEndpoint")+ let local = LocalChat.streamEndpoint(baseURL: "http://localhost:11434", apiKey: nil)+ check("local URL adds /v1", local.url, "http://localhost:11434/v1/chat/completions")+ check("local sends Bearer ollama", local.authorization, "Bearer ollama")+ let emptyKey = LocalChat.streamEndpoint(baseURL: "http://localhost:1234", apiKey: "")+ check("empty key = local", emptyKey.authorization, "Bearer ollama")+ let deepseek = LocalChat.streamEndpoint(baseURL: "https://api.deepseek.com/v1", apiKey: "sk-deep")+ check("cloud URL keeps its /v1", deepseek.url, "https://api.deepseek.com/v1/chat/completions")+ check("cloud sends its key", deepseek.authorization, "Bearer sk-deep")+ let qwen = LocalChat.streamEndpoint(baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1", apiKey: "sk-qwen")+ check("qwen URL", qwen.url, "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions")+ check("qwen sends its key", qwen.authorization, "Bearer sk-qwen")+print("LocalChat.parseSSEDelta")let sseData = #"data: {"id":"1","choices":[{"delta":{"content":"hello"}}]}"#check("parses delta", LocalChat.parseSSEDelta(sseData) ?? "", "hello")@@ -144,6 +157,46 @@ enum ChatParsingTests {failures += 1}+ print("LocalChat.streamChat — cloud provider sends its key (fake server)")++ // A cloud base URL ends with /v1 (https://api.deepseek.com/v1); the fake+ // server answers 401 unless the bearer token is the key passed here.+ do {+ let response = try await LocalChat.streamChat(+ baseURL: baseURL + "/v1",+ model: "deepseek-chat",+ messages: [["role": "user", "content": "hello"]],+ apiKey: "sk-test-cloud-key",+ onToken: { _ in }+ )+ checkTrue("cloud stream authenticated, reply whole", response.contains("## Answer"))+ } catch {+ print(" ✗ unexpected error: \(error)")+ failures += 1+ }++ do {+ _ = try await LocalChat.streamChat(+ baseURL: baseURL + "/v1",+ model: "deepseek-chat",+ messages: [["role": "user", "content": "hello"]],+ apiKey: "sk-wrong-key",+ onToken: { _ in }+ )+ print(" ✗ should have thrown for a wrong key")+ failures += 1+ } catch let e as LocalChatError {+ if case .serverError(let msg) = e {+ checkTrue("wrong key → server's auth message", msg.contains("Authentication Fails"))+ } else {+ print(" ✗ wrong error case: \(e)")+ failures += 1+ }+ } catch {+ print(" ✗ unexpected error type: \(error)")+ failures += 1+ }+print("LocalChat.streamChat — unknown model (fake server)")do {diff --git a/tests/fake_local_llm.py b/tests/fake_local_llm.pyindex d0868493..9317a3f3 100644--- a/tests/fake_local_llm.py+++ b/tests/fake_local_llm.py@@ -9,6 +9,8 @@ Routes:POST /v1/chat/completions → SSE stream with <think> block, reasoning-onlydeltas (content=null), and Markdown answerPOST /v1/chat/completions → 404 when model == "unknown-model"+ POST /v1/chat/completions → 401 unless Authorization is "Bearer ollama"+ or "Bearer " + CLOUD_TEST_KEY"""import json@@ -42,7 +44,10 @@ SSE_EVENTS = [{"choices": [{"delta": {"content": "```python\nprint('hello')\n```"}}]},]-EXPECTED_RESPONSE = "## Answer\n\nHere is the result:\n\n- **item 1**\n- item 2\n\n```python\nprint('hello')\n```"+# The key ChatParsingTests sends as a cloud provider (DeepSeek, Qwen, Moonshot)+CLOUD_TEST_KEY = "sk-test-cloud-key"++EXPECTED_RESPONSE ="## Answer\n\nHere is the result:\n\n- **item 1**\n- item 2\n\n```python\nprint('hello')\n```"class FakeLLMHandler(BaseHTTPRequestHandler):@@ -76,6 +81,22 @@ class FakeLLMHandler(BaseHTTPRequestHandler):self.end_headers()return+ # Wrong bearer token → 401, like DeepSeek's "Authentication Fails".+ # A local call sends "Bearer ollama"; the cloud test sends its key.+ if self.headers.get("Authorization") not in ("Bearer ollama", "Bearer " + CLOUD_TEST_KEY):+ err = json.dumps({+ "error": {+ "message": "Authentication Fails, Your api key is invalid",+ "type": "authentication_error",+ }+ }).encode()+ self.send_response(401)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(err)))+ self.end_headers()+ self.wfile.write(err)+ return+# Unknown model → 404 with OpenAI-format errorif model == "unknown-model":err = json.dumps({