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(android): notes can use their own model, or another OpenAI-compatible service with its own address and key

wquguru49ad40493caf
diff --git a/android/README.md b/android/README.md
index 8940c64..eeb41c6 100644
--- a/android/README.md
+++ b/android/README.md
@@ -46,7 +46,7 @@ scripts/shot.sh # 截图:悬浮窗应是黑块;capture o
scripts/tap.sh "开始听" # 按屏幕上的文字点(系统对话框也行),用来走真实界面
```
-`cicadactl.sh` 的命令见 `app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt`(state、start、stop、feed、sample、view、capture、overlay show|hide|collapse|expand、target、ui、show main|live|records|record|settings|ai|onboarding、import、provider、ai-model、ai-custom-only on|off、key import、voice-try、updatefeed、update check|download|job|notify,以及改正听错的词的 fixes on|off、asknames on|off、silent、heard、vocab add|remove|state、fixstate、fixanswer yes|no、fixrevert、fixlater、fixundo、fixedit、pinyin,分享链接的 share <id>[,full][,pw]、unshare、shares、shareSheet、delete、shareserver、clipboard)。`share` 用正式的 cicada.indaloop.app(`adb reverse tcp:<端口> tcp:<端口>` 后 `shareserver http://127.0.0.1:<端口>` 改指本机的 wrangler dev(模拟器走代理时 10.0.2.2 连不上),另用 files/share-device-local.json),设备只注册一次(files/share-device.json,别删);测试只用合成的会议记录,用完 unshare。`silent` 开一场没有声音的会,`heard <一句话>` 当作听到一整句,翻译和改词都走当前的 AI 服务,不用放声音。只有开发版有,且只接受 adb。开发版默认不检查更新(点设置里的“检查更新”或用下面的命令后才查):`cicadactl.sh push feed.json && cicadactl.sh updatefeed feed.json` 指向一份测试用的 release JSON(不带参数就是 GitHub),`adb shell cmd jobscheduler run -f com.wquguru.cicada.dev 7` 立刻跑一次后台检查。
+`cicadactl.sh` 的命令见 `app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt`(state、start、stop、feed、sample、view、capture、overlay show|hide|collapse|expand、target、ui、show main|live|records|record|settings|ai|onboarding、import、provider、ai-model(hear|text|voice|notes)、ai-base、ai-notes same|own、ai-notes-base、notes-key import|remove、ai-custom-only on|off、key import、voice-try、updatefeed、update check|download|job|notify,以及改正听错的词的 fixes on|off、asknames on|off、silent、heard、vocab add|remove|state、fixstate、fixanswer yes|no、fixrevert、fixlater、fixundo、fixedit、pinyin,分享链接的 share <id>[,full][,pw]、unshare、shares、shareSheet、delete、shareserver、clipboard)。`share` 用正式的 cicada.indaloop.app(`adb reverse tcp:<端口> tcp:<端口>` 后 `shareserver http://127.0.0.1:<端口>` 改指本机的 wrangler dev(模拟器走代理时 10.0.2.2 连不上),另用 files/share-device-local.json),设备只注册一次(files/share-device.json,别删);测试只用合成的会议记录,用完 unshare。`silent` 开一场没有声音的会,`heard <一句话>` 当作听到一整句,翻译和改词都走当前的 AI 服务,不用放声音。只有开发版有,且只接受 adb。开发版默认不检查更新(点设置里的“检查更新”或用下面的命令后才查):`cicadactl.sh push feed.json && cicadactl.sh updatefeed feed.json` 指向一份测试用的 release JSON(不带参数就是 GitHub),`adb shell cmd jobscheduler run -f com.wquguru.cicada.dev 7` 立刻跑一次后台检查。
界面按 claude.ai 上的设计画布实现:首页、正在听、悬浮窗(纪要卡片 / 字幕条 / 小圆点)、三步引导、会议记录、会议详情、设置。文案用 Gemini(`google/gemini-4-argon`)审过一遍,与 Mac 共用的文案沿用 Mac 的译法。
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/AiServiceActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/AiServiceActivity.kt
index 8d3e2f2..9848947 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/AiServiceActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/AiServiceActivity.kt
@@ -47,7 +47,8 @@ class AiServiceActivity : Activity() {
val c = ling.config()
val p = c.provider
val key = listOf(ling.keyState, ling.currentKey()?.takeLast(4), ling.aiCheck.summary, ling.aiCheck.at?.let { it / 60_000 }, ling.lastVoice?.first,
- ling.textCatalog.size, ling.hearCatalog.size, app.settings.toJson(), Strings.language, open).joinToString("|")
+ ling.textCatalog.size, ling.hearCatalog.size, ling.notesCatalog.size, ling.notesHasOwnKey,
+ app.settings.toJson(), Strings.language, open).joinToString("|")
if (key == shown) return
shown = key
page.removeAllViews()
@@ -191,7 +192,7 @@ class AiServiceActivity : Activity() {
layoutParams = LinearLayout.LayoutParams(-1, -2).apply { topMargin = ui.dp(16) }
})
val host = c.base?.let { Uri.parse(it).host } ?: L("你填的地址")
- page.addView(ui.helper(LF("加密存在这台手机上,只发给 %@", host)).apply { setPadding(ui.dp(16), ui.dp(8), ui.dp(16), 0) })
+ page.addView(ui.helper(LF("加密存在这台手机上,只发给 %@", keyHosts(app, c))).apply { setPadding(ui.dp(16), ui.dp(8), ui.dp(16), 0) })
// Never "按所选模型计费" here: the user runs it, or their provider bills it its own way.
val nearby = c.base?.let(Providers::isNearby) ?: false
val foot = (if (nearby) L("跑在你自己的机器上,不按量计费。") else L("费用以这个服务为准。")) +
@@ -214,10 +215,22 @@ class AiServiceActivity : Activity() {
/// Where the custom service's audio and text go: one host when every use shares it. On a phone
/// the hear model always listens, so its address always counts.
- private fun customHosts(c: AIConfig): String {
- val hosts = listOfNotNull(c.base, c.hearBase, c.voiceBase?.takeIf { c.hasVoices })
- .map { Uri.parse(it).host }.toSet()
- return hosts.singleOrNull() ?: L("你填的地址")
+ private fun customHosts(c: AIConfig): String =
+ hostsLine(listOfNotNull(c.base, c.forNotes.base?.takeIf { c.notesApart }, c.hearBase, c.voiceBase?.takeIf { c.hasVoices }))
+
+ /// Where the custom service's key is sent: every use's address, the notes' only while they share it.
+ private fun keyHosts(app: CicadaApp, c: AIConfig): String =
+ hostsLine(listOfNotNull(c.base, c.forNotes.base?.takeIf { c.notesApart && !app.ling.notesHasOwnKey }, c.hearBase,
+ c.voiceBase?.takeIf { c.hasVoices }))
+
+ /// One host, "a 和 b", or 你填的地址 for more.
+ private fun hostsLine(bases: List<String>): String {
+ val hosts = bases.mapNotNull { Uri.parse(it).host }.distinct()
+ return when (hosts.size) {
+ 1 -> hosts[0]
+ 2 -> LF("%@ 和 %@", hosts[0], hosts[1])
+ else -> L("你填的地址")
+ }
}
/// A row that opens to its fields: a state dot, the use, what it runs on, and how it's doing.
@@ -250,30 +263,45 @@ class AiServiceActivity : Activity() {
private val grey = android.graphics.Color.parseColor("#C4C7CE")
+ /// "192.168.1.20 · qwen-mt-turbo", then the notes' model, or their own server after a bar.
+ private fun textDetail(c: AIConfig, host: String): String {
+ if (host.isEmpty() || c.textModel.isEmpty()) return L("填上地址和模型")
+ val line = "$host · ${short(c.textModel)}"
+ if (!c.notesApart) return line
+ val n = c.forNotes
+ val notesHost = n.base?.let { Uri.parse(it).host }
+ if (notesHost != null && n.base != c.base) return line + " | $notesHost · ${short(n.textModel)}"
+ return if (n.textModel == c.textModel) line else line + " · ${short(n.textModel)}"
+ }
+
+ /// 翻译和纪要 (AISettings.swift › textSection): 翻译's address, key and model, then 纪要 on the
+ /// same service (another model at most) or another one with its own address and key.
private fun textSection(app: CicadaApp, c: AIConfig, open: MutableSet<String>, rows: MutableList<View>) {
val ling = app.ling
val s = app.settings
val check = ling.aiCheck
val host = c.base?.let { Uri.parse(it).host }.orEmpty()
- val detail = if (host.isEmpty() || c.textModel.isEmpty()) L("填上地址和模型") else "$host · ${short(c.textModel)}"
val secs = check.translate?.let { "%.1f".format(Strings.locale, it.seconds) }
// The hear model's own failure shows on its row: the text model may be fine.
val failed = check.textFailure != null
+ // Translation works but the notes' own model or server doesn't.
+ val notesDown = !failed && check.notesFailed
val trailing = when {
check.running -> L("正在检查…")
failed && ling.hasKey -> status(app)
+ notesDown -> L("纪要写不了")
else -> secs?.let { LF("翻一句 %@ 秒", it) }
}
val dot = when {
!ling.hasKey -> grey
check.running -> Palette.accent
failed -> Palette.link
- check.slow || check.busy -> AiCheckViews.warn
+ check.slow || check.busy || check.notesFailed -> AiCheckViews.warn
check.at != null && check[AICheck.StepID.Text] is AICheck.State.Ok -> AiCheckViews.ok
else -> grey
}
- rows.add(useRow("text", open, L("翻译和纪要"), detail, dot, trailing,
- if (check.slow) AiCheckViews.warn else if (failed) Palette.link else Palette.tertiary))
+ rows.add(useRow("text", open, L("翻译和纪要"), textDetail(c, host), dot, trailing,
+ if (failed || notesDown) Palette.link else if (check.slow) AiCheckViews.warn else Palette.tertiary))
if ("text" !in open) return
val k = ling.currentKey()
val keyLine = when {
@@ -281,24 +309,220 @@ class AiServiceActivity : Activity() {
k.isEmpty() -> L("本机和局域网服务可不填")
else -> AIKey.masked(k)
}
- val model = if (ling.textCatalog.isNotEmpty())
- modelRow(L("模型"), null, emptyList(), ling.textCatalog, c.textModel) { app.setAiModel("text", it) }
- else fieldRow(L("模型"), s.aiModels["custom"].orEmpty(), L("例如 qwen3:14b"), null) { app.setAiModel("text", it) }
+ val model = modelPicker(L("模型"), s.aiModels["custom"].orEmpty(), L("例如 qwen3:14b"), null, host,
+ { ling.textCatalog }, { ling.fetchCatalog() }) { app.setAiModel("text", it) }
val steps = k != null && (check.running || failed || (check.at != null && check.failure == null && !check.passed))
- val facts = if (!steps && check.at != null && check[AICheck.StepID.Text] is AICheck.State.Ok)
+ val apart = c.notesApart && check.passed && check.translate != null
+ val facts = if (!steps && !apart && check.at != null && check[AICheck.StepID.Text] is AICheck.State.Ok)
listOfNotNull(L("能写纪要"), check.translate?.let { if (it.thinks) L("会先思考") else L("不思考") }).joinToString(" · ") else null
- rows.add(panel(
+ val views = mutableListOf<View?>(
+ groupTitle(L("翻译")),
fieldRow(L("地址"), s.aiCustomBase, "http://192.168.1.20:8000/v1", null, shown = ::where) { s.aiCustomBase = it; s.save(); app.aiChanged() },
badAddress(s.aiCustomBase),
- model,
ui.listRow("key", keyLine, trailing = if (!k.isNullOrEmpty()) ui.text(L("更换"), 15f, Palette.link, bold = true, lines = 1) else null) { editKey(this, ui) },
+ model,
+ ui.divider().apply { layoutParams = LinearLayout.LayoutParams(-1, 1).apply { topMargin = ui.dp(4); bottomMargin = ui.dp(4); leftMargin = ui.dp(16) } },
+ )
+ views.addAll(notesGroup(app, c, host))
+ views.addAll(listOf(
ui.listRow(if (check.running) L("正在检查…") else L("重新检查"), null,
leading = ui.icon(R.drawable.i_restore, 22, if (check.running) Palette.tertiary else Palette.body), chevron = false,
onClick = if (check.running || k == null) null else ({ app.recheck() })),
check.slowLine(app.translator.googleOff)?.let { note(it, AiCheckViews.warn) },
if (steps) AiCheckViews.steps(this, ui, recheck = false) { editKey(this, ui) } else null,
facts?.let { note(it, Palette.tertiary) },
+ if (apart && !steps) checkRows(c, check) else null,
))
+ rows.add(panel(*views.toTypedArray()))
+ }
+
+ private fun groupTitle(text: String) = ui.text(text, 13f, Palette.ink, bold = true, lines = 1).apply {
+ setPadding(ui.dp(16), ui.dp(12), ui.dp(16), ui.dp(2))
+ isAccessibilityHeading = true
+ }
+
+ /// 纪要: the same service as translation (another model at most), or another one with its own
+ /// address and key. Switching back keeps what was typed.
+ private fun notesGroup(app: CicadaApp, c: AIConfig, host: String): List<View?> {
+ val ling = app.ling
+ val s = app.settings
+ val own = s.aiCustomNotesOwn
+ val n = c.forNotes
+ val notesHost = n.base?.let { Uri.parse(it).host } ?: host
+ val shared = !ling.notesHasOwnKey
+ val elsewhere = n.base != c.base
+ val views = mutableListOf<View?>(
+ groupTitle(L("纪要")),
+ ui.segmented(listOf("same" to L("同一个服务"), "own" to L("另一个服务")), if (own) "own" else "same") { app.setNotesOwn(it == "own") }
+ .apply { layoutParams = LinearLayout.LayoutParams(-1, -2).apply { leftMargin = ui.dp(16); rightMargin = ui.dp(16); topMargin = ui.dp(4); bottomMargin = ui.dp(4) } },
+ )
+ if (own) {
+ val nk = if (shared) null else ling.notesKey()
+ views.add(fieldRow(L("地址"), s.aiCustomNotesBase, L("跟上面一样"), null, L("跟上面一样"), ::where) { app.setNotesBase(it) })
+ views.add(badAddress(s.aiCustomNotesBase))
+ views.add(ui.listRow("key", if (nk.isNullOrEmpty()) L("不填就用上面的 key") else AIKey.masked(nk),
+ trailing = if (!nk.isNullOrEmpty()) ui.text(L("更换"), 15f, Palette.link, bold = true, lines = 1) else null) { editNotesKey(app, notesHost) })
+ }
+ views.add(modelPicker(L("模型"), s.aiModels[Providers.NOTES_MODEL].orEmpty(), L("和翻译模型一样"), L("和翻译模型一样"), notesHost,
+ { if (elsewhere) ling.notesCatalog else ling.textCatalog }, { if (elsewhere) ling.fetchNotesCatalog() else ling.fetchCatalog() }) {
+ app.setAiModel("notes", it)
+ })
+ val problem = ling.aiCheck.notesLine(notesHost, n.textModel, sharedKey = shared)
+ views.add(if (problem != null) note(problem, Palette.link) else note(L("用来写实时纪要、识别说话人,默认和翻译用同一个"), Palette.tertiary))
+ return views
+ }
+
+ /// After a check with notes apart: one row each, what it runs and how it did.
+ private fun checkRows(c: AIConfig, check: AICheck): View {
+ val t = check.translate!!
+ val notes = check.notes
+ val notesText = when (notes) {
+ is AICheck.Notes.Ok -> LF("能写纪要 · %@ 秒", "%.1f".format(Strings.locale, notes.seconds))
+ is AICheck.Notes.Fail -> if (notes.why == AICheck.Reason.InvalidKey || notes.why == AICheck.Reason.MgmtKey) L("key 不对") else L("纪要写不了")
+ AICheck.Notes.Running -> L("正在检查…")
+ null -> ""
+ }
+ fun row(use: String, model: String, ok: Boolean, result: String) =
+ ui.listRow(use, short(model), leading = ui.dot(if (ok) AiCheckViews.ok else Palette.link),
+ trailing = ui.text(result, 13f, if (ok) AiCheckViews.ok else Palette.link, lines = 1).apply { fontFeatureSettings = "tnum" }, chevron = false)
+ val translate = LF("翻一句 %@ 秒", "%.1f".format(Strings.locale, t.seconds)) + " · " + (if (t.thinks) L("会先思考") else L("不思考"))
+ return ui.stack(0,
+ row(L("翻译"), c.textModel, true, translate),
+ row(L("纪要"), c.forNotes.textModel, notes?.ok ?: true, notesText))
+ }
+
+ /// The notes' own key (另一个服务): paste, save, or remove it (back to the key above). It goes
+ /// only to the notes' address.
+ private fun editNotesKey(app: CicadaApp, host: String) {
+ lateinit var dialog: android.app.Dialog
+ lateinit var submit: () -> Unit
+ val status = ui.helper("")
+ val box = ui.keyField { submit() }.apply { hint = L("不填就用上面的 key") }
+ val field = LinearLayout(this).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ background = ui.rounded(Palette.ground, 16)
+ setPadding(ui.dp(16), ui.dp(4), ui.dp(4), ui.dp(4))
+ addView(box, ui.weight())
+ addView(ui.button(L("粘贴"), "white", R.drawable.i_clipboard, height = 44) { SettingsActivity.paste(box) })
+ }
+ submit = submit@{
+ val text = box.text.toString().trim()
+ if (text.isEmpty()) { dialog.dismiss(); return@submit }
+ if (!app.setNotesKey(text)) { status.text = L("保存失败"); return@submit }
+ dialog.dismiss()
+ }
+ val body = ui.stack(10, field, status,
+ LinearLayout(this).apply {
+ orientation = LinearLayout.HORIZONTAL
+ addView(ui.button(L("取消"), "quiet") { dialog.dismiss() }, ui.weight())
+ addView(ui.button(L("保存"), "primary") { submit() }, ui.weight().apply { leftMargin = ui.dp(10) })
+ })
+ if (app.ling.notesHasOwnKey) body.addView(ui.textButton(L("移除"), Palette.link) { app.setNotesKey(null); dialog.dismiss() })
+ dialog = ui.sheet(this, LF("粘贴 %@ 的 key", host), body)
+ dialog.window?.setSoftInputMode(android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE or android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
+ dialog.show()
+ box.requestFocus()
+ }
+
+ /// A custom service's model (AISettings.swift › ModelPicker): the row shows it; tapping opens
+ /// the names its `/models` lists, searchable, and takes a name it doesn't list (an alias, a
+ /// model it hides). Without a list the sheet is a plain field. `sameLabel`: a first choice
+ /// that clears the value (和翻译模型一样).
+ private fun modelPicker(label: String, current: String, placeholder: String, sameLabel: String?, host: String,
+ catalog: () -> List<String>, refetch: () -> Unit, pick: (String) -> Unit) =
+ ui.listRow(label, null, trailing = value(if (current.isEmpty()) sameLabel ?: L("未填") else short(current))) {
+ pickModel(label, current, placeholder, sameLabel, host, catalog, refetch, pick)
+ }
+
+ private fun pickModel(title: String, current: String, placeholder: String, sameLabel: String?, host: String,
+ catalog: () -> List<String>, refetch: () -> Unit, pick: (String) -> Unit) {
+ lateinit var d: android.app.Dialog
+ fun choose(id: String) { d.dismiss(); if (id != current) pick(id) }
+ val search = android.widget.EditText(this).apply {
+ setSingleLine()
+ // Model ids: ASCII, no autocorrect, the URL keyboard.
+ inputType = android.text.InputType.TYPE_CLASS_TEXT or android.text.InputType.TYPE_TEXT_VARIATION_URI
+ imeHintLocales = android.os.LocaleList(java.util.Locale.US)
+ imeOptions = android.view.inputmethod.EditorInfo.IME_ACTION_DONE or android.view.inputmethod.EditorInfo.IME_FLAG_FORCE_ASCII
+ setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, 16f)
+ background = ui.rounded(Palette.ground, 16)
+ setPadding(ui.dp(16), 0, ui.dp(16), 0)
+ minHeight = ui.dp(52)
+ }
+ val list = ui.stack(0)
+ val scroll = android.widget.ScrollView(this).apply { addView(list) }
+ val foot = ui.helper("")
+ val buttons = LinearLayout(this).apply {
+ orientation = LinearLayout.HORIZONTAL
+ addView(ui.button(L("取消"), "quiet") { d.dismiss() }, ui.weight())
+ addView(ui.button(L("保存"), "primary") { choose(search.text.toString().trim()) }, ui.weight().apply { leftMargin = ui.dp(10) })
+ }
+ fun row(text: String, on: Boolean, action: () -> Unit) = LinearLayout(this).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ minimumHeight = ui.dp(48)
+ setPadding(ui.dp(16), ui.dp(4), ui.dp(12), ui.dp(4))
+ addView(ui.text(text, 15f, Palette.ink, bold = on, lines = 2), ui.weight())
+ if (on) addView(ui.icon(R.drawable.i_check, 20, Palette.ink), LinearLayout.LayoutParams(ui.dp(20), ui.dp(20)))
+ contentDescription = text
+ isSelected = on
+ ui.tappable(this, 16, if (on) ui.rounded(Palette.ground, 16) else null) { action() }
+ }
+ var shape: Boolean? = null
+ var listed = false
+ fun render() {
+ val all = catalog()
+ val q = search.text.toString().trim()
+ listed = all.isNotEmpty()
+ if (shape != listed) {
+ // No list: a plain field, saved with 保存; a list: search it, or use what was typed.
+ shape = listed
+ search.hint = if (listed) L("搜索或输入模型") else placeholder
+ scroll.visibility = if (listed) View.VISIBLE else View.GONE
+ buttons.visibility = if (listed) View.GONE else View.VISIBLE
+ }
+ foot.text = if (listed) LF("%@ 列出 %lld 个模型", host, all.size) else L("这个地址没列出模型,直接填名字")
+ list.removeAllViews()
+ if (!listed) return
+ val matches = if (q.isEmpty()) all else all.filter { it.contains(q, ignoreCase = true) }
+ if (q.isNotEmpty() && q !in all) list.addView(row(LF("用 %@(列表里没有)", q), false) { choose(q) })
+ if (sameLabel != null && q.isEmpty()) list.addView(row(sameLabel, current.isEmpty()) { choose("") })
+ matches.take(300).forEach { id -> list.addView(row(id, id == current) { choose(id) }) }
+ }
+ search.setOnEditorActionListener { _, a, _ ->
+ if (a != android.view.inputmethod.EditorInfo.IME_ACTION_DONE) return@setOnEditorActionListener false
+ // Done: the only match, else exactly what was typed.
+ val q = search.text.toString().trim()
+ val matches = catalog().filter { it.contains(q, ignoreCase = true) }
+ if (listed && q.isNotEmpty() && matches.size == 1) choose(matches[0]) else if (q.isNotEmpty() || !listed) choose(q)
+ true
+ }
+ search.addTextChangedListener(object : android.text.TextWatcher {
+ override fun beforeTextChanged(t: CharSequence?, a: Int, b: Int, c: Int) {}
+ override fun onTextChanged(t: CharSequence?, a: Int, b: Int, c: Int) {}
+ override fun afterTextChanged(e: android.text.Editable?) { render() }
+ })
+ val again = ui.textButton(L("重新获取")) {
+ val app = cicada
+ app.background.execute { refetch(); app.main.post { if (d.isShowing) render() } }
+ }
+ val footer = LinearLayout(this).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ setPadding(ui.dp(4), 0, ui.dp(4), 0)
+ addView(foot, ui.weight())
+ addView(again)
+ }
+ // Without a list the field holds the name to edit; with one it searches.
+ if (catalog().isEmpty()) search.setText(current)
+ render()
+ val body = ui.stack(10, search, scroll, footer, buttons)
+ (scroll.layoutParams as LinearLayout.LayoutParams).height = ui.dp(48 * 6)
+ d = ui.sheet(this, title, body)
+ d.window?.setSoftInputMode(android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE or android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
+ d.show()
+ search.requestFocus()
}
/// 听对方: the hear model, which may run on its own server; its state is the check's hear step.
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/App.kt b/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
index fb13c7c..4acdbd9 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
@@ -451,7 +451,10 @@ class CicadaApp : Application() {
val s = settings
val p = s.aiProvider
if (kind == "text" && p == "ling") s.model = model.ifEmpty { LingClient.DEFAULT_MODEL }
- else {
+ else if (kind == "notes") {
+ // The custom service's notes model; empty: the translation model.
+ if (model.isNotEmpty()) s.aiModels[Providers.NOTES_MODEL] = model else s.aiModels.remove(Providers.NOTES_MODEL)
+ } else {
val table = when (kind) { "text" -> s.aiModels; "hear" -> s.aiHearModels; "voice" -> s.aiVoiceModels; else -> return }
if (model.isNotEmpty()) table[p] = model else table.remove(p)
}
@@ -459,6 +462,26 @@ class CicadaApp : Application() {
aiChanged()
}
+ /// 纪要 › 同一个服务 / 另一个服务 (the custom service): off keeps the typed address.
+ fun setNotesOwn(on: Boolean) {
+ settings.aiCustomNotesOwn = on
+ settings.save()
+ aiChanged()
+ }
+
+ fun setNotesBase(raw: String) {
+ settings.aiCustomNotesBase = raw.trim()
+ settings.save()
+ aiChanged()
+ }
+
+ /// Notes' own key (另一个服务), sealed like the others; null removes it (back to the key above).
+ fun setNotesKey(raw: String?): Boolean {
+ val ok = if (raw == null) { ling.removeNotesKey(); true } else ling.setNotesKey(raw)
+ if (ok) aiChanged()
+ return ok
+ }
+
/// The service, its address, models or key changed: forget the old check and check again.
fun aiChanged(check: Boolean = true) {
// 语音和文字只发给你的服务 acts on the custom service only: another service brings Google back.
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt b/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt
index 5d31dd3..dec7a47 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt
@@ -20,7 +20,8 @@ import java.util.concurrent.TimeUnit
/// capture on|off | overlay show|hide | show main|live|records|settings|words|onboarding|record [id] | overlay collapse|expand | key reload
/// hear|say <wav in files/> (面对面: the other side / me holding 我说) | tts <lang> <text>
/// import <session.json in files/> | importfile <audio or video in files/> | face | onboarded on|off | target <code> | ui <lang> | clip <text>
-/// provider ling|openrouter|zenmux|custom | ai-model hear|text|voice <id> ("" back to the recommended) | show ai
+/// provider ling|openrouter|zenmux|custom | ai-model hear|text|voice|notes <id> ("" back to the recommended) | show ai
+/// ai-base <url> (the custom service's address) · ai-notes same|own · ai-notes-base <url> · notes-key import <file in files/>|remove (the custom service's 纪要)
/// key import <file in files/> (sealed as the current service's key, the plain file deleted) | voice-try (设置's 试一句)
/// ai-check (重新检查) | ai-check-sim <reason|lowBalance|off> (every check ends that way; the state's ai.check has the steps)
/// 改正听错的词: fixes on|off · asknames on|off · silent (a meeting with no audio) · heard <text> · vocab add|remove|state
@@ -97,6 +98,17 @@ class DebugReceiver : BroadcastReceiver() {
return mapOf("ok" to true, "ai" to ai(app))
} else { app.key.reload(); app.ling.keyChanged(); app.background.execute { app.ling.check() } }
"provider" -> { app.setAiProvider(arg); return mapOf("ok" to true, "ai" to ai(app)) }
+ "ai-base" -> { app.settings.aiCustomBase = arg.removeSurrounding("\"").trim(); app.settings.save(); app.aiChanged(); return mapOf("ok" to true, "ai" to ai(app)) }
+ "ai-notes" -> { app.setNotesOwn(arg == "own"); return mapOf("ok" to true, "ai" to ai(app)) }
+ "ai-notes-base" -> { app.setNotesBase(arg.removeSurrounding("\"")); return mapOf("ok" to true, "ai" to ai(app)) }
+ // The notes' own key, pushed in as a plain file like `key import`, sealed, the plain copy deleted.
+ "notes-key" -> {
+ if (arg == "remove") { app.setNotesKey(null); return mapOf("ok" to true, "ai" to ai(app)) }
+ val f = File(app.filesDir, arg.removePrefix("import ").trim())
+ val text = try { f.readText().trim() } catch (_: Exception) { "" } finally { f.delete() }
+ if (text.isEmpty() || !app.setNotesKey(text)) return mapOf("error" to "no key in ${f.name}")
+ return mapOf("ok" to true, "ai" to ai(app))
+ }
// The 改用 Ling on a status line (says when it isn't offered).
"switchToLing" -> { val offered = app.canSwitchToLing; app.switchToLing(); return mapOf("offered" to offered, "ai" to ai(app)) }
// ai-check-sim <reason|lowBalance|off>: every check ends this way (screenshots of each state).
@@ -249,7 +261,9 @@ class DebugReceiver : BroadcastReceiver() {
return mapOf("provider" to c.provider.id, "base" to c.base, "text" to c.textModel, "hear" to c.hearModel, "hearBase" to c.hearBase, "voice" to c.voiceModel,
"state" to l.keyState.name, "hears" to l.hears, "speaks" to l.speaks, "check" to l.aiCheck.summary,
"voice" to l.lastVoice?.first, "sim" to l.simulateCheck?.name,
- "catalog" to listOf(l.textCatalog.size, l.hearCatalog.size), "keyFile" to app.key.path.name,
+ "catalog" to listOf(l.textCatalog.size, l.hearCatalog.size, l.notesCatalog.size), "keyFile" to app.key.path.name,
+ "notes" to mapOf("apart" to c.notesApart, "base" to c.forNotes.base, "model" to c.forNotes.textModel,
+ "own" to c.notesOwnService, "ownKey" to l.notesHasOwnKey, "bad" to c.notesBadAddress),
"customOnly" to app.settings.aiCustomOnly, "googleOff" to app.translator.googleOff,
"untranslated" to app.translator.sentencesUntranslated)
}
diff --git a/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt b/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt
index 4829e28..e878252 100644
--- a/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt
@@ -42,6 +42,13 @@ object ProviderTests {
"aiCustomCheckTimesARealSentence" to ::customCheckTimes,
"aiTheHearModelMayHaveItsOwnAddress" to ::hearBase,
"aiAHearServerThatCantBeReachedFailsHearing" to ::hearServerDown,
+ "aiNotesGoToTheirModelAndServerTranslationStays" to ::notesApart,
+ "aiNotesWithoutTheirOwnKeyUseTheTranslationKey" to ::notesSharedKey,
+ "aiARefusedNotesKeyLeavesTranslationWorking" to ::notesKeyRefused,
+ "aiNotesFallBackToTranslationUntilSet" to ::notesConfig,
+ "aiNotesWithABadAddressAreNeverSentToTranslation" to ::notesBadAddress,
+ "aiACheckTestsNotesApartWithoutFailingTranslation" to ::notesCheck,
+ "aiEachServerHasItsOwnStartGate" to ::gatePerServer,
)
private fun check(ok: Boolean, what: String) { if (!ok) throw AssertionError(what) }
@@ -53,9 +60,11 @@ object ProviderTests {
val streams: ((String, String) -> Transport.Stream)? = null,
) : Transport {
val sent = mutableListOf<Pair<String, String>>()
+ /// The Authorization header of each request in `sent`.
+ val auths = mutableListOf<String?>()
val streamed = mutableListOf<Pair<String, String>>()
override fun send(url: String, method: String, body: String?, headers: Map<String, String>, timeoutMs: Int): Transport.Response {
- synchronized(sent) { sent.add(url to (body ?: "")) }
+ synchronized(sent) { sent.add(url to (body ?: "")); auths.add(headers["Authorization"]) }
return respond(url, body ?: "")
}
override fun stream(url: String, body: String, headers: Map<String, String>, timeoutMs: Int): Transport.Stream {
@@ -559,4 +568,178 @@ object ProviderTests {
for (madeUp in listOf("00:00", "00:00.", "1:02:03")) check(Translator.isNoise(madeUp, 1.2), "noise: $madeUp")
for (said in listOf("Hello.", "3 点", "15%", "好的")) check(!Translator.isNoise(said, 1.2), "kept: $said")
}
+
+ // MARK: Notes apart (另一个服务)
+
+ private val notesKeys = AIKey(PlainProtector, service = { LingClient.NOTES_KEY })
+
+ /// A custom service at main.example translating with "mt"; notes on "big", at notes.example with `own`.
+ private fun notesSettings(own: Boolean) = AppSettings(aiProvider = "custom", aiCustomBase = "https://main.example/v1",
+ aiModels = mutableMapOf("custom" to "mt", Providers.NOTES_MODEL to "big"), aiCustomNotesOwn = own,
+ aiCustomNotesBase = if (own) "https://notes.example/v1" else "")
+
+ private fun model(body: String) = body(body)["model"]
+
+ fun notesApart() {
+ try {
+ val fake = Fake({ _, _ -> reply("{}") })
+ val ling = client(fake, notesSettings(own = true), key = "sk-main-1111111111")
+ check(ling.setNotesKey("sk-notes-222222222"), "notes key saved")
+ equal("ai-key-custom-notes", notesKeys.path.name, "named as on the Mac")
+ ling.chat("x", "Notes.", Priority.Notes, json = true)
+ ling.chat("y", "Translate.", Priority.Translate)
+ equal(listOf<Any?>("big", "mt"), fake.sent.map { model(it.second) }, "models")
+ equal(listOf("https://notes.example/v1/chat/completions", "https://main.example/v1/chat/completions"), fake.sent.map { it.first }, "servers")
+ equal(listOf<String?>("Bearer sk-notes-222222222", "Bearer sk-main-1111111111"), fake.auths, "keys")
+ check(!Paths.settings.exists() || !Paths.settings.readText().contains("sk-notes"), "never in settings")
+ } finally { notesKeys.remove() }
+ }
+
+ fun notesSharedKey() {
+ try {
+ val fake = Fake({ _, _ -> reply("{}") })
+ val ling = client(fake, notesSettings(own = true), key = "sk-main-1111111111")
+ ling.chat("x", "Notes.", Priority.Notes)
+ equal("https://notes.example/v1/chat/completions", fake.sent[0].first, "their server")
+ equal("Bearer sk-main-1111111111", fake.auths[0], "no key of their own: the translation key")
+ // The same service, another model: same address and key, even with a notes key file left over.
+ notesKeys.save("sk-notes-222222222")
+ val same = Fake({ _, _ -> reply("{}") })
+ val other = client(same, notesSettings(own = false), key = "sk-main-1111111111")
+ other.chat("x", "Notes.", Priority.Notes)
+ equal("https://main.example/v1/chat/completions", same.sent[0].first, "translation's server")
+ equal("Bearer sk-main-1111111111", same.auths[0], "translation's key")
+ equal("big", model(same.sent[0].second), "notes' model")
+ // Removing it brings the translation key back.
+ val own = client(Fake({ _, _ -> reply("{}") }), notesSettings(own = true), key = "sk-main-1111111111")
+ check(own.notesHasOwnKey, "has its own")
+ own.removeNotesKey()
+ check(!own.notesHasOwnKey, "removed")
+ equal("sk-main-1111111111", own.notesKey(), "back to the translation key")
+ } finally { notesKeys.remove() }
+ }
+
+ fun notesKeyRefused() {
+ val fake = Fake({ _, b -> if (model(b) == "big") Transport.Response(401, "{}") else reply("好") })
+ val ling = client(fake, notesSettings(own = true), key = "sk-main-1111111111")
+ try { ling.chat("x", "Notes.", Priority.Notes); throw AssertionError("accepted") }
+ catch (e: LingException) { equal(LingException.Kind.InvalidKey, e.kind, "refused") }
+ check(ling.keyState != KeyState.Invalid, "translation's key isn't marked invalid: ${ling.keyState}")
+ equal("好", ling.chat("y", "Translate.", Priority.Translate), "translation still works")
+ equal(AICheck.Reason.InvalidKey, ling.aiCheck.notes?.reason, "the notes' result says why")
+ equal(null, ling.aiCheck.failure, "translation's steps untouched")
+ check(ling.aiCheck.notesFailed, "notes failed")
+ check(ling.aiCheck.notesLine("notes.example", "big", sharedKey = true)!!.contains("notes.example"), "names the notes server")
+ // Refused once: the next notes ask isn't sent.
+ val n = fake.sent.size
+ try { ling.chat("x", "Notes.", Priority.Notes) } catch (_: LingException) {}
+ equal(n, fake.sent.size, "not sent again until settings change")
+ }
+
+ fun notesConfig() {
+ val plain = AppSettings(aiProvider = "custom", aiCustomBase = "https://main.example/v1", aiModels = mutableMapOf("custom" to "mt")).aiConfig()
+ check(!plain.notesApart && plain.forNotes === plain, "not set: the same as translation")
+ val model = AppSettings(aiProvider = "custom", aiCustomBase = "https://main.example/v1",
+ aiModels = mutableMapOf("custom" to "mt", Providers.NOTES_MODEL to "big")).aiConfig()
+ check(model.notesApart, "another model")
+ equal("big", model.forNotes.textModel, "notes' model")
+ equal("https://main.example/v1/", model.forNotes.base, "same address")
+ equal("https://main.example/v1/", model.forNotes.hearBase, "hearing stays where it was")
+ val sameName = AppSettings(aiProvider = "custom", aiCustomBase = "https://main.example/v1",
+ aiModels = mutableMapOf("custom" to "mt", Providers.NOTES_MODEL to "mt")).aiConfig()
+ check(!sameName.notesApart, "the translation model named again is no split")
+ // 同一个服务 keeps the typed address, unused.
+ val off = notesSettings(own = true).apply { aiCustomNotesOwn = false }.aiConfig()
+ equal("https://main.example/v1/", off.forNotes.base, "off: translation's address")
+ equal(null, off.notesBase, "off: not used")
+ val on = notesSettings(own = true).aiConfig()
+ equal("https://notes.example/v1/", on.forNotes.base, "on: their own")
+ // Only the custom service splits.
+ val ling = AppSettings(aiProvider = "ling", aiModels = mutableMapOf(Providers.NOTES_MODEL to "big")).aiConfig()
+ check(!ling.notesApart && ling.forNotes.textModel == ling.textModel, "Ling never splits")
+ try {
+ notesSettings(own = true).save()
+ val back = AppSettings.load()
+ check(back.aiCustomNotesOwn, "另一个服务 kept across a restart")
+ equal("https://notes.example/v1", back.aiCustomNotesBase, "address kept")
+ equal("big", back.aiModels[Providers.NOTES_MODEL], "model kept")
+ } finally { Paths.settings.delete() }
+ }
+
+ fun notesBadAddress() {
+ val s = notesSettings(own = true).apply { aiCustomNotesBase = "http://notes.example/v1" }
+ val c = s.aiConfig()
+ check(c.notesBadAddress && c.notesApart, "http to the internet can't be used")
+ val fake = Fake({ _, _ -> reply("{}") })
+ val ling = client(fake, s, key = "sk-main-1111111111")
+ try { ling.chat("x", "Notes.", Priority.Notes); throw AssertionError("sent") } catch (_: LingException) {}
+ equal(0, fake.sent.size, "not sent to translation's server instead")
+ equal("好", client(Fake({ _, _ -> reply("好") }), s, key = "sk-main-1111111111").chat("y", "Translate.", Priority.Translate), "translation works")
+ }
+
+ fun notesCheck() {
+ try {
+ // Notes' server takes no JSON and answers none: their row fails, translation passes.
+ val fake = Fake({ url, b ->
+ when {
+ url.endsWith("models") -> if ("notes.example" in url) Transport.Response(200, """{"data":[{"id":"big"},{"id":"bigger"}]}""")
+ else Transport.Response(200, """{"data":[{"id":"other"}]}""")
+ "notes.example" in url -> if ("response_format" in b) Transport.Response(400, "{}") else reply("Sure!")
+ else -> reply("{\"ok\": true}")
+ }
+ })
+ val s = notesSettings(own = true).apply { aiHearModels["custom"] = "omni" }
+ val ling = client(fake, s, key = "sk-main-1111111111")
+ ling.check()
+ val r = ling.aiCheck
+ equal(null, r.failure, "translation isn't failed by notes: ${r.summary}")
+ check(r[AICheck.StepID.Text] is AICheck.State.Ok, "the sentence proved the text model even though /models doesn't list it")
+ equal(AICheck.Reason.NoJSON, r.notes?.reason, "notes: no JSON")
+ check(r.passed && r.notesFailed && "notes=fail(noJSON 400)" in r.summary, "summary: ${r.summary}")
+ equal(KeyState.Ok, ling.keyState, "the key works")
+ equal(listOf("big", "bigger"), ling.notesCatalog, "notes' own list for their menu")
+ check(fake.sent.none { "notes.example" in it.first && it.second.contains("Translate the text") }, "the sentence went to translation only")
+ // Fixed: notes pass.
+ val good = Fake({ url, _ -> if (url.endsWith("models")) Transport.Response(404, "") else reply("{\"ok\": true}") })
+ val ok = client(good, s, key = "sk-main-1111111111")
+ ok.check()
+ check(ok.aiCheck.notes is AICheck.Notes.Ok && !ok.aiCheck.notesFailed, "notes ok: ${ok.aiCheck.summary}")
+ // Notes on the same service: no row of their own; the JSON check is translation's.
+ val same = client(Fake({ url, _ -> if (url.endsWith("models")) Transport.Response(404, "") else reply("{\"ok\": true}") }),
+ AppSettings(aiProvider = "custom", aiCustomBase = "https://main.example/v1", aiModels = mutableMapOf("custom" to "mt"),
+ aiHearModels = mutableMapOf("custom" to "omni")), key = "sk-main-1111111111")
+ same.check()
+ equal(null, same.aiCheck.notes, "no notes row")
+ } finally { notesKeys.remove() }
+ }
+
+ /// The start gate's time, moved on by each wait instead of waiting.
+ private class StepClock : GateClock() {
+ var t = 1_000_000L
+ override fun now() = t
+ override fun wait(lock: Object, ms: Long) { check(ms > 0) { "would wait forever" }; t += ms }
+ }
+
+ fun gatePerServer() {
+ // Notes' server is out of requests: its 429s pause it, not translation's server.
+ val fake = Fake({ url, _ -> if ("notes.example" in url) Transport.Response(429, "", "20") else reply("好") })
+ val s = notesSettings(own = true)
+ val k = AIKey(PlainProtector, service = { s.aiProvider }).apply { save("sk-main-1111111111") }
+ val ling = LingClient(k, fake, config = s::aiConfig, clock = StepClock())
+ try { ling.chat("x", "Notes.", Priority.Notes); throw AssertionError("answered") }
+ catch (e: LingException) { equal(LingException.Kind.RateLimited, e.kind, "notes gave up") }
+ // A translation fails at once while its own server is cooling down; this one isn't.
+ equal("好", ling.chat("y", "Translate.", Priority.Translate), "translation starts at once")
+ check(ling.keyState != KeyState.Invalid, "key fine")
+ // chat_template_kwargs refused by the notes' server only: translation keeps sending it.
+ val kw = Fake({ url, b -> if ("notes.example" in url && "chat_template_kwargs" in b) Transport.Response(422, "{}") else reply("{}") })
+ val two = client(kw, s, key = "sk-main-1111111111")
+ two.chat("x", "Notes.", Priority.Notes)
+ two.chat("x", "Notes.", Priority.Notes)
+ two.chat("y", "Translate.", Priority.Translate)
+ val notes = kw.sent.filter { "notes.example" in it.first }
+ equal(3, notes.size, "refused, asked without, then left out")
+ check("chat_template_kwargs" !in notes[2].second, "left out at the notes' server")
+ check("chat_template_kwargs" in kw.sent.last().second, "translation's server still gets it")
+ }
}
diff --git a/android/core/src/main/kotlin/cicada/AICheck.kt b/android/core/src/main/kotlin/cicada/AICheck.kt
index 0f73534..8f3c19f 100644
--- a/android/core/src/main/kotlin/cicada/AICheck.kt
+++ b/android/core/src/main/kotlin/cicada/AICheck.kt
@@ -24,7 +24,23 @@ data class AICheck(
val balance: Double? = null,
/** A custom service: how long one real sentence took, and whether the model thought first. */
val translate: Speed? = null,
+ /** A custom service whose notes go to another model or server: how that one answered. Null
+ * while notes use the translation model (then `steps` say it all). A notes failure doesn't
+ * stop translation: `failure` and `passed` stay about translation. */
+ val notes: Notes? = null,
) {
+ sealed class Notes {
+ object Running : Notes() { override fun toString() = "running" }
+ data class Ok(val seconds: Double) : Notes() {
+ override fun toString() = "ok(${String.format(java.util.Locale.US, "%.1f", seconds)}s)"
+ }
+ data class Fail(val why: Reason, val code: Int? = null) : Notes() {
+ override fun toString() = "fail(${lower(why.name)}${code?.let { " $it" } ?: ""})"
+ }
+ val ok get() = this is Ok
+ val reason get() = (this as? Fail)?.why
+ }
+
data class Speed(val seconds: Double, val thinks: Boolean) {
/// A sentence that takes this long often misses the 6 s a translation is given
/// (Translator.translate) and falls back to Google.
@@ -65,7 +81,9 @@ data class AICheck(
return null
}
- val running get() = steps.any { it.state == State.Running }
+ val running get() = steps.any { it.state == State.Running } || notes == Notes.Running
+ /** Translation works but the notes' own model or server doesn't (a busy one fixes itself). */
+ val notesFailed get() = notes?.reason.let { it != null && it != Reason.Busy }
val busy get() = steps.any { it.state == State.Busy }
/** Every step passed (busy counts; a step nothing has tested yet does not block). */
val passed get() = at != null && failure == null && !running
@@ -166,6 +184,23 @@ data class AICheck(
else LF("翻一句要 %@ 秒,超过 6 秒会改用 Google。换一个更小的模型会快一些。", secs)
}
+ /// 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.
+ fun notesLine(host: String, model: String, sharedKey: Boolean): String? {
+ val n = notes as? Notes.Fail ?: return null
+ return when (n.why) {
+ Reason.InvalidKey, Reason.MgmtKey ->
+ if (sharedKey) LF("%@ 不认上面的 key,给它单独填一个。", host) else LF("%@ 说这个 key 无效,可能没复制全,或已删除。", host)
+ Reason.Unreachable -> LF("这台手机访问不到 %@。", host)
+ Reason.BadAddress -> L("地址要用 https;这台手机和局域网里的服务可以用 http。")
+ Reason.NoCredit -> LF("%@ 账户余额不足。", host)
+ Reason.NoModel -> LF("%@ 上找不到 %@ 这个模型。", host, model)
+ Reason.NoJSON -> L("这个模型没按要求返回 JSON,写不了纪要。换一个通用模型。")
+ Reason.Deaf, Reason.Busy -> null
+ Reason.ServerError -> LF("%@ 暂时出错(HTTP %lld),稍后再试。", host, n.code ?: 0)
+ }
+ }
+
/// The proxy line under "can't reach": what this phone's proxy looks like, and what to do.
fun proxyLine(service: String, host: String): String? {
if (failure?.reason != Reason.Unreachable) return null
@@ -197,7 +232,8 @@ data class AICheck(
}
return parts + (proxy?.let { " proxy=${lower(it.name)}" } ?: "") +
(balance?.let { " balance=${String.format(java.util.Locale.US, "%.2f", it)}" } ?: "") + (if (passive) " passive" else "") +
- (translate?.let { " translate=${String.format(java.util.Locale.US, "%.1f", it.seconds)}s${if (it.thinks) " thinks" else ""}" } ?: "")
+ (translate?.let { " translate=${String.format(java.util.Locale.US, "%.1f", it.seconds)}s${if (it.thinks) " thinks" else ""}" } ?: "") +
+ (notes?.let { " notes=$it" } ?: "")
}
companion object {
diff --git a/android/core/src/main/kotlin/cicada/Ling.kt b/android/core/src/main/kotlin/cicada/Ling.kt
index 8b00264..1d7f0ed 100644
--- a/android/core/src/main/kotlin/cicada/Ling.kt
+++ b/android/core/src/main/kotlin/cicada/Ling.kt
@@ -73,6 +73,9 @@ class AIKey(private val protector: KeyProtector, private val file: File? = null,
/// Reads the files again (a dev build's key pushed in with adb).
@Synchronized fun reload() { cache.clear() }
+ /// Another key file in the same store, sealed the same way (the custom service's notes key).
+ fun sibling(service: String) = AIKey(protector, service = { service })
+
companion object {
/// "sk-••••••••••••3f9a" for display.
fun masked(key: String) = if (key.length <= 8) "sk-…" else key.take(3) + "•".repeat(12) + key.takeLast(4)
@@ -161,8 +164,12 @@ class LingClient(
private val transport: Transport = UrlTransport,
val config: () -> AIConfig = { Providers.configFrom(AppSettings()) },
private val clock: GateClock = GateClock(),
+ /** The custom service's notes server's own key (另一个服务): `ai-key-custom-notes`, as on the Mac. */
+ private val notesKeys: AIKey = key.sibling(NOTES_KEY),
) {
companion object {
+ /// The key file of the custom service's notes server.
+ const val NOTES_KEY = "custom-notes"
val BASE = Providers.LING.base!!
val DEFAULT_MODEL = Providers.LING.textModels[0].id
val AUDIO_MODEL = Providers.LING.hearModels[0].id
@@ -241,8 +248,10 @@ class LingClient(
/// Debug control only: report this OpenRouter balance instead of the real one.
@Volatile var simulateBalance: Double? = null
private val checkLock = Any()
- /// The custom service refused `chat_template_kwargs` once: leave it out until settings change.
- @Volatile private var noTemplateKwargs = false
+ /// Which servers refused `chat_template_kwargs` once (by host): leave it out there until settings change.
+ @Volatile private var noTemplateKwargs: Set<String> = emptySet()
+ /// Notes' own server's text models from its `/models` (empty while notes share translation's address).
+ @Volatile var notesCatalog: List<String> = emptyList(); private set
private val listeners = mutableListOf<() -> Unit>()
fun onChange(listener: () -> Unit) { synchronized(listeners) { listeners.add(listener) } }
@@ -259,6 +268,19 @@ class LingClient(
}
val hasKey get() = currentKey() != null
+
+ /// The key notes are sent with: with 另一个服务, their own key file if there is one, else the
+ /// translation key ("不填就用上面的 key").
+ fun notesKey(): String? {
+ if (config().notesOwnService) notesKeys.read()?.let { return it }
+ return currentKey()
+ }
+ /// Notes have a key file of their own (另一个服务 only).
+ val notesHasOwnKey get() = config().notesOwnService && notesKeys.read() != null
+ /// Notes' own key (另一个服务), saved; the caller checks again.
+ fun setNotesKey(raw: String): Boolean = raw.trim().isNotEmpty() && notesKeys.save(raw)
+ /// Notes go back to the translation key.
+ fun removeNotesKey() = notesKeys.remove()
val usable get() = hasKey && keyState != KeyState.Invalid
/// The service's own voice reads my words to the other side (otherwise the phone's voice).
val speaks get() = usable && config().hasVoices
@@ -319,7 +341,9 @@ class LingClient(
/// The key, the service or its models changed: forget what the last check found.
fun keyChanged() {
key.reload()
- noTemplateKwargs = false
+ notesKeys.reload()
+ noTemplateKwargs = emptySet()
+ notesCatalog = emptyList()
keyState = if (currentKey() == null) KeyState.None else KeyState.Unchecked
synchronized(checkLock) { aiCheck = AICheck() }
lastVoice = null
@@ -388,7 +412,13 @@ class LingClient(
r = r.pass(AICheck.StepID.Text, (System.nanoTime() - started) / 1e9)
}
if (c.provider.id == "openrouter") r = r.copy(balance = openRouterBalance(c, k))
- if (c.provider.id == "custom") {
+ if (c.notesApart) {
+ // Notes at their own model or server: their failure is theirs, translation goes on.
+ r = r.copy(notes = AICheck.Notes.Running)
+ synchronized(checkLock) { aiCheck = r }
+ changed()
+ r = r.copy(notes = checkNotes(c))
+ } else if (c.provider.id == "custom") {
val ask = "Reply with the JSON object {\"ok\": true}."
try {
chat(ask, "Reply.", Priority.Speak, json = true, maxTokens = 20, timeout = 30.0, jsonFallback = false)
@@ -432,16 +462,58 @@ class LingClient(
val listed = fetchCatalog()
val hearOwn = hearListed
if (listed != null) {
- // A model the service no longer lists fails here, before a meeting finds out.
- // A hear model on its own server isn't on this list: that server's own was read for it.
+ // A model the service no longer lists fails here, before a meeting finds out. On a custom
+ // service, one a real sentence just went through exists whatever the list says (an alias,
+ // a name typed by hand). A hear model on its own server isn't on this list: that server's
+ // own was read for it.
val hearing = if (c.hearsElsewhere) hearOwn else listed.second
- if (c.textModel !in listed.first) r = r.fail(AICheck.StepID.Text, AICheck.Reason.NoModel)
+ val proven = c.provider.id == "custom" && r[AICheck.StepID.Text] is AICheck.State.Ok
+ if (!proven && c.textModel !in listed.first) r = r.fail(AICheck.StepID.Text, AICheck.Reason.NoModel)
else if (hearing != null && c.hearModel !in hearing) r = r.fail(AICheck.StepID.Hear, AICheck.Reason.Deaf)
}
}
return finishCheck(r, c)
}
+ /// Notes' own model or server: one JSON request the way a meeting's notes ask (straight to the
+ /// server: a check doesn't wait out 429s), then, at another address, its model list for the menu.
+ private fun checkNotes(config: AIConfig): AICheck.Notes {
+ if (config.notesBadAddress) return AICheck.Notes.Fail(AICheck.Reason.BadAddress)
+ val c = config.forNotes
+ val k = notesKey()
+ val base = c.base
+ if (k == null || base == null) return AICheck.Notes.Fail(AICheck.Reason.InvalidKey)
+ val url = base + "chat/completions"
+ val json = linkedMapOf<String, Any?>("model" to c.textModel, "messages" to listOf(
+ mapOf("role" to "system", "content" to "Reply with the JSON object {\"ok\": true}."), mapOf("role" to "user", "content" to "Reply.")))
+ c.shape(json, 20, templateKwargs = host(base) !in noTemplateKwargs)
+ json["response_format"] = mapOf("type" to "json_object")
+ val started = System.nanoTime()
+ fun seconds() = (System.nanoTime() - started) / 1e9
+ val result = try {
+ postChat(url, json, k, 60.0, notes = true)
+ AICheck.Notes.Ok(seconds())
+ } catch (e: LingException) {
+ if (e.kind == LingException.Kind.Http && (e.status == 400 || e.status == 422)) {
+ // JSON mode refused: meetings then ask without it, so what counts is a JSON object back.
+ json.remove("response_format")
+ val said = try {
+ postChat(url, json, k, 60.0, notes = true)["choices"].arr().firstOrNull().obj()?.get("message").obj()?.get("content").str()
+ } catch (_: LingException) { null }
+ if (answersJSON(said)) AICheck.Notes.Ok(seconds()) else AICheck.Notes.Fail(AICheck.Reason.NoJSON, e.status)
+ } else {
+ val f = AICheck.classify(e, AICheck.StepID.Text)
+ AICheck.Notes.Fail(f?.reason ?: AICheck.Reason.ServerError, f?.code)
+ }
+ } catch (e: InterruptedException) {
+ throw e
+ } catch (_: Exception) {
+ AICheck.Notes.Fail(AICheck.Reason.Unreachable)
+ }
+ if (c.base != config.base) fetchNotesCatalog()
+ return result
+ }
+
private fun finishCheck(result: AICheck, c: AIConfig): KeyState {
var r = result
if (r.failure?.reason == AICheck.Reason.Unreachable && r.proxy == null && !unreachableNearby(r)) r = r.copy(proxy = proxyHint?.invoke())
@@ -479,8 +551,25 @@ class LingClient(
/// A real request (hearing, 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 fun observe(failure: LingException?, seconds: Double = 0.0, audio: Boolean = false) {
+ private fun observe(failure: LingException?, seconds: Double = 0.0, audio: Boolean = false, notes: Boolean = false) {
if (!hasKey || simulateCheck != null) return
+ if (notes) {
+ // Notes at their own model or server: theirs alone, translation's steps are untouched.
+ val now = if (failure != null) {
+ val f = AICheck.classify(failure, AICheck.StepID.Text) ?: return
+ if (f.reason == AICheck.Reason.ServerError) return
+ AICheck.Notes.Fail(f.reason, f.code)
+ } else AICheck.Notes.Ok(seconds)
+ synchronized(checkLock) {
+ val before = aiCheck
+ if (before.running || checking > 0) return
+ if (before.notes?.ok == true && now.ok) return
+ aiCheck = before.copy(notes = now)
+ }
+ Log.d("ai: notes from a real request -> $now")
+ changed()
+ return
+ }
val step = if (audio) AICheck.StepID.Hear else AICheck.StepID.Text
val now: AICheck
val wasUnreachable: Boolean
@@ -543,6 +632,18 @@ class LingClient(
return listed to AICheck.listedHearing(body)
}
+ /// Notes' own address's text models, for its menu. Quietly empty when it has no `/models`.
+ fun fetchNotesCatalog() {
+ val c = config()
+ val base = c.forNotes.base
+ val k = notesKey()
+ if (!c.notesApart || base == null || base == c.base || k == null) return
+ val body = models(base, k) ?: return
+ notesCatalog = Providers.catalog(body, emptyList(), hears = false)
+ Log.d("ai notes: ${notesCatalog.size} models")
+ changed()
+ }
+
/// Which models the hear model's own server says take audio (null: it says nothing, or the
/// hear model shares the text model's address).
@Volatile private var hearListed: Set<String>? = null
@@ -566,10 +667,17 @@ class LingClient(
audioType: String = "audio/wav", patient: Boolean = false, jsonFallback: Boolean = true,
reply: ((Map<String, Any?>) -> Unit)? = null,
): String {
- val k = currentKey() ?: throw LingException(LingException.Kind.NoKey)
- if (keyState == KeyState.Invalid) throw LingException(LingException.Kind.InvalidKey)
- val c = config()
+ val all = config()
+ // Notes (实时纪要, 说话人) go to their own model or server when set; never with their key to
+ // translation's server because their own address can't be used.
+ val notesSide = priority == Priority.Notes && audio == null && all.notesApart
+ if (notesSide && all.notesBadAddress) throw LingException(LingException.Kind.NoKey)
+ val c = if (notesSide) all.forNotes else all
+ val k = (if (notesSide) notesKey() else currentKey()) ?: throw LingException(LingException.Kind.NoKey)
+ if (if (notesSide) aiCheck.notes?.reason == AICheck.Reason.InvalidKey else keyState == KeyState.Invalid)
+ throw LingException(LingException.Kind.InvalidKey)
val base = (if (audio != null) c.hearBase else c.base) ?: throw LingException(LingException.Kind.NoKey)
+ val gate = gate(base)
val m = model ?: c.textModel
val user: Any = if (audio == null) instruction else listOf(c.audioPart(audio, m, audioType), mapOf("type" to "text", "text" to instruction))
val body = linkedMapOf<String, Any?>(
@@ -577,7 +685,7 @@ class LingClient(
"messages" to listOf(mapOf("role" to "system", "content" to content), mapOf("role" to "user", "content" to user)),
"stream" to false,
)
- c.shape(body, maxTokens, templateKwargs = !noTemplateKwargs)
+ c.shape(body, maxTokens, templateKwargs = host(base) !in noTemplateKwargs)
if (json) body["response_format"] = mapOf("type" to "json_object")
val waits = retryWaits(priority, audio != null, patient)
@@ -585,17 +693,17 @@ class LingClient(
var ticket: Long? = null
while (true) {
// One that wouldn't retry fails at once while the service is cooling down: its caller falls back.
- ticket = acquire(priority, c.provider.spacing, ticket, failIfPaused = waits.isEmpty())
+ ticket = acquire(priority, c.provider.spacing, gate, ticket, failIfPaused = waits.isEmpty())
val started = System.nanoTime()
try {
val root = try {
- postChat(base + "chat/completions", body, k, timeout)
+ postChat(base + "chat/completions", body, k, timeout, notesSide)
} catch (e: LingException) {
if (!jsonFallback || e.kind != LingException.Kind.Http || e.status != 400 || body.remove("response_format") == null) throw e
// 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.
Log.d("ling: $priority JSON mode refused (400), asking again without it")
- postChat(base + "chat/completions", body, k, timeout)
+ postChat(base + "chat/completions", body, k, timeout, notesSide)
}
reply?.invoke(root)
val choice = root["choices"].arr().firstOrNull().obj()
@@ -610,13 +718,13 @@ class LingClient(
val usage = root["usage"].obj()
Log.d("ai ${c.provider.id}: $priority ok ${(System.nanoTime() - started) / 1_000_000} ms tokens=${usage?.get("prompt_tokens")}/${usage?.get("completion_tokens")}")
if (rateLimitedAt != null) { rateLimitedAt = null; changed() }
- observe(null, (System.nanoTime() - started) / 1e9, audio = audio != null)
+ observe(null, (System.nanoTime() - started) / 1e9, audio = audio != null, notes = notesSide)
return trimmed
} catch (e: LingException) {
// A reply we drop (a search essay) still proves the service answers.
- observe(e.takeIf { it.kind != LingException.Kind.Hijacked }, audio = audio != null)
+ observe(e.takeIf { it.kind != LingException.Kind.Hijacked }, audio = audio != null, notes = notesSide)
if (e.kind != LingException.Kind.RateLimited) throw e
- val wait = rateLimited(if (waits.isEmpty()) 1.0 else waits[minOf(attempt, waits.size) - 1], e.retryAfter)
+ val wait = rateLimited(if (waits.isEmpty()) 1.0 else waits[minOf(attempt, waits.size) - 1], e.retryAfter, gate)
if (attempt > waits.size || wait == null) { rateLimitedAt = System.currentTimeMillis(); changed(); throw e }
Log.d("ling: $priority 429, retry in ${"%.1f".format(wait)} s")
attempt++
@@ -655,7 +763,7 @@ class LingClient(
val ids = c.voices.map { it.id }
body["voice"] = if (voice in ids) voice else ids.firstOrNull() ?: c.customVoice ?: "Kore"
}
- acquire(Priority.Speak, c.provider.spacing)
+ acquire(Priority.Speak, c.provider.spacing, gate(voiceBase))
val started = System.nanoTime()
val res = try {
transport.stream(voiceBase + "audio/speech", Json.write(body, pretty = false), headers(k), (timeout * 1000).toInt())
@@ -723,20 +831,22 @@ class LingClient(
/// works, isn't sent it again until settings change. A second refusal was about something else
/// (a hear model that takes no audio, no JSON mode): the field stays, in `body` too, so a
/// request asked again without JSON mode still turns thinking off.
- private fun postChat(url: String, body: Map<String, Any?>, k: String, timeout: Double): Map<String, Any?> {
+ /// `notes`: a request to the notes' own model or server (a refused key is theirs, not translation's).
+ private fun postChat(url: String, body: Map<String, Any?>, k: String, timeout: Double, notes: Boolean = false): Map<String, Any?> {
try {
- return post(url, Json.write(body, pretty = false), k, timeout)
+ return post(url, Json.write(body, pretty = false), k, timeout, notes)
} catch (e: LingException) {
if (e.kind != LingException.Kind.Http || e.status !in listOf(400, 422) || "chat_template_kwargs" !in body) throw e
val plain = LinkedHashMap(body).apply { remove("chat_template_kwargs") }
- val root = try { post(url, Json.write(plain, pretty = false), k, timeout) } catch (_: LingException) { throw e }
- if (!noTemplateKwargs) Log.d("ai custom: chat_template_kwargs refused (HTTP ${e.status}), sent without it from now on")
- noTemplateKwargs = true
+ val root = try { post(url, Json.write(plain, pretty = false), k, timeout, notes) } catch (_: LingException) { throw e }
+ val h = host(url)
+ if (h !in noTemplateKwargs) Log.d("ai custom: chat_template_kwargs refused by $h (HTTP ${e.status}), sent without it from now on")
+ noTemplateKwargs = noTemplateKwargs + h
return root
}
}
- private fun post(url: String, payload: String, k: String, timeout: Double): Map<String, Any?> {
+ private fun post(url: String, payload: String, k: String, timeout: Double, notes: Boolean = false): Map<String, Any?> {
val res = try {
transport.send(url, "POST", payload, headers(k), (timeout * 1000).toInt())
} catch (_: SocketTimeoutException) {
@@ -748,7 +858,7 @@ class LingClient(
when (res.status) {
200 -> {}
401, 403 -> {
- if (keyState != KeyState.Invalid) { keyState = KeyState.Invalid; changed() }
+ if (!notes && keyState != KeyState.Invalid) { keyState = KeyState.Invalid; changed() }
throw LingException(LingException.Kind.InvalidKey)
}
429 -> throw LingException(LingException.Kind.RateLimited, 429, retryAfterSeconds(res.retryAfter))
@@ -761,51 +871,59 @@ class LingClient(
}
// Start gate: request starts ≥ `spacing` apart, the most urgent waiting one first, none while
- // the service is cooling down after a 429.
+ // the server is cooling down after a 429. One per server (by host): notes on another server
+ // don't wait behind translation, and a 429 there doesn't hold translation back.
private class Ticket(val priority: Priority, val seq: Long)
- private val gate = Object()
- private val waiting = mutableListOf<Ticket>()
- private var lastStart = Long.MIN_VALUE / 2
- private var pausedUntil = 0L
- private var seq = 0L
+ private class StartGate {
+ val lock = Object()
+ val waiting = mutableListOf<Ticket>()
+ var lastStart = Long.MIN_VALUE / 2
+ /// After a 429 no request starts here before this (`rateLimited`).
+ var pausedUntil = 0L
+ }
+ private val gates = HashMap<String, StartGate>()
+ private val seq = java.util.concurrent.atomic.AtomicLong()
+
+ /// The gate of the server at `base`.
+ private fun gate(base: String?): StartGate = synchronized(gates) { gates.getOrPut(host(base)) { StartGate() } }
/// 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.
- private fun acquire(priority: Priority, serviceSpacing: Double, ticket: Long? = null, failIfPaused: Boolean = false): Long {
+ private fun acquire(priority: Priority, serviceSpacing: Double, g: StartGate, ticket: Long? = null, failIfPaused: Boolean = false): Long {
val spacing = LingClient.spacing ?: serviceSpacing
- synchronized(gate) {
- if (failIfPaused && pausedUntil > clock.now()) throw LingException(LingException.Kind.RateLimited)
- val me = Ticket(priority, ticket ?: ++seq)
- waiting.add(me)
+ synchronized(g.lock) {
+ if (failIfPaused && g.pausedUntil > clock.now()) throw LingException(LingException.Kind.RateLimited)
+ val me = Ticket(priority, ticket ?: seq.incrementAndGet())
+ g.waiting.add(me)
try {
while (true) {
- val head = waiting.minWith(compareBy<Ticket>({ it.priority.ordinal }, { it.seq }))
+ val head = g.waiting.minWith(compareBy<Ticket>({ it.priority.ordinal }, { it.seq }))
val now = clock.now()
- val wait = maxOf((spacing * 1000).toLong() - (now - lastStart), pausedUntil - now)
+ val wait = maxOf((spacing * 1000).toLong() - (now - g.lastStart), g.pausedUntil - now)
if (head === me && wait <= 0) {
- waiting.remove(me)
- lastStart = now
- gate.notifyAll()
+ g.waiting.remove(me)
+ g.lastStart = now
+ g.lock.notifyAll()
return me.seq
}
- clock.wait(gate, if (head === me) wait else 0)
+ clock.wait(g.lock, if (head === me) wait else 0)
}
} catch (e: InterruptedException) {
- waiting.remove(me); gate.notifyAll(); throw e
+ g.waiting.remove(me); g.lock.notifyAll(); throw e
}
}
}
- /// After a 429: no request starts for `backoff` seconds, or as long as the service asked
+ /// After a 429: no request starts at that server for `backoff` seconds, or as long as it asked
/// (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. Null when that is over MAX_PAUSE (the
/// gate still holds for MAX_PAUSE): an outage, not a busy moment.
- private fun rateLimited(backoff: Double, retryAfter: Double?): Double? {
+ private fun rateLimited(backoff: Double, retryAfter: Double?, g: StartGate): Double? {
val wait = maxOf(backoff, retryAfter ?: 0.0) + Math.random() * 0.5
- synchronized(gate) {
- pausedUntil = maxOf(pausedUntil, clock.now() + (minOf(wait, MAX_PAUSE) * 1000).toLong())
- gate.notifyAll()
+ synchronized(g.lock) {
+ g.pausedUntil = maxOf(g.pausedUntil, clock.now() + (minOf(wait, MAX_PAUSE) * 1000).toLong())
+ g.lock.notifyAll()
}
return if (wait <= MAX_PAUSE) wait else null
}
diff --git a/android/core/src/main/kotlin/cicada/Providers.kt b/android/core/src/main/kotlin/cicada/Providers.kt
index cbcf247..b767099 100644
--- a/android/core/src/main/kotlin/cicada/Providers.kt
+++ b/android/core/src/main/kotlin/cicada/Providers.kt
@@ -66,6 +66,9 @@ object Providers {
fun named(raw: String?): Provider = ALL.firstOrNull { it.id == raw } ?: LING
+ /// The custom service's notes model in `aiModels` (the Mac's key): empty is the translation model.
+ const val NOTES_MODEL = "custom.notes"
+
/// This phone itself: a model running in Termux, say.
fun isLocal(hostOrUrl: String): Boolean = host(hostOrUrl) in listOf("localhost", "127.0.0.1", "::1")
@@ -123,8 +126,17 @@ object Providers {
val name = s.aiCustomVoice.trim()
// The hear model may run on its own server (an omni model beside a text one): empty is the same address.
val hearBase = if (s.aiCustomHearBase.isNotBlank()) customBase(s.aiCustomHearBase) else base
- return AIConfig(p, base, s.aiModels["custom"]?.trim().orEmpty(), s.aiHearModels["custom"]?.trim().orEmpty(),
- voice.ifEmpty { null }, if (voice.isNotEmpty()) voiceBase else null, name.ifEmpty { null }, hearBase)
+ // Notes (实时纪要, 说话人) may use another model, and with 另一个服务 another server: empty
+ // is translation's. 同一个服务 keeps the typed address but doesn't use it.
+ val textModel = s.aiModels["custom"]?.trim().orEmpty()
+ val notesModel = s.aiModels[NOTES_MODEL]?.trim().orEmpty()
+ val notesAddress = if (s.aiCustomNotesOwn) s.aiCustomNotesBase.trim() else ""
+ val notesBase = if (notesAddress.isEmpty()) null else customBase(notesAddress)
+ return AIConfig(p, base, textModel, s.aiHearModels["custom"]?.trim().orEmpty(),
+ voice.ifEmpty { null }, if (voice.isNotEmpty()) voiceBase else null, name.ifEmpty { null }, hearBase,
+ notesModel = notesModel.takeIf { it.isNotEmpty() && it != textModel },
+ notesBase = notesBase.takeIf { it != base }, notesOwnService = s.aiCustomNotesOwn,
+ notesBadAddress = notesAddress.isNotEmpty() && notesBase == null)
}
return AIConfig(p, p.base, s.aiModels[p.id]?.ifBlank { null } ?: p.textModels[0].id,
s.aiHearModels[p.id]?.ifBlank { null } ?: p.hearModels[0].id,
@@ -169,7 +181,23 @@ class AIConfig(
val customVoice: String? = null,
/** Where the hear model is asked (a custom service may name its own; null: not a valid address). */
val hearBase: String? = base,
+ /** A custom service's notes (实时纪要, 说话人): another model, and with 另一个服务 another server
+ * with its own key. Null: the same as translation. */
+ val notesModel: String? = null,
+ val notesBase: String? = null,
+ /** 另一个服务 is picked: notes use their own key file when there is one. */
+ val notesOwnService: Boolean = false,
+ /** 另一个服务 with an address that can't be used (http to the internet): notes fail the check. */
+ val notesBadAddress: Boolean = false,
) {
+ /// Notes go somewhere translation doesn't: they get their own check, result and start gate.
+ val notesApart get() = provider.id == "custom" && (notesModel != null || notesBase != null || notesOwnService)
+
+ /// What a notes call is sent with: notes' model at notes' address, the rest as translation.
+ val forNotes: AIConfig get() = if (!notesApart) this else
+ AIConfig(provider, notesBase ?: base, notesModel ?: textModel, hearModel, voiceModel, voiceBase, customVoice, hearBase,
+ notesModel, notesBase, notesOwnService, notesBadAddress)
+
val isLing get() = provider.id == "ling"
val hasVoices get() = voiceModel != null && voiceBase != null
diff --git a/android/core/src/main/kotlin/cicada/Settings.kt b/android/core/src/main/kotlin/cicada/Settings.kt
index 5188d0c..9fbaa29 100644
--- a/android/core/src/main/kotlin/cicada/Settings.kt
+++ b/android/core/src/main/kotlin/cicada/Settings.kt
@@ -24,6 +24,11 @@ class AppSettings(
/// 语音和文字只发给你的服务: with the custom service, Google Translate is never asked. Kept when
/// another service is picked, but only acts on the custom one (`customOnly`).
var aiCustomOnly: Boolean = false,
+ /// 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).
+ var aiCustomNotesOwn: Boolean = false,
+ var aiCustomNotesBase: String = "",
/// "notes" (live notes, default) or "subtitles" (the subtitle bar), for the floating window.
var view: String = "notes",
/// 共享屏幕时让对方看到: let the floating window show up in screenshots and screen recording.
@@ -77,6 +82,7 @@ class AppSettings(
"aiVoiceModels" to aiVoiceModels.toSortedMap(), "aiCustomBase" to aiCustomBase,
"aiCustomVoiceBase" to aiCustomVoiceBase, "aiCustomVoice" to aiCustomVoice,
"aiCustomHearBase" to aiCustomHearBase, "aiCustomOnly" to aiCustomOnly,
+ "aiCustomNotesOwn" to aiCustomNotesOwn, "aiCustomNotesBase" to aiCustomNotesBase,
"showInCapture" to showInCapture, "onboarded" to onboarded, "uiLanguage" to uiLanguage,
"source" to source, "overlay" to overlay, "silenceEnd" to silenceEnd, "silenceMinutes" to silenceMinutes,
"speakerVoices" to speakerVoices, "recordAudio" to recordAudio, "speakBack" to speakBack,
@@ -110,6 +116,7 @@ class AppSettings(
aiVoiceModels = strings(o["aiVoiceModels"]), aiCustomBase = o["aiCustomBase"].str() ?: "",
aiCustomVoiceBase = o["aiCustomVoiceBase"].str() ?: "", aiCustomVoice = o["aiCustomVoice"].str() ?: "",
aiCustomHearBase = o["aiCustomHearBase"].str() ?: "", aiCustomOnly = o["aiCustomOnly"].bool() ?: false,
+ aiCustomNotesOwn = o["aiCustomNotesOwn"].bool() ?: false, aiCustomNotesBase = o["aiCustomNotesBase"].str() ?: "",
showInCapture = o["showInCapture"].bool() ?: false, onboarded = o["onboarded"].bool() ?: false,
uiLanguage = o["uiLanguage"].str() ?: d.uiLanguage, source = o["source"].str() ?: d.source,
overlay = o["overlay"].bool() ?: true,