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): when the AI service fails, Settings shows which step broke and how to fix it

wquguru3d808339d39b
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/AiCheckViews.kt b/android/app/src/main/kotlin/com/wquguru/cicada/AiCheckViews.kt
new file mode 100644
index 0000000..c6625d3
--- /dev/null
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/AiCheckViews.kt
@@ -0,0 +1,280 @@
+package com.wquguru.cicada
+
+import android.app.Activity
+import android.content.Context
+import android.content.Intent
+import android.graphics.Color
+import android.net.ConnectivityManager
+import android.net.Uri
+import android.view.Gravity
+import android.view.View
+import android.widget.LinearLayout
+import cicada.AICheck
+import cicada.AICheck.Reason
+import cicada.AICheck.State
+import cicada.AICheck.StepID
+import cicada.Strings
+import cicada.Strings.L
+import cicada.Strings.LF
+
+/// The AI service's check, step by step (AICheckView.swift): 设置 › AI 服务 and the onboarding
+/// show the same list; the home card and the 开始听 sheet say the same in fewer words. Every step
+/// that ran shows its result; the one that failed says why in one line and offers the one thing
+/// that fixes it.
+object AiCheckViews {
+ /// "Busy, retrying": a passing state that still deserves a word (Palette.warn on the Mac).
+ val warn = Color.parseColor("#8A5900")
+ val warnPale = Color.parseColor("#FFF4D6")
+ val ok = Color.parseColor("#1E7B45")
+ val okPale = Color.parseColor("#E3F3E8")
+
+ /// The steps show while something is wrong or being checked; all passed folds into one line.
+ fun showSteps(c: AICheck) = c.running || c.failure != null || c.busy || (c.at != null && !c.passed)
+
+ /// The list of steps. `recheck`: 重新检查 in the failed step (onboarding; the settings have
+ /// their own row). `changeKey` opens the key field.
+ fun steps(a: Activity, ui: Ui, recheck: Boolean, changeKey: () -> Unit): LinearLayout {
+ val app = a.cicada
+ val ling = app.ling
+ val c = ling.aiCheck
+ val cfg = ling.config()
+ val box = ui.stack(0)
+ c.steps.forEachIndexed { i, step ->
+ val st = step.state
+ val row = LinearLayout(a).apply {
+ orientation = LinearLayout.HORIZONTAL
+ setPadding(ui.dp(16), ui.dp(12), ui.dp(16), ui.dp(12))
+ }
+ row.addView(icon(ui, st), LinearLayout.LayoutParams(ui.dp(22), ui.dp(22)).apply { topMargin = ui.dp(1) })
+ val faint = st == State.Skipped || st == State.Untested
+ val texts = ui.stack(4, ui.text(AICheck.title(step.id, ling.serviceHost), 15f, if (faint) Palette.tertiary else Palette.ink, medium = true))
+ if (st is State.Ok && step.id == StepID.Text && !cfg.isLing) texts.addView(ui.text(AiServiceActivity.short(cfg.textModel), 13f, Palette.tertiary, lines = 1))
+ if (st is State.Ok && step.id == StepID.Hear && !cfg.isLing) texts.addView(ui.text(AiServiceActivity.short(cfg.hearModel), 13f, Palette.tertiary, lines = 1))
+ if (st is State.Fail || st == State.Busy) problem(a, ui, texts, st == State.Busy, recheck, changeKey)
+ row.addView(texts, ui.weight().apply { leftMargin = ui.dp(12) })
+ if (st is State.Ok && st.seconds != null)
+ row.addView(ui.text(LF("%@ 秒", "%.1f".format(Strings.locale, st.seconds)), 13f, Palette.tertiary, lines = 1).apply { fontFeatureSettings = "tnum" })
+ row.contentDescription = AICheck.title(step.id, ling.serviceHost)
+ if (i > 0) box.addView(ui.divider())
+ box.addView(row)
+ }
+ return box
+ }
+
+ private fun icon(ui: Ui, s: State): View {
+ val (glyph, fg, bg) = when (s) {
+ is State.Ok -> Triple("✓", ok, okPale)
+ is State.Fail -> Triple("✕", Palette.link, Palette.accentPale)
+ State.Busy -> Triple("!", warn, warnPale)
+ State.Running -> Triple("…", Palette.link, Palette.accentPale)
+ else -> Triple("–", Palette.tertiary, Palette.ground)
+ }
+ return ui.text(glyph, 12f, fg, bold = true).apply { gravity = Gravity.CENTER; background = ui.rounded(bg, 11) }
+ }
+
+ /// Why it failed, the proxy hint when it's the network, and the fix: one dark button, at most one other.
+ private fun problem(a: Activity, ui: Ui, into: LinearLayout, busy: Boolean, recheck: Boolean, changeKey: () -> Unit) {
+ val ling = a.cicada.ling
+ ling.checkMessage()?.let { into.addView(ui.text(it, 13f, if (busy) warn else Palette.link)) }
+ ling.aiCheck.proxyLine(ling.serviceName, ling.serviceHost)?.let {
+ into.addView(ui.text(it, 13f, Palette.body).apply {
+ background = ui.rounded(Palette.ground, 10)
+ setPadding(ui.dp(10), ui.dp(8), ui.dp(10), ui.dp(8))
+ }, ui.lp(top = 4))
+ }
+ val acts = actions(a, recheck, changeKey)
+ if (acts.isEmpty()) return
+ val buttons = LinearLayout(a).apply { orientation = LinearLayout.HORIZONTAL }
+ acts.forEachIndexed { i, (title, run) ->
+ buttons.addView(ui.button(title, if (i == 0) "primary" else "quiet", height = 40) { run() },
+ LinearLayout.LayoutParams(-2, -2).apply { if (i > 0) leftMargin = ui.dp(8) })
+ }
+ into.addView(buttons, ui.lp(top = 6))
+ }
+
+ /// One primary fix and at most one other, by why it failed.
+ fun actions(a: Activity, recheck: Boolean, changeKey: () -> Unit): List<Pair<String, () -> Unit>> {
+ val app = a.cicada
+ val ling = app.ling
+ val f = ling.aiCheck.failure ?: return emptyList()
+ val p = ling.provider
+ 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
+ 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
+ Reason.NoModel -> recommended(p.textModels.firstOrNull()?.id, cfg.textModel)?.let { listOf<Pair<String, () -> Unit>>(LF("换成推荐的 %@", AiServiceActivity.short(it)) to { app.useRecommended("text") }) } ?: again
+ Reason.Deaf -> recommended(p.hearModels.firstOrNull()?.id, cfg.hearModel)?.let { listOf<Pair<String, () -> Unit>>(LF("换成推荐的 %@", AiServiceActivity.short(it)) to { app.useRecommended("hear") }) } ?: again
+ Reason.ServerError -> again
+ Reason.BadAddress, Reason.NoJSON, Reason.Busy -> emptyList()
+ }
+ }
+
+ private fun recommended(first: String?, current: String) = first?.takeIf { it != current }
+
+ /// Where to add money: OpenRouter's credits page, else the service's own site.
+ fun topUp(p: cicada.Provider) = if (p.id == "openrouter") "https://openrouter.ai/settings/credits" else p.site ?: "https://zenmux.ai"
+
+ /// The website's proxy help, in the UI language.
+ fun helpUrl(): String {
+ val prefix = when (Strings.language) { "en" -> "/en"; "ja" -> "/ja"; "ko" -> "/ko"; else -> "" }
+ return "https://cicada.indaloop.app$prefix/start/#proxy"
+ }
+
+ fun open(a: Context, url: String) {
+ try { a.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } catch (_: Exception) {}
+ }
+
+ /// All passed, in one line: "已连接 · 文字 1.8 秒 · 听 0.9 秒", or when the newest evidence came
+ /// from a meeting, "正常 · 12 分钟前开会时用过". Null otherwise.
+ fun summary(c: AICheck): String? {
+ if (!c.passed || c.busy) return null
+ val at = c.at
+ if (c.passive && at != null) return L("正常") + " · " + LF("%@ 开会时用过", relative(at))
+ val text = (c[StepID.Text] as? State.Ok)?.seconds
+ val hear = (c[StepID.Hear] as? State.Ok)?.seconds
+ val parts = listOfNotNull(text?.let { LF("文字 %@ 秒", "%.1f".format(Strings.locale, it)) }, hear?.let { LF("听 %@ 秒", "%.1f".format(Strings.locale, it)) })
+ return (listOf(L("已连接")) + parts).joinToString(" · ")
+ }
+
+ /// "2 分钟前" in the app's language (not the phone's, which may differ).
+ fun relative(at: Long): String {
+ val f = android.icu.text.RelativeDateTimeFormatter.getInstance(android.icu.util.ULocale.forLocale(Strings.locale), null,
+ android.icu.text.RelativeDateTimeFormatter.Style.SHORT, android.icu.text.DisplayContext.CAPITALIZATION_NONE)
+ val minutes = (System.currentTimeMillis() - at) / 60_000
+ return when {
+ minutes < 1 -> f.format(android.icu.text.RelativeDateTimeFormatter.Direction.PLAIN, android.icu.text.RelativeDateTimeFormatter.AbsoluteUnit.NOW)
+ minutes < 60 -> f.format(minutes.toDouble(), android.icu.text.RelativeDateTimeFormatter.Direction.LAST, android.icu.text.RelativeDateTimeFormatter.RelativeUnit.MINUTES)
+ minutes < 60 * 24 -> f.format((minutes / 60).toDouble(), android.icu.text.RelativeDateTimeFormatter.Direction.LAST, android.icu.text.RelativeDateTimeFormatter.RelativeUnit.HOURS)
+ else -> f.format((minutes / 1440).toDouble(), android.icu.text.RelativeDateTimeFormatter.Direction.LAST, android.icu.text.RelativeDateTimeFormatter.RelativeUnit.DAYS)
+ }
+ }
+
+ // MARK: Home card (there is no tray: the card sits where 有新版本 does)
+
+ /// Title and detail when the user must fix something; null otherwise. On a phone the service
+ /// hears too, so most failures stop listening, not just the notes.
+ fun cardWords(app: CicadaApp): Pair<String, String>? {
+ val ling = app.ling
+ val c = ling.aiCheck
+ if (!ling.hasKey || !c.needsUser || c.running) return null
+ val name = ling.serviceName
+ val cfg = ling.config()
+ val stops = L("修好之前听不了")
+ val notesStop = L("字幕照常,纪要先停下")
+ val f = c.failure ?: return c.balanceLine(name)?.let { it to L("用完后就听不了了") }
+ return when (f.reason) {
+ Reason.Unreachable -> LF("连不上 %@", name) to stops
+ Reason.InvalidKey, Reason.MgmtKey -> LF("%@ 的 key 用不了", name) to stops
+ Reason.NoCredit -> LF("%@ 账户余额不足。", name) to stops
+ Reason.NoModel -> LF("%@ 上找不到 %@ 这个模型。", name, AiServiceActivity.short(cfg.textModel)) to notesStop
+ Reason.Deaf -> LF("%@ 听不了声音。", AiServiceActivity.short(cfg.hearModel)) to stops
+ Reason.BadAddress -> L("AI 服务的设置要改一下") to stops
+ Reason.NoJSON -> L("AI 服务的设置要改一下") to notesStop
+ Reason.Busy, Reason.ServerError -> null
+ }
+ }
+
+ fun card(a: Activity, ui: Ui): View? {
+ val (title, detail) = cardWords(a.cicada) ?: return null
+ return LinearLayout(a).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ background = ui.rounded(Palette.card, 22)
+ setPadding(ui.dp(16), ui.dp(12), ui.dp(8), ui.dp(12))
+ addView(ui.tile(R.drawable.i_info, 40, Palette.accentPale, Palette.link).apply { background = ui.rounded(Palette.accentPale, 20) })
+ addView(ui.stack(2, ui.text(title, 15f, Palette.ink, medium = true), ui.helper(detail)), ui.weight().apply { leftMargin = ui.dp(12) })
+ addView(ui.textButton(L("打开设置")) { a.startActivity(Intent(a, AiServiceActivity::class.java)) })
+ accessibilityLiveRegion = View.ACCESSIBILITY_LIVE_REGION_POLITE
+ }
+ }
+
+ // MARK: 开始听
+
+ /// 开始听 stops only on a failure already known: a hear model that takes no audio, or a service
+ /// that still can't be reached after one more look. Anything else (unknown, busy) just starts.
+ fun start(a: Activity, kind: String) {
+ val app = a.cicada
+ val ling = app.ling
+ // Already looking (the re-check below takes up to 20 s offline): one sheet, not two.
+ if (ling.aiCheck.running) return
+ when (ling.aiCheck.failure?.reason) {
+ Reason.Deaf -> deafSheet(a, kind)
+ Reason.Unreachable -> {
+ app.startProblem = L("正在检查…"); app.changed()
+ app.background.execute {
+ ling.check()
+ app.main.post {
+ app.startProblem = null; app.changed()
+ if (a.isFinishing || a.isDestroyed) return@post
+ when (ling.aiCheck.failure?.reason) {
+ Reason.Unreachable -> unreachableSheet(a, kind)
+ Reason.Deaf -> deafSheet(a, kind)
+ else -> app.startListening(a, kind, gate = false)
+ }
+ }
+ }
+ }
+ else -> app.startListening(a, kind, gate = false)
+ }
+ }
+
+ /// Whether 开始听 must stop and say why first (the tile hands it to the home screen).
+ fun blocks(app: CicadaApp) = app.ling.aiCheck.failure?.reason.let { it == Reason.Deaf || it == Reason.Unreachable }
+
+ private fun deafSheet(a: Activity, kind: String) {
+ val app = a.cicada
+ val ui = Ui(a)
+ val cfg = app.ling.config()
+ val model = AiServiceActivity.short(cfg.hearModel)
+ val rec = recommended(cfg.provider.hearModels.firstOrNull()?.id, cfg.hearModel)
+ lateinit var d: android.app.Dialog
+ val body = ui.stack(0, ui.text(LF("%@ 只收文字。换成推荐的模型就能开始听。", model), 15f, Palette.secondary).apply { gravity = Gravity.CENTER; setPadding(ui.dp(12), 0, ui.dp(12), 0) })
+ body.addView(buttons(ui, L("打开设置") to { d.dismiss(); a.startActivity(Intent(a, AiServiceActivity::class.java)) },
+ rec?.let { L("换成推荐的并开始") to { d.dismiss(); app.useRecommended("hear"); app.startListening(a, kind, gate = false) } }), ui.lp(top = 18))
+ d = ui.sheet(a, LF("%@ 现在听不了声音", model), body)
+ d.show()
+ }
+
+ private fun unreachableSheet(a: Activity, kind: String) {
+ val app = a.cicada
+ val ling = app.ling
+ val ui = Ui(a)
+ lateinit var d: android.app.Dialog
+ val body = ui.stack(10)
+ ling.checkMessage()?.let { body.addView(ui.text(it, 15f, Palette.secondary).apply { gravity = Gravity.CENTER }) }
+ ling.aiCheck.proxyLine(ling.serviceName, ling.serviceHost)?.let {
+ body.addView(ui.text(it, 14f, Palette.body).apply { background = ui.rounded(Palette.ground, 12); setPadding(ui.dp(12), ui.dp(10), ui.dp(12), ui.dp(10)) })
+ }
+ body.addView(ui.textButton(L("怎么设置代理")) { open(a, helpUrl()) }.apply {
+ layoutParams = LinearLayout.LayoutParams(-2, -2).apply { gravity = Gravity.CENTER_HORIZONTAL }
+ })
+ body.addView(buttons(ui, L("打开设置") to { d.dismiss(); a.startActivity(Intent(a, AiServiceActivity::class.java)) },
+ L("重新检查并开始") to { d.dismiss(); start(a, kind) }), ui.lp(top = 8))
+ d = ui.sheet(a, LF("连不上 %@", ling.serviceName), body)
+ d.show()
+ }
+
+ /// The fix on top, full width: side by side, English cut "Check Again and Start" short.
+ private fun buttons(ui: Ui, quiet: Pair<String, () -> Unit>, primary: Pair<String, () -> Unit>?) = ui.stack(10).apply {
+ if (primary != null) addView(ui.button(primary.first, "primary") { primary.second() })
+ addView(ui.button(quiet.first, "quiet") { quiet.second() })
+ }
+
+ // MARK: Proxy (read only, to word the hint; the app never sets or uses a proxy of its own)
+
+ /// A proxy set on the network in use (Wi-Fi › 代理, or a VPN app's), or for the whole phone.
+ /// A phone has no proxy app port to look for, so only "on" or "none".
+ fun proxyHint(context: Context): AICheck.ProxyHint {
+ val cm = context.getSystemService(ConnectivityManager::class.java)
+ val link = try { cm?.getLinkProperties(cm.activeNetwork)?.httpProxy } catch (_: Exception) { null }
+ val global = try { cm?.defaultProxy } catch (_: Exception) { null }
+ val prop = System.getProperty("https.proxyHost") ?: System.getProperty("http.proxyHost")
+ val on = link?.host?.isNotEmpty() == true || link?.pacFileUrl?.let { it != Uri.EMPTY } == true ||
+ global?.host?.isNotEmpty() == true || !prop.isNullOrEmpty()
+ cicada.Log.d("ai: proxy link=${link != null} global=${global != null} property=${!prop.isNullOrEmpty()} -> ${if (on) "on" else "none"}")
+ return if (on) AICheck.ProxyHint.SystemOn else AICheck.ProxyHint.None
+ }
+}
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 c1f0598..77b6e1f 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/AiServiceActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/AiServiceActivity.kt
@@ -7,9 +7,9 @@ import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
+import cicada.AICheck
import cicada.AIConfig
import cicada.AIKey
-import cicada.KeyState
import cicada.Model
import cicada.Provider
import cicada.Providers
@@ -44,7 +44,7 @@ class AiServiceActivity : Activity() {
val ling = app.ling
val c = ling.config()
val p = c.provider
- val key = listOf(ling.keyState, ling.currentKey()?.takeLast(4), ling.hears, ling.problem, ling.seconds?.let { "%.1f".format(it) },
+ 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("|")
if (key == shown) return
shown = key
@@ -70,6 +70,24 @@ class AiServiceActivity : Activity() {
if (k == null && p.site != null) rows.add(ui.listRow(LF("打开 %@", name), null, trailing = ui.icon(R.drawable.i_external, 18, Palette.link), chevron = false) {
try { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(p.site))) } catch (_: Exception) {}
})
+ // Where it broke and the one thing that fixes it; all passed folds into the key's line.
+ val check = ling.aiCheck
+ if (k != null && AiCheckViews.showSteps(check)) rows.add(AiCheckViews.steps(this, ui, recheck = false) { editKey(this, ui) })
+ check.balanceLine(name)?.let { low ->
+ // Wraps: English runs two lines.
+ rows.add(LinearLayout(this).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ minimumHeight = ui.dp(56)
+ setPadding(ui.dp(16), ui.dp(8), ui.dp(8), ui.dp(8))
+ setBackgroundColor(AiCheckViews.warnPale)
+ addView(ui.text(low, 15f, AiCheckViews.warn), ui.weight())
+ addView(ui.textButton(L("去充值")) { AiCheckViews.open(this@AiServiceActivity, AiCheckViews.topUp(p)) })
+ })
+ }
+ if (k != null) rows.add(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) null else ({ app.recheck() })))
page.addView(ui.group(rows))
val host = c.base?.let { Uri.parse(it).host } ?: L("你填的地址")
page.addView(ui.helper(LF("加密存在这台手机上,只发给 %@(%@)", name, host)).apply { setPadding(ui.dp(16), ui.dp(8), ui.dp(16), 0) })
@@ -87,28 +105,44 @@ class AiServiceActivity : Activity() {
/// 现在能用的 (AISettings.swift › usage): what each part of the app uses with this service.
private fun usesRows(app: CicadaApp, c: AIConfig, name: String): List<View> {
val ling = app.ling
- val on = ling.usable
+ // Only what the last result supports: when the service can't be reached (or the key
+ // fails) nothing says "用 ZenMux"; a deaf hear model greys only what hears.
+ val reason = ling.aiCheck.failure?.reason
+ val down = ling.hasKey && reason in listOf(AICheck.Reason.Unreachable, AICheck.Reason.BadAddress, AICheck.Reason.InvalidKey,
+ AICheck.Reason.MgmtKey, AICheck.Reason.NoCredit)
+ val on = ling.usable && !down
val uses = LF("用 %@", name)
- val needKey = Triple(L("需要 key"), false, L("填好 key 后可用"))
- val deaf = Triple(L("还不能用"), false, L("这个模型听不了声音,换一个支持音频输入的"))
+ val needKey = Triple(L("需要 key"), 0, L("填好 key 后可用"))
+ val off = Triple(L("暂不可用"), 0, if (reason == AICheck.Reason.Unreachable) LF("连上 %@ 后可用", name) else L("换好 key 后可用"))
+ val notReady = if (down) off else needKey
+ val deaf = Triple(L("还不能用"), 0, LF("%@ 听不了声音。", short(c.hearModel)))
val hear = when {
- !on -> needKey
+ !on -> notReady
ling.hears == false -> deaf
- c.isLing -> Triple(uses, true, L("Ming 一次识别并翻译"))
- else -> Triple(uses, true, short(c.hearModel) + " · " + L("比 Ling 晚 1–2 秒出字"))
+ c.isLing -> Triple(uses, 1, L("Ming 一次识别并翻译"))
+ else -> Triple(uses, 1, short(c.hearModel) + " · " + L("比 Ling 晚 1–2 秒出字"))
+ }
+ val notes = when {
+ !on -> notReady
+ reason == AICheck.Reason.NoModel -> Triple(L("暂不可用"), 0, L("换一个模型后可用"))
+ reason == AICheck.Reason.NoJSON -> Triple(L("暂不可用"), 0, L("这个服务不支持 JSON"))
+ ling.aiCheck.busy -> Triple(L("很忙"), 2, L("会自动重试,纪要可能晚一点"))
+ else -> Triple(uses, 1, L("会中每 45 秒更新"))
}
- val notes = if (on) Triple(uses, true, L("会中每 45 秒更新")) else needKey
val voice = cloudVoice(app)
val say = when {
- !on -> needKey
+ !on -> notReady
ling.hears == false -> deaf
- else -> Triple(uses, true, if (voice != null) LF("%@ 的声音读给对方", voice) else L("手机的声音读给对方"))
+ voice != null && ling.lastVoice?.first == false -> Triple(uses, 1, L("上次同传没出声,用了手机的声音"))
+ voice != null && ling.lastVoice?.first == true -> Triple(uses, 1, LF("%@ 的声音读给对方", voice) + " · " + L("上次同传时正常"))
+ else -> Triple(uses, 1, if (voice != null) LF("%@ 的声音读给对方", voice) else L("手机的声音读给对方"))
}
val rows = mutableListOf(L("听对方") to hear, L("实时纪要") to notes, L("我说 · 面对面") to say)
- if (!c.isLing) rows.add(L("你自己的声音") to Triple(L("只有 Ling"), false, L("换用 Ling 才有")))
+ if (!c.isLing) rows.add(L("你自己的声音") to Triple(L("只有 Ling"), 0, L("换用 Ling 才有")))
return rows.map { (title, u) ->
- val (tag, ok, note) = u
- ui.listRow(title, note, trailing = ui.badge(tag, fg = if (ok) Palette.ink else Palette.secondary, bg = if (ok) Palette.selected else Palette.ground), chevron = false)
+ val (tag, style, note) = u
+ val (fg, bg) = when (style) { 1 -> Palette.ink to Palette.selected; 2 -> AiCheckViews.warn to AiCheckViews.warnPale; else -> Palette.secondary to Palette.ground }
+ ui.listRow(title, note, trailing = ui.badge(tag, fg = fg, bg = bg), chevron = false)
}
}
@@ -170,27 +204,51 @@ class AiServiceActivity : Activity() {
/// How the service is doing, under its key; null when there's nothing to say.
fun status(app: CicadaApp): String? {
val ling = app.ling
- val c = ling.config()
- val name = name(c.provider)
- val problem = ling.problem?.let { pr -> LF(pr[0] as String, *pr.drop(1).map { if (it is String) L(it) else it }.toTypedArray()) }
- return when (ling.keyState) {
- KeyState.None, KeyState.Unchecked -> null
- KeyState.Checking -> L("正在检查…")
- KeyState.Invalid -> if (c.isLing) L("这个 Ling key 无效,看看有没有复制全,或换一个新的")
- else LF("%@ 提示 key 无效,请检查是否复制完整,或重新创建一个", name)
- KeyState.Unreachable -> problem ?: if (c.isLing) L("连不上 Ling,检查一下网络") else LF("连不上 %@,请检查网络或代理", name)
- KeyState.Ok -> problem ?: (L("已连接") + " · " + LF("%@ · 响应约 %@ 秒", short(c.textModel), "%.1f".format(ling.seconds ?: 0.0)))
+ val check = ling.aiCheck
+ if (!ling.hasKey) return null
+ if (check.running) return L("正在检查…")
+ // Named after the step that failed: a missing model is not a connection problem.
+ check.failure?.takeIf { it.reason != AICheck.Reason.Busy }?.let {
+ return when (it.step) {
+ AICheck.StepID.Reach -> L("暂时连不上")
+ AICheck.StepID.Key -> L("这个 key 用不了")
+ AICheck.StepID.Text, AICheck.StepID.Hear -> L("模型用不了")
+ }
}
+ if (check.busy) return LF("%@ 现在很忙", ling.serviceName)
+ return AiCheckViews.summary(check)
}
/// The 设置 row's line: connected (and what that costs in delay), or what's wrong.
fun summary(app: CicadaApp): String {
val ling = app.ling
val k = ling.currentKey() ?: return L("还没填 API key")
- if (ling.keyState != KeyState.Ok) return status(app) ?: AIKey.masked(k)
- if (ling.hears == false) return L("这个模型听不了声音,换一个支持音频输入的")
- if (ling.problem != null) return status(app)!!
- return if (ling.config().isLing) AIKey.masked(k) + " · " + L("正常") else L("已连接") + " · " + L("听对方比 Ling 晚 1–2 秒出字")
+ val check = ling.aiCheck
+ if (check.failure != null || check.busy) return ling.checkMessage() ?: status(app) ?: AIKey.masked(k)
+ if (ling.config().isLing) return AIKey.masked(k) + " · " + L("正常")
+ return status(app) ?: L("已连接")
+ }
+
+ /// The prefix says whose key it is: a management key can't call models, and another
+ /// service's key goes there with one tap (改用 %@ into `into`), never a silent switch.
+ /// True when the key isn't for `service`: don't save it here.
+ fun keyHint(ui: Ui, key: String, service: String, status: android.widget.TextView, into: LinearLayout, switched: () -> Unit): Boolean {
+ val (owner, management) = AICheck.owner(key) ?: return false
+ if (management) {
+ status.text = L("这是 ZenMux 的管理 key,不能用来调用模型。请粘贴 sk-payg 开头的 key。")
+ } else if (owner != service) {
+ val name = Providers.named(owner).name
+ status.text = LF("这是 %@ 的 key。", name)
+ into.addView(ui.button(LF("改用 %@", name), "primary", height = 44) {
+ into.removeAllViews()
+ ui.context.cicada.switchService(owner, key)
+ switched()
+ })
+ } else return false
+ status.setTextColor(Palette.link)
+ status.setCompoundDrawablesRelative(null, null, null, null)
+ status.announceForAccessibility(status.text)
+ return true
}
/// Change or remove the key of the service in use: a sheet with the field, 粘贴, and 删除.
@@ -210,15 +268,18 @@ class AiServiceActivity : Activity() {
addView(box, ui.weight())
addView(ui.button(L("粘贴"), "white", R.drawable.i_clipboard, height = 44) { SettingsActivity.paste(box) })
}
+ val other = LinearLayout(activity).apply { orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_HORIZONTAL }
submit = submit@{
val text = box.text.toString().trim()
+ other.removeAllViews()
+ if (keyHint(ui, text, p.id, status, other) { dialog.dismiss() }) return@submit
if (isLing && !text.startsWith("sk-")) { status.text = L("要粘贴 sk- 开头的 Ling key"); status.setTextColor(Palette.link); return@submit }
if (text.isEmpty()) return@submit
if (!app.key.save(text)) { status.text = L("保存失败"); return@submit }
app.aiChanged()
dialog.dismiss()
}
- val body = ui.stack(10, field, status,
+ val body = ui.stack(10, field, status, other,
LinearLayout(activity).apply {
orientation = LinearLayout.HORIZONTAL
addView(ui.button(L("取消"), "quiet") { dialog.dismiss() }, ui.weight())
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 d4f3f61..e621940 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
@@ -83,6 +83,8 @@ class CicadaApp : Application() {
// The AI service in use (设置 › AI 服务): its key file, address and models, read on every call.
key = AIKey(KeystoreProtector, service = { settings.aiProvider })
ling = LingClient(key, config = { settings.aiConfig() })
+ ling.proxyHint = { AiCheckViews.proxyHint(this) }
+ watchNetwork()
store = SessionStore(loadNow = false)
background.execute { val t = System.currentTimeMillis(); store.load(); Log.d("store: loaded ${store.all().size} in ${System.currentTimeMillis() - t} ms") }
notes = NotesEngine(ling, store)
@@ -157,17 +159,22 @@ class CicadaApp : Application() {
/// Between 开始听 and the service starting (permissions, the consent dialog): further taps wait.
@Volatile var starting = 0L
- fun startListening(context: Context, kind: String) {
- startIntent(context, kind)?.let { context.startActivity(it) }
+ /// From a screen, a known AI service failure first gets its sheet (AiCheckViews.start).
+ fun startListening(context: Context, kind: String, gate: Boolean = true) {
+ if (gate && context is android.app.Activity && !listen.listening && ling.hasKey) { AiCheckViews.start(context, kind); return }
+ startIntent(context, kind, gate = false)?.let { context.startActivity(it) }
}
/// What starting takes: the permissions and consent screen, or onboarding without a key. Null
- /// while already listening or starting (a second tap). The Quick Settings tile opens it itself.
- fun startIntent(context: Context, kind: String): Intent? {
+ /// while already listening or starting (a second tap). The Quick Settings tile opens it itself;
+ /// a known failure sends it to the home screen, which says why (`gate`).
+ fun startIntent(context: Context, kind: String, gate: Boolean = true): Intent? {
if (listen.listening) return null
if (System.currentTimeMillis() - starting < 60_000) return null
startProblem = null
if (!ling.hasKey) return Intent(context, OnboardingActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ if (gate && AiCheckViews.blocks(this))
+ return Intent(context, MainActivity::class.java).putExtra("start", kind).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
starting = System.currentTimeMillis()
return Intent(context, ProjectionActivity::class.java).putExtra("kind", kind).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
@@ -421,6 +428,43 @@ class CicadaApp : Application() {
changed()
}
+ /// 重新检查.
+ fun recheck() { if (ling.hasKey && !ling.aiCheck.running) background.execute { ling.check() } }
+
+ /// One tap on 换成推荐的 ("text" or "hear"): the service's first recommended model, then a
+ /// fresh check. Never done without that tap.
+ fun useRecommended(kind: String) {
+ val p = ling.provider
+ val first = (if (kind == "hear") p.hearModels else p.textModels).firstOrNull()?.id ?: return
+ Log.d("ai: recommended $kind model chosen")
+ setAiModel(kind, if (p.id == "ling") first else "")
+ }
+
+ /// A key pasted for one service that belongs to another (改用 OpenRouter): switch, save it
+ /// there (the key file follows the service), check.
+ fun switchService(id: String, key: String) {
+ settings.aiProvider = id
+ settings.save()
+ Log.d("ai: provider $id (the key's own)")
+ if (!this.key.save(key)) return
+ aiChanged()
+ }
+
+ /// Any change of route (Wi-Fi back, a VPN or proxy turned on) waits 3 s for the network to
+ /// settle, then the client looks again if the service was unreachable. No timer: nothing is
+ /// checked while the network stays the same.
+ private fun watchNetwork() {
+ val cm = getSystemService(android.net.ConnectivityManager::class.java) ?: return
+ val recheck = Runnable { background.execute { ling.networkChanged() } }
+ fun later() { main.removeCallbacks(recheck); main.postDelayed(recheck, 3000) }
+ try {
+ cm.registerDefaultNetworkCallback(object : android.net.ConnectivityManager.NetworkCallback() {
+ override fun onAvailable(network: android.net.Network) = later()
+ override fun onLinkPropertiesChanged(network: android.net.Network, lp: android.net.LinkProperties) = later()
+ })
+ } catch (e: Exception) { Log.d("ai: no network callback ${e.javaClass.simpleName}") }
+ }
+
/// 保存会议录音: what is heard goes to system.m4a as it comes (the Mac keeps it the same way).
private fun startRecording() {
val id = listen.sessionId ?: return
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 f9b6633..7280e93 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt
@@ -21,6 +21,7 @@ import java.util.concurrent.TimeUnit
/// 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
/// 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)
class DebugReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (!BuildConfig.DEBUG) return
@@ -91,6 +92,14 @@ 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-check-sim <reason|lowBalance|off>: every check ends this way (screenshots of each state).
+ "ai-check-sim" -> {
+ app.ling.simulateCheck = cicada.AICheck.reasonNamed(arg)
+ app.ling.simulateBalance = if (arg == "lowBalance") 0.4 else null
+ app.background.execute { app.ling.check() }
+ }
+ // 重新检查.
+ "ai-check" -> app.background.execute { app.ling.check() }
"ai-model" -> {
val kind = arg.substringBefore(' ')
val model = arg.substringAfter(' ', "").trim().removeSurrounding("\"")
@@ -133,7 +142,8 @@ class DebugReceiver : BroadcastReceiver() {
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,
- "state" to l.keyState.name, "hears" to l.hears, "speaks" to l.speaks, "problem" to l.problem,
+ "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/kotlin/com/wquguru/cicada/MainActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/MainActivity.kt
index e5d0729..32b752e 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/MainActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/MainActivity.kt
@@ -41,6 +41,7 @@ class MainActivity : Activity() {
super.onCreate(savedInstanceState)
ui = Ui(this)
if (!cicada.settings.onboarded) startActivity(Intent(this, OnboardingActivity::class.java))
+ startFromTile = intent?.getStringExtra("start")
top = FrameLayout(this); recent = FrameLayout(this)
val body = ui.stack(8, top, recent).apply { setPadding(ui.dp(16), ui.dp(8), ui.dp(16), ui.dp(24)) }
builtTitle = L("会议记录")
@@ -49,6 +50,13 @@ class MainActivity : Activity() {
}
private var builtTitle = ""
+ /// The Quick Settings tile's 开始听, held back by a known AI service failure: say why here.
+ private var startFromTile: String? = null
+
+ override fun onNewIntent(intent: Intent) {
+ super.onNewIntent(intent)
+ startFromTile = intent.getStringExtra("start")
+ }
override fun onResume() {
super.onResume()
@@ -60,6 +68,7 @@ class MainActivity : Activity() {
render()
cicada.updates.checkIfDue(UpdateChecker.STALE)
cicada.main.postDelayed(tick, 1000)
+ startFromTile?.let { kind -> startFromTile = null; AiCheckViews.start(this, kind) }
}
override fun onPause() {
@@ -76,7 +85,7 @@ class MainActivity : Activity() {
val app = cicada
val file = app.importing
val key = listOf(NotesViews.liveKey(app), app.autoEnded, app.settings.source, app.settings.target, app.canOverlay, app.settings.overlay, micDenied, app.listen.spoken,
- app.startProblem, file?.done?.toInt(), app.updates.available?.version).joinToString("|")
+ app.startProblem, file?.done?.toInt(), app.updates.available?.version, AiCheckViews.cardWords(app)).joinToString("|")
if (key == shownTop) return
shownTop = key
top.removeAllViews()
@@ -87,6 +96,8 @@ class MainActivity : Activity() {
else -> startCard()
})
if (app.settings.overlay && !app.canOverlay && file == null) column.addView(tipCard())
+ // The AI service needs the user (a phone has no tray): where the update card goes.
+ if (file == null && !app.listen.listening) AiCheckViews.card(this, ui)?.let { column.addView(it) }
// A new version, under the start card; never while a meeting or a file is going on.
app.updates.available?.takeIf { file == null && !app.listen.listening }?.let { column.addView(updateCard(it)) }
top.addView(column)
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/NotesViews.kt b/android/app/src/main/kotlin/com/wquguru/cicada/NotesViews.kt
index bddba6e..7a7beac 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/NotesViews.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/NotesViews.kt
@@ -96,9 +96,11 @@ object NotesViews {
fun banner(ui: Ui, app: CicadaApp, onMic: (() -> Unit)?): View? {
val problem = app.listen.problem
+ val network = app.listen.problemKind == "network"
val (iconRes, text) = when {
- app.listen.problemKind == "network" -> R.drawable.i_wifi_off to
- (if (app.ling.provider.id == "ling") L("连不上 Ling,联网后继续出字幕") else problem ?: "")
+ network -> R.drawable.i_wifi_off to
+ (if (app.ling.provider.id == "ling") L("连不上 Ling,联网后继续出字幕")
+ else LF("连不上 %@,这段时间的纪要先停在 %@。网络恢复后自动继续。", app.ling.serviceName, notesClock(app)))
app.micSilenced && app.listen.listening -> R.drawable.i_mic to L("麦克风正被通话或其他 app 占用,用完后接着听")
problem != null -> R.drawable.i_info to problem
silent(app) -> R.drawable.i_speaker_off to L("20 秒没听到声音。通话和会议 app 的声音系统不让录")
@@ -113,10 +115,20 @@ object NotesViews {
addView(ui.icon(R.drawable.i_info, 22, Palette.link).apply { setImageDrawable(ui.drawable(iconRes, Palette.link)) })
addView(ui.text(text, 14f, Palette.ink), ui.weight().apply { leftMargin = ui.dp(12) })
if (silent(app) && onMic != null) addView(ui.textButton(L("换成面对面"), onClick = onMic))
+ // The network or the proxy, not the notes: 设置 says which (only on Cicada's own screens).
+ if (network && onMic != null && app.ling.provider.id != "ling")
+ addView(ui.textButton(L("设置")) { ui.context.startActivity(android.content.Intent(ui.context, AiServiceActivity::class.java)) })
accessibilityLiveRegion = View.ACCESSIBILITY_LIVE_REGION_POLITE
}
}
+ /// Where this meeting's notes stop: the time of the last line they cover.
+ private fun notesClock(app: CicadaApp): String {
+ val lines = app.listen.sessionId?.let { app.store.lines(it) }.orEmpty()
+ val covered = app.notes.notes.covered
+ return Languages.clock(if (covered in 1..lines.size) lines[covered - 1].t else 0.0)
+ }
+
/// An import's progress: the bar and "26:40 / 42:15".
fun progress(ui: Ui, file: FileSource): LinearLayout {
val box = ui.stack(8)
@@ -242,15 +254,21 @@ object NotesViews {
NotesEngine.State.NoKey -> CicadaApp.shared.noKeyText()
NotesEngine.State.InvalidKey -> CicadaApp.shared.ling.provider.let { p ->
if (p.id == "ling") L("这个 Ling key 无效,看看有没有复制全,或换一个新的")
- else cicada.Strings.LF("%@ 提示 key 无效,请检查是否复制完整,或重新创建一个", L(p.name))
+ else cicada.Strings.LF("%@ 说这个 key 无效,可能没复制全,或已删除。", L(p.name))
}
- NotesEngine.State.RateLimited -> L("请求过于频繁,稍后会自动重试。")
+ NotesEngine.State.RateLimited -> LF("%@ 很忙,纪要稍后补上。字幕照常。", CicadaApp.shared.ling.serviceName)
NotesEngine.State.Updating -> L("正在整理纪要…")
else -> if (listening) L("说几句后生成纪要,之后每 45 秒更新") else ""
}
if (hint.isNotEmpty()) body.addView(ui.text(hint, 14f, Palette.secondary))
return body
}
+ // A busy service: the notes catch up by themselves, the subtitles never stopped.
+ if (status == NotesEngine.State.RateLimited && listening)
+ body.addView(ui.text(LF("%@ 很忙,纪要稍后补上。字幕照常。", CicadaApp.shared.ling.serviceName), 13f, AiCheckViews.warn).apply {
+ background = ui.rounded(AiCheckViews.warnPale, 10)
+ setPadding(ui.dp(10), ui.dp(8), ui.dp(10), ui.dp(8))
+ }, LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = ui.dp(12) })
if (!compact) {
val head = LinearLayout(ui.context).apply {
orientation = LinearLayout.HORIZONTAL
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/OnboardingActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/OnboardingActivity.kt
index 4b40f4f..0784739 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/OnboardingActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/OnboardingActivity.kt
@@ -53,7 +53,25 @@ class OnboardingActivity : Activity() {
render()
}
- override fun onResume() { super.onResume(); unobserve = cicada.observe { if (step == 2) render() }; shown = null; render(); cicada.main.post(tick) }
+ override fun onResume() { super.onResume(); unobserve = cicada.observe { if (step == 2) render(); checkShown?.invoke() }; shown = null; render(); cicada.main.post(tick) }
+
+ /// The key step's (or its sheet's) check, redrawn when the AI client changes: the same step
+ /// list as the settings, and on to the next step once it passes.
+ private var checkShown: (() -> Unit)? = null
+ private var checkKey: String? = null
+
+ /// Fills `into` with the steps of a check this page started; true once it passed.
+ private fun showCheck(into: LinearLayout): Boolean {
+ val ling = cicada.ling
+ val c = ling.aiCheck
+ val key = c.summary + Strings.language
+ if (key == checkKey) return c.passed
+ checkKey = key
+ into.removeAllViews()
+ if (ling.hasKey && AiCheckViews.showSteps(c) && !c.passed)
+ into.addView(ui.group(listOf(AiCheckViews.steps(this, ui, recheck = true) { cicada.key.remove(); cicada.aiChanged(check = false) })))
+ return c.passed
+ }
override fun onPause() { super.onPause(); unobserve?.invoke(); unobserve = null; cicada.main.removeCallbacks(tick) }
// Back goes to the previous step. Android 13+ delivers back through OnBackInvokedCallback
@@ -170,23 +188,35 @@ class OnboardingActivity : Activity() {
}
imeShown = ime
}
+ // Another service's key pasted here: what it is, and 改用 it with one tap.
+ val other = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
+ val steps = ui.stack(0)
+ var tried = false
+ checkKey = null
+ checkShown = {
+ if (step == 0 && tried && app.ling.hasKey) {
+ if (showCheck(steps)) { tried = false; checkShown = null; next() }
+ else if (!app.ling.aiCheck.running) showStatus(L("加密存在本机,只发给 Ling").let { if (app.ling.provider.id == "ling") it else LF("加密存在这台手机上,只发给 %@", app.ling.serviceName) }, false)
+ }
+ }
submit = submit@{
val text = box.text.toString().trim()
+ other.removeAllViews()
+ // Onboarding never blocks: a key that was checked and failed still goes on (the steps say why).
+ if (tried && !app.ling.aiCheck.running && (text.isEmpty() || text == app.ling.currentKey())) { checkShown = null; next(); return@submit }
+ if (AiServiceActivity.keyHint(ui, text, "ling", status, other) { tried = true; checkKey = null; status.text = L("正在检查…") }) {
+ field.background = ui.rounded(Palette.card, 16, Palette.link, 2)
+ return@submit
+ }
if (!text.startsWith("sk-")) { showStatus(L("要粘贴 sk- 开头的 Ling key"), true); return@submit }
// Back on this page after choosing another service: a Ling key means Ling again.
app.setAiProvider("ling", check = false)
app.key.save(text)
app.ling.keyChanged()
+ tried = true
+ checkKey = null
status.text = L("正在检查…"); status.setTextColor(Palette.secondary)
- app.background.execute {
- val state = app.ling.check()
- app.main.post {
- if (state == KeyState.Ok) { next(); return@post }
- // A key that doesn't work isn't kept: the next launch would skip this step.
- if (state == KeyState.Invalid) { app.key.remove(); app.ling.keyChanged() }
- showStatus(if (state == KeyState.Invalid) L("这个 Ling key 无效,看看有没有复制全,或换一个新的") else L("连不上 Ling,检查一下网络"), true)
- }
- }
+ app.background.execute { app.ling.check() }
}
fun stepRow(n: Int, text: String, action: View? = null) = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
@@ -211,7 +241,7 @@ class OnboardingActivity : Activity() {
ui.logo(64),
intro(L("接上 Ling"), L("识别、翻译和纪要都靠它,大约 1 分钟")),
ui.group(listOf(stepRow(1, L("打开 Ling 开放平台"), open), stepRow(2, L("点“创建令牌”,复制 sk- 开头的 Ling key")), stepRow(3, L("回到这里粘贴")))),
- ui.stack(8, ui.text(L("Ling key"), 13f, Palette.body, bold = true).apply { setPadding(ui.dp(4), 0, 0, 0); labelFor = View.generateViewId().also { box.id = it } }, field, status.apply { setPadding(ui.dp(4), 0, 0, 0) }),
+ ui.stack(8, ui.text(L("Ling key"), 13f, Palette.body, bold = true).apply { setPadding(ui.dp(4), 0, 0, 0); labelFor = View.generateViewId().also { box.id = it } }, field, status.apply { setPadding(ui.dp(4), 0, 0, 0) }, other, steps),
// A way out for people who can't use Ling: another service, in a sheet, saying what it lacks.
ui.textButton(L("用不了 Ling?"), Palette.link) { otherService() }.apply {
layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
@@ -235,23 +265,32 @@ class OnboardingActivity : Activity() {
lateinit var box: android.widget.EditText
box = ui.keyField { check(box.text.toString().trim()) }.apply { hint = LF("粘贴 %@ 的 key", p.name) }
fun problem(text: String) { status.text = text; status.setTextColor(Palette.link); status.announceForAccessibility(text) }
+ val other = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
+ val steps = ui.stack(0)
+ // After a check that failed: the steps say why, and onboarding still goes on.
+ val goOn = ui.textButton(L("继续"), Palette.link) { checkShown = null; dialog.dismiss(); next() }.apply { visibility = View.GONE }
+ fun watch() {
+ checkKey = null
+ checkShown = {
+ if (showCheck(steps)) { checkShown = null; dialog.dismiss(); next() }
+ else {
+ val c = app.ling.aiCheck
+ if (!c.running) status.text = LF("加密存在这台手机上,只发给 %@", app.ling.serviceName)
+ goOn.visibility = if (!c.running && c.failure != null) View.VISIBLE else View.GONE
+ }
+ }
+ }
check = check@{ text ->
+ other.removeAllViews()
+ if (AiServiceActivity.keyHint(ui, text, p.id, status, other) { status.text = L("正在检查…"); watch() }) return@check
if (!text.startsWith("sk-")) { problem(LF("剪贴板里没有 sk- 开头的 key,请先去 %@ 复制。", p.name)); return@check }
- val before = app.settings.aiProvider
+ // The service and key stay as chosen even if the check fails: the steps say why.
app.setAiProvider(p.id, check = false)
app.key.save(text)
app.aiChanged(check = false)
status.text = L("正在检查…"); status.setTextColor(Palette.secondary)
- app.background.execute {
- val state = app.ling.check()
- app.main.post {
- if (state == KeyState.Ok) { dialog.dismiss(); next(); return@post }
- // A key that doesn't work isn't kept, and the service goes back to what it was.
- if (state == KeyState.Invalid) app.key.remove()
- app.setAiProvider(before)
- problem(if (state == KeyState.Invalid) L("这个 key 无效,请检查是否复制完整,或重新创建一个") else LF("连不上 %@,请检查网络或代理", p.name))
- }
- }
+ watch()
+ app.background.execute { app.ling.check() }
}
val field = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
@@ -274,6 +313,9 @@ class OnboardingActivity : Activity() {
sheet.addView(open)
sheet.addView(field)
sheet.addView(status.apply { setPadding(ui.dp(4), 0, ui.dp(4), 0) })
+ sheet.addView(other)
+ sheet.addView(steps.apply { background = ui.rounded(Palette.ground, 16) })
+ sheet.addView(goOn.apply { layoutParams = LinearLayout.LayoutParams(-2, -2).apply { gravity = Gravity.CENTER_HORIZONTAL } })
sheet.addView(ui.button(L("粘贴并检查"), "primary", R.drawable.i_clipboard) {
SettingsActivity.paste(box)
check(box.text.toString().trim())
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt
index 88a8275..6288578 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt
@@ -12,7 +12,6 @@ import android.view.View
import android.widget.LinearLayout
import android.widget.Switch
import cicada.AIKey
-import cicada.KeyState
import cicada.Languages
import cicada.Log
import cicada.Strings
@@ -46,7 +45,7 @@ class SettingsActivity : Activity() {
private fun build() {
val app = cicada
val s = app.settings
- val key = listOf(app.ling.keyState, app.ling.currentKey()?.takeLast(4), app.ling.hears, s.toJson(), app.canOverlay, Strings.language, app.updates.available?.version, app.updates.manual).joinToString("|")
+ val key = listOf(app.ling.keyState, app.ling.currentKey()?.takeLast(4), app.ling.aiCheck.summary, s.toJson(), app.canOverlay, Strings.language, app.updates.available?.version, app.updates.manual).joinToString("|")
if (key == shown) return
shown = key
page.removeAllViews()
diff --git a/android/app/src/main/strings/en.lproj/Android.strings b/android/app/src/main/strings/en.lproj/Android.strings
index c47a64b..6e27287 100644
--- a/android/app/src/main/strings/en.lproj/Android.strings
+++ b/android/app/src/main/strings/en.lproj/Android.strings
@@ -30,7 +30,6 @@
"换成面对面" = "Switch to In person";
"正在听下一句…" = "Listening for next line…";
"这个 Ling key 无效,看看有没有复制全,或换一个新的" = "Invalid Ling key. Check if it's complete, or create a new one.";
-"请求过于频繁,稍后会自动重试。" = "Too many requests; retrying shortly.";
"说几句后生成纪要,之后每 45 秒更新" = "Notes appear after a few lines, then update every 45s";
"返回" = "Back";
"加密存在本机,只发给 Ling" = "Encrypted on this device. Sent only to Ling.";
@@ -207,3 +206,18 @@
"没人说话时不乱写" = "Writes nothing when no one speaks";
"最快,偶尔把杂音写成字" = "Fastest; sometimes writes noise as words";
"更快" = "Faster";
+
+/* AI 服务检查 (AICheck.kt, AiCheckViews.kt): the phone's words */
+"文字 %@ 秒" = "text %@ s";
+"听 %@ 秒" = "listening %@ s";
+"修好之前听不了" = "Listening needs this fixed first";
+"字幕照常,纪要先停下" = "Subtitles go on; notes pause";
+"用完后就听不了了" = "Listening stops when it runs out";
+"%@ 听不了声音。" = "%@ can't take audio.";
+"%@ 只收文字。换成推荐的模型就能开始听。" = "%@ takes text only. Switch to the recommended model to start listening.";
+"换成推荐的并开始" = "Use Recommended and Start";
+"%@ 现在听不了声音" = "%@ can't take audio";
+"重新检查并开始" = "Check Again and Start";
+"上次同传没出声,用了手机的声音" = "Silent last time; the phone's voice spoke instead";
+"这台手机访问不到 %@。" = "This phone can't reach %@.";
+"这台手机没开代理。在国内通常要开代理才能用 %@。" = "No proxy is on. In mainland China, %@ usually needs one.";
diff --git a/android/app/src/main/strings/ja.lproj/Android.strings b/android/app/src/main/strings/ja.lproj/Android.strings
index 2101ecd..a59d37e 100644
--- a/android/app/src/main/strings/ja.lproj/Android.strings
+++ b/android/app/src/main/strings/ja.lproj/Android.strings
@@ -30,7 +30,6 @@
"换成面对面" = "対面に切り替える";
"正在听下一句…" = "次の発言を聞いています…";
"这个 Ling key 无效,看看有没有复制全,或换一个新的" = "この Ling key は無効です。すべてコピーしたか確認するか、新しく作成してください";
-"请求过于频繁,稍后会自动重试。" = "リクエストが多すぎます。まもなく自動で再試行します。";
"说几句后生成纪要,之后每 45 秒更新" = "数文話すと議事メモが作成され、以後45秒ごとに更新されます";
"返回" = "戻る";
"加密存在本机,只发给 Ling" = "端末内に暗号化して保存され、Lingにのみ送信されます";
@@ -207,3 +206,18 @@
"没人说话时不乱写" = "誰も話していないときに勝手に書かない";
"最快,偶尔把杂音写成字" = "最速。ときどき雑音を文字にする";
"更快" = "より速い";
+
+/* AI 服务检查 (AICheck.kt, AiCheckViews.kt): the phone's words */
+"文字 %@ 秒" = "テキスト %@ 秒";
+"听 %@ 秒" = "聞き取り %@ 秒";
+"修好之前听不了" = "直すまで聞き取りはできません";
+"字幕照常,纪要先停下" = "字幕はそのまま、議事メモは一時停止";
+"用完后就听不了了" = "使い切ると聞き取りが止まります";
+"%@ 听不了声音。" = "%@ は音声を聞き取れません。";
+"%@ 只收文字。换成推荐的模型就能开始听。" = "%@ はテキストしか受け取れません。おすすめのモデルに変えると聞き取りを始められます。";
+"换成推荐的并开始" = "おすすめに変えて開始";
+"%@ 现在听不了声音" = "%@ は今は音声を聞き取れません";
+"重新检查并开始" = "再確認して開始";
+"上次同传没出声,用了手机的声音" = "前回は音声が出ず、スマホの声で読み上げました";
+"这台手机访问不到 %@。" = "このスマホから %@ にアクセスできません。";
+"这台手机没开代理。在国内通常要开代理才能用 %@。" = "プロキシがオフです。中国本土では %@ を使うのに通常プロキシが必要です。";
diff --git a/android/app/src/main/strings/ko.lproj/Android.strings b/android/app/src/main/strings/ko.lproj/Android.strings
index bc4cdae..e0eaf92 100644
--- a/android/app/src/main/strings/ko.lproj/Android.strings
+++ b/android/app/src/main/strings/ko.lproj/Android.strings
@@ -30,7 +30,6 @@
"换成面对面" = "대면으로 전환";
"正在听下一句…" = "다음 문장 듣는 중…";
"这个 Ling key 无效,看看有没有复制全,或换一个新的" = "유효하지 않은 Ling key예요. 끝까지 복사했는지 확인하거나 새로 만들어 보세요";
-"请求过于频繁,稍后会自动重试。" = "요청이 너무 많습니다. 잠시 후 자동으로 다시 시도합니다.";
"说几句后生成纪要,之后每 45 秒更新" = "몇 마디 나누면 회의록이 나오고, 이후 45초마다 업데이트돼요";
"返回" = "뒤로";
"加密存在本机,只发给 Ling" = "이 휴대폰에 암호화되어 저장되며 Ling에만 전송돼요";
@@ -207,3 +206,18 @@
"没人说话时不乱写" = "아무도 말하지 않을 때 지어내지 않음";
"最快,偶尔把杂音写成字" = "가장 빠름. 가끔 잡음을 글자로 씀";
"更快" = "더 빠름";
+
+/* AI 服务检查 (AICheck.kt, AiCheckViews.kt): the phone's words */
+"文字 %@ 秒" = "텍스트 %@초";
+"听 %@ 秒" = "듣기 %@초";
+"修好之前听不了" = "고치기 전에는 들을 수 없습니다";
+"字幕照常,纪要先停下" = "자막은 그대로, 회의록은 잠시 멈춥니다";
+"用完后就听不了了" = "다 쓰면 들을 수 없습니다";
+"%@ 听不了声音。" = "%@은(는) 오디오를 들을 수 없습니다.";
+"%@ 只收文字。换成推荐的模型就能开始听。" = "%@은(는) 텍스트만 받습니다. 추천 모델로 바꾸면 듣기를 시작할 수 있습니다.";
+"换成推荐的并开始" = "추천 모델로 바꾸고 시작";
+"%@ 现在听不了声音" = "%@은(는) 지금 오디오를 들을 수 없습니다";
+"重新检查并开始" = "다시 확인하고 시작";
+"上次同传没出声,用了手机的声音" = "지난번에는 소리가 나지 않아 휴대폰 음성으로 읽었습니다";
+"这台手机访问不到 %@。" = "이 휴대폰에서 %@에 연결할 수 없습니다.";
+"这台手机没开代理。在国内通常要开代理才能用 %@。" = "프록시가 꺼져 있습니다. 중국 본토에서는 %@을(를) 쓰려면 보통 프록시가 필요합니다.";
diff --git a/android/cli/src/main/kotlin/cicada/cli/AICheckTests.kt b/android/cli/src/main/kotlin/cicada/cli/AICheckTests.kt
new file mode 100644
index 0000000..1a16186
--- /dev/null
+++ b/android/cli/src/main/kotlin/cicada/cli/AICheckTests.kt
@@ -0,0 +1,267 @@
+// AI 服务检查 (AICheck.kt): the Mac's AICheckTests, plus the port's fourth step (hearing) and the
+// client's check and passive results against a fake transport. No network.
+package cicada.cli
+
+import cicada.*
+import cicada.AICheck.Reason
+import cicada.AICheck.State
+import cicada.AICheck.StepID
+
+object AICheckTests {
+ val tests: List<Pair<String, () -> Unit>> = listOf(
+ "aiCheckEachFailureStopsAtItsStep" to ::classify,
+ "aiCheckAFailedStepSkipsTheRestAndAReplyProvesTheOnesBefore" to ::failSkips,
+ "aiCheckASuccessClearsAnEarlierFailure" to ::passClears,
+ "aiCheckHeardAudioSaysNothingAboutTheTextModel" to ::hearIsNotText,
+ "aiCheckBusyPassesAndNeedsNobody" to ::busyPasses,
+ "aiCheckKeyPrefixesTellWhoseKeyItIs" to ::prefixes,
+ "aiCheckBalanceIsTheSmallerOfKeyLimitAndCredits" to ::balance,
+ "aiCheckListedModelsReadsEveryID" to ::listed,
+ "aiCheckMessagesNameTheServiceAndTheProxyHintFollowsTheProxy" to ::messages,
+ "aiCheckAllFourStepsPassOnAGoodService" to ::clientPasses,
+ "aiCheckAModelTheServiceNoLongerListsIsMissing" to ::clientNoModel,
+ "aiCheckTheHearCatalogCountsOnlyWhenItSaysWhatHears" to ::clientHearCatalog,
+ "aiCheckAManagementKeyIsNeverSent" to ::clientMgmtKey,
+ "aiCheckOpenRouterReadsItsBalance" to ::clientBalance,
+ "aiCheckUnreachableAsksTheProxyAndTheNetworkLooksAgain" to ::clientUnreachable,
+ "aiCheckRealRequestsKeepTheStepsCurrent" to ::clientPassive,
+ "aiCheckSimulatedReasonsForScreenshots" to ::simulated,
+ )
+
+ private fun check(ok: Boolean, what: String) { if (!ok) throw AssertionError(what) }
+ private fun <T> equal(expected: T, actual: T, what: String) { if (expected != actual) throw AssertionError("$what: expected «$expected», got «$actual»") }
+ private fun http(code: Int) = LingException(LingException.Kind.Http, code)
+
+ fun classify() {
+ equal(AICheck.Failure(StepID.Reach, Reason.Unreachable, null), AICheck.classify(LingException(LingException.Kind.Network), StepID.Text), "network")
+ equal(AICheck.Failure(StepID.Reach, Reason.Unreachable, null), AICheck.classify(LingException(LingException.Kind.Timeout), StepID.Hear), "timeout")
+ equal(AICheck.Failure(StepID.Key, Reason.InvalidKey, null), AICheck.classify(LingException(LingException.Kind.InvalidKey), StepID.Text), "401")
+ equal(AICheck.Failure(StepID.Key, Reason.NoCredit, 402), AICheck.classify(http(402), StepID.Text), "402")
+ equal(AICheck.Failure(StepID.Text, Reason.NoModel, 404), AICheck.classify(http(404), StepID.Text), "text 404")
+ equal(AICheck.Failure(StepID.Text, Reason.NoModel, 400), AICheck.classify(http(400), StepID.Text), "text 400")
+ equal(AICheck.Failure(StepID.Text, Reason.Busy, null), AICheck.classify(LingException(LingException.Kind.RateLimited), StepID.Text), "429")
+ equal(AICheck.Failure(StepID.Key, Reason.ServerError, 503), AICheck.classify(http(503), StepID.Key), "5xx")
+ equal(null, AICheck.classify(LingException(LingException.Kind.Hijacked), StepID.Text), "hijacked")
+ // The hear model: the same codes mean it takes no audio, not that it is missing.
+ for (code in listOf(400, 404, 415, 422)) equal(AICheck.Failure(StepID.Hear, Reason.Deaf, code), AICheck.classify(http(code), StepID.Hear), "hear $code")
+ equal(AICheck.Failure(StepID.Text, Reason.ServerError, 415), AICheck.classify(http(415), StepID.Text), "text 415")
+ equal(AICheck.Failure(StepID.Hear, Reason.Busy, null), AICheck.classify(LingException(LingException.Kind.RateLimited), StepID.Hear), "hear 429")
+ }
+
+ fun failSkips() {
+ val c = AICheck().fail(StepID.Key, Reason.InvalidKey)
+ equal(State.Ok(), c[StepID.Reach], "reach proven")
+ equal(State.Fail(Reason.InvalidKey), c[StepID.Key], "key")
+ equal(State.Skipped, c[StepID.Text], "text skipped")
+ equal(State.Skipped, c[StepID.Hear], "hear skipped")
+ equal(StepID.Key, c.failure?.step, "failure")
+ equal(State.Untested, AICheck().fail(StepID.Key, Reason.MgmtKey, reached = false)[StepID.Reach], "nothing sent")
+ }
+
+ fun passClears() {
+ val c = AICheck().fail(StepID.Reach, Reason.Unreachable).copy(proxy = AICheck.ProxyHint.None).pass(StepID.Text, 1.5)
+ equal(null, c.failure, "cleared")
+ check(c[StepID.Reach] == State.Ok() && c[StepID.Text] == State.Ok(1.5), "proven")
+ equal(State.Untested, c[StepID.Hear], "hearing open again")
+ equal(null, c.proxy, "no proxy hint")
+ }
+
+ fun hearIsNotText() {
+ // Heard audio proves the address, the key and the hear model, never the text model.
+ val c = AICheck().fail(StepID.Reach, Reason.Unreachable).pass(StepID.Hear, 0.9)
+ equal(State.Untested, c[StepID.Text], "text unproven")
+ equal(State.Ok(0.9), c[StepID.Hear], "hear")
+ // A deaf reply doesn't make the text model look fine either, nor clear its own failure.
+ val d = AICheck().fail(StepID.Hear, Reason.Deaf, 400)
+ equal(State.Untested, d[StepID.Text], "text still unproven")
+ val m = AICheck().fail(StepID.Text, Reason.NoModel, 404).pass(StepID.Hear, 1.0)
+ equal(Reason.NoModel, m.failure?.reason, "a missing text model stays missing")
+ }
+
+ fun busyPasses() {
+ val c = AICheck().pass(StepID.Text, null).with(StepID.Text, State.Busy).copy(at = 1)
+ check(c.passed && c.busy && !c.needsUser, "busy passes")
+ }
+
+ fun prefixes() {
+ equal("openrouter" to false, AICheck.owner("sk-or-v1-abc"), "OpenRouter")
+ equal("zenmux" to false, AICheck.owner(" sk-payg-abc\n"), "ZenMux")
+ equal("zenmux" to true, AICheck.owner("sk-mgmt-abc"), "management")
+ equal(null, AICheck.owner("sk-abc"), "Ling or anyone")
+ }
+
+ fun balance() {
+ val key = Json.parseObject("""{"data":{"limit_remaining":1.72}}""")
+ val credits = Json.parseObject("""{"data":{"total_credits":10,"total_usage":3.92}}""")
+ equal(1.72, AICheck.balance(key, credits), "smaller")
+ check(Math.abs(AICheck.balance(Json.parseObject("""{"data":{"limit_remaining":null}}"""), credits)!! - 6.08) < 0.001, "no key limit")
+ equal(1.72, AICheck.balance(key, null), "key only")
+ equal(null, AICheck.balance(null, null), "nothing")
+ val c = AICheck(balance = 0.3)
+ check(c.lowBalance && c.needsUser, "low")
+ check(c.balanceLine("OpenRouter")!!.contains("0.30"), "says how much")
+ }
+
+ fun listed() {
+ equal(setOf("inclusionai/ling-3.0-flash", "qwen/qwen3.8-flash"),
+ AICheck.listedModels("""{"data":[{"id":"inclusionai/ling-3.0-flash"},{"id":"qwen/qwen3.8-flash"}]}"""), "ids")
+ equal(null, AICheck.listedModels("{}"), "none")
+ equal(null, AICheck.listedModels("""{"data":[]}"""), "empty")
+ equal(setOf("q/omni"), AICheck.listedHearing("""{"data":[{"id":"q/omni","input_modalities":["text","audio"]},{"id":"q/text","architecture":{"input_modalities":["text"]}}]}"""), "audio in")
+ equal(null, AICheck.listedHearing("""{"data":[{"id":"qwen3:14b"}]}"""), "says nothing about modalities")
+ }
+
+ fun messages() {
+ var c = AICheck().fail(StepID.Reach, Reason.Unreachable)
+ check(c.message("ZenMux", "zenmux.ai", "m", "h")!!.contains("zenmux.ai"), "host")
+ equal(null, c.proxyLine("ZenMux", "zenmux.ai"), "no hint before it's known")
+ c = c.copy(proxy = AICheck.ProxyHint.SystemOn)
+ check(c.proxyLine("ZenMux", "zenmux.ai")!!.contains("zenmux.ai"), "proxy on: the host")
+ c = c.copy(proxy = AICheck.ProxyHint.None)
+ check(c.proxyLine("ZenMux", "zenmux.ai")!!.contains("ZenMux"), "no proxy: the service")
+ check(AICheck().fail(StepID.Text, Reason.NoModel, 404).message("ZenMux", "zenmux.ai", "x/y", "h")!!.contains("x/y"), "text model")
+ check(AICheck().fail(StepID.Hear, Reason.Deaf, 400).message("ZenMux", "zenmux.ai", "x/y", "a/deaf")!!.contains("a/deaf"), "hear model")
+ equal(null, AICheck().fail(StepID.Key, Reason.InvalidKey).copy(proxy = AICheck.ProxyHint.None).proxyLine("ZenMux", "zenmux.ai"), "not the network")
+ }
+
+ // MARK: The client
+
+ private class Fake(val respond: (String, String) -> Transport.Response) : Transport {
+ val sent = mutableListOf<String>()
+ override fun send(url: String, method: String, body: String?, headers: Map<String, String>, timeoutMs: Int): Transport.Response {
+ synchronized(sent) { sent.add(url) }
+ return respond(url, body ?: "")
+ }
+ }
+
+ private fun reply(content: String) = Transport.Response(200, Json.write(mapOf(
+ "choices" to listOf(mapOf("message" to mapOf("content" to content), "finish_reason" to "stop"))), pretty = false))
+
+ private val MODELS = Json.write(mapOf("data" to listOf(
+ mapOf("id" to "inclusionai/ling-3.0-flash", "input_modalities" to listOf("text"), "output_modalities" to listOf("text")),
+ mapOf("id" to "qwen/qwen3.8-omni-flash", "input_modalities" to listOf("text", "audio"), "output_modalities" to listOf("text")),
+ mapOf("id" to "x/text-only", "input_modalities" to listOf("text"), "output_modalities" to listOf("text")))), pretty = false)
+
+ private fun service(url: String, body: String) = when {
+ url.endsWith("models") -> Transport.Response(200, MODELS)
+ "input_audio" in body -> reply("NONE")
+ else -> reply("OK")
+ }
+
+ private fun client(fake: Transport, s: AppSettings, key: String = "sk-payg-test-0000"): LingClient {
+ val k = AIKey(PlainProtector, service = { s.aiProvider })
+ k.remove()
+ k.save(key)
+ return LingClient(k, fake, config = s::aiConfig)
+ }
+
+ fun clientPasses() {
+ val ling = client(Fake(::service), AppSettings(aiProvider = "zenmux"))
+ equal(KeyState.Ok, ling.check(), "ok")
+ val c = ling.aiCheck
+ check(c.passed && c.failure == null, "passed: ${c.summary}")
+ check(c.steps.all { AICheck.isOk(it.state) }, "every step: ${c.summary}")
+ check((c[StepID.Text] as State.Ok).seconds != null && (c[StepID.Hear] as State.Ok).seconds != null, "timed")
+ equal(true, ling.hears, "hears")
+ }
+
+ fun clientNoModel() {
+ val s = AppSettings(aiProvider = "zenmux", aiModels = mutableMapOf("zenmux" to "gone/model"))
+ val ling = client(Fake(::service), s)
+ ling.check()
+ equal(AICheck.Failure(StepID.Text, Reason.NoModel, null), ling.aiCheck.failure, "absent from /models")
+ equal(State.Skipped, ling.aiCheck[StepID.Hear], "hearing not reached")
+ equal(KeyState.Ok, ling.keyState, "the key itself works")
+ }
+
+ fun clientHearCatalog() {
+ // Answers the silent clip, but the service says it takes no audio in.
+ val s = AppSettings(aiProvider = "zenmux", aiHearModels = mutableMapOf("zenmux" to "x/text-only"))
+ val ling = client(Fake(::service), s)
+ ling.check()
+ equal(Reason.Deaf, ling.aiCheck.failure?.reason, "deaf by the catalog")
+ equal(false, ling.hears, "can't hear")
+ // A custom service that lists models without saying what they take: the probe decides.
+ val custom = AppSettings(aiProvider = "custom", aiCustomBase = "https://x.example/v1", aiModels = mutableMapOf("custom" to "qwen3:14b"),
+ aiHearModels = mutableMapOf("custom" to "qwen3-omni"))
+ val plain = client(Fake { url, body -> if (url.endsWith("models")) Transport.Response(200, """{"data":[{"id":"qwen3:14b"},{"id":"qwen3-omni"}]}""") else service(url, body) }, custom, key = "sk-x-0000")
+ plain.check()
+ check(plain.aiCheck.passed && plain.aiCheck.failure == null, "passes: ${plain.aiCheck.summary}")
+ }
+
+ fun clientMgmtKey() {
+ val fake = Fake(::service)
+ val ling = client(fake, AppSettings(aiProvider = "zenmux"), key = "sk-mgmt-0000")
+ equal(KeyState.Invalid, ling.check(), "refused")
+ equal(Reason.MgmtKey, ling.aiCheck.failure?.reason, "management")
+ equal(State.Untested, ling.aiCheck[StepID.Reach], "nothing sent")
+ check(fake.sent.isEmpty(), "no request")
+ }
+
+ fun clientBalance() {
+ val fake = Fake { url, body ->
+ when {
+ url.endsWith("/key") -> Transport.Response(200, """{"data":{"limit_remaining":0.4}}""")
+ url.endsWith("/credits") -> Transport.Response(200, """{"data":{"total_credits":5,"total_usage":1}}""")
+ url.endsWith("models") -> Transport.Response(200, """{"data":[{"id":"inclusionai/ling-3.1-flash","architecture":{"input_modalities":["text"]}},{"id":"qwen/qwen3.8-omni-flash","architecture":{"input_modalities":["audio","text"]}}]}""")
+ else -> service(url, body)
+ }
+ }
+ val ling = client(fake, AppSettings(aiProvider = "openrouter"), key = "sk-or-v1-0000")
+ ling.check()
+ equal(0.4, ling.aiCheck.balance, "the smaller")
+ check(ling.aiCheck.passed && ling.aiCheck.lowBalance && ling.aiCheck.needsUser, "passed, but low: ${ling.aiCheck.summary}")
+ }
+
+ fun clientUnreachable() {
+ var down = true
+ val ling = client(Fake { url, body -> if (down) throw java.io.IOException("no route") else service(url, body) }, AppSettings(aiProvider = "zenmux"))
+ ling.proxyHint = { AICheck.ProxyHint.None }
+ equal(KeyState.Unreachable, ling.check(), "unreachable")
+ equal("reach=fail(unreachable) key=skipped text=skipped hear=skipped proxy=none", ling.aiCheck.summary.substringBefore(" passive"), "steps")
+ check(ling.aiCheck.proxyLine(ling.serviceName, ling.serviceHost) != null, "the hint")
+ down = false
+ ling.networkChanged()
+ check(ling.aiCheck.passed, "looked again: ${ling.aiCheck.summary}")
+ // Only after an unreachable result: a good service isn't checked on every network change.
+ val calls = (ling.aiCheck.at)
+ ling.networkChanged()
+ equal(calls, ling.aiCheck.at, "no check")
+ }
+
+ fun clientPassive() {
+ var answer: (String) -> Transport.Response = { reply("OK") }
+ val ling = client(Fake { url, body -> if (url.endsWith("models")) Transport.Response(200, MODELS) else answer(body) }, AppSettings(aiProvider = "zenmux"))
+ ling.check()
+ // Heard audio in a meeting: the hear step, from a real request.
+ answer = { Transport.Response(400, "{}") }
+ try { ling.chat("c", "i", Priority.Translate, model = "qwen/qwen3.8-omni-flash", audio = byteArrayOf(1)) } catch (_: LingException) {}
+ equal(Reason.Deaf, ling.aiCheck.failure?.reason, "deaf from a meeting")
+ check(ling.aiCheck.passive, "passive")
+ // The notes: a 429 is busy, not a failure; then a good reply clears it.
+ answer = { Transport.Response(429, "{}") }
+ try { ling.chat("c", "i", Priority.Translate) } catch (_: LingException) {}
+ answer = { reply("fine") }
+ ling.chat("c", "i", Priority.Translate)
+ equal(State.Ok::class, ling.aiCheck[StepID.Text]::class, "text proven")
+ // The network goes in the middle of a meeting.
+ answer = { throw java.io.IOException("down") }
+ try { ling.chat("c", "i", Priority.Translate) } catch (_: LingException) {}
+ equal(Reason.Unreachable, ling.aiCheck.failure?.reason, "unreachable")
+ // A server error once isn't worth repainting the settings for.
+ answer = { reply("back") }
+ ling.chat("c", "i", Priority.Translate)
+ answer = { Transport.Response(503, "{}") }
+ try { ling.chat("c", "i", Priority.Translate) } catch (_: LingException) {}
+ check(ling.aiCheck.failure?.reason != Reason.ServerError, "ignored")
+ }
+
+ fun simulated() {
+ for (r in Reason.values()) {
+ val c = AICheck.simulated(r)
+ if (r == Reason.Busy) check(c.busy && c.failure == null, "busy") else equal(r, c.failure?.reason, "$r")
+ equal(r, AICheck.reasonNamed(AICheck.lower(r.name)), "named ${r.name}")
+ }
+ equal(Reason.NoJSON, AICheck.reasonNamed("noJSON"), "noJSON")
+ }
+}
diff --git a/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt b/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt
index 5089f00..9a3edc4 100644
--- a/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt
@@ -201,19 +201,23 @@ object ProviderTests {
}), s)
equal(KeyState.Ok, ling.check(), "the key works")
equal(false, ling.hears, "the hear model refuses audio")
+ equal(AICheck.State.Fail(AICheck.Reason.Deaf, 400), ling.aiCheck[AICheck.StepID.Hear], "deaf at the hear step")
+ check(AICheck.isOk(ling.aiCheck[AICheck.StepID.Text]), "the text model still answers")
check(!ling.canHear, "can't hear")
check(ling.usable, "notes and translation still work")
- check("a/b" in ling.textCatalog, "catalog fetched")
s.aiHearModels.clear()
ling.keyChanged()
equal(null, ling.hears, "forgotten")
}
fun checkSaysWhy() {
- equal(KeyState.Invalid, client(Fake({ _, _ -> Transport.Response(401, "") }), AppSettings(aiProvider = "zenmux")).check(), "401")
+ val bad = client(Fake({ _, _ -> Transport.Response(401, "") }), AppSettings(aiProvider = "zenmux"))
+ equal(KeyState.Invalid, bad.check(), "401")
+ equal("reach=ok key=fail(invalidKey) text=skipped hear=skipped", bad.aiCheck.summary, "stops at the key")
val ling = client(Fake({ _, _ -> Transport.Response(404, "") }), AppSettings(aiProvider = "zenmux"))
ling.check()
- equal(listOf<Any>("%@ 拒绝了请求(HTTP %lld),请检查模型名", "ZenMux", 404), ling.problem, "404 names the service")
+ equal(AICheck.Failure(AICheck.StepID.Text, AICheck.Reason.NoModel, 404), ling.aiCheck.failure, "404 is the text model")
+ check(ling.checkMessage()!!.contains("inclusionai/ling-3.0-flash"), "names the model")
equal(KeyState.None, client(Fake({ _, _ -> reply("ok") }), AppSettings(aiProvider = "openrouter"), key = null).keyState, "no key")
}
diff --git a/android/cli/src/main/kotlin/cicada/cli/Tests.kt b/android/cli/src/main/kotlin/cicada/cli/Tests.kt
index 039368d..d6ab2e4 100644
--- a/android/cli/src/main/kotlin/cicada/cli/Tests.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/Tests.kt
@@ -68,7 +68,7 @@ object Tests {
"lingMarksABadKey" to ::lingMarksABadKey,
"lingGateSpacesStartsAndServesPriorityFirst" to ::lingGate,
"listenEngineEndToEndWithAFakeMing" to ::listenEndToEnd,
- ) + ProviderTests.tests
+ ) + ProviderTests.tests + AICheckTests.tests
var passed = 0; var failed = 0
for ((name, test) in tests) {
try { test(); passed++ } catch (e: Throwable) { failed++; println("FAIL $name: ${e.message ?: e.javaClass.simpleName}") }
diff --git a/android/core/src/main/kotlin/cicada/AICheck.kt b/android/core/src/main/kotlin/cicada/AICheck.kt
new file mode 100644
index 0000000..3292e7a
--- /dev/null
+++ b/android/core/src/main/kotlin/cicada/AICheck.kt
@@ -0,0 +1,267 @@
+package cicada
+
+import cicada.Strings.L
+import cicada.Strings.LF
+
+/// What the last look at the AI service found, step by step (AICheck.swift): can this phone reach
+/// it, does it take the key, does the text model answer, does the hear model take audio. A failed
+/// step stops the ones after it, so the settings can say exactly where it broke and offer the one
+/// thing that fixes it. The port has a fourth step the Mac doesn't: it hears through the service.
+///
+/// Most of the time the answer comes from real requests (hearing, notes, translation): every call
+/// reports back here, so a meeting keeps the steps current without any extra request. An explicit
+/// check runs only when the service, model or key changes, at launch, on 重新检查, and when the
+/// network changes after the service was unreachable. Immutable: LingClient swaps in a new one.
+data class AICheck(
+ val steps: List<Step> = StepID.values().map { Step(it, State.Untested) },
+ /** When the newest result came in (epoch ms); null before any. */
+ val at: Long? = null,
+ /** The newest result came from a real request in a meeting, not from a check. */
+ val passive: Boolean = false,
+ /** Where the phone's proxy stands when the service can't be reached: only read, to word the hint. */
+ val proxy: ProxyHint? = null,
+ /** OpenRouter only: dollars left (the smaller of the key's limit and the account's credits). */
+ val balance: Double? = null,
+) {
+ enum class StepID { Reach, Key, Text, Hear }
+
+ enum class Reason { Unreachable, BadAddress, InvalidKey, MgmtKey, NoCredit, NoModel, NoJSON, Deaf, Busy, ServerError }
+
+ sealed class State {
+ object Running : State()
+ /** `seconds` of the request that proved it; null when it came with another step's request. */
+ data class Ok(val seconds: Double? = null) : State()
+ /** 429: the service is busy but the key works. Counts as passed. */
+ object Busy : State()
+ data class Fail(val reason: Reason, val code: Int? = null) : State()
+ object Skipped : State()
+ /** Nothing has proven it yet. */
+ object Untested : State()
+ }
+
+ data class Step(val id: StepID, val state: State)
+
+ /// A phone has no proxy app port to look for (the Mac's appRunning): only the system's.
+ enum class ProxyHint { SystemOn, None }
+
+ data class Failure(val step: StepID, val reason: Reason, val code: Int?)
+
+ operator fun get(id: StepID): State = steps.firstOrNull { it.id == id }?.state ?: State.Untested
+
+ fun with(id: StepID, state: State) = copy(steps = steps.map { if (it.id == id) Step(id, state) else it })
+
+ /// The first step that failed, and why.
+ val failure: Failure? get() {
+ for (s in steps) { val st = s.state; if (st is State.Fail) return Failure(s.id, st.reason, st.code) }
+ return null
+ }
+
+ val running get() = steps.any { it.state == State.Running }
+ 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
+ val lowBalance get() = (balance ?: Double.POSITIVE_INFINITY) < LOW_BALANCE
+
+ /** Something only the user can fix (a busy service fixes itself). */
+ val needsUser: Boolean get() {
+ val f = failure ?: return lowBalance
+ return f.reason != Reason.Busy && f.reason != Reason.ServerError
+ }
+
+ /// `step` failed and the ones after it were never reached. `reached`: a reply came back, so the
+ /// steps that request proves before it passed (false when nothing was sent, like a management key).
+ fun fail(step: StepID, reason: Reason, code: Int? = null, reached: Boolean = true): AICheck {
+ val proves = proves(step)
+ var after = false
+ val next = steps.map { s ->
+ when {
+ s.id == step -> { after = true; Step(s.id, State.Fail(reason, code)) }
+ after -> Step(s.id, State.Skipped)
+ reached && s.id in proves && !isOk(s.state) -> Step(s.id, State.Ok())
+ // The text step comes before hearing but a hear request says nothing about it.
+ s.id !in proves && s.state == State.Skipped -> Step(s.id, State.Untested)
+ // Nothing was sent: the step a check had started on was never tried.
+ s.state == State.Running -> Step(s.id, State.Untested)
+ else -> s
+ }
+ }
+ return copy(steps = next, proxy = if (reason == Reason.Unreachable) proxy else null)
+ }
+
+ /// One request proved `step` and what it rests on (a chat proves the address, the key and the
+ /// text model; heard audio the address, the key and the hear model). Clears what failed before;
+ /// steps that were skipped are open again.
+ fun pass(step: StepID, seconds: Double?): AICheck {
+ val proves = proves(step)
+ val next = steps.map { s ->
+ when {
+ s.id == step -> Step(s.id, State.Ok(seconds))
+ s.id in proves -> if (isOk(s.state)) s else Step(s.id, State.Ok())
+ s.state == State.Skipped -> Step(s.id, State.Untested)
+ else -> s
+ }
+ }
+ return copy(steps = next, proxy = null)
+ }
+
+ // MARK: Words
+
+ /// Why the failed step failed, in one sentence. `model`: the text model; `hearModel`: the hear model.
+ fun message(service: String, host: String, model: String, hearModel: String): String? {
+ 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.InvalidKey -> LF("%@ 说这个 key 无效,可能没复制全,或已删除。", service)
+ Reason.MgmtKey -> L("这是 ZenMux 的管理 key,不能用来调用模型。请粘贴 sk-payg 开头的 key。")
+ Reason.NoCredit -> LF("%@ 账户余额不足。", service)
+ Reason.NoModel -> LF("%@ 上找不到 %@ 这个模型。", service, model)
+ Reason.NoJSON -> L("这个服务不支持 JSON,纪要写不了;翻译照常。")
+ Reason.Deaf -> LF("%@ 听不了声音。", hearModel)
+ Reason.Busy -> LF("%@ 现在很忙,key 没问题。开会时会自动重试。", service)
+ Reason.ServerError -> LF("%@ 暂时出错(HTTP %lld),稍后再试。", service, f.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
+ return when (proxy ?: return null) {
+ ProxyHint.SystemOn -> LF("开了代理也连不上:换一个节点,或检查代理软件是否放过 %@。", host)
+ ProxyHint.None -> LF("这台手机没开代理。在国内通常要开代理才能用 %@。", service)
+ }
+ }
+
+ /// "OpenRouter 余额快用完了(还剩 $0.40)" when it is.
+ fun balanceLine(service: String): String? {
+ val b = balance ?: return null
+ if (!lowBalance) return null
+ return LF("%@ 余额快用完了(还剩 $%@)", service, String.format(java.util.Locale.US, "%.2f", maxOf(0.0, b)))
+ }
+
+ /// Debug and logs: "reach=ok key=fail(invalidKey) text=skipped hear=skipped".
+ val summary: String get() {
+ val parts = steps.joinToString(" ") { s ->
+ val v = when (val st = s.state) {
+ State.Running -> "running"
+ is State.Ok -> st.seconds?.let { "ok(${String.format(java.util.Locale.US, "%.1f", it)}s)" } ?: "ok"
+ State.Busy -> "busy"
+ is State.Fail -> "fail(${lower(st.reason.name)}${st.code?.let { " $it" } ?: ""})"
+ State.Skipped -> "skipped"
+ State.Untested -> "untested"
+ }
+ "${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 ""
+ }
+
+ companion object {
+ const val LOW_BALANCE = 0.5
+
+ fun isOk(s: State) = s is State.Ok
+
+ /// The steps a request that reached `step` also proves.
+ fun proves(step: StepID): Set<StepID> = when (step) {
+ StepID.Reach -> setOf(StepID.Reach)
+ StepID.Key -> setOf(StepID.Reach, StepID.Key)
+ StepID.Text -> setOf(StepID.Reach, StepID.Key, StepID.Text)
+ StepID.Hear -> setOf(StepID.Reach, StepID.Key, StepID.Hear)
+ }
+
+ fun lower(name: String) = name.replaceFirstChar { it.lowercaseChar() }
+
+ /// A reason by its debug name ("noModel"), for `ai-check-sim`.
+ fun reasonNamed(name: String): Reason? = Reason.values().firstOrNull { lower(it.name).equals(name, ignoreCase = true) }
+
+ fun title(id: StepID, host: String): String = when (id) {
+ StepID.Reach -> LF("连上 %@", host)
+ StepID.Key -> L("key 可以用")
+ StepID.Text -> L("纪要和翻译")
+ StepID.Hear -> L("听对方")
+ }
+
+ /// Which step a failed request stops at, and why. `step` is the step the request was
+ /// proving: the text model for a chat, the hear model for heard audio (a 400/404/415/422
+ /// there means the model doesn't take audio, not that it is missing).
+ fun classify(e: LingException, step: StepID): Failure? = when (e.kind) {
+ LingException.Kind.Network, LingException.Kind.Timeout -> Failure(StepID.Reach, Reason.Unreachable, null)
+ LingException.Kind.InvalidKey -> Failure(StepID.Key, Reason.InvalidKey, null)
+ LingException.Kind.RateLimited -> Failure(step, Reason.Busy, null)
+ LingException.Kind.Http -> when {
+ e.status == 402 -> Failure(StepID.Key, Reason.NoCredit, 402)
+ step == StepID.Hear && e.status in DEAF_CODES -> Failure(StepID.Hear, Reason.Deaf, e.status)
+ e.status == 400 || e.status == 404 ->
+ if (step == StepID.Key) Failure(StepID.Key, Reason.ServerError, e.status) else Failure(StepID.Text, Reason.NoModel, e.status)
+ else -> Failure(step, Reason.ServerError, e.status)
+ }
+ LingException.Kind.NoKey, LingException.Kind.Hijacked, LingException.Kind.Parse -> null
+ }
+
+ /// What a hear model that doesn't take audio answers.
+ val DEAF_CODES = listOf(400, 404, 415, 422)
+
+ /// The prefix of a key says whose it is: `sk-or-` OpenRouter, `sk-payg` ZenMux, `sk-mgmt`
+ /// ZenMux's management key (it can't call models). Null: nothing to tell.
+ fun owner(key: String): Pair<String, Boolean>? {
+ val k = key.trim()
+ return when {
+ k.startsWith("sk-or-") -> "openrouter" to false
+ k.startsWith("sk-payg") -> "zenmux" to false
+ k.startsWith("sk-mgmt") -> "zenmux" to true
+ else -> null
+ }
+ }
+
+ /// Every model id in a `/models` reply (null when the reply can't be read or lists none).
+ fun listedModels(body: String): Set<String>? {
+ val root = Json.parseObject(body) ?: return null
+ val ids = root["data"].arr().mapNotNull { it.obj()?.get("id").str() }.filter { it.isNotEmpty() }
+ return if (ids.isEmpty()) null else ids.toSet()
+ }
+
+ /// The ids a `/models` reply says take audio in. Null when it says nothing about what models
+ /// take (a custom service, Ollama): then only the silent-audio probe can tell.
+ fun listedHearing(body: String): Set<String>? {
+ val root = Json.parseObject(body) ?: return null
+ var told = false
+ val ids = mutableSetOf<String>()
+ for (raw in root["data"].arr()) {
+ val m = raw.obj() ?: continue
+ val id = m["id"].str() ?: continue
+ val ins = (m["input_modalities"] ?: m["architecture"].obj()?.get("input_modalities")) ?: continue
+ told = true
+ if (ins.arr().any { it.str() == "audio" }) ids.add(id)
+ }
+ return if (told) ids else null
+ }
+
+ /// OpenRouter: dollars left from `/key` (`limit_remaining`, null without a key limit) and
+ /// `/credits` (bought minus used); the smaller one is what the next meeting can spend.
+ fun balance(key: Map<String, Any?>?, credits: Map<String, Any?>?): Double? {
+ val k = key?.get("data").obj()?.get("limit_remaining").num()
+ val d = credits?.get("data").obj()
+ val total = d?.get("total_credits").num()
+ val used = d?.get("total_usage").num()
+ val c = if (total != null && used != null) total - used else null
+ return when {
+ k != null && c != null -> minOf(k, c)
+ else -> k ?: c
+ }
+ }
+
+ /// A made-up result for `reason` (debug screenshots of every state).
+ fun simulated(reason: Reason): AICheck {
+ val r = AICheck()
+ return when (reason) {
+ Reason.Busy -> r.pass(StepID.Text, 1.2).pass(StepID.Hear, 0.9).with(StepID.Text, State.Busy)
+ Reason.Unreachable, Reason.BadAddress -> r.fail(StepID.Reach, reason, reached = false)
+ Reason.InvalidKey, Reason.NoCredit -> r.fail(StepID.Key, reason, code = if (reason == Reason.NoCredit) 402 else null)
+ Reason.MgmtKey -> r.fail(StepID.Key, reason, reached = false)
+ Reason.NoModel, Reason.NoJSON -> r.fail(StepID.Text, reason, code = 404)
+ Reason.Deaf -> r.pass(StepID.Text, 1.1).fail(StepID.Hear, reason, code = 400)
+ Reason.ServerError -> r.fail(StepID.Text, reason, code = 503)
+ }
+ }
+ }
+}
diff --git a/android/core/src/main/kotlin/cicada/Ling.kt b/android/core/src/main/kotlin/cicada/Ling.kt
index ae2a29e..701ea0e 100644
--- a/android/core/src/main/kotlin/cicada/Ling.kt
+++ b/android/core/src/main/kotlin/cicada/Ling.kt
@@ -163,6 +163,8 @@ class LingClient(
}
/// Ming, Gemini TTS and Kokoro all speak 24 kHz mono 16-bit.
const val TTS_RATE = 24000
+ /// Failures of a model rather than of the service or the key: the key still works.
+ val MODEL_REASONS = setOf(AICheck.Reason.Busy, AICheck.Reason.Deaf, AICheck.Reason.NoModel, AICheck.Reason.NoJSON)
// Search essays (Ling.swift), and the canned refusal some audio prompts get.
private val HIJACK_PREFIXES = listOf("根据现有检索证据", "暂未找到足够可靠的信息", "根据检索", "作为一个人工智能语言模型")
/// Tests only: overrides the service's spacing.
@@ -187,15 +189,19 @@ class LingClient(
@Volatile var keyState = if (currentKey() == null) KeyState.None else KeyState.Unchecked; private set
@Volatile var rateLimitedAt: Long? = null; private set
- /// Why the last check failed, shown under the key: a Mac string key and its arguments for LF()
- /// ("连不上 %@,请检查网络或代理", "ZenMux"); null when it didn't.
- @Volatile var problem: List<Any>? = null; private set
- /// How long the last good check took, in seconds.
- @Volatile var seconds: Double? = null; private set
- /// Whether the hear model takes audio: null until a check asked (always true on Ling).
- @Volatile var hears: Boolean? = if (config().isLing) true else null; private set
+ /// Step by step, where the service stands (`keyState` is its short form for older callers).
+ @Volatile var aiCheck = AICheck(); private set
+ /// The last time the service's voice spoke (or failed to) for 我说: (ok, epoch ms).
+ @Volatile var lastVoice: Pair<Boolean, Long>? = null; private set
@Volatile var textCatalog: List<String> = emptyList(); private set
@Volatile var hearCatalog: List<String> = emptyList(); private set
+ /// Reads this phone's proxy settings to word the "can't reach" hint (never used to connect).
+ @Volatile var proxyHint: (() -> AICheck.ProxyHint)? = null
+ /// Debug control only: the next checks end this way (for screenshots of every state).
+ @Volatile var simulateCheck: AICheck.Reason? = null
+ /// Debug control only: report this OpenRouter balance instead of the real one.
+ @Volatile var simulateBalance: Double? = null
+ private val checkLock = Any()
private val listeners = mutableListOf<() -> Unit>()
fun onChange(listener: () -> Unit) { synchronized(listeners) { listeners.add(listener) } }
@@ -215,97 +221,216 @@ class LingClient(
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
+ /// Whether the hear model takes audio: false once it refused (a check or a meeting), true once
+ /// it heard, null until then (always true on Ling: Ming).
+ val hears: Boolean? get() = when (val s = aiCheck[AICheck.StepID.Hear]) {
+ is AICheck.State.Ok, AICheck.State.Busy -> true
+ is AICheck.State.Fail -> if (s.reason == AICheck.Reason.Deaf) false else null
+ else -> if (config().isLing) true else null
+ }
+ /// 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()
+ /// 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 } } ?: ""
+
+ /// The failed (or busy) step's sentence, for the screens.
+ fun checkMessage(): String? = config().let { aiCheck.message(serviceName, serviceHost, it.textModel, it.hearModel) }
+
/// The key, the service or its models changed: forget what the last check found.
fun keyChanged() {
key.reload()
keyState = if (currentKey() == null) KeyState.None else KeyState.Unchecked
- problem = null
- hears = if (config().isLing) true else null
+ synchronized(checkLock) { aiCheck = AICheck() }
+ lastVoice = null
textCatalog = emptyList(); hearCatalog = emptyList()
changed()
}
- /// The cheapest request that proves the key: Ling's tiny model, else one token from the text
- /// model. The others' hear model must also take audio (half a second of silence), and a custom
- /// service must return JSON (the notes need it).
+ /// 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
+ /// (half a second of silence), and the model list then tells whether both models still exist.
fun check(): KeyState {
- keyState = KeyState.Checking; problem = null; changed()
+ // One at a time (a service change and a key import come close together), and the probes'
+ // own replies are not passive results.
+ synchronized(checkRun) {
+ checking++
+ try { return runCheck() } finally { checking-- }
+ }
+ }
+
+ private val checkRun = Any()
+ @Volatile private var checking = 0
+
+ private fun runCheck(): KeyState {
val c = config()
- val name = if (c.provider.id == "custom") "这个服务" else c.provider.name
- val started = System.nanoTime()
- var state = try {
+ val k = currentKey()
+ if (k == null) { keyState = KeyState.None; synchronized(checkLock) { aiCheck = AICheck() }; changed(); return keyState }
+ keyState = KeyState.Checking
+ var r = AICheck().with(AICheck.StepID.Reach, AICheck.State.Running)
+ synchronized(checkLock) { aiCheck = r }
+ changed()
+ simulateCheck?.let { return finishCheck(AICheck.simulated(it), c) }
+ if (c.provider.id == "custom" && c.base == null)
+ return finishCheck(r.fail(AICheck.StepID.Reach, AICheck.Reason.BadAddress, reached = false), c)
+ if (AICheck.owner(k)?.second == true)
+ return finishCheck(r.fail(AICheck.StepID.Key, AICheck.Reason.MgmtKey, reached = false), c)
+ // The probes below go through chat(), which reports to observe(): it waits while running.
+ var step = AICheck.StepID.Text
+ try {
+ var started = System.nanoTime()
if (c.isLing) {
chat("Reply with OK.", "Reply.", Priority.Speak, maxTokens = 5, timeout = 10.0, model = "Ling-3.0-tiny")
- seconds = (System.nanoTime() - started) / 1e9
- hears = true
+ // Ming hears on every Ling key: nothing to probe.
+ r = r.pass(AICheck.StepID.Text, (System.nanoTime() - started) / 1e9).pass(AICheck.StepID.Hear, null)
} else {
- if (c.base == null || c.textModel.isEmpty()) throw LingException(LingException.Kind.NoKey)
+ if (c.textModel.isEmpty()) throw LingException(LingException.Kind.Http, 404)
chat("Reply with OK.", "Reply.", Priority.Speak, maxTokens = 5, timeout = 20.0)
- seconds = (System.nanoTime() - started) / 1e9
+ 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)
} catch (e: LingException) {
- if (e.kind == LingException.Kind.Http) problem = listOf("这个服务不支持 JSON(HTTP %lld),纪要用不了", e.status) else throw e
+ if (e.kind == LingException.Kind.Http) r = r.fail(AICheck.StepID.Text, AICheck.Reason.NoJSON, e.status) else throw e
+ }
+ }
+ if (r.failure == null) {
+ step = AICheck.StepID.Hear
+ started = System.nanoTime()
+ if (c.hearModel.isEmpty()) throw LingException(LingException.Kind.Http, 404)
+ try {
+ chat("Transcribe the audio.", "Reply with what is said, or NONE.", Priority.Speak, maxTokens = 10, timeout = 20.0,
+ model = c.hearModel, audio = silenceWav())
+ } catch (e: LingException) {
+ // Heard, and answered with something we drop anyway: it takes audio.
+ if (e.kind != LingException.Kind.Hijacked && e.kind != LingException.Kind.Parse) throw e
}
+ r = r.pass(AICheck.StepID.Hear, (System.nanoTime() - started) / 1e9)
}
- hears = hearsAudio(c)
}
- KeyState.Ok
} catch (e: LingException) {
- val s = when (e.kind) {
- LingException.Kind.NoKey -> KeyState.None
- LingException.Kind.InvalidKey -> KeyState.Invalid
- LingException.Kind.RateLimited -> KeyState.Ok // a busy key is still a good key
- else -> KeyState.Unreachable
+ val f = AICheck.classify(e, step)
+ 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) {
+ // A reply came back: the service and key are fine, the words just weren't usable.
+ r = r.pass(step, null)
}
- if (e.kind == LingException.Kind.Http && (e.status == 400 || e.status == 404))
- problem = if (c.provider.id == "custom") listOf("找不到模型,或地址不对(HTTP %lld)", e.status)
- else listOf("%@ 拒绝了请求(HTTP %lld),请检查模型名", name, e.status)
- else if (s == KeyState.Unreachable) problem = listOf("连不上 %@,请检查网络或代理", name)
- s
+ } catch (e: InterruptedException) {
+ throw e
} catch (e: Exception) {
- problem = listOf("连不上 %@,请检查网络或代理", name)
- KeyState.Unreachable
+ r = r.fail(AICheck.StepID.Reach, AICheck.Reason.Unreachable)
}
- keyState = state
- Log.d("ai ${c.provider.id}: key check -> $state${if (hears == false) " (hear model refuses audio)" else ""}")
+ if (r.failure == null && !c.isLing) {
+ val listed = fetchCatalog()
+ if (listed != null) {
+ // A model the service no longer lists fails here, before a meeting finds out.
+ val hearing = 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)
+ }
+ }
+ return finishCheck(r, c)
+ }
+
+ 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())
+ simulateBalance?.let { r = r.copy(balance = it) }
+ r = r.copy(at = System.currentTimeMillis())
+ synchronized(checkLock) { aiCheck = r }
+ syncKeyState()
+ Log.d("ai ${c.provider.id}: check -> ${r.summary}")
changed()
- if (state == KeyState.Ok && !c.isLing) fetchCatalog()
- return state
+ return keyState
}
- /// Whether the hear model takes audio: a 400, 404, 415 or 422 says no; anything else can't tell.
- private fun hearsAudio(c: AIConfig): Boolean? {
- if (c.hearModel.isEmpty()) return false
- return try {
- chat("Transcribe the audio.", "Reply with what is said, or NONE.", Priority.Speak, maxTokens = 10, timeout = 20.0,
- model = c.hearModel, audio = silenceWav())
- true
- } catch (e: LingException) {
- when {
- e.kind == LingException.Kind.Http && e.status in listOf(400, 404, 415, 422) -> false
- e.kind == LingException.Kind.Hijacked -> true
- else -> null
+ /// OpenRouter's dollars left; null when it can't tell (never fails the check).
+ private fun openRouterBalance(c: AIConfig, k: String): Double? {
+ val base = c.base ?: return null
+ fun get(path: String) = try {
+ transport.send(base + path, "GET", null, headers(k), 10_000).takeIf { it.status == 200 }?.let { Json.parseObject(it.body) }
+ } catch (_: Exception) { null }
+ return AICheck.balance(get("key"), get("credits"))
+ }
+
+ /// The short form older callers read: Invalid stops every request; Unreachable is any failure
+ /// of the service itself. A missing or deaf model is a model problem: the key still works.
+ private fun syncKeyState() {
+ if (!hasKey) { keyState = KeyState.None; return }
+ val c = aiCheck
+ val f = c.failure
+ keyState = when {
+ f != null && (f.reason == AICheck.Reason.InvalidKey || f.reason == AICheck.Reason.MgmtKey) -> KeyState.Invalid
+ f != null && f.reason !in MODEL_REASONS -> KeyState.Unreachable
+ c.running -> KeyState.Checking
+ else -> KeyState.Ok
+ }
+ }
+
+ /// 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) {
+ if (!hasKey || simulateCheck != null) return
+ val step = if (audio) AICheck.StepID.Hear else AICheck.StepID.Text
+ val now: AICheck
+ val wasUnreachable: Boolean
+ synchronized(checkLock) {
+ val before = aiCheck
+ if (before.running || checking > 0) return
+ var r = before
+ if (failure != null) {
+ val f = AICheck.classify(failure, step) ?: 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 {
+ r = r.pass(step, seconds)
}
+ r = r.copy(at = System.currentTimeMillis(), passive = true)
+ if (r.failure?.reason != AICheck.Reason.Unreachable) r = r.copy(proxy = null)
+ wasUnreachable = before.failure?.reason == AICheck.Reason.Unreachable
+ if (r.steps == before.steps && before.passive) { aiCheck = before.copy(at = r.at); return }
+ aiCheck = r
+ now = r
+ }
+ syncKeyState()
+ Log.d("ai: from a real request -> ${now.summary}")
+ changed()
+ val hint = proxyHint
+ if (now.failure?.reason == AICheck.Reason.Unreachable && !wasUnreachable && hint != null) {
+ val p = hint()
+ synchronized(checkLock) { if (aiCheck.failure?.reason == AICheck.Reason.Unreachable) aiCheck = aiCheck.copy(proxy = p) }
+ changed()
}
}
+ /// The network came back (or changed) while the service was unreachable: look again. Blocks.
+ fun networkChanged() {
+ if (!hasKey || aiCheck.failure?.reason != AICheck.Reason.Unreachable || aiCheck.running) return
+ Log.d("ai: network changed while unreachable, checking again")
+ check()
+ }
+
/// 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`.
- fun fetchCatalog() {
+ /// 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).
+ fun fetchCatalog(): Pair<Set<String>, Set<String>?>? {
val c = config()
- val k = currentKey() ?: return
- if (c.isLing || c.base == null) return
- val res = try { transport.send(c.base + "models", "GET", null, headers(k), 20_000) } catch (_: Exception) { return }
- if (res.status != 200) return
+ 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)
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)
}
/// One chat completion. `content` goes in the system message, `instruction` is the fixed user
@@ -351,8 +476,11 @@ 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)
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)
if (e.kind != LingException.Kind.RateLimited) throw e
if (attempt > waits.size) { rateLimitedAt = System.currentTimeMillis(); changed(); throw e }
val wait = waits[attempt - 1] + Math.random() * 0.5
@@ -368,6 +496,18 @@ class LingClient(
/// `language` is Ming's language_id, Ling only. Replies come three ways and all are read:
/// server-sent base64 chunks (Ling, ZenMux), raw PCM (OpenRouter), or one JSON `{"audio": <WAV>}`.
fun speech(text: String, voice: String? = null, language: String? = null, timeout: Double = 20.0, onPcm: (ByteArray) -> Unit) {
+ // The voice isn't part of a check (it costs money): its real outcome is what 现在能用的 says.
+ try {
+ speak(text, voice, language, timeout, onPcm)
+ lastVoice = true to System.currentTimeMillis(); changed()
+ } catch (e: LingException) {
+ lastVoice = false to System.currentTimeMillis(); changed()
+ throw e
+ }
+ // Anything else came from onPcm: the phone stopped it on purpose, not a failure.
+ }
+
+ private fun speak(text: String, voice: String?, language: String?, timeout: Double, onPcm: (ByteArray) -> Unit) {
val k = currentKey() ?: throw LingException(LingException.Kind.NoKey)
val c = config()
val voiceBase = c.voiceBase