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): your own AI server can be set per job, on a LAN or Tailscale address over http with no key, and its check says when the model thinks before answering

wquguru31a3e9b2eacd
diff --git a/android/README.md b/android/README.md
index 8cf0169..1927203 100644
--- a/android/README.md
+++ b/android/README.md
@@ -3,7 +3,7 @@
Cicada 的 Android 版:把手机里播放的声音(或面对面时麦克风听到的话)变成双语字幕和实时纪要,存成和 Mac 版同一格式的会议记录。面对面时按住“按住说话”说一句,松开后手机用对方的语言读出来。方案和取舍见 [docs/android-plan.md](../docs/android-plan.md)。
- 声音来源:手机里的声音(`AudioPlaybackCapture`,Android 10 起,排除知了自己;会议和通话 app 系统不让采集)或面对面(麦克风)。
-- 识别:分段发给 AI 服务的“听的模型”,一次请求返回语言、原文和译文。默认 Ling 的 Ming(`Ming-3.0-audio-flash`,片段压成 AAC 再传);用不了 Ling 时可在 设置 › AI 服务 或引导里换成 OpenRouter、ZenMux 或兼容 OpenAI 的自建服务(`core/.../Providers.kt`,推荐 Qwen 3.8 Omni Flash,比 Ming 慢 1–2 秒,片段按 WAV 传,流量大约是 AAC 的 10 倍)。纪要和翻译跟着换;“我说”在有声音模型的服务上用它的声音(OpenRouter、ZenMux 是 Gemini),其余用手机自带的声音;只有“你自己的声音”只能用 Ling。都需要一个 key,声音都会发到所选服务。和 Windows、Linux 同一套做法。
+- 识别:分段发给 AI 服务的“听的模型”,一次请求返回语言、原文和译文。默认 Ling 的 Ming(`Ming-3.0-audio-flash`,片段压成 AAC 再传);用不了 Ling 时可在 设置 › AI 服务 或引导里换成 OpenRouter、ZenMux 或兼容 OpenAI 的自建服务(`core/.../Providers.kt`,推荐 Qwen 3.8 Omni Flash,比 Ming 慢 1–2 秒,片段按 WAV 传,流量大约是 AAC 的 10 倍)。纪要和翻译跟着换;“我说”在有声音模型的服务上用它的声音(OpenRouter、ZenMux 是 Gemini),其余用手机自带的声音;只有“你自己的声音”只能用 Ling。都需要一个 key(自建服务在这台手机或局域网里时可不填,也可以用 http),声音都会发到所选服务(自建服务的听的模型可以另填地址)。和 Windows、Linux 同一套做法。
- 悬浮窗:纪要或字幕条,`FLAG_NOT_FOCUSABLE` 不抢输入,`FLAG_SECURE` 默认不出现在截图和录屏里;打开“共享屏幕时让对方看到”后显示“对方可见”。
- 纪要、记录格式(逐字节和 Mac 一致)、提示词、文案都和 Mac 版一致;英日韩翻译直接用 `Resources/*.lproj/Localizable.strings`,Android 独有的在 `app/src/main/strings/`。
- 检查更新:每天在后台查一次 GitHub Releases,有新版本时在首页、设置和通知里提示,点“更新”用浏览器下载 APK,由系统安装器覆盖安装(签名一致才行),不需要安装权限。
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 41d8547..0e2169f 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -21,6 +21,7 @@
android:icon="@mipmap/ic_launcher"
android:allowBackup="false"
android:dataExtractionRules="@xml/data_extraction_rules"
+ android:networkSecurityConfig="@xml/network_security_config"
android:localeConfig="@xml/locales_config"
android:allowAudioPlaybackCapture="false"
android:supportsRtl="false"
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/AiCheckViews.kt b/android/app/src/main/kotlin/com/wquguru/cicada/AiCheckViews.kt
index 41a41b0..99b2823 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/AiCheckViews.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/AiCheckViews.kt
@@ -101,7 +101,8 @@ object AiCheckViews {
val cfg = ling.config()
val again = if (recheck) listOf(L("重新检查") to { app.recheck() }) else emptyList()
return when (f.reason) {
- Reason.Unreachable -> listOf<Pair<String, () -> Unit>>(L("怎么设置代理") to { open(a, helpUrl()) }) + again
+ // A server on the local network: the proxy help has nothing to say.
+ Reason.Unreachable -> if (ling.unreachableNearby()) again else listOf<Pair<String, () -> Unit>>(L("怎么设置代理") to { open(a, helpUrl()) }) + again
Reason.InvalidKey, Reason.MgmtKey ->
listOf<Pair<String, () -> Unit>>(L("更换 key") to changeKey) + (p.site?.let { listOf<Pair<String, () -> Unit>>(LF("打开 %@", p.name) to { open(a, it) }) } ?: emptyList())
Reason.NoCredit -> listOf<Pair<String, () -> Unit>>(L("去充值") to { open(a, topUp(p)) }) + again
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 77b6e1f..273ca5e 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/AiServiceActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/AiServiceActivity.kt
@@ -26,6 +26,8 @@ class AiServiceActivity : Activity() {
private lateinit var page: LinearLayout
private var unobserve: (() -> Unit)? = null
private var shown: String? = null
+ /// A custom service's rows that are open (翻译和纪要, 听对方, 同传声音); null until the page first decides.
+ private var open: MutableSet<String>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@@ -45,22 +47,19 @@ 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).joinToString("|")
+ ling.textCatalog.size, ling.hearCatalog.size, app.settings.toJson(), Strings.language, open).joinToString("|")
if (key == shown) return
shown = key
page.removeAllViews()
val name = name(p)
+ if (p.id == "custom") { customPage(app, c); return }
// The service, its key (and a custom service's address).
page.addView(ui.sectionLabel(L("服务")))
val rows = mutableListOf<View>(choiceRow(L("服务"), Providers.ALL.map { it.id to label(it) }, p.id) { app.setAiProvider(it) })
- if (p.id == "custom") rows.add(fieldRow(L("地址"), app.settings.aiCustomBase, "https://api.example.com/v1", null) {
- app.settings.aiCustomBase = it; app.settings.save(); app.aiChanged()
- })
val k = ling.currentKey()
val title = when {
k == null -> if (p.id == "custom") L("还没填好") else L("还没填 API key")
- k.isEmpty() -> L("本机服务,不用 key")
else -> AIKey.masked(k)
}
val trailing = if (!k.isNullOrEmpty()) ui.text(L("更换"), 15f, Palette.link, bold = true, lines = 1) else null
@@ -97,8 +96,7 @@ class AiServiceActivity : Activity() {
page.addView(ui.sectionLabel(L("自己选模型")))
page.addView(ui.group(modelRows(app, c)))
- val sent = if (p.id == "custom") host else name
- val foot = (if (c.isLing) "" else L("按所选模型计费。")) + LF("听的时候,声音会发给 %@。", sent)
+ val foot = (if (c.isLing) "" else L("按所选模型计费。")) + LF("听的时候,声音会发给 %@。", name)
page.addView(ui.helper(foot).apply { setPadding(ui.dp(16), ui.dp(12), ui.dp(16), 0) })
}
@@ -153,11 +151,6 @@ class AiServiceActivity : Activity() {
if (p.id == "ling") return listOf(
choiceRow(L("文字模型"), p.textModels.map { it.id to it.id }, c.textModel, helper = L("3.1 更准;3.0 更快、更省")) { app.setAiModel("text", it) },
ui.listRow(L("听的模型"), L("Ming 一次识别并翻译"), trailing = value(c.hearModel), chevron = false))
- if (p.id == "custom") return listOf(
- fieldRow(L("文字模型"), s.aiModels["custom"].orEmpty(), L("例如 qwen3:14b"), L("纪要和整句翻译")) { app.setAiModel("text", it) },
- fieldRow(L("听的模型"), s.aiHearModels["custom"].orEmpty(), L("例如 qwen3-omni"), L("要能输入音频:听对方和“我说”都用它")) { app.setAiModel("hear", it) },
- fieldRow(L("声音模型"), s.aiVoiceModels["custom"].orEmpty(), L("例如 kokoro"), L("需支持 /audio/speech;不填就用手机的声音")) { app.setAiModel("voice", it) },
- fieldRow(L("声音"), s.aiCustomVoice, L("例如 af_heart"), null) { s.aiCustomVoice = it; s.save(); app.aiChanged(check = false) })
val rows = mutableListOf(
modelRow(L("听的模型"), L("听对方和“我说”都用它"), p.hearModels, app.ling.hearCatalog, c.hearModel) { app.setAiModel("hear", it) },
modelRow(L("文字模型"), L("纪要和整句翻译"), p.textModels, app.ling.textCatalog, c.textModel) { app.setAiModel("text", it) })
@@ -165,8 +158,166 @@ class AiServiceActivity : Activity() {
return rows
}
+ // MARK: Own service
+
+ /// 其他(兼容 OpenAI)(AISettings.swift › customPage): one row per use, each at its own address if
+ /// need be (a text model, an audio model and a speech model often run as separate servers),
+ /// each opening to its fields and saying whether it works and how fast. On a phone the hear
+ /// model is what listens: there is no on-device recognition to fall back to.
+ private fun customPage(app: CicadaApp, c: AIConfig) {
+ val ling = app.ling
+ val check = ling.aiCheck
+ // A service that isn't set up yet, or doesn't work, opens where it needs filling in.
+ val opened = open ?: mutableSetOf<String>().also {
+ if (check.failure?.step == AICheck.StepID.Hear) it.add("hear") else if (!check.passed || check.slow) it.add("text")
+ open = it
+ }
+ page.addView(ui.sectionLabel(L("服务")))
+ page.addView(ui.group(listOf(choiceRow(L("服务"), Providers.ALL.map { it.id to label(it) }, c.provider.id) { app.setAiProvider(it) })))
+ page.addView(ui.helper(L("每样可以接不同的机器;这台手机和局域网里的服务可以用 http。")).apply { setPadding(ui.dp(16), ui.dp(8), ui.dp(16), 0) })
+ page.addView(ui.sectionLabel(L("按功能指定")))
+ val rows = mutableListOf<View>()
+ textSection(app, c, opened, rows)
+ hearSection(app, c, opened, rows)
+ voiceSection(app, c, opened, rows)
+ page.addView(ui.group(rows))
+ 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) })
+ // 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("费用以这个服务为准。")) +
+ LF("听的时候,声音会发给 %@。", ling.hearHost.ifEmpty { host })
+ page.addView(ui.helper(foot).apply { setPadding(ui.dp(16), ui.dp(12), ui.dp(16), 0) })
+ }
+
+ /// A row that opens to its fields: a state dot, the use, what it runs on, and how it's doing.
+ private fun useRow(id: String, open: MutableSet<String>, title: String, detail: String, dot: Int, trailing: String?,
+ trailingColor: Int = Palette.tertiary): View {
+ val row = ui.listRow(title, detail, leading = ui.dot(dot), trailing = trailing?.let { ui.text(it, 13f, trailingColor, lines = 1).apply { fontFeatureSettings = "tnum" } }) {
+ if (!open.remove(id)) open.add(id)
+ build()
+ }
+ row.getChildAt(row.childCount - 1).rotation = if (id in open) 90f else 0f
+ return row
+ }
+
+ /// The fields under an open row, indented under its title.
+ private fun panel(vararg views: View?) = ui.stack(0).apply {
+ setPadding(ui.dp(18), 0, 0, ui.dp(8))
+ views.filterNotNull().forEach { addView(it) }
+ }
+
+ private fun note(text: String, color: Int) = ui.text(text, 13f, color).apply { setPadding(ui.dp(16), ui.dp(4), ui.dp(16), ui.dp(8)) }
+
+ private fun badAddress(raw: String) =
+ if (raw.isNotBlank() && Providers.customBase(raw) == null) note(L("地址要用 https;这台手机和局域网里的服务可以用 http。"), Palette.link) else null
+
+ /// An address as the row shows it: host and port ("192.168.1.20:8000").
+ private fun where(raw: String): String {
+ val u = Uri.parse(Providers.customBase(raw) ?: return raw)
+ return (u.host ?: raw) + if (u.port > 0) ":${u.port}" else ""
+ }
+
+ private val grey = android.graphics.Color.parseColor("#C4C7CE")
+
+ 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
+ val trailing = when {
+ check.running -> L("正在检查…")
+ failed && ling.hasKey -> status(app)
+ 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.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))
+ if ("text" !in open) return
+ val k = ling.currentKey()
+ val keyLine = when {
+ k == null -> L("还没填 API key")
+ 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 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)
+ listOfNotNull(L("能写纪要"), check.translate?.let { if (it.thinks) L("会先思考") else L("不思考") }).joinToString(" · ") else null
+ rows.add(panel(
+ 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) },
+ 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()?.let { note(it, AiCheckViews.warn) },
+ if (steps) AiCheckViews.steps(this, ui, recheck = false) { editKey(this, ui) } else null,
+ facts?.let { note(it, Palette.tertiary) },
+ ))
+ }
+
+ /// 听对方: the hear model, which may run on its own server; its state is the check's hear step.
+ private fun hearSection(app: CicadaApp, c: AIConfig, open: MutableSet<String>, rows: MutableList<View>) {
+ val ling = app.ling
+ val s = app.settings
+ val st = ling.aiCheck[AICheck.StepID.Hear]
+ val detail = listOf(ling.hearHost, short(c.hearModel).ifEmpty { L("未填") }).filter { it.isNotEmpty() }.joinToString(" · ")
+ val (dot, trailing) = when {
+ !ling.hasKey -> grey to null
+ st == AICheck.State.Running -> Palette.accent to L("正在检查…")
+ st is AICheck.State.Ok -> AiCheckViews.ok to st.seconds?.let { LF("听 %@ 秒", "%.1f".format(Strings.locale, it)) }
+ st == AICheck.State.Busy -> AiCheckViews.warn to LF("%@ 现在很忙", ling.serviceName)
+ st is AICheck.State.Fail -> Palette.link to (if (st.reason == AICheck.Reason.Unreachable) L("暂时连不上") else L("模型用不了"))
+ else -> grey to null
+ }
+ rows.add(useRow("hear", open, L("听对方"), detail, dot, trailing, if (st is AICheck.State.Fail) Palette.link else Palette.tertiary))
+ if ("hear" !in open) return
+ val problem = if (ling.aiCheck.failure?.step == AICheck.StepID.Hear) ling.checkMessage() else null
+ rows.add(panel(
+ fieldRow(L("模型"), s.aiHearModels["custom"].orEmpty(), L("例如 qwen3-omni"), L("要能输入音频:听对方和“我说”都用它")) { app.setAiModel("hear", it) },
+ fieldRow(L("地址"), s.aiCustomHearBase, L("跟上面一样"), null, L("跟上面一样"), ::where) { s.aiCustomHearBase = it; s.save(); app.aiChanged() },
+ badAddress(s.aiCustomHearBase),
+ problem?.let { note(it, Palette.link) },
+ ))
+ }
+
+ /// 同传声音: the speech model that reads 我说 to the other side; empty is the phone's voice.
+ private fun voiceSection(app: CicadaApp, c: AIConfig, open: MutableSet<String>, rows: MutableList<View>) {
+ val ling = app.ling
+ val s = app.settings
+ val voiceModel = s.aiVoiceModels["custom"].orEmpty()
+ val host = c.voiceBase?.let { Uri.parse(it).host }.orEmpty()
+ val detail = if (voiceModel.isEmpty()) L("没填,用手机的声音") else listOf(host, voiceModel, s.aiCustomVoice).filter { it.isNotEmpty() }.joinToString(" · ")
+ val last = ling.lastVoice?.first
+ val dot = if (voiceModel.isEmpty() || last == null) grey else if (last) AiCheckViews.ok else Palette.link
+ val trailing = if (voiceModel.isEmpty()) null else last?.let { if (it) L("上次正常") else L("上次没出声") }
+ rows.add(useRow("voice", open, L("同传声音"), detail, dot, trailing, if (last == false) Palette.link else Palette.tertiary))
+ if ("voice" !in open) return
+ rows.add(panel(
+ fieldRow(L("模型"), voiceModel, L("例如 kokoro"), L("需支持 /audio/speech;不填就用手机的声音")) { app.setAiModel("voice", it) },
+ fieldRow(L("声音"), s.aiCustomVoice, L("例如 af_heart"), null) { s.aiCustomVoice = it; s.save(); app.aiChanged(check = false) },
+ fieldRow(L("地址"), s.aiCustomVoiceBase, L("跟上面一样"), null, L("跟上面一样"), ::where) { s.aiCustomVoiceBase = it; s.save(); app.aiChanged(check = false) },
+ badAddress(s.aiCustomVoiceBase),
+ ))
+ }
+
/// Recommended models first, with why, then everything else the service lists.
- private fun modelRow(label: String, helper: String, recommended: List<Model>, listed: List<String>, current: String, pick: (String) -> Unit): View {
+ private fun modelRow(label: String, helper: String?, recommended: List<Model>, listed: List<String>, current: String, pick: (String) -> Unit): View {
val options = recommended.map { it.id to (it.id + if (it.note.isNotEmpty()) " · " + L(it.note) else "") }.toMutableList()
for (id in listed) if (options.none { it.first == id }) options.add(id to id)
if (current.isNotEmpty() && options.none { it.first == current }) options.add(current to current)
@@ -181,8 +332,9 @@ class AiServiceActivity : Activity() {
}
/// A typed value (a custom service's address and models): the row shows it, tapping edits it.
- private fun fieldRow(label: String, current: String, hint: String, helper: String?, save: (String) -> Unit) =
- ui.listRow(label, helper, trailing = value(current.ifEmpty { L("未填") }.let(::short))) {
+ private fun fieldRow(label: String, current: String, hint: String, helper: String?, empty: String = L("未填"),
+ shown: (String) -> String = ::short, save: (String) -> Unit) =
+ ui.listRow(label, helper, trailing = value(if (current.isEmpty()) empty else shown(current))) {
ui.input(this, label, current, helper = helper, hint = hint) { if (it != current) save(it) }
}
@@ -260,6 +412,9 @@ class AiServiceActivity : Activity() {
lateinit var dialog: android.app.Dialog
lateinit var submit: () -> Unit
val box = ui.keyField { submit() }
+ // A service on this phone or the local network may need none (the key is optional there).
+ val base = app.ling.config().base
+ if (p.id == "custom" && base != null && Providers.isNearby(base)) box.hint = L("本机和局域网服务可不填")
val field = LinearLayout(activity).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
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 7280e93..e5da8c1 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt
@@ -141,7 +141,7 @@ class DebugReceiver : BroadcastReceiver() {
fun ai(app: CicadaApp): Map<String, Any?> {
val l = app.ling
val c = l.config()
- return mapOf("provider" to c.provider.id, "base" to c.base, "text" to c.textModel, "hear" to c.hearModel, "voice" to c.voiceModel,
+ 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)
diff --git a/android/app/src/main/res/xml/network_security_config.xml b/android/app/src/main/res/xml/network_security_config.xml
new file mode 100644
index 0000000..8cb47e8
--- /dev/null
+++ b/android/app/src/main/res/xml/network_security_config.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Plain http is allowed so a custom AI service on this phone or the local network (Ollama,
+ vLLM on a box at home or work, a Tailscale address) can be reached. This file can't name IP
+ ranges, so the real gate is Providers.customBase: it builds an http address only for such
+ hosts (isNearby), and every other address the app calls is https. -->
+<network-security-config>
+ <base-config cleartextTrafficPermitted="true" />
+</network-security-config>
diff --git a/android/app/src/main/strings/en.lproj/Android.strings b/android/app/src/main/strings/en.lproj/Android.strings
index 3204595..9283878 100644
--- a/android/app/src/main/strings/en.lproj/Android.strings
+++ b/android/app/src/main/strings/en.lproj/Android.strings
@@ -175,7 +175,6 @@
/* AI 服务: other services than Ling (Providers.kt, AiServiceActivity) */
"服务" = "Service";
-"本机服务,不用 key" = "Local service, no key needed";
"加密存在这台手机上,只发给 %@(%@)" = "Encrypted on this phone, sent only to %1$@ (%2$@)";
"加密存在这台手机上,只发给 %@" = "Encrypted on this phone, sent only to %@";
"按所选模型计费。" = "Billed by the models you choose. ";
@@ -219,3 +218,8 @@
"上次同传没出声,用了手机的声音" = "Silent last time; the phone's voice spoke instead";
"这台手机访问不到 %@。" = "This phone can't reach %@.";
"这台手机没开代理。在国内通常要开代理才能用 %@。" = "No proxy is on. In mainland China, %@ usually needs one.";
+"每样可以接不同的机器;这台手机和局域网里的服务可以用 http。" = "Each can use a different machine; services on this phone or your local network can use http.";
+"按功能指定" = "By use";
+"地址要用 https;这台手机和局域网里的服务可以用 http。" = "The address must use https; services on this phone or your local network can use http.";
+"没填,用手机的声音" = "Not set: the phone's voice";
+"本机和局域网服务可不填" = "Optional on this phone or your local network";
diff --git a/android/app/src/main/strings/ja.lproj/Android.strings b/android/app/src/main/strings/ja.lproj/Android.strings
index a6e5436..8704047 100644
--- a/android/app/src/main/strings/ja.lproj/Android.strings
+++ b/android/app/src/main/strings/ja.lproj/Android.strings
@@ -175,7 +175,6 @@
/* AI 服务: other services than Ling (Providers.kt, AiServiceActivity) */
"服务" = "サービス";
-"本机服务,不用 key" = "ローカルサービスのため key は不要です";
"加密存在这台手机上,只发给 %@(%@)" = "このスマホに暗号化して保存し、%1$@(%2$@)にのみ送信します";
"加密存在这台手机上,只发给 %@" = "このスマホに暗号化して保存し、%@ にのみ送信します";
"按所选模型计费。" = "選んだモデルに応じて課金されます。";
@@ -219,3 +218,8 @@
"上次同传没出声,用了手机的声音" = "前回は音声が出ず、スマホの声で読み上げました";
"这台手机访问不到 %@。" = "このスマホから %@ にアクセスできません。";
"这台手机没开代理。在国内通常要开代理才能用 %@。" = "プロキシがオフです。中国本土では %@ を使うのに通常プロキシが必要です。";
+"每样可以接不同的机器;这台手机和局域网里的服务可以用 http。" = "それぞれ別のマシンを使えます。このスマホやローカルネットワークのサービスは http も使えます。";
+"按功能指定" = "用途ごとに設定";
+"地址要用 https;这台手机和局域网里的服务可以用 http。" = "アドレスは https にしてください。このスマホやローカルネットワークのサービスは http も使えます。";
+"没填,用手机的声音" = "未設定:スマホの声";
+"本机和局域网服务可不填" = "このスマホやローカルネットワークでは省略可";
diff --git a/android/app/src/main/strings/ko.lproj/Android.strings b/android/app/src/main/strings/ko.lproj/Android.strings
index 1eecacd..ec1aa36 100644
--- a/android/app/src/main/strings/ko.lproj/Android.strings
+++ b/android/app/src/main/strings/ko.lproj/Android.strings
@@ -175,7 +175,6 @@
/* AI 服务: other services than Ling (Providers.kt, AiServiceActivity) */
"服务" = "서비스";
-"本机服务,不用 key" = "로컬 서비스라 key가 필요 없습니다";
"加密存在这台手机上,只发给 %@(%@)" = "이 휴대폰에 암호화해 저장하고 %1$@(%2$@)에만 보냅니다";
"加密存在这台手机上,只发给 %@" = "이 휴대폰에 암호화해 저장하고 %@에만 보냅니다";
"按所选模型计费。" = "선택한 모델에 따라 요금이 부과됩니다. ";
@@ -219,3 +218,8 @@
"上次同传没出声,用了手机的声音" = "지난번에는 소리가 나지 않아 휴대폰 음성으로 읽었습니다";
"这台手机访问不到 %@。" = "이 휴대폰에서 %@에 연결할 수 없습니다.";
"这台手机没开代理。在国内通常要开代理才能用 %@。" = "프록시가 꺼져 있습니다. 중국 본토에서는 %@을(를) 쓰려면 보통 프록시가 필요합니다.";
+"每样可以接不同的机器;这台手机和局域网里的服务可以用 http。" = "기능마다 다른 컴퓨터를 쓸 수 있습니다. 이 휴대폰이나 로컬 네트워크의 서비스는 http도 쓸 수 있습니다.";
+"按功能指定" = "기능별 설정";
+"地址要用 https;这台手机和局域网里的服务可以用 http。" = "주소는 https여야 합니다. 이 휴대폰이나 로컬 네트워크의 서비스는 http도 쓸 수 있습니다.";
+"没填,用手机的声音" = "설정 안 함: 휴대폰 음성";
+"本机和局域网服务可不填" = "이 휴대폰이나 로컬 네트워크에서는 생략 가능";
diff --git a/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt b/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt
index cc853ef..b7bd684 100644
--- a/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt
@@ -27,6 +27,14 @@ object ProviderTests {
"aiProblemsNameTheService" to ::problemsNameTheService,
"aiAClockIsNotSpeech" to ::clockIsNotSpeech,
"aiFinalNotesKeepRetryingForAboutAMinute" to ::finalNotesRetry,
+ "aiTheLocalNetworkMayUsePlainHTTP" to ::localNetwork,
+ "aiCustomTurnsThinkingOffThroughTheChatTemplate" to ::templateKwargs,
+ "aiAThinkingModelIsSeenFromItsReply" to ::thought,
+ "aiASlowSentenceIsFlagged" to ::slowSentence,
+ "aiAServerThatRefusesTemplateKwargsIsAskedWithout" to ::kwargsRefused,
+ "aiCustomCheckTimesARealSentence" to ::customCheckTimes,
+ "aiTheHearModelMayHaveItsOwnAddress" to ::hearBase,
+ "aiAHearServerThatCantBeReachedFailsHearing" to ::hearServerDown,
)
private fun check(ok: Boolean, what: String) { if (!ok) throw AssertionError(what) }
@@ -95,6 +103,149 @@ object ProviderTests {
equal(null, Providers.customBase(" "), "empty")
}
+ fun localNetwork() {
+ for (ok in listOf("http://192.168.1.20:8000/v1", "10.0.0.5:8000/v1", "http://172.20.1.1/v1", "http://100.101.102.103:8000/v1",
+ "http://169.254.3.4/v1", "http://gpu.local:30000/v1", "http://[fd12:3456::1]:8000/v1", "http://[fe80::1]/v1",
+ "http://[::1]:8000/v1", "http://localhost:8000/v1"))
+ equal("http", Providers.customBase(ok)?.substringBefore("://"), ok)
+ for (no in listOf("http://172.32.0.1/v1", "http://172.15.0.1/v1", "http://100.128.0.1/v1", "http://100.63.0.1/v1", "http://8.8.8.8/v1",
+ "http://192.169.1.1/v1", "http://gpu.example.com/v1", "http://10.0.0.5.evil.com/v1", "http://10.0.0.256/v1",
+ "http://[2001:db8::1]/v1"))
+ equal(null, Providers.customBase(no), no)
+ equal("http://192.168.1.20:8000/v1/", Providers.customBase("192.168.1.20:8000/v1"), "http added for a nearby host")
+ equal("https://10.0.0.5.evil.com/v1/", Providers.customBase("10.0.0.5.evil.com/v1"), "https added for a lookalike")
+ check(Providers.isNearby("http://192.168.1.20:8000/v1/") && !Providers.isLocal("http://192.168.1.20:8000/v1/"), "nearby, not local")
+ // A service on the local network needs no key either.
+ val s = AppSettings(aiProvider = "custom", aiCustomBase = "192.168.1.20:8000/v1", aiModels = mutableMapOf("custom" to "qwen3:14b"))
+ equal("", client(Fake({ _, _ -> reply("ok") }), s, key = null).currentKey(), "no key on the LAN")
+ }
+
+ fun templateKwargs() {
+ val custom = AppSettings(aiProvider = "custom", aiCustomBase = "http://192.168.1.20:8000/v1").aiConfig()
+ val b = mutableMapOf<String, Any?>()
+ custom.shape(b, 50)
+ equal(mapOf("enable_thinking" to false), b["chat_template_kwargs"], "Qwen3 on vLLM / SGLang / llama.cpp: thinking off")
+ val plain = mutableMapOf<String, Any?>()
+ custom.shape(plain, 50, templateKwargs = false)
+ check("chat_template_kwargs" !in plain, "left out for a server that refused it")
+ for (id in listOf("ling", "zenmux", "openrouter")) {
+ val o = mutableMapOf<String, Any?>()
+ AppSettings(aiProvider = id).aiConfig().shape(o, 50)
+ check("chat_template_kwargs" !in o, "$id never gets it")
+ }
+ }
+
+ fun thought() {
+ fun r(message: Map<String, Any?>, usage: Map<String, Any?>? = null): Map<String, Any?> =
+ mapOf("choices" to listOf(mapOf("message" to message))) + (usage?.let { mapOf("usage" to it) } ?: emptyMap())
+ check(!AIConfig.thought(r(mapOf("content" to "周五发布。"))), "a plain answer")
+ check(AIConfig.thought(r(mapOf("content" to "周五发布。", "reasoning_content" to "The user wants…"))), "reasoning_content")
+ // A reasoning parser on the server: the answer itself sits in reasoning_content.
+ check(AIConfig.thought(r(mapOf("content" to "", "reasoning_content" to "周五发布。"))), "answer in reasoning_content")
+ check(AIConfig.thought(r(mapOf("content" to "周五发布。", "reasoning" to "hmm"))), "reasoning (OpenRouter's name)")
+ check(AIConfig.thought(r(mapOf("content" to "<think>hmm</think>周五发布。"))), "<think>")
+ check(AIConfig.thought(r(mapOf("content" to "周五发布。"), mapOf("completion_tokens_details" to mapOf("reasoning_tokens" to 212)))), "reasoning tokens")
+ check(!AIConfig.thought(r(mapOf("content" to "周五发布。", "reasoning_content" to " "), mapOf("completion_tokens_details" to mapOf("reasoning_tokens" to 0)))), "blank and zero")
+ }
+
+ fun slowSentence() {
+ check(!AICheck.Speed(0.4, false).slow, "fast")
+ check(AICheck.Speed(0.4, true).slow, "thinks")
+ check(AICheck.Speed(6.4, false).slow, "slow")
+ val c = AICheck(at = 1).pass(AICheck.StepID.Text, 4.2).copy(translate = AICheck.Speed(4.2, true))
+ check(c.slow && c.slowLine()!!.contains("4.2"), "the slow line says how long")
+ check(AICheck(at = 1).pass(AICheck.StepID.Text, 0.5).copy(translate = AICheck.Speed(0.5, false)).slowLine() == null, "nothing to say")
+ check("translate=4.2s thinks" in c.summary, "in the summary (the settings repaint on it)")
+ }
+
+ fun kwargsRefused() {
+ val s = AppSettings(aiProvider = "custom", aiCustomBase = "http://192.168.1.20:8000/v1", aiModels = mutableMapOf("custom" to "m"))
+ val fake = Fake({ _, b -> if ("chat_template_kwargs" in b) Transport.Response(422, "{}") else reply("好") })
+ val ling = client(fake, s, key = null)
+ equal("好", ling.chat("c", "i", Priority.Translate), "answered without it")
+ equal(2, fake.sent.size, "asked twice")
+ check("chat_template_kwargs" in fake.sent[0].second && "chat_template_kwargs" !in fake.sent[1].second, "the retry leaves it out")
+ ling.chat("c", "i", Priority.Translate)
+ equal(3, fake.sent.size, "not sent again")
+ ling.keyChanged()
+ ling.chat("c", "i", Priority.Translate)
+ check("chat_template_kwargs" in fake.sent[3].second, "back after settings change")
+ // A second refusal is about something else: the field isn't given up.
+ val deaf = Fake({ _, _ -> Transport.Response(400, "{}") })
+ val other = client(deaf, s, key = null)
+ try { other.chat("c", "i", Priority.Translate); throw AssertionError("accepted") } catch (e: LingException) { equal(400, e.status, "the refusal") }
+ try { other.chat("c", "i", Priority.Translate) } catch (_: LingException) {}
+ equal(4, deaf.sent.size, "each call tried both ways")
+ check("chat_template_kwargs" in deaf.sent[2].second, "still sent")
+ }
+
+ fun customCheckTimes() {
+ val s = AppSettings(aiProvider = "custom", aiCustomBase = "http://192.168.1.20:8000/v1", aiModels = mutableMapOf("custom" to "qwen3:14b"),
+ aiHearModels = mutableMapOf("custom" to "qwen3-omni"))
+ val thinking = Transport.Response(200, Json.write(mapOf("choices" to listOf(mapOf(
+ "message" to mapOf("content" to "我们会在周五设计评审后发布新版本。", "reasoning_content" to "Okay, the user…"), "finish_reason" to "stop"))), pretty = false))
+ val fake = Fake({ url, b -> if (url.endsWith("models")) Transport.Response(404, "") else if ("Translate the text" in b) thinking else reply("{\"ok\": true}") })
+ val ling = client(fake, s, key = null)
+ ling.check()
+ val first = body(fake.sent[0].second)
+ equal(120, first["max_tokens"].num()?.toInt(), "a real sentence's room")
+ check("ship the new version on Friday" in first["messages"].arr()[0].obj()!!["content"].str()!!, "the sentence")
+ equal("Translate.", first["messages"].arr()[1].obj()!!["content"], "the instruction")
+ val t = ling.aiCheck.translate
+ check(t != null && t.thinks, "thinking found: ${ling.aiCheck.summary}")
+ check(ling.aiCheck.slow && ling.aiCheck.failure == null, "works, but slow")
+ }
+
+ fun hearBase() {
+ val s = AppSettings(aiProvider = "custom", aiCustomBase = "http://192.168.1.20:8000/v1", aiModels = mutableMapOf("custom" to "m"),
+ aiHearModels = mutableMapOf("custom" to "qwen3-omni"))
+ equal("http://192.168.1.20:8000/v1/", s.aiConfig().hearBase, "empty: the text model's address")
+ check(!s.aiConfig().hearsElsewhere, "same server")
+ s.aiCustomHearBase = "192.168.1.21:8001/v1"
+ equal("http://192.168.1.21:8001/v1/", s.aiConfig().hearBase, "its own")
+ check(s.aiConfig().hearsElsewhere, "another server")
+ s.aiCustomHearBase = "http://hear.example.com/v1"
+ equal(null, s.aiConfig().hearBase, "not a valid address")
+ equal("https://zenmux.ai/api/v1/", AppSettings(aiProvider = "zenmux").aiConfig().hearBase, "others: the service's")
+ s.aiCustomHearBase = "192.168.1.21:8001/v1"
+ val fake = Fake({ _, _ -> reply("LANG: en\nORIGINAL: Hi.\nTRANSLATION: 嗨。") })
+ val ling = client(fake, s, key = null)
+ ling.chat("c", "i", Priority.Translate, model = s.aiConfig().hearModel, audio = byteArrayOf(1))
+ equal("http://192.168.1.21:8001/v1/chat/completions", fake.sent[0].first, "audio to the hear model's address")
+ ling.chat("c", "i", Priority.Translate)
+ equal("http://192.168.1.20:8000/v1/chat/completions", fake.sent[1].first, "text to the text model's")
+ try {
+ s.aiCustomHearBase = "http://192.168.1.21:8001/v1"
+ s.save()
+ equal("http://192.168.1.21:8001/v1", AppSettings.load().aiCustomHearBase, "kept across a restart")
+ } finally { Paths.settings.delete() }
+ }
+
+ fun hearServerDown() {
+ val s = AppSettings(aiProvider = "custom", aiCustomBase = "http://192.168.1.20:8000/v1", aiModels = mutableMapOf("custom" to "m"),
+ aiHearModels = mutableMapOf("custom" to "qwen3-omni"), aiCustomHearBase = "http://192.168.1.21:8001/v1")
+ val fake = Fake({ url, _ ->
+ when {
+ url.endsWith("models") -> Transport.Response(404, "")
+ "192.168.1.21" in url -> throw java.io.IOException("down")
+ else -> reply("{\"ok\": true}")
+ }
+ })
+ val ling = client(fake, s, key = null)
+ ling.proxyHint = { AICheck.ProxyHint.None }
+ ling.check()
+ val f = ling.aiCheck.failure
+ equal(AICheck.StepID.Hear to AICheck.Reason.Unreachable, f?.step to f?.reason, "the hear step: ${ling.aiCheck.summary}")
+ check(ling.checkMessage()!!.contains("192.168.1.21"), "names the hear server: ${ling.checkMessage()}")
+ equal(null, ling.aiCheck.proxy, "no proxy hint for a server on the local network")
+ // A bad hear address stops at hearing, not at the text model's.
+ s.aiCustomHearBase = "http://hear.example.com/v1"
+ ling.keyChanged()
+ ling.check()
+ equal(AICheck.StepID.Hear to AICheck.Reason.BadAddress, ling.aiCheck.failure?.step to ling.aiCheck.failure?.reason, "bad hear address")
+ check(!ling.canHear, "listening can't start without a hear address")
+ }
+
fun settingsRoundTrip() {
try {
AppSettings(aiProvider = "zenmux", aiHearModels = mutableMapOf("zenmux" to "bytedance/doubao-seed-2.0-mini")).save()
@@ -117,6 +268,7 @@ object ProviderTests {
val b = mutableMapOf<String, Any?>()
AppSettings(aiProvider = "custom", aiCustomBase = "https://x.example/v1").aiConfig().shape(b, 5)
check("reasoning" !in b && "thinking" !in b, "a custom service gets neither")
+ check("chat_template_kwargs" in b, "but the chat template's switch")
}
fun audioPart() {
diff --git a/android/core/src/main/kotlin/cicada/AICheck.kt b/android/core/src/main/kotlin/cicada/AICheck.kt
index 4ecf851..2d8275d 100644
--- a/android/core/src/main/kotlin/cicada/AICheck.kt
+++ b/android/core/src/main/kotlin/cicada/AICheck.kt
@@ -22,7 +22,16 @@ data class AICheck(
val proxy: ProxyHint? = null,
/** OpenRouter only: dollars left (the smaller of the key's limit and the account's credits). */
val balance: Double? = null,
+ /** A custom service: how long one real sentence took, and whether the model thought first. */
+ val translate: Speed? = null,
) {
+ 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.
+ val slow get() = thinks || seconds >= SLOW_AFTER
+ companion object { const val SLOW_AFTER = 3.0 }
+ }
+
enum class StepID { Reach, Key, Text, Hear }
enum class Reason { Unreachable, BadAddress, InvalidKey, MgmtKey, NoCredit, NoModel, NoJSON, Deaf, Busy, ServerError }
@@ -61,6 +70,10 @@ data class AICheck(
/** Every step passed (busy counts; a step nothing has tested yet does not block). */
val passed get() = at != null && failure == null && !running
val lowBalance get() = (balance ?: Double.POSITIVE_INFINITY) < LOW_BALANCE
+ /** Text works but every sentence is slow (a thinking model): translations will fall back. */
+ val slow get() = textFailure == null && translate?.slow == true
+ /** The failure, unless it is only the hear model's (a custom service's rows show that apart). */
+ val textFailure get() = failure?.takeIf { it.step != StepID.Hear }
/** Something only the user can fix (a busy service fixes itself). */
val needsUser: Boolean get() {
@@ -111,7 +124,7 @@ data class AICheck(
val f = failure ?: return if (busy) LF("%@ 现在很忙,key 没问题。开会时会自动重试。", service) else null
return when (f.reason) {
Reason.Unreachable -> LF("这台手机访问不到 %@。", host)
- Reason.BadAddress -> L("地址要用 https,只有 localhost 可以用 http。")
+ Reason.BadAddress -> L("地址要用 https;这台手机和局域网里的服务可以用 http。")
Reason.InvalidKey -> LF("%@ 说这个 key 无效,可能没复制全,或已删除。", service)
Reason.MgmtKey -> L("这是 ZenMux 的管理 key,不能用来调用模型。请粘贴 sk-payg 开头的 key。")
Reason.NoCredit -> LF("%@ 账户余额不足。", service)
@@ -142,6 +155,14 @@ data class AICheck(
}
}
+ /// Why translations are slow, and what to do (a custom service).
+ fun slowLine(): String? {
+ val t = translate?.takeIf { slow } ?: return null
+ val secs = String.format(Strings.locale, "%.1f", t.seconds)
+ return if (t.thinks) LF("这个模型先思考再回答,翻一句要 %@ 秒,超过 6 秒会改用 Google。在服务端关掉思考,或换一个不思考的模型。", secs)
+ else LF("翻一句要 %@ 秒,超过 6 秒会改用 Google。换一个更小的模型会快一些。", secs)
+ }
+
/// 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
@@ -172,7 +193,8 @@ data class AICheck(
"${lower(s.id.name)}=$v"
}
return parts + (proxy?.let { " proxy=${lower(it.name)}" } ?: "") +
- (balance?.let { " balance=${String.format(java.util.Locale.US, "%.2f", it)}" } ?: "") + if (passive) " passive" else ""
+ (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 ""}" } ?: "")
}
companion object {
diff --git a/android/core/src/main/kotlin/cicada/Ling.kt b/android/core/src/main/kotlin/cicada/Ling.kt
index b117fa0..fdce5e2 100644
--- a/android/core/src/main/kotlin/cicada/Ling.kt
+++ b/android/core/src/main/kotlin/cicada/Ling.kt
@@ -234,6 +234,8 @@ 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
private val listeners = mutableListOf<() -> Unit>()
fun onChange(listener: () -> Unit) { synchronized(listeners) { listeners.add(listener) } }
@@ -241,11 +243,11 @@ class LingClient(
val provider: Provider get() = config().provider
- /// The key for the service in use. A custom service on this phone may need none: "".
+ /// The key for the service in use. A custom service on this phone or the local network may need none: "".
fun currentKey(): String? {
val c = config()
val k = key.read()
- if (k == null && c.provider.id == "custom" && c.base != null && Providers.isLocal(c.base)) return ""
+ if (k == null && c.provider.id == "custom" && c.base != null && Providers.isNearby(c.base)) return ""
return k
}
@@ -263,14 +265,38 @@ class LingClient(
/// How long the last good check's newest request took, in seconds.
val seconds: Double? get() = aiCheck.steps.mapNotNull { (it.state as? AICheck.State.Ok)?.seconds }.lastOrNull()
/// Listening and 我说 can work: the hear model wasn't found to refuse audio.
- val canHear get() = usable && hears != false && config().hearModel.isNotEmpty()
+ val canHear get() = usable && hears != false && config().let { it.hearModel.isNotEmpty() && it.hearBase != null }
/// The service's name for messages ("这个服务" for a custom address, localized) and its host.
val serviceName: String get() = provider.let { if (it.id == "custom") Strings.L("这个服务") else it.name }
- val serviceHost: String get() = (config().base ?: provider.base)?.let { try { java.net.URI(it).host } catch (_: Exception) { null } } ?: ""
+ val serviceHost: String get() = host(config().base ?: provider.base)
+ /// Where the hear model is asked: the service's host unless a custom service names its own.
+ val hearHost: String get() = config().let { c -> if (c.hearsElsewhere) host(c.hearBase) else serviceHost }
- /// The failed (or busy) step's sentence, for the screens.
- fun checkMessage(): String? = config().let { aiCheck.message(serviceName, serviceHost, it.textModel, it.hearModel) }
+ private fun host(base: String?) = base?.let { try { java.net.URI(it).host } catch (_: Exception) { null } } ?: ""
+
+ /// The failed (or busy) step's sentence, for the screens; a hear model on its own server that
+ /// can't be reached names that server.
+ fun checkMessage(): String? = config().let {
+ val host = if (aiCheck.failure?.step == AICheck.StepID.Hear) hearHost else serviceHost
+ aiCheck.message(serviceName, host, it.textModel, it.hearModel)
+ }
+
+ /// The server that can't be reached is on this phone or the local network: a proxy has nothing
+ /// to do with it, so there's no proxy hint.
+ fun unreachableNearby(r: AICheck = aiCheck): Boolean {
+ val c = config()
+ val base = if (r.failure?.step == AICheck.StepID.Hear) c.hearBase else c.base
+ return r.failure?.reason == AICheck.Reason.Unreachable && base != null && Providers.isNearby(base)
+ }
+
+ /// AICheck.classify, except that a hear model on its own server that can't be reached fails
+ /// the hear step: the text model's address is fine.
+ private fun classify(e: LingException, step: AICheck.StepID, c: AIConfig): AICheck.Failure? {
+ val f = AICheck.classify(e, step) ?: return null
+ return if (step == AICheck.StepID.Hear && c.hearsElsewhere && f.reason == AICheck.Reason.Unreachable)
+ AICheck.Failure(AICheck.StepID.Hear, AICheck.Reason.Unreachable, null) else f
+ }
/// Something only the user can fix, in one line ("Ling 的 key 用不了 · 修好之前听不了"): the
/// listening notification and the live screens. Null without a key (onboarding asks for it).
@@ -283,6 +309,7 @@ class LingClient(
/// The key, the service or its models changed: forget what the last check found.
fun keyChanged() {
key.reload()
+ noTemplateKwargs = false
keyState = if (currentKey() == null) KeyState.None else KeyState.Unchecked
synchronized(checkLock) { aiCheck = AICheck() }
lastVoice = null
@@ -292,7 +319,8 @@ class LingClient(
/// The cheapest requests that prove each step: Ling's tiny model, else one token from the text
/// model (OpenRouter also reads its key info and credits, for the balance). A custom service
- /// must also return JSON (the notes need it). Another service's hear model must take audio
+ /// translates one real sentence instead, timed, to catch a model that thinks before every
+ /// answer, and must also return JSON (the notes need it). Another service's hear model must take audio
/// (half a second of silence), and the model list then tells whether both models still exist.
fun check(): KeyState {
// One at a time (a service change and a key import come close together), and the probes'
@@ -329,12 +357,22 @@ class LingClient(
r = r.pass(AICheck.StepID.Text, (System.nanoTime() - started) / 1e9).pass(AICheck.StepID.Hear, null)
} else {
if (c.textModel.isEmpty()) throw LingException(LingException.Kind.Http, 404)
- chat("Reply with OK.", "Reply.", Priority.Speak, maxTokens = 5, timeout = 20.0)
- r = r.pass(AICheck.StepID.Text, (System.nanoTime() - started) / 1e9)
+ if (c.provider.id == "custom") {
+ // A real sentence, the way a meeting translates: one token says nothing about a
+ // model that thinks for six seconds before every answer.
+ var thinks = false
+ chat("Translate the text into Simplified Chinese. Reply with the translation only.\n\nWe will ship the new version on Friday after the design review.",
+ "Translate.", Priority.Speak, maxTokens = 120, timeout = 30.0) { thinks = AIConfig.thought(it) }
+ val seconds = (System.nanoTime() - started) / 1e9
+ r = r.pass(AICheck.StepID.Text, seconds).copy(translate = AICheck.Speed(seconds, thinks))
+ } else {
+ chat("Reply with OK.", "Reply.", Priority.Speak, maxTokens = 5, timeout = 20.0)
+ 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") {
try {
- chat("Reply with the JSON object {\"ok\": true}.", "Reply.", Priority.Speak, json = true, maxTokens = 20, timeout = 20.0)
+ chat("Reply with the JSON object {\"ok\": true}.", "Reply.", Priority.Speak, json = true, maxTokens = 20, timeout = 30.0)
} catch (e: LingException) {
if (e.kind == LingException.Kind.Http) r = r.fail(AICheck.StepID.Text, AICheck.Reason.NoJSON, e.status) else throw e
}
@@ -343,6 +381,7 @@ class LingClient(
step = AICheck.StepID.Hear
started = System.nanoTime()
if (c.hearModel.isEmpty()) throw LingException(LingException.Kind.Http, 404)
+ if (c.hearBase == null) return finishCheck(r.fail(AICheck.StepID.Hear, AICheck.Reason.BadAddress, reached = false), c)
try {
chat("Transcribe the audio.", "Reply with what is said, or NONE.", Priority.Speak, maxTokens = 10, timeout = 20.0,
model = c.hearModel, audio = silenceWav())
@@ -354,7 +393,7 @@ class LingClient(
}
}
} catch (e: LingException) {
- val f = AICheck.classify(e, step)
+ val f = classify(e, step, c)
if (f != null) {
r = if (f.reason == AICheck.Reason.Busy) r.pass(f.step, null).with(f.step, AICheck.State.Busy) else r.fail(f.step, f.reason, f.code)
} else if (e.kind == LingException.Kind.Hijacked || e.kind == LingException.Kind.Parse) {
@@ -368,9 +407,11 @@ class LingClient(
}
if (r.failure == null && !c.isLing) {
val listed = fetchCatalog()
+ val hearOwn = hearListed
if (listed != null) {
// A model the service no longer lists fails here, before a meeting finds out.
- val hearing = listed.second
+ // 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)
else if (hearing != null && c.hearModel !in hearing) r = r.fail(AICheck.StepID.Hear, AICheck.Reason.Deaf)
}
@@ -380,7 +421,7 @@ class LingClient(
private fun finishCheck(result: AICheck, c: AIConfig): KeyState {
var r = result
- if (r.failure?.reason == AICheck.Reason.Unreachable && r.proxy == null) r = r.copy(proxy = proxyHint?.invoke())
+ if (r.failure?.reason == AICheck.Reason.Unreachable && r.proxy == null && !unreachableNearby(r)) r = r.copy(proxy = proxyHint?.invoke())
simulateBalance?.let { r = r.copy(balance = it) }
r = r.copy(at = System.currentTimeMillis())
synchronized(checkLock) { aiCheck = r }
@@ -425,7 +466,7 @@ class LingClient(
if (before.running || checking > 0) return
var r = before
if (failure != null) {
- val f = AICheck.classify(failure, step) ?: return
+ val f = classify(failure, step, config()) ?: return
if (f.reason == AICheck.Reason.ServerError) return
r = if (f.reason == AICheck.Reason.Busy) r.pass(AICheck.StepID.Key, null).with(f.step, AICheck.State.Busy) else r.fail(f.step, f.reason, f.code)
} else {
@@ -442,7 +483,7 @@ class LingClient(
Log.d("ai: from a real request -> ${now.summary}")
changed()
val hint = proxyHint
- if (now.failure?.reason == AICheck.Reason.Unreachable && !wasUnreachable && hint != null) {
+ if (now.failure?.reason == AICheck.Reason.Unreachable && !wasUnreachable && hint != null && !unreachableNearby(now)) {
val p = hint()
synchronized(checkLock) { if (aiCheck.failure?.reason == AICheck.Reason.Unreachable) aiCheck = aiCheck.copy(proxy = p) }
changed()
@@ -458,19 +499,34 @@ class LingClient(
/// The service's models, for the model pickers: those that chat, and those that hear. Quietly
/// just the recommended ones when the service has no `/models`. Returns every listed id and,
- /// when the reply says which take audio, those (to tell whether the chosen models exist).
+ /// when the reply says which take audio, those (to tell whether the chosen models exist). A
+ /// hear model on its own server: that server's list fills the hear picker and `hearListed`.
fun fetchCatalog(): Pair<Set<String>, Set<String>?>? {
val c = config()
val k = currentKey() ?: return null
if (c.isLing || c.base == null) return null
- val res = try { transport.send(c.base + "models", "GET", null, headers(k), 20_000) } catch (_: Exception) { return null }
- if (res.status != 200) return null
- textCatalog = Providers.catalog(res.body, c.provider.textModels.map { it.id }, hears = false)
- hearCatalog = Providers.catalog(res.body, c.provider.hearModels.map { it.id }, hears = true)
+ hearListed = null
+ val hearBody = if (c.hearsElsewhere && c.hearBase != null) models(c.hearBase, k) else null
+ if (hearBody != null) {
+ hearCatalog = Providers.catalog(hearBody, c.provider.hearModels.map { it.id }, hears = true)
+ hearListed = AICheck.listedHearing(hearBody)
+ }
+ val body = models(c.base, k) ?: return null
+ textCatalog = Providers.catalog(body, c.provider.textModels.map { it.id }, hears = false)
+ if (!c.hearsElsewhere) hearCatalog = Providers.catalog(body, c.provider.hearModels.map { it.id }, hears = true)
Log.d("ai ${c.provider.id}: ${textCatalog.size} models, ${hearCatalog.size} hear")
changed()
- val listed = AICheck.listedModels(res.body) ?: return null
- return listed to AICheck.listedHearing(res.body)
+ val listed = AICheck.listedModels(body) ?: return null
+ return listed to AICheck.listedHearing(body)
+ }
+
+ /// 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
+
+ private fun models(base: String, k: String): String? {
+ val res = try { transport.send(base + "models", "GET", null, headers(k), 20_000) } catch (_: Exception) { return null }
+ return if (res.status == 200) res.body else null
}
/// One chat completion. `content` goes in the system message, `instruction` is the fixed user
@@ -478,15 +534,17 @@ class LingClient(
/// retry 429s with backoff (retryWaits); the rest fail fast so the caller can fall back.
/// `patient` (the final notes) keeps retrying for about a minute. A 429 holds every request
/// start for a while (rateLimited), and a retry keeps its place in the queue, so lines stay in order.
+ /// Audio goes to the hear model's address (a custom service may name its own). `reply` sees the
+ /// whole reply (the check reads whether the model thought).
fun chat(
content: String, instruction: String, priority: Priority, json: Boolean = false,
maxTokens: Int = 1024, timeout: Double = 30.0, model: String? = null, audio: ByteArray? = null,
- audioType: String = "audio/wav", patient: Boolean = false,
+ audioType: String = "audio/wav", patient: Boolean = false, 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 base = c.base ?: throw LingException(LingException.Kind.NoKey)
+ val base = (if (audio != null) c.hearBase else c.base) ?: throw LingException(LingException.Kind.NoKey)
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?>(
@@ -494,9 +552,8 @@ 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)
+ c.shape(body, maxTokens, templateKwargs = !noTemplateKwargs)
if (json) body["response_format"] = mapOf("type" to "json_object")
- val payload = Json.write(body, pretty = false)
val waits = retryWaits(priority, audio != null, patient)
var attempt = 1
@@ -506,7 +563,8 @@ class LingClient(
ticket = acquire(priority, c.provider.spacing, ticket, failIfPaused = waits.isEmpty())
val started = System.nanoTime()
try {
- val root = post(base + "chat/completions", payload, k, timeout)
+ val root = postChat(base + "chat/completions", body, k, timeout)
+ reply?.invoke(root)
val choice = root["choices"].arr().firstOrNull().obj()
val text = choice?.get("message").obj()?.get("content").str() ?: throw LingException(LingException.Kind.Parse)
val finish = choice?.get("finish_reason").str()
@@ -627,6 +685,22 @@ class LingClient(
return h
}
+ /// 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, when that
+ /// works, isn't sent it again until settings change. A second refusal was about something else
+ /// (a hear model that takes no audio): the field stays. `body` loses the field either way.
+ private fun postChat(url: String, body: MutableMap<String, Any?>, k: String, timeout: Double): Map<String, Any?> {
+ try {
+ return post(url, Json.write(body, pretty = false), k, timeout)
+ } catch (e: LingException) {
+ if (e.kind != LingException.Kind.Http || e.status !in listOf(400, 422) || body.remove("chat_template_kwargs") == null) throw e
+ val root = post(url, Json.write(body, pretty = false), k, timeout)
+ if (!noTemplateKwargs) Log.d("ai custom: chat_template_kwargs refused (HTTP ${e.status}), sent without it from now on")
+ noTemplateKwargs = true
+ return root
+ }
+ }
+
private fun post(url: String, payload: String, k: String, timeout: Double): Map<String, Any?> {
val res = try {
transport.send(url, "POST", payload, headers(k), (timeout * 1000).toInt())
diff --git a/android/core/src/main/kotlin/cicada/Providers.kt b/android/core/src/main/kotlin/cicada/Providers.kt
index 3b8899c..cbcf247 100644
--- a/android/core/src/main/kotlin/cicada/Providers.kt
+++ b/android/core/src/main/kotlin/cicada/Providers.kt
@@ -66,24 +66,45 @@ object Providers {
fun named(raw: String?): Provider = ALL.firstOrNull { it.id == raw } ?: LING
- fun isLocal(hostOrUrl: String): Boolean {
- val u = if ("://" in hostOrUrl) hostOrUrl else "http://$hostOrUrl"
- val host = try { URI(u).host } catch (_: Exception) { null } ?: hostOrUrl
- return host in listOf("localhost", "127.0.0.1", "::1", "[::1]")
+ /// This phone itself: a model running in Termux, say.
+ fun isLocal(hostOrUrl: String): Boolean = host(hostOrUrl) in listOf("localhost", "127.0.0.1", "::1")
+
+ /// This phone or the local network (AIProvider.isNearby on the Mac): plain http is allowed and
+ /// a key isn't needed. Private IPv4 (10/8, 172.16/12, 192.168/16), link-local, Tailscale's
+ /// 100.64/10, IPv6 unique and link-local addresses, and `.local` names. On a phone "localhost"
+ /// is the phone, so a GPU box at home or work is the usual case.
+ fun isNearby(hostOrUrl: String): Boolean {
+ val h = host(hostOrUrl).lowercase()
+ if (isLocal(h) || h.endsWith(".local")) return true
+ val labels = h.split('.')
+ val parts = labels.mapNotNull { it.toIntOrNull() }
+ if (labels.size == 4 && parts.size == 4 && parts.all { it in 0..255 }) {
+ val (a, b) = parts
+ return a == 10 || (a == 192 && b == 168) || (a == 169 && b == 254) || (a == 172 && b in 16..31) || (a == 100 && b in 64..127)
+ }
+ if (':' in h) return h.startsWith("fc") || h.startsWith("fd") || h.startsWith("fe80")
+ return false
+ }
+
+ private fun host(hostOrUrl: String): String {
+ val s = hostOrUrl.trim()
+ val u = if ("://" in s) s else "http://$s"
+ val host = try { URI(u).host } catch (_: Exception) { null } ?: s
+ return host.trim('[', ']')
}
- /// The address as typed, normalized: https, or http only on this device; ends in "/". On a
- /// phone "localhost" is the phone itself (a model running in Termux, say).
+ /// The address as typed, normalized: https, or http only on this phone or the local network;
+ /// ends in "/".
fun customBase(raw: String?): String? {
var s = raw?.trim() ?: return null
if (s.isEmpty()) return null
- if ("://" !in s) s = (if (isLocal(s)) "http://" else "https://") + s
+ if ("://" !in s) s = (if (isNearby(s)) "http://" else "https://") + s
if (!s.endsWith("/")) s += "/"
val uri = try { URI(s) } catch (_: Exception) { return null }
val host = uri.host ?: return null
return when (uri.scheme) {
"https" -> s
- "http" -> if (isLocal(host)) s else null
+ "http" -> if (isNearby(host)) s else null
else -> null
}
}
@@ -100,8 +121,10 @@ object Providers {
val voice = s.aiVoiceModels["custom"]?.trim().orEmpty()
val voiceBase = if (s.aiCustomVoiceBase.isNotBlank()) customBase(s.aiCustomVoiceBase) else base
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 })
+ voice.ifEmpty { null }, if (voice.isNotEmpty()) voiceBase else null, name.ifEmpty { null }, hearBase)
}
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,
@@ -144,6 +167,8 @@ class AIConfig(
val voiceModel: String? = null,
val voiceBase: String? = null,
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,
) {
val isLing get() = provider.id == "ling"
val hasVoices get() = voiceModel != null && voiceBase != null
@@ -155,12 +180,31 @@ class AIConfig(
else -> provider.voices
}
- /// Each service turns thinking off its own way (AIConfig.shape on the Mac).
- fun shape(body: MutableMap<String, Any?>, maxTokens: Int) {
+ /// The hear model is on another server than the text model.
+ val hearsElsewhere get() = hearBase != base
+
+ /// Each service turns thinking off its own way (AIConfig.shape on the Mac). A custom service
+ /// gets `chat_template_kwargs` (vLLM, SGLang and llama.cpp pass it to the chat template, which
+ /// is how Qwen3 turns thinking off); `templateKwargs` false leaves it out for a server that refused it.
+ fun shape(body: MutableMap<String, Any?>, maxTokens: Int, templateKwargs: Boolean = true) {
body["max_tokens"] = maxTokens
body["temperature"] = 0.2
if (isLing) body["thinking"] = mapOf("type" to "disabled")
else if (provider.id == "openrouter" || provider.id == "zenmux") body["reasoning"] = mapOf("enabled" to false)
+ else if (provider.id == "custom" && templateKwargs) body["chat_template_kwargs"] = mapOf("enable_thinking" to false)
+ }
+
+ companion object {
+ /// The model thought before answering, which makes every translation slow: a
+ /// `reasoning_content` (or `reasoning`) field, reasoning tokens in the usage, or a `<think>`
+ /// block in the answer.
+ fun thought(root: Map<String, Any?>): Boolean {
+ val message = root["choices"].arr().firstOrNull().obj()?.get("message").obj()
+ for (k in listOf("reasoning_content", "reasoning")) if (!message?.get(k).str().isNullOrBlank()) return true
+ val n = root["usage"].obj()?.get("completion_tokens_details").obj()?.get("reasoning_tokens").num()
+ if (n != null && n > 0) return true
+ return message?.get("content").str()?.contains("<think>") == true
+ }
}
/// One clip in a user message: Ming takes a data URL (of any type: the app sends AAC); the
diff --git a/android/core/src/main/kotlin/cicada/Settings.kt b/android/core/src/main/kotlin/cicada/Settings.kt
index 9e76a67..fd4984d 100644
--- a/android/core/src/main/kotlin/cicada/Settings.kt
+++ b/android/core/src/main/kotlin/cicada/Settings.kt
@@ -19,6 +19,8 @@ class AppSettings(
var aiCustomBase: String = "",
var aiCustomVoiceBase: String = "",
var aiCustomVoice: String = "",
+ /// The custom service's hear model's own address (the Mac's aiCustomHearBase); empty: the text model's.
+ var aiCustomHearBase: 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.
@@ -63,6 +65,7 @@ class AppSettings(
"aiProvider" to aiProvider, "aiModels" to aiModels.toSortedMap(), "aiHearModels" to aiHearModels.toSortedMap(),
"aiVoiceModels" to aiVoiceModels.toSortedMap(), "aiCustomBase" to aiCustomBase,
"aiCustomVoiceBase" to aiCustomVoiceBase, "aiCustomVoice" to aiCustomVoice,
+ "aiCustomHearBase" to aiCustomHearBase,
"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,
@@ -94,6 +97,7 @@ class AppSettings(
aiModels = strings(o["aiModels"]), aiHearModels = strings(o["aiHearModels"]),
aiVoiceModels = strings(o["aiVoiceModels"]), aiCustomBase = o["aiCustomBase"].str() ?: "",
aiCustomVoiceBase = o["aiCustomVoiceBase"].str() ?: "", aiCustomVoice = o["aiCustomVoice"].str() ?: "",
+ aiCustomHearBase = o["aiCustomHearBase"].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,