Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

feat: notes can use their own model, or another OpenAI-compatible service with its own address and key

wquguru21642b9bf74e
diff --git a/Resources/en.lproj/Localizable.strings b/Resources/en.lproj/Localizable.strings
index 5d0bfec..36c99c7 100644
--- a/Resources/en.lproj/Localizable.strings
+++ b/Resources/en.lproj/Localizable.strings
@@ -134,6 +134,21 @@
"纪要写不了" = "Can't write notes";
"会先思考" = "Thinks first";
"不思考" = "Doesn't think";
+"%@ 不认上面的 key,给它单独填一个。" = "%@ doesn't accept the key above. Give it its own.";
+"这个模型没按要求返回 JSON,写不了纪要。换一个通用模型。" = "This model didn't return JSON, so it can't write notes. Try a general-purpose model.";
+"%@ 和 %@" = "%@ and %@";
+"用来写实时纪要、识别说话人,默认和翻译用同一个" = "For live notes and telling speakers apart. Same as translation unless you pick one.";
+"能写纪要 · %@ 秒" = "Writes notes · %@ s";
+"key 不对" = "Wrong key";
+"同一个服务" = "Same service";
+"另一个服务" = "Another service";
+"不填就用上面的 key" = "Empty: the key above";
+"和翻译模型一样" = "Same as translation";
+"这个地址没列出模型,直接填名字" = "This address lists no models. Type the name.";
+"重新获取" = "Refresh";
+"搜索或输入模型" = "Search or type a model";
+"用 %@(列表里没有)" = "Use %@ (not listed)";
+"%@ 列出 %lld 个模型" = "%1$@ lists %2$lld models";
"上次正常" = "Worked last time";
"上次没出声" = "Silent last time";
"需支持 /audio/speech;不填则用本机声音。" = "Needs /audio/speech; leave blank to use the on-device voice.";
diff --git a/Resources/ja.lproj/Localizable.strings b/Resources/ja.lproj/Localizable.strings
index ae32f0f..6272a8a 100644
--- a/Resources/ja.lproj/Localizable.strings
+++ b/Resources/ja.lproj/Localizable.strings
@@ -134,6 +134,21 @@
"纪要写不了" = "メモを作成できません";
"会先思考" = "先に考えます";
"不思考" = "思考しません";
+"%@ 不认上面的 key,给它单独填一个。" = "%@ は上のキーを受け付けません。専用のキーを入力してください。";
+"这个模型没按要求返回 JSON,写不了纪要。换一个通用模型。" = "このモデルは JSON を返さないため、メモを作成できません。汎用モデルに変えてください。";
+"%@ 和 %@" = "%@ と %@";
+"用来写实时纪要、识别说话人,默认和翻译用同一个" = "ライブメモと話者の識別に使います。既定では翻訳と同じです。";
+"能写纪要 · %@ 秒" = "メモ作成可 · %@ 秒";
+"key 不对" = "キーが違います";
+"同一个服务" = "同じサービス";
+"另一个服务" = "別のサービス";
+"不填就用上面的 key" = "空欄なら上のキー";
+"和翻译模型一样" = "翻訳と同じモデル";
+"这个地址没列出模型,直接填名字" = "このアドレスはモデル一覧を返しません。名前を入力してください。";
+"重新获取" = "再取得";
+"搜索或输入模型" = "モデルを検索または入力";
+"用 %@(列表里没有)" = "%@ を使う(一覧にありません)";
+"%@ 列出 %lld 个模型" = "%1$@ のモデル %2$lld 個";
"上次正常" = "前回は正常";
"上次没出声" = "前回は無音";
"需支持 /audio/speech;不填则用本机声音。" = "/audio/speech の対応が必要です。未入力の場合はオンデバイス音声を使います。";
diff --git a/Resources/ko.lproj/Localizable.strings b/Resources/ko.lproj/Localizable.strings
index f7aec82..e4070e2 100644
--- a/Resources/ko.lproj/Localizable.strings
+++ b/Resources/ko.lproj/Localizable.strings
@@ -134,6 +134,21 @@
"纪要写不了" = "노트 작성 불가";
"会先思考" = "먼저 생각함";
"不思考" = "생각하지 않음";
+"%@ 不认上面的 key,给它单独填一个。" = "%@에서 위의 키를 받지 않습니다. 따로 키를 입력하세요.";
+"这个模型没按要求返回 JSON,写不了纪要。换一个通用模型。" = "이 모델은 JSON을 반환하지 않아 노트를 작성할 수 없습니다. 범용 모델로 바꾸세요.";
+"%@ 和 %@" = "%@ 및 %@";
+"用来写实时纪要、识别说话人,默认和翻译用同一个" = "실시간 노트와 화자 구분에 씁니다. 기본값은 번역과 같습니다.";
+"能写纪要 · %@ 秒" = "노트 작성 가능 · %@초";
+"key 不对" = "키가 틀림";
+"同一个服务" = "같은 서비스";
+"另一个服务" = "다른 서비스";
+"不填就用上面的 key" = "비우면 위의 키";
+"和翻译模型一样" = "번역과 같은 모델";
+"这个地址没列出模型,直接填名字" = "이 주소는 모델 목록을 주지 않습니다. 이름을 직접 입력하세요.";
+"重新获取" = "다시 가져오기";
+"搜索或输入模型" = "모델 검색 또는 입력";
+"用 %@(列表里没有)" = "%@ 사용 (목록에 없음)";
+"%@ 列出 %lld 个模型" = "%1$@의 모델 %2$lld개";
"上次正常" = "지난번 정상";
"上次没出声" = "지난번 소리 없음";
"需支持 /audio/speech;不填则用本机声音。" = "/audio/speech 지원 필요. 비워두면 온디바이스 음성을 사용합니다.";
diff --git a/Sources/Cicada/AICheck.swift b/Sources/Cicada/AICheck.swift
index f2d89b5..abbfb6e 100644
--- a/Sources/Cicada/AICheck.swift
+++ b/Sources/Cicada/AICheck.swift
@@ -56,6 +56,18 @@ struct AICheck: Equatable {
var translate: Speed?
/// A custom service that recognizes the meeting: whether its speech model took audio.
var hear: Hearing?
+ /// A custom service whose notes go to another model or server: how that one answered. nil
+ /// while notes use the translation model (then `steps` say it all). A notes failure doesn't
+ /// stop translation: `failure` and `passed` stay about translation.
+ var notes: Notes?
+
+ enum Notes: Equatable {
+ case running
+ case ok(seconds: Double)
+ case fail(Reason, code: Int? = nil)
+ var ok: Bool { if case .ok = self { true } else { false } }
+ var reason: Reason? { if case .fail(let r, _) = self { r } else { nil } }
+ }
struct Speed: Equatable {
let seconds: Double
@@ -91,7 +103,9 @@ struct AICheck: Equatable {
return nil
}
- var running: Bool { steps.contains { $0.state == .running } }
+ var running: Bool { steps.contains { $0.state == .running } || notes == .running }
+ /// Translation works but the notes' own model or server doesn't (a busy one fixes itself).
+ var notesFailed: Bool { notes?.reason.map { $0 != .busy } ?? false }
var busy: Bool { steps.contains { $0.state == .busy } }
/// Every step passed (busy counts; a step nothing has tested yet does not block).
var passed: Bool { at != nil && failure == nil && !running }
@@ -234,6 +248,25 @@ struct AICheck: Equatable {
: L("翻一句要 \(secs) 秒,超过 6 秒会改用 Google。换一个更小的模型会快一些。")
}
+ /// The notes' own model or server's problem, in one sentence. `sharedKey`: notes use the
+ /// translation key, so a refused key wants one of their own.
+ func notesLine(host: String, model: String, sharedKey: Bool) -> String? {
+ guard let reason = notes?.reason else { return nil }
+ switch reason {
+ case .invalidKey, .mgmtKey:
+ return sharedKey ? L("\(host) 不认上面的 key,给它单独填一个。") : L("\(host) 说这个 key 无效,可能没复制全,或已删除。")
+ case .unreachable: return L("这台 Mac 访问不到 \(host)。")
+ case .badAddress: return L("地址要用 https;这台 Mac 和局域网里的服务可以用 http。")
+ case .noCredit: return L("\(host) 账户余额不足。")
+ case .noModel: return L("\(host) 上找不到 \(model) 这个模型。")
+ case .noJSON: return L("这个模型没按要求返回 JSON,写不了纪要。换一个通用模型。")
+ case .busy: return nil
+ case .serverError:
+ if case .fail(_, let code) = notes { return L("\(host) 暂时出错(HTTP \(code ?? 0)),稍后再试。") }
+ return nil
+ }
+ }
+
/// The speech model's problem, in one sentence.
func hearLine(host: String, model: String) -> String? {
switch hear {
@@ -279,5 +312,6 @@ struct AICheck: Equatable {
+ (passive ? " passive" : "")
+ (translate.map { " translate=\(String(format: "%.1f", $0.seconds))s\($0.thinks ? " thinks" : "")" } ?? "")
+ (hear.map { " hear=\($0)" } ?? "")
+ + (notes.map { " notes=\($0)" } ?? "")
}
}
diff --git a/Sources/Cicada/AIProviders.swift b/Sources/Cicada/AIProviders.swift
index a67ee93..e15303b 100644
--- a/Sources/Cicada/AIProviders.swift
+++ b/Sources/Cicada/AIProviders.swift
@@ -149,11 +149,31 @@ struct AIConfig: Equatable {
/// when recognition stays on this Mac.
var hearModel: String? = nil
var hearBase: URL? = nil
+ /// A custom service's notes (实时纪要, 说话人, files' corrections): another model, and with
+ /// 另一个服务 another server with its own key. nil: the same as translation.
+ var notesModel: String? = nil
+ var notesBase: URL? = nil
+ /// 另一个服务 is picked: notes use their own key file when there is one.
+ var notesOwnService = false
+ /// 另一个服务 with an address that can't be used (http to the internet): notes fail the check.
+ var notesBadAddress = false
var hasVoices: Bool { voiceModel != nil && voiceBase != nil }
/// The meeting is recognized by the custom service instead of on this Mac.
var transcribes: Bool { provider.id == .custom && hearModel != nil && hearBase != nil }
+ /// Notes go somewhere translation doesn't: they get their own check, result and start gate.
+ var notesApart: Bool { provider.id == .custom && (notesModel != nil || notesBase != nil || notesOwnService) }
+
+ /// What a notes call is sent with: notes' model at notes' address, the rest as translation.
+ var forNotes: AIConfig {
+ guard notesApart else { return self }
+ var c = self
+ if let notesModel { c.textModel = notesModel }
+ if let notesBase { c.base = notesBase }
+ return c
+ }
+
/// The voices the room can pick from with this service.
var voices: [CloudVoice] {
guard hasVoices else { return [] }
diff --git a/Sources/Cicada/AISettings.swift b/Sources/Cicada/AISettings.swift
index 8c44e7e..4e99dcb 100644
--- a/Sources/Cicada/AISettings.swift
+++ b/Sources/Cicada/AISettings.swift
@@ -12,6 +12,8 @@ struct AISettingsView: View {
@State private var editing = false
@State private var baseDraft = ""
@State private var textDraft = ""
+ @State private var notesKeyDraft = ""
+ @State private var editingNotesKey = false
/// A pasted key that belongs elsewhere: what it is, and (for another service's key) where it fits.
@State private var keyHint: (text: String, service: AIProvider.Kind?, key: String)?
@@ -143,24 +145,40 @@ struct AISettingsView: View {
private var customHosts: String {
let c = settings.aiConfig
var hosts = [c.base?.host]
+ if c.notesApart { hosts.append(c.forNotes.base?.host) }
if c.hasVoices { hosts.append(c.voiceBase?.host) }
if c.transcribes { hosts.append(c.hearBase?.host) }
- let set = Set(hosts.compactMap { $0 })
- return set.count == 1 ? set.first! : L("你填的地址")
+ var seen: [String] = []
+ for h in hosts.compactMap({ $0 }) where !seen.contains(h) { seen.append(h) }
+ if seen.count == 2 { return L("\(seen[0]) 和 \(seen[1])") }
+ return seen.count == 1 ? seen[0] : L("你填的地址")
}
private var textHost: String { AIProvider.customBase(baseDraft)?.host ?? settings.aiConfig.base?.host ?? "" }
+ /// "192.168.1.20 · qwen-mt-turbo", then the notes' model, or their own server after a bar.
+ private var textDetail: String {
+ let c = settings.aiConfig
+ let model = settings.aiModels["custom"] ?? ""
+ if textHost.isEmpty || model.isEmpty { return L("填上地址和模型") }
+ let line = "\(textHost) · \(model)"
+ guard c.notesApart else { return line }
+ let n = c.forNotes
+ if let host = n.base?.host, n.base != c.base { return line + " | \(host) · \(n.textModel)" }
+ return n.textModel == model ? line : line + " · \(n.textModel)"
+ }
+
@ViewBuilder private var textSection: some View {
let check = ling.aiCheck
- let model = settings.aiModels["custom"] ?? ""
- let detail = textHost.isEmpty || model.isEmpty ? L("填上地址和模型") : "\(textHost) · \(model)"
+ let notesDown = check.failure == nil && check.notesFailed
let trailing: String? = check.running ? L("正在检查…") : check.failure != nil && ling.hasKey ? statusTitle
+ : notesDown ? L("纪要写不了")
: check.translate.map { L("翻一句 \(String(format: "%.1f", $0.seconds)) 秒") }
- sectionHeader("text", title: L("翻译和纪要"), detail: detail, dot: customTextDot, trailing: trailing,
- trailingColor: check.slow ? Palette.warn : check.failure != nil ? Palette.error : Palette.tertiary)
+ sectionHeader("text", title: L("翻译和纪要"), detail: textDetail, dot: customTextDot, trailing: trailing,
+ trailingColor: check.failure != nil || notesDown ? Palette.error : check.slow ? Palette.warn : Palette.tertiary)
if open.contains("text") {
VStack(alignment: .leading, spacing: 8) {
+ groupTitle(L("翻译"))
field(L("地址"), "http://192.168.1.20:8000/v1", $baseDraft)
if !baseDraft.isEmpty, AIProvider.customBase(baseDraft) == nil {
Text("地址要用 https;这台 Mac 和局域网里的服务可以用 http。").font(.system(size: 11)).foregroundStyle(Palette.error)
@@ -169,30 +187,9 @@ struct AISettingsView: View {
localNetworkNote(baseDraft)
}
HStack(spacing: 8) {
- Text("模型").font(.system(size: 12)).foregroundStyle(Palette.secondary).frame(minWidth: 34, alignment: .leading).fixedSize()
- if ling.catalog.isEmpty {
- TextField(L("例如 qwen3:14b"), text: $textDraft)
- .textFieldStyle(.plain).font(.system(size: 13, design: .monospaced))
- .padding(.horizontal, 12).frame(height: 32)
- .background(RoundedRectangle(cornerRadius: 9).fill(Color.white))
- .overlay(RoundedRectangle(cornerRadius: 9).stroke(Palette.line, lineWidth: 1))
- .onSubmit(save)
- } else {
- // The models the service lists: picking one saves and checks it.
- ModelMenu(value: textDraft, recommended: [], catalog: ling.catalog) {
- textDraft = $0
- save()
- }
- Spacer()
- }
- }
- HStack(spacing: 8) {
- Text("key").font(.system(size: 12)).foregroundStyle(Palette.secondary).frame(minWidth: 34, alignment: .leading).fixedSize()
+ fieldLabel("key")
if let key = ling.key, !key.isEmpty, !editing {
- Text(AIKey.masked(key)).font(.system(size: 13, design: .monospaced)).foregroundStyle(Palette.ink)
- .padding(.horizontal, 12).frame(maxWidth: .infinity, minHeight: 32, alignment: .leading)
- .background(RoundedRectangle(cornerRadius: 9).fill(Color.white))
- .overlay(RoundedRectangle(cornerRadius: 9).stroke(Palette.line, lineWidth: 1))
+ maskedKey(key)
SoftButton(L("更换")) { draft = ""; editing = true }
} else {
SecureField(keyPlaceholder, text: $draft)
@@ -202,12 +199,26 @@ struct AISettingsView: View {
.overlay(RoundedRectangle(cornerRadius: 9).stroke(Palette.line, lineWidth: 1))
.onSubmit(save)
}
- SoftButton(check.running ? L("正在检查…") : L("保存并检查"), dark: true, action: save)
- .disabled(check.running)
}
if let hint = keyHint {
Text(hint.text).font(.system(size: 12)).foregroundStyle(Palette.error).fixedSize(horizontal: false, vertical: true)
}
+ HStack(spacing: 8) {
+ fieldLabel(L("模型"))
+ // The models the service lists; a name it doesn't list can be typed. Picking saves and checks.
+ ModelPicker(value: textDraft, placeholder: L("例如 qwen3:14b"), catalog: ling.catalog, host: textHost,
+ refetch: { Task { await ling.fetchCatalog() } }) {
+ textDraft = $0
+ save()
+ }
+ }
+ Divider().padding(.vertical, 4)
+ notesGroup
+ HStack {
+ Spacer()
+ SoftButton(check.running ? L("正在检查…") : L("保存并检查"), dark: true, action: save)
+ .disabled(check.running)
+ }
if let slow = check.slowLine(googleOff: settings.aiCustomOnly) {
Text(slow).font(.system(size: 12)).foregroundStyle(Palette.warn).fixedSize(horizontal: false, vertical: true)
}
@@ -216,6 +227,8 @@ struct AISettingsView: View {
.padding(.horizontal, 12).padding(.vertical, 2)
.background(RoundedRectangle(cornerRadius: 10).fill(Color.white))
.overlay(RoundedRectangle(cornerRadius: 10).stroke(Palette.line, lineWidth: 1))
+ } else if check.passed, settings.aiConfig.notesApart, let t = check.translate {
+ checkRows(t)
} else if check.passed {
Text(textFacts).font(.system(size: 11)).foregroundStyle(Palette.tertiary)
}
@@ -224,6 +237,118 @@ struct AISettingsView: View {
}
}
+ /// 纪要: the same service as translation (another model at most), or another one with its own
+ /// address and key. Switching back keeps what was typed.
+ @ViewBuilder private var notesGroup: some View {
+ let c = settings.aiConfig
+ let own = settings.aiCustomNotesOwn
+ let notesHost = c.forNotes.base?.host ?? textHost
+ // "给它单独填一个" only where a key of its own can be given (另一个服务).
+ let shared = own && !ling.notesHasOwnKey
+ HStack {
+ groupTitle(L("纪要"))
+ Spacer()
+ Segments(options: [("same", L("同一个服务")), ("own", L("另一个服务"))], value: own ? "own" : "same") {
+ settings.aiCustomNotesOwn = $0 == "own"
+ model.applyAIService()
+ }
+ }
+ if own {
+ CommitField(label: L("地址"), placeholder: L("跟上面一样"), value: settings.aiCustomNotesBase) {
+ settings.aiCustomNotesBase = $0
+ model.applyAIService()
+ }
+ if c.notesBadAddress {
+ Text("地址要用 https;这台 Mac 和局域网里的服务可以用 http。").font(.system(size: 11)).foregroundStyle(Palette.error)
+ .padding(.leading, 42)
+ } else {
+ localNetworkNote(settings.aiCustomNotesBase)
+ }
+ HStack(spacing: 8) {
+ fieldLabel("key")
+ if let key = ling.notesKey, ling.notesHasOwnKey, !key.isEmpty, !editingNotesKey {
+ maskedKey(key)
+ SoftButton(L("更换")) { notesKeyDraft = ""; editingNotesKey = true }
+ SoftButton(L("移除")) { ling.removeNotesKey() }
+ } else {
+ SecureField(L("不填就用上面的 key"), text: $notesKeyDraft)
+ .textFieldStyle(.plain).font(.system(size: 13, design: .monospaced))
+ .padding(.horizontal, 12).frame(height: 30)
+ .background(RoundedRectangle(cornerRadius: 9).fill(Color.white))
+ .overlay(RoundedRectangle(cornerRadius: 9).stroke(
+ ling.aiCheck.notes?.reason == .invalidKey ? Palette.error : Palette.line, lineWidth: 1))
+ .onSubmit(save)
+ }
+ }
+ }
+ HStack(spacing: 8) {
+ fieldLabel(L("模型"))
+ ModelPicker(value: settings.aiModels["custom.notes"] ?? "", placeholder: L("和翻译模型一样"),
+ sameLabel: L("和翻译模型一样"),
+ catalog: c.forNotes.base != c.base ? ling.notesCatalog : ling.catalog, host: notesHost,
+ refetch: { Task { c.forNotes.base != c.base ? await ling.fetchNotesCatalog() : await ling.fetchCatalog() } }) {
+ settings.aiModels["custom.notes"] = $0
+ model.applyAIService()
+ }
+ }
+ if let line = ling.aiCheck.notesLine(host: notesHost, model: c.forNotes.textModel, sharedKey: shared) {
+ Text(line).font(.system(size: 12)).foregroundStyle(Palette.error)
+ .fixedSize(horizontal: false, vertical: true).padding(.leading, 42)
+ } else {
+ Text("用来写实时纪要、识别说话人,默认和翻译用同一个").font(.system(size: 11)).foregroundStyle(Palette.tertiary)
+ .fixedSize(horizontal: false, vertical: true).padding(.leading, 42)
+ }
+ }
+
+ /// After a check with notes apart: one row each, what it runs and how it did.
+ private func checkRows(_ t: AICheck.Speed) -> some View {
+ let c = settings.aiConfig
+ let notes = ling.aiCheck.notes
+ let notesText: String = switch notes {
+ case .ok(let s)?: L("能写纪要 · \(String(format: "%.1f", s)) 秒")
+ case .fail(.invalidKey, _)?, .fail(.mgmtKey, _)?: L("key 不对")
+ case .fail(.noJSON, _)?: L("纪要写不了")
+ case .fail?: L("纪要写不了")
+ case .running?: L("正在检查…")
+ case nil: ""
+ }
+ return VStack(spacing: 0) {
+ checkRow(L("翻译"), c.textModel, ok: true,
+ L("翻一句 \(String(format: "%.1f", t.seconds)) 秒") + " · " + (t.thinks ? L("会先思考") : L("不思考")))
+ Divider()
+ checkRow(L("纪要"), c.forNotes.textModel, ok: notes?.reason == nil, notesText)
+ }
+ .padding(.horizontal, 12)
+ .background(RoundedRectangle(cornerRadius: 10).fill(Color.white))
+ .overlay(RoundedRectangle(cornerRadius: 10).stroke(Palette.line, lineWidth: 1))
+ }
+
+ private func checkRow(_ use: String, _ model: String, ok: Bool, _ result: String) -> some View {
+ HStack(spacing: 10) {
+ Circle().fill(ok ? Palette.ok : Palette.error).frame(width: 6, height: 6)
+ Text(use).font(.system(size: 12)).foregroundStyle(Palette.ink).frame(minWidth: 34, alignment: .leading).fixedSize()
+ Text(model).font(.system(size: 12, design: .monospaced)).foregroundStyle(Palette.secondary).lineLimit(1).truncationMode(.middle)
+ Spacer(minLength: 8)
+ Text(result).font(.system(size: 12).monospacedDigit()).foregroundStyle(ok ? Palette.ok : Palette.error).lineLimit(1).fixedSize()
+ }
+ .frame(minHeight: 36)
+ }
+
+ private func groupTitle(_ text: String) -> some View {
+ Text(text).font(.system(size: 12, weight: .semibold)).foregroundStyle(Palette.ink).frame(height: 22)
+ }
+
+ private func fieldLabel(_ text: String) -> some View {
+ Text(text).font(.system(size: 12)).foregroundStyle(Palette.secondary).frame(minWidth: 34, alignment: .leading).fixedSize()
+ }
+
+ private func maskedKey(_ key: String) -> some View {
+ Text(AIKey.masked(key)).font(.system(size: 13, design: .monospaced)).foregroundStyle(Palette.ink)
+ .padding(.horizontal, 12).frame(maxWidth: .infinity, minHeight: 32, alignment: .leading)
+ .background(RoundedRectangle(cornerRadius: 9).fill(Color.white))
+ .overlay(RoundedRectangle(cornerRadius: 9).stroke(Palette.line, lineWidth: 1))
+ }
+
private var model_: AppModel { model }
/// "能写纪要 · 不思考": what the check proved beyond the speed.
@@ -238,7 +363,7 @@ struct AISettingsView: View {
if !ling.hasKey { return Color(white: 0.75) }
if check.running { return Palette.accent }
if check.failure != nil { return Palette.error }
- if check.slow || check.busy { return Palette.warn }
+ if check.slow || check.busy || check.notesFailed { return Palette.warn }
return check.passed ? Palette.ok : Color(white: 0.75)
}
@@ -477,17 +602,37 @@ struct AISettingsView: View {
}
private var lockLine: String {
- let host = provider.id == .custom ? (settings.aiConfig.base?.host ?? L("你填的地址")) : (provider.base?.host ?? "")
+ let host = provider.id == .custom ? keyHosts : (provider.base?.host ?? "")
return provider.id == .custom ? L("key 只存在这台 Mac 上(只有你的账户能读),只发给 \(host)")
: L("只存在这台 Mac 上(只有你的账户能读),只发给 \(name)(\(host))")
}
+ /// Where the custom service's key is sent: every use's address, the notes' only while they share it.
+ private var keyHosts: String {
+ let c = settings.aiConfig
+ var hosts = [c.base?.host]
+ if c.notesApart, !ling.notesHasOwnKey { hosts.append(c.forNotes.base?.host) }
+ if c.hasVoices { hosts.append(c.voiceBase?.host) }
+ if c.transcribes { hosts.append(c.hearBase?.host) }
+ var seen: [String] = []
+ for h in hosts.compactMap({ $0 }) where !seen.contains(h) { seen.append(h) }
+ if seen.count == 2 { return L("\(seen[0]) 和 \(seen[1])") }
+ return seen.count == 1 ? seen[0] : L("你填的地址")
+ }
+
/// Saves what was typed (a custom service's address and model too), then checks.
private func save() {
if provider.id == .custom {
settings.aiCustomBase = baseDraft.trimmingCharacters(in: .whitespaces)
settings.aiModels["custom"] = textDraft.trimmingCharacters(in: .whitespaces)
model.applyAIService()
+ // Notes' own key (另一个服务): saved here too; it goes only to the notes' address.
+ let nk = notesKeyDraft.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !nk.isEmpty, settings.aiCustomNotesOwn {
+ notesKeyDraft = ""
+ editingNotesKey = false
+ Task { await ling.setNotesKey(nk) }
+ }
}
let k = draft.trimmingCharacters(in: .whitespacesAndNewlines)
keyHint = nil
@@ -769,6 +914,130 @@ struct ModelMenu: View {
}
}
+/// A custom service's model: the names its `/models` lists, searchable, and any name typed that it
+/// doesn't list (an alias, a model it hides). Without a list it is a plain field.
+struct ModelPicker: View {
+ let value: String
+ let placeholder: String
+ /// A first choice that clears the value ("和翻译模型一样"); nil: none.
+ var sameLabel: String? = nil
+ let catalog: [String]
+ /// The address the list came from, for the line under it.
+ let host: String
+ let refetch: () -> Void
+ let onPick: (String) -> Void
+ @State private var open = false
+ @State private var query = ""
+ @State private var typed = ""
+ @FocusState private var focused: Bool
+
+ var body: some View {
+ if catalog.isEmpty {
+ HStack(spacing: 8) {
+ TextField(sameLabel ?? placeholder, text: $typed)
+ .textFieldStyle(.plain).font(.system(size: 13, design: .monospaced))
+ .padding(.horizontal, 12).frame(height: 32)
+ .background(RoundedRectangle(cornerRadius: 9).fill(Color.white))
+ .overlay(RoundedRectangle(cornerRadius: 9).stroke(Palette.line, lineWidth: 1))
+ .focused($focused)
+ .onSubmit(commitTyped)
+ .onChange(of: focused) { _, now in if !now { commitTyped() } }
+ .help(L("这个地址没列出模型,直接填名字"))
+ if !host.isEmpty { SoftButton(L("重新获取"), action: refetch) }
+ }
+ .onAppear { typed = value }
+ .onChange(of: value) { _, v in typed = v }
+ } else {
+ Button { query = ""; open = true } label: {
+ HStack(spacing: 6) {
+ Text(value.isEmpty ? (sameLabel ?? L("选一个")) : value)
+ .font(value.isEmpty ? .system(size: 13) : .system(size: 13, design: .monospaced))
+ .foregroundStyle(value.isEmpty ? Palette.secondary : Palette.ink).lineLimit(1).truncationMode(.middle)
+ Spacer(minLength: 6)
+ Image(systemName: "chevron.up.chevron.down").font(.system(size: 9, weight: .semibold)).foregroundStyle(Palette.secondary)
+ }
+ .padding(.horizontal, 12).frame(maxWidth: .infinity, minHeight: 32)
+ .background(RoundedRectangle(cornerRadius: 9).fill(Color.white))
+ .overlay(RoundedRectangle(cornerRadius: 9).stroke(open ? Palette.ink : Palette.line, lineWidth: 1))
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .popover(isPresented: $open, arrowEdge: .bottom) { list }
+ }
+ }
+
+ private var matches: [String] {
+ let q = query.trimmingCharacters(in: .whitespaces)
+ return q.isEmpty ? catalog : catalog.filter { $0.localizedCaseInsensitiveContains(q) }
+ }
+
+ private var list: some View {
+ let q = query.trimmingCharacters(in: .whitespaces)
+ return VStack(alignment: .leading, spacing: 0) {
+ HStack(spacing: 6) {
+ Image(systemName: "magnifyingglass").font(.system(size: 11)).foregroundStyle(Palette.tertiary)
+ TextField(L("搜索或输入模型"), text: $query)
+ .textFieldStyle(.plain).font(.system(size: 12, design: .monospaced))
+ .onSubmit {
+ // Return: the only match, else exactly what was typed.
+ let m = matches
+ if m.count == 1 { pick(m[0]) } else if !q.isEmpty { pick(q) }
+ }
+ }
+ .padding(.horizontal, 10).frame(height: 32)
+ Divider()
+ ScrollView {
+ VStack(alignment: .leading, spacing: 0) {
+ if !q.isEmpty, !catalog.contains(q) {
+ row(L("用 \(q)(列表里没有)"), selected: false, mono: false) { pick(q) }
+ Divider().padding(.vertical, 4)
+ }
+ if let sameLabel, q.isEmpty {
+ row(sameLabel, selected: value.isEmpty, mono: false) { pick("") }
+ Divider().padding(.vertical, 4)
+ }
+ ForEach(matches, id: \.self) { id in row(id, selected: id == value, mono: true) { pick(id) } }
+ }
+ .padding(4)
+ }
+ .frame(maxHeight: 280)
+ Divider()
+ HStack {
+ Text(L("\(host) 列出 \(catalog.count) 个模型")).font(.system(size: 11)).foregroundStyle(Palette.tertiary)
+ Spacer()
+ Button(L("重新获取"), action: refetch).buttonStyle(.plain).font(.system(size: 11)).foregroundStyle(Palette.link)
+ }
+ .padding(.horizontal, 10).frame(height: 28)
+ }
+ .frame(width: 320)
+ }
+
+ private func row(_ text: String, selected: Bool, mono: Bool, action: @escaping () -> Void) -> some View {
+ Button(action: action) {
+ HStack(spacing: 6) {
+ Image(systemName: "checkmark").font(.system(size: 10, weight: .semibold)).opacity(selected ? 1 : 0)
+ Text(text).font(mono ? .system(size: 12, design: .monospaced) : .system(size: 12)).lineLimit(1).truncationMode(.middle)
+ Spacer(minLength: 0)
+ }
+ .foregroundStyle(Palette.ink)
+ .padding(.horizontal, 8).frame(height: 26)
+ .background(RoundedRectangle(cornerRadius: 6).fill(selected ? Palette.fill : Color.clear))
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ }
+
+ private func pick(_ id: String) {
+ open = false
+ if id != value { onPick(id) }
+ }
+
+ private func commitTyped() {
+ let t = typed.trimmingCharacters(in: .whitespaces)
+ if t != value { onPick(t) }
+ }
+}
+
/// A labelled text field that saves on return or when it loses focus.
private struct CommitField: View {
let label: String
diff --git a/Sources/Cicada/Ling.swift b/Sources/Cicada/Ling.swift
index a7a7783..29313fe 100644
--- a/Sources/Cicada/Ling.swift
+++ b/Sources/Cicada/Ling.swift
@@ -212,6 +212,18 @@ final class LingClient: ObservableObject {
}
return AIKey.read(c.provider.id.rawValue)
}
+ /// The key notes are sent with: with 另一个服务, their own key file if there is one, else the
+ /// translation key ("不填就用上面的 key").
+ var notesKey: String? {
+ let c = config()
+ guard c.notesOwnService, !hideKey, let own = AIKey.read(Self.notesKeyName) else { return key }
+ return own
+ }
+ /// Notes have a key file of their own (另一个服务 only).
+ var notesHasOwnKey: Bool { config().notesOwnService && AIKey.read(Self.notesKeyName) != nil }
+ /// The key file of the custom service's notes server.
+ static let notesKeyName = "custom-notes"
+
/// The key is known to work (or at least not known to be bad): notes and translation.
var usable: Bool { hasKey && keyState != .invalid }
/// Voices in the room from this service (else the Mac's).
@@ -222,8 +234,10 @@ final class LingClient: ObservableObject {
var hearsAudio: Bool { usable && provider.hearsAudio }
/// The meeting recognized by the custom service's speech model instead of on this Mac.
var transcribes: Bool { usable && config().transcribes }
- /// The custom service refused `chat_template_kwargs` once: leave it out until settings change.
- private var noTemplateKwargs = false
+ /// Which servers refused `chat_template_kwargs` once (by host): leave it out there until settings change.
+ private var noTemplateKwargs: Set<String> = []
+ /// Notes' own server's text models from its `/models` (empty while notes share translation's address).
+ @Published private(set) var notesCatalog: [String] = []
init() {
keyState = AIKey.read() == nil ? .none : .unchecked
@@ -232,10 +246,11 @@ final class LingClient: ObservableObject {
/// Settings switched service, address or model: forget the old state and check again.
func reconfigure() {
settingsGeneration += 1
- noTemplateKwargs = false
+ noTemplateKwargs = []
recheck?.cancel()
catalog = []
listed = nil
+ notesCatalog = []
aiCheck = AICheck()
lastVoice = nil
keyState = hasKey ? .unchecked : .none
@@ -265,6 +280,20 @@ final class LingClient: ObservableObject {
await check()
}
+ /// Notes' own key (另一个服务): saved, then everything checked again.
+ func setNotesKey(_ raw: String) async {
+ let k = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !k.isEmpty, !hideKey else { return }
+ AIKey.save(k, Self.notesKeyName)
+ await check()
+ }
+
+ /// Notes go back to the translation key.
+ func removeNotesKey() {
+ AIKey.remove(Self.notesKeyName)
+ Task { await check() }
+ }
+
func removeKey() {
AIKey.remove(provider.id.rawValue)
catalog = []
@@ -332,22 +361,19 @@ final class LingClient: ObservableObject {
var body: [String: Any] = ["model": c.textModel, "messages": [
["role": "system", "content": "Translate the text into Simplified Chinese. Reply with the translation only.\n\nWe will ship the new version on Friday after the design review."],
["role": "user", "content": "Translate."]]]
- c.shape(&body, maxTokens: 120, templateKwargs: !noTemplateKwargs)
+ c.shape(&body, maxTokens: 120, templateKwargs: !noTemplateKwargs.contains(Self.server(c.base)))
let asked = Date()
- let root = try await postChat(body, key: key, timeout: 30)
+ let root = try await postChat(body, base: c.base, key: key, timeout: 30)
let seconds = Date().timeIntervalSince(asked)
r.pass(upTo: .text, seconds: Date().timeIntervalSince(started))
r.translate = AICheck.Speed(seconds: seconds, thinks: AIConfig.thought(root))
- var json: [String: Any] = ["model": c.textModel, "response_format": ["type": "json_object"],
- "messages": [["role": "system", "content": "Reply with the JSON object {\"ok\": true}."],
- ["role": "user", "content": "Reply."]]]
- c.shape(&json, maxTokens: 20, templateKwargs: !noTemplateKwargs)
- do { _ = try await postChat(json, key: key, timeout: 30) } catch Failure.http(let code) {
- // JSON mode refused (some hosts of a model do): meetings then ask without it, so
- // what counts is whether the model still answers with a JSON object.
- json["response_format"] = nil
- let plain = try? await postChat(json, key: key, timeout: 30)
- if !Self.answersJSON(plain) { r.fail(.text, .noJSON, code: code) }
+ if c.notesApart {
+ // Notes at their own model or server: their failure is theirs, translation goes on.
+ r.notes = .running
+ if generation == checkGeneration { aiCheck = r }
+ r.notes = await checkNotes(c)
+ } else if let code = try await jsonRefused(c, key: key) {
+ r.fail(.text, .noJSON, code: code)
}
if r.failure == nil, c.transcribes {
r.hear = await checkHearing(c, key: key)
@@ -363,14 +389,63 @@ final class LingClient: ObservableObject {
}
if r.failure == nil, c.provider.id != .ling {
await fetchCatalog()
- // A model the service no longer lists fails here, before a meeting finds out.
- if let listed, !c.textModel.isEmpty {
- if !listed.contains(c.textModel) { r.fail(.text, .noModel) } else if r[.text] == .untested { r[.text] = .ok(seconds: nil) }
+ // A model the service no longer lists fails here, before a meeting finds out. One a real
+ // sentence just went through exists whatever the list says (an alias, a name typed by hand).
+ if let listed, !c.textModel.isEmpty, r[.text] == .untested {
+ if !listed.contains(c.textModel) { r.fail(.text, .noModel) } else { r[.text] = .ok(seconds: nil) }
}
}
await finishCheck(r, c, generation)
}
+ /// A JSON request the way notes ask; the HTTP code when the model can't answer one, else nil.
+ private func jsonRefused(_ c: AIConfig, key: String) async throws -> Int? {
+ let host = Self.server(c.base)
+ var json: [String: Any] = ["model": c.textModel, "response_format": ["type": "json_object"],
+ "messages": [["role": "system", "content": "Reply with the JSON object {\"ok\": true}."],
+ ["role": "user", "content": "Reply."]]]
+ c.shape(&json, maxTokens: 20, templateKwargs: !noTemplateKwargs.contains(host))
+ do { _ = try await postChat(json, base: c.base, key: key, timeout: 30) } catch Failure.http(let code) {
+ // JSON mode refused (some hosts of a model do): meetings then ask without it, so
+ // what counts is whether the model still answers with a JSON object.
+ json["response_format"] = nil
+ let plain = try? await postChat(json, base: c.base, key: key, timeout: 30)
+ if !Self.answersJSON(plain) { return code }
+ }
+ return nil
+ }
+
+ /// Notes' own model or server: one JSON request the way a meeting's notes ask, then (another
+ /// address) its model list for the menu.
+ private func checkNotes(_ config: AIConfig) async -> AICheck.Notes {
+ if config.notesBadAddress { return .fail(.badAddress) }
+ let c = config.forNotes
+ guard let key = notesKey, let base = c.base else { return .fail(.invalidKey) }
+ let host = Self.server(base)
+ var json: [String: Any] = ["model": c.textModel, "response_format": ["type": "json_object"],
+ "messages": [["role": "system", "content": "Reply with the JSON object {\"ok\": true}."],
+ ["role": "user", "content": "Reply."]]]
+ c.shape(&json, maxTokens: 20, templateKwargs: !noTemplateKwargs.contains(host))
+ let asked = Date()
+ let result: AICheck.Notes
+ do {
+ _ = try await postChat(json, base: base, key: key, timeout: 60, notes: true)
+ result = .ok(seconds: Date().timeIntervalSince(asked))
+ } catch Failure.http(let code) where code == 400 || code == 422 {
+ json["response_format"] = nil
+ let plain = try? await postChat(json, base: base, key: key, timeout: 60, notes: true)
+ result = Self.answersJSON(plain) ? .ok(seconds: Date().timeIntervalSince(asked)) : .fail(.noJSON, code: code)
+ } catch let failure as Failure {
+ // A reply that isn't a chat completion (parse, a search-style answer): no notes from it.
+ let (_, reason, code) = AICheck.classify(failure, at: .text) ?? (.text, .noJSON, nil)
+ result = .fail(reason, code: code)
+ } catch {
+ result = .fail(.unreachable)
+ }
+ if c.base != config.base { await fetchNotesCatalog() }
+ return result
+ }
+
/// Bumped by every check: a slower, older check (a model changed twice quickly) must not
/// land after the newer one and overwrite it.
private var checkGeneration = 0
@@ -428,9 +503,23 @@ final class LingClient: ObservableObject {
/// A real request (notes, translation) came back: keep the steps current without a check.
/// One server error in a meeting isn't worth repainting the settings for.
- private func observe(_ failure: Failure?, seconds: Double = 0, audio: Bool = false, generation: Int) {
+ private func observe(_ failure: Failure?, seconds: Double = 0, audio: Bool = false, notes: Bool = false, generation: Int) {
// Sent before the service, address or model changed (a meeting's last notes, say): not this one's.
guard hasKey, !aiCheck.running, simulateCheck == nil, generation == settingsGeneration else { return }
+ if notes {
+ // Notes at their own model or server: theirs alone, translation's steps are untouched.
+ let now: AICheck.Notes
+ if let failure {
+ guard let (_, reason, code) = AICheck.classify(failure, at: .text), reason != .serverError else { return }
+ now = .fail(reason, code: code)
+ } else {
+ now = .ok(seconds: seconds)
+ }
+ if aiCheck.notes?.ok == true, now.ok { return }
+ aiCheck.notes = now
+ debugLog("ai: notes from a real request → \(now)")
+ return
+ }
var r = aiCheck
if let failure {
guard let (step, reason, code) = AICheck.classify(failure, at: .text), reason != .serverError else { return }
@@ -484,10 +573,20 @@ final class LingClient: ObservableObject {
Task { await check() }
}
+ /// Notes' own address's text models, for its menu. Quietly empty when it has no `/models`.
+ func fetchNotesCatalog() async {
+ let c = config()
+ let base = c.forNotes.base
+ guard c.notesApart, base != c.base, let key = notesKey,
+ let data = try? await getData("models", base: base, key: key, notes: true) else { return }
+ notesCatalog = AIConfig.textModels(fromCatalog: data, recommended: [])
+ debugLog("ai notes: \(notesCatalog.count) models")
+ }
+
/// The service's text models, for the model menu. Quietly empty when it has no `/models`.
func fetchCatalog() async {
let c = config()
- guard let key, c.provider.id != .ling, let data = try? await getData("models", key: key) else { return }
+ guard let key, c.provider.id != .ling, let data = try? await getData("models", base: c.base, key: key) else { return }
catalog = AIConfig.textModels(fromCatalog: data, recommended: c.provider.textModels.map(\.id))
listed = AICheck.listedModels(data)
debugLog("ai \(c.provider.id.rawValue): \(catalog.count) models")
@@ -503,13 +602,23 @@ final class LingClient: ObservableObject {
func chat(content: String, instruction: String, priority: Priority, json: Bool = false,
maxTokens: Int = 1024, timeout: TimeInterval = 30, model: String? = nil, audio: Data? = nil,
role: String? = nil, patient: Bool = false, onQueued: ((Double) -> Void)? = nil) async throws -> String {
- guard let key else { throw Failure.noKey }
- guard keyState != .invalid else { throw Failure.invalidKey }
+ let all = config()
+ // Notes (实时纪要, 说话人, a file's corrections) go to their own model or server when set.
+ let notesSide = priority == .notes && all.notesApart
+ // 另一个服务 with an address that can't be used: never hand the notes' key to translation's server.
+ if notesSide && all.notesBadAddress { throw Failure.noKey }
+ let c = notesSide ? all.forNotes : all
+ guard let key = notesSide ? notesKey : key else { throw Failure.noKey }
+ // A key known to be refused isn't sent again: the notes' own, or translation's when they share it.
+ let refused = notesSide ? aiCheck.notes?.reason == .invalidKey || (!notesHasOwnKey && keyState == .invalid)
+ : keyState == .invalid
+ guard !refused else { throw Failure.invalidKey }
if let simulate {
if simulate == .rateLimited { rateLimitedAt = Date() }
throw simulate
}
- let c = config()
+ let host = Self.server(c.base)
+ let gate = gate(c.base)
let generation = settingsGeneration
let call = CallLabel(provider: c.provider.id.rawValue, model: model ?? c.textModel,
role: role ?? (priority == .notes ? "notes" : "translate"))
@@ -524,28 +633,28 @@ final class LingClient: ObservableObject {
],
"stream": false,
]
- c.shape(&body, maxTokens: maxTokens, templateKwargs: !noTemplateKwargs)
+ c.shape(&body, maxTokens: maxTokens, templateKwargs: !noTemplateKwargs.contains(host))
if json { body["response_format"] = ["type": "json_object"] }
let waits = Self.retryWaits(priority, audio: audio != nil, patient: patient)
var ticket: Int?
for attempt in 1...(waits.count + 1) {
// One that wouldn't retry fails at once while the service is cooling down: its caller falls back.
- if waits.isEmpty && pausedUntil > Date() { throw Failure.rateLimited }
+ if waits.isEmpty && gate.pausedUntil > Date() { throw Failure.rateLimited }
let asked = Date()
- ticket = await acquire(priority, ticket: ticket)
+ ticket = await acquire(priority, ticket: ticket, gate: gate)
let queued = Date().timeIntervalSince(asked)
onQueued?(queued)
let started = Date()
do {
let root: [String: Any]
do {
- root = try await postChat(body, key: key, timeout: timeout)
+ root = try await postChat(body, base: c.base, key: key, timeout: timeout, notes: notesSide)
} catch Failure.http(400) where body["response_format"] != nil {
// Some hosts of a model refuse JSON mode (on OpenRouter, Novita for Ling 3.1 Flash)
// while the model answers JSON anyway: the prompt asks for it, the parsers find it.
debugLog("ling: \(priority) JSON mode refused (400), asking again without it")
body["response_format"] = nil
- root = try await postChat(body, key: key, timeout: timeout)
+ root = try await postChat(body, base: c.base, key: key, timeout: timeout, notes: notesSide)
}
guard let choice = (root["choices"] as? [[String: Any]])?.first,
let message = choice["message"] as? [String: Any],
@@ -563,13 +672,13 @@ final class LingClient: ObservableObject {
report(call, priority, at: started, queued: queued, outcome: "ok",
tokens: (usage?["prompt_tokens"] as? Int ?? 0, usage?["completion_tokens"] as? Int ?? 0))
if rateLimitedAt != nil { rateLimitedAt = nil }
- observe(nil, seconds: Double(ms) / 1000, audio: audio != nil, generation: generation)
+ observe(nil, seconds: Double(ms) / 1000, audio: audio != nil, notes: notesSide, generation: generation)
return trimmed
} catch let failure as Failure {
report(call, priority, at: started, queued: queued, outcome: Self.name(failure))
- observe(failure, audio: audio != nil, generation: generation)
+ observe(failure, audio: audio != nil, notes: notesSide, generation: generation)
guard failure == .rateLimited else { throw failure }
- let wait = rateLimited(waits.isEmpty ? 1 : waits[min(attempt, waits.count) - 1], retryAfter: lastRetryAfter)
+ let wait = rateLimited(waits.isEmpty ? 1 : waits[min(attempt, waits.count) - 1], retryAfter: lastRetryAfter, gate: gate)
guard attempt <= waits.count, let wait else {
rateLimitedAt = Date()
throw failure
@@ -615,9 +724,9 @@ final class LingClient: ObservableObject {
/// (Retry-After; Ling sends none), plus a little jitter. The queue waits at the gate instead of
/// each request spending its retries on the same limit. nil when the service asks for longer
/// than `maxPause`: that is an outage (the gate still holds for `maxPause`).
- private func rateLimited(_ backoff: Double, retryAfter: Double?) -> Double? {
+ private func rateLimited(_ backoff: Double, retryAfter: Double?, gate: StartGate) -> Double? {
let wait = max(backoff, retryAfter ?? 0) + Double.random(in: 0...0.5)
- pausedUntil = max(pausedUntil, Date().addingTimeInterval(min(wait, Self.maxPause)))
+ gate.pausedUntil = max(gate.pausedUntil, Date().addingTimeInterval(min(wait, Self.maxPause)))
return wait <= Self.maxPause ? wait : nil
}
@@ -786,7 +895,7 @@ final class LingClient: ObservableObject {
} catch let failure as Failure {
report(call, .translate, at: started, queued: queued, outcome: Self.name(failure))
// The server's limit is shared: the rest of the queue waits it out too.
- if failure == .rateLimited { _ = rateLimited(1, retryAfter: lastRetryAfter) }
+ if failure == .rateLimited { _ = rateLimited(1, retryAfter: lastRetryAfter, gate: gate()) }
throw failure
} catch {
report(call, .translate, at: started, queued: queued, outcome: "parse")
@@ -825,18 +934,19 @@ final class LingClient: ObservableObject {
/// A chat completion. A custom server that refuses `chat_template_kwargs` (a strict gateway
/// answers 400 or 422 to fields it doesn't know) is asked again without it, and isn't sent it
/// again until settings change.
- private func postChat(_ body: [String: Any], key: String, timeout: TimeInterval) async throws -> [String: Any] {
+ private func postChat(_ body: [String: Any], base: URL? = nil, key: String, timeout: TimeInterval,
+ notes: Bool = false) async throws -> [String: Any] {
do {
- return try await post("chat/completions", body: body, key: key, timeout: timeout)
+ return try await post("chat/completions", body: body, base: base, key: key, timeout: timeout, notes: notes)
} catch Failure.http(let code) where (code == 400 || code == 422) && body["chat_template_kwargs"] != nil {
// Only when the same request goes through without it: a 400 for something else (no
// JSON mode) must not turn thinking back on for every translation.
var plain = body
plain["chat_template_kwargs"] = nil
do {
- let root = try await post("chat/completions", body: plain, key: key, timeout: timeout)
+ let root = try await post("chat/completions", body: plain, base: base, key: key, timeout: timeout, notes: notes)
debugLog("ai custom: chat_template_kwargs refused (HTTP \(code)), sent without it from now on")
- noTemplateKwargs = true
+ noTemplateKwargs.insert(Self.server(base ?? config().base))
return root
} catch {
throw Failure.http(code)
@@ -844,13 +954,16 @@ final class LingClient: ObservableObject {
}
}
- private func post(_ path: String, body: [String: Any], key: String, timeout: TimeInterval) async throws -> [String: Any] {
- guard let base = config().base else { throw Failure.noKey }
+ /// `base`: another address than the service's (notes' own server); `notes`: a refused key is
+ /// the notes', not translation's.
+ private func post(_ path: String, body: [String: Any], base: URL? = nil, key: String, timeout: TimeInterval,
+ notes: Bool = false) async throws -> [String: Any] {
+ guard let base = base ?? config().base else { throw Failure.noKey }
var req = URLRequest(url: base.appendingPathComponent(path))
req.httpMethod = "POST"
req.timeoutInterval = timeout
req.httpBody = try JSONSerialization.data(withJSONObject: body)
- let data = try await send(req, key: key)
+ let data = try await send(req, key: key, notes: notes)
guard let root = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw Failure.parse }
return root
}
@@ -860,14 +973,15 @@ final class LingClient: ObservableObject {
return (try? JSONSerialization.jsonObject(with: data) as? [String: Any]) ?? [:]
}
- private func getData(_ path: String, key: String) async throws -> Data {
- guard let base = config().base else { throw Failure.noKey }
+ private func getData(_ path: String, base: URL? = nil, key: String, notes: Bool = false) async throws -> Data {
+ guard let base = base ?? config().base else { throw Failure.noKey }
var req = URLRequest(url: base.appendingPathComponent(path))
req.timeoutInterval = 15
- return try await send(req, key: key)
+ return try await send(req, key: key, notes: notes)
}
- private func send(_ request: URLRequest, key: String, contentType: String? = "application/json") async throws -> Data {
+ private func send(_ request: URLRequest, key: String, contentType: String? = "application/json",
+ notes: Bool = false) async throws -> Data {
var req = request
if !key.isEmpty { req.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization") }
if let contentType { req.setValue(contentType, forHTTPHeaderField: "Content-Type") }
@@ -885,7 +999,7 @@ final class LingClient: ObservableObject {
switch code {
case 200: return data
case 401, 403:
- if keyState != .invalid { keyState = .invalid }
+ if !notes, keyState != .invalid { keyState = .invalid }
throw Failure.invalidKey
case 429:
lastRetryAfter = Self.retryAfterSeconds((response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Retry-After"))
@@ -898,51 +1012,72 @@ final class LingClient: ObservableObject {
// MARK: Start gate
- private var lastStart = Date.distantPast
- private var waiting: [(priority: Priority, seq: Int, resume: CheckedContinuation<Void, Never>)] = []
+ /// One per server (by host): notes on another server don't wait behind translation, and its
+ /// 429 doesn't hold translation back.
+ private final class StartGate {
+ var lastStart = Date.distantPast
+ var waiting: [(priority: Priority, seq: Int, resume: CheckedContinuation<Void, Never>)] = []
+ var pumping = false
+ /// After a 429 no request starts here before this (`rateLimited`).
+ var pausedUntil = Date.distantPast
+ }
+ private var gates: [String: StartGate] = [:]
private var seq = 0
- private var pumping = false
- /// After a 429 no request starts before this (`rateLimited`).
- private var pausedUntil = Date.distantPast
/// The last 429's Retry-After in seconds, nil when it sent none (Ling doesn't). Read right
/// after the throw, with no suspension in between, so it is that request's.
private var lastRetryAfter: Double?
+ /// A server's identity for gates and refusals: host and port (two local servers differ by port).
+ private static func server(_ base: URL?) -> String {
+ guard let base, let host = base.host else { return "" }
+ return base.port.map { "\(host):\($0)" } ?? host
+ }
+
+ /// The gate of the server at `base` (nil: the service's own).
+ private func gate(_ base: URL? = nil) -> StartGate {
+ let host = Self.server(base ?? config().base)
+ if let g = gates[host] { return g }
+ let g = StartGate()
+ gates[host] = g
+ return g
+ }
+
/// Waits for this request's turn to start. `ticket` is a retry's first one, which keeps its
/// place ahead of requests queued after it. Returns the ticket.
@discardableResult
- private func acquire(_ priority: Priority, ticket: Int? = nil) async -> Int {
+ private func acquire(_ priority: Priority, ticket: Int? = nil, gate g: StartGate? = nil) async -> Int {
+ let gate = g ?? self.gate()
let n: Int
if let ticket { n = ticket } else { seq += 1; n = seq }
- if waiting.isEmpty && Date().timeIntervalSince(lastStart) >= provider.spacing && pausedUntil <= Date() {
- lastStart = Date()
+ if gate.waiting.isEmpty && Date().timeIntervalSince(gate.lastStart) >= provider.spacing && gate.pausedUntil <= Date() {
+ gate.lastStart = Date()
return n
}
await withCheckedContinuation { cont in
- waiting.append((priority, n, cont))
- pump()
+ gate.waiting.append((priority, n, cont))
+ pump(gate)
}
return n
}
- private func pump() {
- guard !pumping, !waiting.isEmpty else { return }
- pumping = true
+ private func pump(_ gate: StartGate) {
+ guard !gate.pumping, !gate.waiting.isEmpty else { return }
+ gate.pumping = true
let now = Date()
- let wait = max(0, provider.spacing - now.timeIntervalSince(lastStart), pausedUntil.timeIntervalSince(now))
+ let wait = max(0, provider.spacing - now.timeIntervalSince(gate.lastStart), gate.pausedUntil.timeIntervalSince(now))
DispatchQueue.main.asyncAfter(deadline: .now() + wait) { [weak self] in
MainActor.assumeIsolated {
guard let self else { return }
- self.pumping = false
+ gate.pumping = false
// A 429 came in while this one waited: wait out the pause first.
- if self.pausedUntil > Date() { self.pump(); return }
- guard let i = self.waiting.indices.min(by: {
- (self.waiting[$0].priority, self.waiting[$0].seq) < (self.waiting[$1].priority, self.waiting[$1].seq)
+ if gate.pausedUntil > Date() { self.pump(gate); return }
+ guard let i = gate.waiting.indices.min(by: {
+ (gate.waiting[$0].priority, gate.waiting[$0].seq) < (gate.waiting[$1].priority, gate.waiting[$1].seq)
}) else { return }
- let next = self.waiting.remove(at: i)
- self.lastStart = Date()
+ let next = gate.waiting.remove(at: i)
+ gate.lastStart = Date()
next.resume.resume()
- self.pump()
+ self.pump(gate)
}
}
}
diff --git a/Sources/Cicada/Settings.swift b/Sources/Cicada/Settings.swift
index 5095882..cd1d63b 100644
--- a/Sources/Cicada/Settings.swift
+++ b/Sources/Cicada/Settings.swift
@@ -136,6 +136,15 @@ final class AppSettings: ObservableObject {
@Published var aiCustomRecognize: Bool {
didSet { save() }
}
+ /// The custom service's notes: 另一个服务 (its own address, empty: the same one, and its own key
+ /// in the `custom-notes` key file). Off keeps the address, so switching back and forth loses
+ /// nothing. The notes model is `aiModels["custom.notes"]` (empty: the translation model).
+ @Published var aiCustomNotesOwn: Bool {
+ didSet { save() }
+ }
+ @Published var aiCustomNotesBase: String {
+ didSet { save() }
+ }
/// 语音和文字只发给你的服务: with the custom service, Google Translate is never asked (partial
/// lines show the original). Kept when another service is picked, but only acts on the custom one.
@Published var aiCustomOnly: Bool {
@@ -158,9 +167,16 @@ final class AppSettings: ObservableObject {
let hear = aiCustomHearModel.trimmingCharacters(in: .whitespaces)
let hearBase = aiCustomHearBase.isEmpty ? base : AIProvider.customBase(aiCustomHearBase)
let recognizes = aiCustomRecognize && !hear.isEmpty
- return AIConfig(provider: p, base: base, textModel: aiModels["custom"] ?? "", voiceModel: voice.isEmpty ? nil : voice,
+ let textModel = aiModels["custom"] ?? ""
+ let notesModel = (aiModels["custom.notes"] ?? "").trimmingCharacters(in: .whitespaces)
+ let notesAddress = aiCustomNotesOwn ? aiCustomNotesBase.trimmingCharacters(in: .whitespaces) : ""
+ let notesBase = notesAddress.isEmpty ? nil : AIProvider.customBase(notesAddress)
+ return AIConfig(provider: p, base: base, textModel: textModel, voiceModel: voice.isEmpty ? nil : voice,
voiceBase: voiceBase, customVoice: name.isEmpty ? nil : name,
- hearModel: recognizes ? hear : nil, hearBase: recognizes ? hearBase : nil)
+ hearModel: recognizes ? hear : nil, hearBase: recognizes ? hearBase : nil,
+ notesModel: notesModel.isEmpty || notesModel == textModel ? nil : notesModel,
+ notesBase: notesBase == base ? nil : notesBase, notesOwnService: aiCustomNotesOwn,
+ notesBadAddress: !notesAddress.isEmpty && notesBase == nil)
default:
return AIConfig(provider: p, base: p.base, textModel: aiModels[p.id.rawValue] ?? p.textModels.first?.id ?? "",
voiceModel: p.hasVoices ? aiVoiceModels[p.id.rawValue] ?? p.voiceModels.first?.id : nil, voiceBase: p.base)
@@ -271,6 +287,8 @@ final class AppSettings: ObservableObject {
aiCustomHearBase = defaults.string(forKey: "aiCustomHearBase") ?? ""
aiCustomRecognize = defaults.bool(forKey: "aiCustomRecognize")
aiCustomOnly = defaults.bool(forKey: "aiCustomOnly")
+ aiCustomNotesOwn = defaults.bool(forKey: "aiCustomNotesOwn")
+ aiCustomNotesBase = defaults.string(forKey: "aiCustomNotesBase") ?? ""
displayMode = defaults.string(forKey: "displayMode") ?? "notes"
speakVoices = defaults.dictionary(forKey: "speakVoices") as? [String: String] ?? [:]
endWithApp = defaults.object(forKey: "endWithApp") as? Bool ?? true
@@ -328,6 +346,8 @@ final class AppSettings: ObservableObject {
defaults.set(aiCustomHearBase, forKey: "aiCustomHearBase")
defaults.set(aiCustomRecognize, forKey: "aiCustomRecognize")
defaults.set(aiCustomOnly, forKey: "aiCustomOnly")
+ defaults.set(aiCustomNotesOwn, forKey: "aiCustomNotesOwn")
+ defaults.set(aiCustomNotesBase, forKey: "aiCustomNotesBase")
defaults.set(displayMode, forKey: "displayMode")
defaults.set(speakVoices, forKey: "speakVoices")
defaults.set(endWithApp, forKey: "endWithApp")
diff --git a/Tests/CicadaTests/LingTests.swift b/Tests/CicadaTests/LingTests.swift
index c58784a..83e6777 100644
--- a/Tests/CicadaTests/LingTests.swift
+++ b/Tests/CicadaTests/LingTests.swift
@@ -7,12 +7,14 @@ import Testing
final class LingStub: URLProtocol, @unchecked Sendable {
nonisolated(unsafe) static var reply: (Int, String) = (200, "")
nonisolated(unsafe) static var seen: [(at: Date, body: [String: Any])] = []
+ /// Where each request went and the key it carried, in order.
+ nonisolated(unsafe) static var sent: [(host: String, auth: String?)] = []
/// Answers each request by what it asked, instead of `reply`.
nonisolated(unsafe) static var respond: (([String: Any]) -> (Int, String))?
private static let lock = NSLock()
static func reset(_ status: Int = 200, _ body: String) {
- lock.withLock { reply = (status, body); seen = []; respond = nil }
+ lock.withLock { reply = (status, body); seen = []; sent = []; respond = nil }
}
static func chatReply(_ text: String, finish: String? = "stop") -> String {
@@ -34,7 +36,11 @@ final class LingStub: URLProtocol, @unchecked Sendable {
stream.close()
}
let body = (try? JSONSerialization.jsonObject(with: data) as? [String: Any]) ?? [:]
- let (status, text) = Self.lock.withLock { Self.seen.append((Date(), body)); return Self.respond?(body) ?? Self.reply }
+ let (status, text) = Self.lock.withLock {
+ Self.seen.append((Date(), body))
+ Self.sent.append((request.url?.host ?? "", request.value(forHTTPHeaderField: "Authorization")))
+ return Self.respond?(body) ?? Self.reply
+ }
let response = HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)!
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
client?.urlProtocol(self, didLoad: Data(text.utf8))
@@ -91,6 +97,76 @@ final class LingStub: URLProtocol, @unchecked Sendable {
#expect(LingStub.seen.last?.body["chat_template_kwargs"] != nil)
}
+ // MARK: Notes apart
+
+ private func notesClient(own: Bool) -> LingClient {
+ let ling = client()
+ AIKey.save("sk-main-1111111111", "custom")
+ ling.config = { AIConfig(provider: .custom, base: URL(string: "https://main.example/v1/"), textModel: "mt",
+ notesModel: "big", notesBase: own ? URL(string: "https://notes.example/v1/") : nil,
+ notesOwnService: own) }
+ return ling
+ }
+
+ @Test func notesGoToTheirModelAndServerTranslationStays() async throws {
+ LingStub.reset(200, LingStub.chatReply("{}"))
+ let ling = notesClient(own: true)
+ AIKey.save("sk-notes-222222222", LingClient.notesKeyName)
+ _ = try await ling.chat(content: "x", instruction: "Notes.", priority: .notes, json: true)
+ _ = try await ling.chat(content: "y", instruction: "Translate.", priority: .translate)
+ #expect(LingStub.seen.map { $0.body["model"] as? String } == ["big", "mt"])
+ #expect(LingStub.sent.map(\.host) == ["notes.example", "main.example"])
+ #expect(LingStub.sent.map(\.auth) == ["Bearer sk-notes-222222222", "Bearer sk-main-1111111111"])
+ }
+
+ @Test func notesWithoutTheirOwnKeyUseTheTranslationKey() async throws {
+ LingStub.reset(200, LingStub.chatReply("{}"))
+ let ling = notesClient(own: true)
+ _ = try await ling.chat(content: "x", instruction: "Notes.", priority: .notes)
+ #expect(LingStub.sent.first?.auth == "Bearer sk-main-1111111111")
+ // The same service, another model: same address and key.
+ let same = notesClient(own: false)
+ AIKey.save("sk-notes-222222222", LingClient.notesKeyName)
+ _ = try await same.chat(content: "x", instruction: "Notes.", priority: .notes)
+ #expect(LingStub.sent.last?.host == "main.example" && LingStub.sent.last?.auth == "Bearer sk-main-1111111111")
+ #expect(LingStub.seen.last?.body["model"] as? String == "big")
+ }
+
+ @Test func aRefusedNotesKeyLeavesTranslationWorking() async throws {
+ LingStub.reset(200, "")
+ LingStub.respond = { body in body["model"] as? String == "big" ? (401, "{}") : (200, LingStub.chatReply("好")) }
+ let ling = notesClient(own: true)
+ await #expect(throws: LingClient.Failure.invalidKey) {
+ try await ling.chat(content: "x", instruction: "Notes.", priority: .notes)
+ }
+ #expect(ling.keyState != .invalid)
+ #expect(try await ling.chat(content: "y", instruction: "Translate.", priority: .translate) == "好")
+ }
+
+ @Test func notesAtAnUnusableAddressSendNothing() async throws {
+ LingStub.reset(200, LingStub.chatReply("{}"))
+ let ling = client()
+ AIKey.save("sk-main-1111111111", "custom")
+ AIKey.save("sk-notes-222222222", LingClient.notesKeyName)
+ ling.config = { AIConfig(provider: .custom, base: URL(string: "https://main.example/v1/"), textModel: "mt",
+ notesOwnService: true, notesBadAddress: true) }
+ await #expect(throws: LingClient.Failure.noKey) {
+ try await ling.chat(content: "x", instruction: "Notes.", priority: .notes)
+ }
+ #expect(LingStub.sent.isEmpty)
+ }
+
+ @Test func notesFallBackToTranslationUntilSet() {
+ let base = URL(string: "https://main.example/v1/")
+ let plain = AIConfig(provider: .custom, base: base, textModel: "mt")
+ #expect(!plain.notesApart && plain.forNotes == plain)
+ let model = AIConfig(provider: .custom, base: base, textModel: "mt", notesModel: "big")
+ #expect(model.notesApart && model.forNotes.textModel == "big" && model.forNotes.base == base)
+ // Only the custom service splits.
+ let ling = AIConfig(provider: .ling, base: AIProvider.ling.base, textModel: "x", notesModel: "big")
+ #expect(!ling.notesApart && ling.forNotes.textModel == "x")
+ }
+
// MARK: Retries
@Test func finalNotesKeepRetryingForAboutAMinute() {