知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
feat: add a Ling API key kept in the Keychain, a shared Ling client and the AI settings page
wquguru427c0f6e96a3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5be1ddc..8366a84 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ the release workflow publishes it as the release notes.- New: a sound test for the virtual microphone: the app plays a sentence into it, listens back and shows what the room will hear.- New: a settings window with a sidebar (听 / 我说话也翻译 / 字幕条 / 会议记录) replaces the settings sheet; the virtual microphone is set up from a three-step checklist there and in the first-run guide.- Changed: hold the right ⌥ key on its own to talk, instead of ⌥ Space (which other apps' launchers often use, and which types a space). Pressing another key while holding it cancels, so ⌥ + letter still types. It needs the "输入监控" permission; the app asks for it.+- New: Settings › AI 服务 takes your own Ling (ant-ling.com) API key. It is kept in the macOS Keychain, checked with a one-token request, and shown masked; without a key everything works as before.- New: both shortcuts (talk, hide/show the subtitle bar) can be changed in settings: click and press new keys. Combinations without ⌃ or ⌘, system shortcuts and ones another app already uses are refused with a reason.## 2.0.0 — 2026-11-01diff --git a/Sources/LiveSubs/AISettings.swift b/Sources/LiveSubs/AISettings.swiftnew file mode 100644index 0000000..70e6ab1--- /dev/null+++ b/Sources/LiveSubs/AISettings.swift@@ -0,0 +1,137 @@+import AppKit+import SwiftUI++/// Settings › AI 服务: the one Ling key the whole app uses, and what uses it.+struct AISettingsView: View {+ @ObservedObject var model: AppModel+ @ObservedObject var ling: LingClient+ @ObservedObject var settings: AppSettings+ @State private var draft = ""+ @State private var editing = false++ var body: some View {+ VStack(alignment: .leading, spacing: 14) {+ keyCard+ Text("用在哪里").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.secondary)+ .padding(.top, 4)+ SettingsCard {+ usageRow("实时纪要", tag: ling.usable ? "用 Ling" : "需要 key", on: ling.usable,+ note: ling.usable ? "会中每 45 秒更新" : "填上 key 才有")+ usageRow("翻译", tag: ling.usable ? "用 Ling" : "Google", on: ling.usable,+ note: ling.usable ? "整句用 Ling;不行时换 Google、本机" : "没有 key 时照常可用")+ usageRow("语音识别", tag: "本机", on: false, note: "更快,不花钱", divider: false)+ }+ SettingsCard {+ SettingsRow(title: "模型", detail: "3.1 更准;3.0 更快、更省", divider: false) {+ PillMenu(value: settings.aiModel, options: LingClient.models.map { ($0, $0) }) { settings.aiModel = $0 }+ }+ }+ Text("一小时会议约 ¥0.15–1(目前优惠价)。发出去的只有文字,语音识别留在本机。")+ .font(.system(size: 12)).foregroundStyle(Palette.tertiary)+ }+ }++ // MARK: Key++ private var keyCard: some View {+ VStack(alignment: .leading, spacing: 12) {+ HStack(spacing: 8) {+ Circle().fill(statusColor).frame(width: 8, height: 8)+ Text(statusTitle).font(.system(size: 14, weight: .semibold)).foregroundStyle(Palette.ink)+ if let detail = statusDetail {+ Text(detail).font(.system(size: 12)).foregroundStyle(Palette.tertiary).lineLimit(1)+ }+ Spacer()+ }+ if let key = ling.key, !editing {+ HStack(spacing: 8) {+ Text(AIKey.masked(key)).font(.system(size: 13, design: .monospaced)).foregroundStyle(Palette.ink)+ .padding(.horizontal, 12).frame(maxWidth: .infinity, minHeight: 36, alignment: .leading)+ .background(RoundedRectangle(cornerRadius: 10).fill(Color.white))+ .overlay(RoundedRectangle(cornerRadius: 10).stroke(Palette.line, lineWidth: 1))+ SoftButton("更换") { draft = ""; editing = true }+ if case .invalid = ling.keyState {} else if case .unreachable = ling.keyState {+ SoftButton("重试") { Task { await ling.check() } }+ }+ }+ } else {+ if ling.key == nil {+ Text("在 Ling 开放平台点“创建令牌”,复制以 sk- 开头的那串。")+ .font(.system(size: 12)).foregroundStyle(Palette.secondary)+ }+ HStack(spacing: 8) {+ SecureField("sk-…", text: $draft)+ .textFieldStyle(.plain).font(.system(size: 13, design: .monospaced))+ .padding(.horizontal, 12).frame(height: 36)+ .background(RoundedRectangle(cornerRadius: 10).fill(Color.white))+ .overlay(RoundedRectangle(cornerRadius: 10).stroke(Palette.ink.opacity(0.6), lineWidth: 1))+ .onSubmit(save)+ SoftButton("保存并检查", dark: true, action: save)+ if editing { SoftButton("取消") { editing = false } }+ }+ Button("打开 Ling 开放平台 ↗") {+ if let url = URL(string: "https://chat.ant-ling.com/open") { NSWorkspace.shared.open(url) }+ }+ .buttonStyle(.plain).font(.system(size: 12)).foregroundStyle(Palette.secondary)+ }+ HStack(spacing: 6) {+ Image(systemName: "lock").font(.system(size: 11)).foregroundStyle(Palette.tertiary)+ Text("加密存在这台 Mac 的钥匙串里,只发给 Ling(ant-ling.com)")+ .font(.system(size: 11)).foregroundStyle(Palette.tertiary)+ Spacer()+ if ling.key != nil && !editing {+ Button("移除") { ling.removeKey() }+ .buttonStyle(.plain).font(.system(size: 11)).foregroundStyle(Palette.secondary)+ }+ }+ }+ .padding(16)+ .background(RoundedRectangle(cornerRadius: 14).fill(Color(red: 0.961, green: 0.965, blue: 0.973)))+ }++ private func save() {+ let k = draft.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !k.isEmpty else { return }+ draft = ""+ editing = false+ Task { await ling.setKey(k) }+ }++ private var statusColor: Color {+ switch ling.keyState {+ case .ok: Palette.ok+ case .invalid, .unreachable: Palette.error+ case .checking, .unchecked: Palette.accent+ case .none: Color(white: 0.75)+ }+ }++ private var statusTitle: String {+ switch ling.keyState {+ case .none: "还没填 API key"+ case .unchecked, .checking: "正在检查…"+ case .ok: "已连接"+ case .invalid: "这个 key 用不了"+ case .unreachable: "暂时连不上"+ }+ }++ private var statusDetail: String? {+ switch ling.keyState {+ case .ok(let s): "\(settings.aiModel) · 响应约 \(String(format: "%.1f", s)) 秒"+ case .invalid: "Ling 说这个令牌无效,检查是否复制完整,或新建一个"+ case .unreachable(let why): why+ case .none: "没有 key 时,字幕和翻译照常可用"+ default: nil+ }+ }++ private func usageRow(_ title: String, tag: String, on: Bool, note: String, divider: Bool = true) -> some View {+ SettingsRow(title: title, detail: note, divider: divider) {+ Text(tag).font(.system(size: 11, weight: .semibold))+ .foregroundStyle(on ? Palette.ok : Palette.secondary)+ .padding(.horizontal, 8).padding(.vertical, 3)+ .background(RoundedRectangle(cornerRadius: 6).fill(on ? Palette.okPale : Palette.fill))+ }+ }+}diff --git a/Sources/LiveSubs/AppModel.swift b/Sources/LiveSubs/AppModel.swiftindex e92b0b1..d560211 100644--- a/Sources/LiveSubs/AppModel.swift+++ b/Sources/LiveSubs/AppModel.swift@@ -35,6 +35,7 @@ final class AppModel: ObservableObject {private var permissionPoll: Timer?private var shortcutsSuspended = falselet installer = VirtualMicInstaller()+ let ling = LingClient()let sample = SamplePlayer()var openOnboarding: (() -> Void)?@@ -63,6 +64,9 @@ final class AppModel: ObservableObject {self.store.setTranslation(lineID: line, text)}+ ling.model = { [weak self] in self?.settings.aiModel ?? "Ling-3.1-flash" }+ if ling.hasKey { Task { await ling.check() } }+installer.speakThrough = { [weak self] text, lang, device inawait self?.speak.speak(text, language: lang, device: device)}@@ -437,6 +441,12 @@ final class AppModel: ObservableObject {debugLog("\(parts[0]) \(arg): \(refusal ?? "ok")")case "shortcuts":debugLog("shortcuts talk=\(settings.talkKey.display) armed=\(talkRight.isRunning || talkCombo.isRegistered) needsPermission=\(talkNeedsPermission) inputMonitoring=\(RightOptionKey.allowed) toggle=\(settings.toggleKey.display) taken=\(toggleKeyTaken)")+ case "aiKeyFile":+ // Dev testing: the key comes from a file so it never passes through the log.+ if let k = try? String(contentsOfFile: arg, encoding: .utf8) { Task { await ling.setKey(k) } }+ case "aiCheck": Task { await ling.check() }+ case "aiRemove": ling.removeKey()+ case "aiState": debugLog("ai state=\(ling.keyState) hasKey=\(ling.hasKey) model=\(settings.aiModel)")case "speakOn": enableSpeaking(true)case "speakOff": enableSpeaking(false)case "speakOut": speak.debugOutputURL = arg.isEmpty ? nil : URL(fileURLWithPath: arg)diff --git a/Sources/LiveSubs/Ling.swift b/Sources/LiveSubs/Ling.swiftnew file mode 100644index 0000000..c3dabbb--- /dev/null+++ b/Sources/LiveSubs/Ling.swift@@ -0,0 +1,279 @@+import Foundation+import Security++// MARK: - API key (Keychain)++/// The user's Ling API key, kept in the login Keychain (encrypted by the system, readable only by+/// this app's code signature). Never written to UserDefaults, logs or exports.+enum AIKey {+ /// Dev and release builds keep separate keys, like their other settings.+ private static var service: String { (Bundle.main.bundleIdentifier ?? "com.wquguru.cicada.swiftrun") + ".ai" }+ private static let account = "ling"+ private static var cached: String??++ static func read() -> String? {+ if let cached { return cached }+ let query: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: service,+ kSecAttrAccount as String: account,+ kSecReturnData as String: true,+ kSecMatchLimit as String: kSecMatchLimitOne,+ ]+ var out: AnyObject?+ let status = SecItemCopyMatching(query as CFDictionary, &out)+ let value = status == errSecSuccess ? (out as? Data).flatMap { String(data: $0, encoding: .utf8) } : nil+ if status != errSecSuccess && status != errSecItemNotFound { debugLog("keychain read failed: \(status)") }+ cached = .some(value)+ return value+ }++ @discardableResult+ static func save(_ key: String) -> Bool {+ remove()+ let item: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: service,+ kSecAttrAccount as String: account,+ kSecAttrLabel as String: "Live Subs · Ling API key",+ kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,+ kSecValueData as String: Data(key.utf8),+ ]+ let status = SecItemAdd(item as CFDictionary, nil)+ if status != errSecSuccess { debugLog("keychain save failed: \(status)") }+ cached = .some(status == errSecSuccess ? key : nil)+ return status == errSecSuccess+ }++ static func remove() {+ let query: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: service,+ kSecAttrAccount as String: account,+ ]+ SecItemDelete(query as CFDictionary)+ cached = .some(nil)+ }++ /// "sk-…3f9a" for display.+ static func masked(_ key: String) -> String {+ guard key.count > 8 else { return "sk-…" }+ return String(key.prefix(3)) + String(repeating: "•", count: 12) + String(key.suffix(4))+ }+}++// MARK: - Ling client++/// Ling (ant-ling.com), OpenAI-compatible. One shared instance for the whole app: the account+/// allows about 2 requests per second across every model, so request *starts* go through one+/// gate (≥ 0.6 s apart, overlapping is fine) in priority order: speak-back, translation, notes.+///+/// Two quirks found in testing shape every call:+/// - `thinking` is on by default: always disable it (otherwise +2.6 s and billed reasoning).+/// - When the user message reads like a factual question, the gateway answers it with a search+/// essay instead of following the prompt. So the content always goes in the system message and+/// the user message is a fixed instruction; a search-style reply is detected and dropped.+@MainActor+final class LingClient: ObservableObject {+ enum Priority: Int, Comparable {+ case speak = 0, translate = 1, notes = 2+ static func < (a: Priority, b: Priority) -> Bool { a.rawValue < b.rawValue }+ }++ enum KeyState: Equatable {+ case none+ case unchecked+ case checking+ case ok(seconds: Double)+ case invalid+ case unreachable(String)+ }++ enum Failure: Error, Equatable {+ case noKey, invalidKey, rateLimited, hijacked, timeout, http(Int), network, parse+ }++ static let models = ["Ling-3.1-flash", "Ling-3.0-flash"]+ private static let base = URL(string: "https://api.ant-ling.com/v1/")!+ private static let hijackPrefixes = ["根据现有检索证据", "暂未找到足够可靠的信息", "根据检索"]++ @Published private(set) var keyState: KeyState+ @Published private(set) var rateLimitedAt: Date?+ var model: () -> String = { "Ling-3.1-flash" }++ var hasKey: Bool { key != nil }+ var key: String? { AIKey.read() }+ /// The key is known to work (or at least not known to be bad).+ var usable: Bool { hasKey && keyState != .invalid }++ init() {+ keyState = AIKey.read() == nil ? .none : .unchecked+ }++ // MARK: Key++ /// Saves the key and checks it with the cheapest possible request.+ func setKey(_ raw: String) async {+ let k = raw.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !k.isEmpty else { return }+ AIKey.save(k)+ await check()+ }++ func removeKey() {+ AIKey.remove()+ keyState = .none+ }++ func check() async {+ guard let key else { keyState = .none; return }+ keyState = .checking+ let started = Date()+ let body: [String: Any] = [+ "model": "Ling-3.0-tiny",+ "messages": [["role": "user", "content": "hi"]],+ "max_tokens": 1,+ "thinking": ["type": "disabled"],+ ]+ do {+ _ = try await post("chat/completions", body: body, key: key, timeout: 15)+ keyState = .ok(seconds: Date().timeIntervalSince(started))+ } catch Failure.invalidKey {+ keyState = .invalid+ } catch Failure.rateLimited {+ keyState = .ok(seconds: Date().timeIntervalSince(started))+ } catch {+ keyState = .unreachable("连不上 Ling,检查网络或代理")+ }+ debugLog("ling: key check → \(keyState)")+ }++ // MARK: Chat++ /// One chat completion. `content` goes in the system message, `instruction` is the fixed user+ /// message. Notes retry 429s with backoff; translation and speak-back fail fast so the caller+ /// can fall back to another translator.+ func chat(content: String, instruction: String, priority: Priority, json: Bool = false,+ maxTokens: Int = 1024, timeout: TimeInterval = 30, model: String? = nil) async throws -> String {+ guard let key else { throw Failure.noKey }+ guard keyState != .invalid else { throw Failure.invalidKey }+ var body: [String: Any] = [+ "model": model ?? self.model(),+ "messages": [+ ["role": "system", "content": content],+ ["role": "user", "content": instruction],+ ],+ "max_tokens": maxTokens,+ "temperature": 0.2,+ "thinking": ["type": "disabled"],+ "stream": false,+ ]+ if json { body["response_format"] = ["type": "json_object"] }+ let attempts = priority == .notes ? 4 : 1+ var delay = 1.0+ for attempt in 1...attempts {+ await acquire(priority)+ let started = Date()+ do {+ let root = try await post("chat/completions", body: body, key: key, timeout: timeout)+ guard let choice = (root["choices"] as? [[String: Any]])?.first,+ let message = choice["message"] as? [String: Any],+ let text = message["content"] as? String else { throw Failure.parse }+ let finish = choice["finish_reason"] as? String+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)+ if finish == nil || Self.hijackPrefixes.contains(where: { trimmed.hasPrefix($0) }) {+ debugLog("ling: \(priority) search-style reply dropped (finish=\(finish ?? "nil"))")+ throw Failure.hijacked+ }+ let ms = Int(Date().timeIntervalSince(started) * 1000)+ let usage = root["usage"] as? [String: Any]+ debugLog("ling: \(priority) ok \(ms) ms tokens=\(usage?["prompt_tokens"] ?? "?")/\(usage?["completion_tokens"] ?? "?")")+ if rateLimitedAt != nil { rateLimitedAt = nil }+ return trimmed+ } catch Failure.rateLimited where attempt < attempts {+ let wait = delay + Double.random(in: 0...0.5)+ debugLog("ling: \(priority) 429, retry in \(String(format: "%.1f", wait)) s")+ try? await Task.sleep(nanoseconds: UInt64(wait * 1_000_000_000))+ delay *= 2+ } catch Failure.rateLimited {+ rateLimitedAt = Date()+ throw Failure.rateLimited+ }+ }+ throw Failure.rateLimited+ }++ // MARK: Transport++ private func post(_ path: String, body: [String: Any], key: String, timeout: TimeInterval) async throws -> [String: Any] {+ var req = URLRequest(url: Self.base.appendingPathComponent(path))+ req.httpMethod = "POST"+ req.timeoutInterval = timeout+ req.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization")+ req.setValue("application/json", forHTTPHeaderField: "Content-Type")+ req.httpBody = try JSONSerialization.data(withJSONObject: body)+ let data: Data+ let response: URLResponse+ do {+ (data, response) = try await URLSession.shared.data(for: req)+ } catch let e as URLError where e.code == .timedOut {+ throw Failure.timeout+ } catch {+ debugLog("ling: network error \(error.localizedDescription)")+ throw Failure.network+ }+ let code = (response as? HTTPURLResponse)?.statusCode ?? 0+ switch code {+ case 200: break+ case 401, 403:+ if keyState != .invalid { keyState = .invalid }+ throw Failure.invalidKey+ case 429: throw Failure.rateLimited+ default:+ debugLog("ling: HTTP \(code)")+ throw Failure.http(code)+ }+ guard let root = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw Failure.parse }+ return root+ }++ // MARK: Start gate++ private static let spacing: TimeInterval = 0.6+ private var lastStart = Date.distantPast+ private var waiting: [(priority: Priority, seq: Int, resume: CheckedContinuation<Void, Never>)] = []+ private var seq = 0+ private var pumping = false++ private func acquire(_ priority: Priority) async {+ if waiting.isEmpty && Date().timeIntervalSince(lastStart) >= Self.spacing {+ lastStart = Date()+ return+ }+ seq += 1+ let n = seq+ await withCheckedContinuation { cont in+ waiting.append((priority, n, cont))+ pump()+ }+ }++ private func pump() {+ guard !pumping, !waiting.isEmpty else { return }+ pumping = true+ let wait = max(0, Self.spacing - Date().timeIntervalSince(lastStart))+ DispatchQueue.main.asyncAfter(deadline: .now() + wait) { [weak self] in+ MainActor.assumeIsolated {+ guard let self else { return }+ self.pumping = false+ guard let i = self.waiting.indices.min(by: {+ (self.waiting[$0].priority, self.waiting[$0].seq) < (self.waiting[$1].priority, self.waiting[$1].seq)+ }) else { return }+ let next = self.waiting.remove(at: i)+ self.lastStart = Date()+ next.resume.resume()+ self.pump()+ }+ }+ }+}diff --git a/Sources/LiveSubs/Settings.swift b/Sources/LiveSubs/Settings.swiftindex 449c8fe..c785307 100644--- a/Sources/LiveSubs/Settings.swift+++ b/Sources/LiveSubs/Settings.swift@@ -53,6 +53,11 @@ final class AppSettings: ObservableObject {didSet { save() }}+ /// Ling model for notes and translation.+ @Published var aiModel: String {+ didSet { save() }+ }+var debug: Bool { defaults.bool(forKey: "debug") }init() {@@ -73,6 +78,7 @@ final class AppSettings: ObservableObject {overlayHideAfter = defaults.object(forKey: "overlayHideAfter") as? Double ?? 4talkKey = Shortcut(stored: defaults.string(forKey: "talkKey")) ?? .defaultTalktoggleKey = Shortcut(stored: defaults.string(forKey: "toggleKey")) ?? .defaultToggle+ aiModel = defaults.string(forKey: "aiModel") ?? "Ling-3.1-flash"}private func save() {@@ -90,6 +96,7 @@ final class AppSettings: ObservableObject {defaults.set(overlayHideAfter, forKey: "overlayHideAfter")defaults.set(talkKey.stored, forKey: "talkKey")defaults.set(toggleKey.stored, forKey: "toggleKey")+ defaults.set(aiModel, forKey: "aiModel")}/// Target language. "Follow system" uses the first system language thatdiff --git a/Sources/LiveSubs/SettingsWindow.swift b/Sources/LiveSubs/SettingsWindow.swiftindex 9b9ea0d..89675bd 100644--- a/Sources/LiveSubs/SettingsWindow.swift+++ b/Sources/LiveSubs/SettingsWindow.swift@@ -3,7 +3,7 @@ import Carbon.HIToolboximport SwiftUIenum SettingsSection: String, CaseIterable, Identifiable {- case listen, speak, overlay, records+ case listen, speak, overlay, records, aivar id: String { rawValue }var title: String {switch self {@@ -11,6 +11,7 @@ enum SettingsSection: String, CaseIterable, Identifiable {case .speak: "我说话也翻译"case .overlay: "字幕条"case .records: "会议记录"+ case .ai: "AI 服务"}}var icon: String {@@ -19,6 +20,7 @@ enum SettingsSection: String, CaseIterable, Identifiable {case .speak: "mic"case .overlay: "captions.bubble"case .records: "doc.text"+ case .ai: "key"}}}@@ -354,6 +356,7 @@ struct SettingsView: View {case .speak: speakcase .overlay: overlaycase .records: records+ case .ai: AISettingsView(model: model, ling: model.ling, settings: settings)}}.padding(.leading, 12).padding(.trailing, 28).padding(.top, 40).padding(.bottom, 28)diff --git a/Sources/LiveSubs/Views.swift b/Sources/LiveSubs/Views.swiftindex 21384d6..5d4f12e 100644--- a/Sources/LiveSubs/Views.swift+++ b/Sources/LiveSubs/Views.swift@@ -10,6 +10,16 @@ enum Palette {static let accent = Color(red: 0.91, green: 0.33, blue: 0.17)static let accentInk = Color(red: 0.70, green: 0.23, blue: 0.08)static let accentPale = Color(red: 0.99, green: 0.93, blue: 0.906)+ /// Controls, chips, search fields.+ static let fill = Color(red: 0.949, green: 0.953, blue: 0.961)+ /// Emphasis blocks (summary, setting cards).+ static let raised = Color(red: 0.961, green: 0.965, blue: 0.973)+ /// Current row while something is live.+ static let accentWash = Color(red: 1.0, green: 0.98, blue: 0.973)+ static let ok = Color(red: 0.122, green: 0.478, blue: 0.271)+ static let okPale = Color(red: 0.906, green: 0.961, blue: 0.925)+ static let error = Color(red: 0.706, green: 0.137, blue: 0.094)+ static let errorPale = Color(red: 0.992, green: 0.925, blue: 0.918)}struct LogoTile: View {