知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
feat(linux): when the AI service fails, Settings shows which step broke and how to fix it
wquguruc3f2a699a297
diff --git a/linux/README.md b/linux/README.mdindex 123f612..238149d 100644--- a/linux/README.md+++ b/linux/README.md@@ -55,7 +55,7 @@ linux/vm/vmctl.sh shot shot.png # 截屏(QEMU,不受 Waylandlinux/scripts/build.sh && linux/vm/push.sh # 把 build/cicada-linux 和测试工具放进虚拟机的 ~/cicada-linux```-在虚拟机里 `~/cicada-linux/bin/cicada --dev` 启动开发版(记录在 `~/.local/share/cicada-dev`,日志在 `~/.local/state/cicada-dev/debug.log`),再用 `scripts/cicadactl` 驱动它:`state`、`start`、`stop`、`feed <wav>`、`sample`、`view notes|subtitles`、`show records|notes|settings|onboarding`、`windows`、`quit`;结束会议用 `calls zoom=Zoom|none|real`(假装会议软件在通话)、`realcalls`、`endtimes <没人说话秒数> <倒计时> <挂断宽限>|off`、`endkeep`;纪要窗用 `notes-tab notes|transcript`、`notes-search <词>`、`notes-wide on|off`、`notes-end ask|keep|end`(结束前的确认)、`notes-status failed|invalidKey|rateLimited|idle`(看出错横幅);记录用 `rename <id> [标题]`(不给标题即恢复自动标题)、`delete <id>`;还有 `onboarding-step <0-4>`、`settings-scroll <0-1>`。`scripts/smoke.sh` 一步跑完:开窗口、放一段声音、确认 monitor 听到了。+在虚拟机里 `~/cicada-linux/bin/cicada --dev` 启动开发版(记录在 `~/.local/share/cicada-dev`,日志在 `~/.local/state/cicada-dev/debug.log`),再用 `scripts/cicadactl` 驱动它:`state`、`start`、`stop`、`feed <wav>`、`sample`、`view notes|subtitles`、`show records|notes|settings|onboarding`、`windows`、`quit`;结束会议用 `calls zoom=Zoom|none|real`(假装会议软件在通话)、`realcalls`、`endtimes <没人说话秒数> <倒计时> <挂断宽限>|off`、`endkeep`;纪要窗用 `notes-tab notes|transcript`、`notes-search <词>`、`notes-wide on|off`、`notes-end ask|keep|end`(结束前的确认)、`notes-status failed|invalidKey|rateLimited|idle`(看出错横幅);记录用 `rename <id> [标题]`(不给标题即恢复自动标题)、`delete <id>`;还有 `onboarding-step <0-4>`、`settings-scroll <0-1>`;AI 服务检查用 `ai-check`(现在查一次)、`ai-check-sim <原因|lowBalance|off>`(每次检查都按这个原因结束,截各状态的图)、`ask settings|fix|close`(回答开始听时的对话框)、`settings-ai`、`tray-menu`(顶栏菜单的各项)。`scripts/smoke.sh` 一步跑完:开窗口、放一段声音、确认 monitor 听到了。焦点:`bin/focus_test.sh` 开一个最大化的“会议 app”(`focus_probe.py`),用 `click.py`(uinput,真实指针)点纪要窗和“字幕”链接,再在 Mac 上 `linux/vm/vmctl.sh type ok`;`/tmp/focus-probe.log` 里不能出现 `active=False`,最后一行应是 `text=…ok`。xdotool 只到 XWayland,测不了这个。diff --git a/linux/cicada/app/aicheck_view.py b/linux/cicada/app/aicheck_view.pynew file mode 100644index 0000000..45c448a--- /dev/null+++ b/linux/cicada/app/aicheck_view.py@@ -0,0 +1,171 @@+"""The AI service's check, step by step (AICheckView.swift): the settings and the onboarding show the+same list. Every step that ran shows its result; the one that failed says why in one line and+offers the one thing that fixes it. Also the words the tray, the checklist and 开始听 use."""+from __future__ import annotations++from gi.repository import Gtk++from ..core import aicheck+from ..core import strings+from ..core.strings import L, LF+from . import ui++ICONS = {aicheck.OK: ("object-select-symbolic", "ok"), aicheck.FAIL: ("window-close-symbolic", "fail"),+ aicheck.BUSY_STATE: ("dialog-warning-symbolic", "busy"), aicheck.RUNNING: ("content-loading-symbolic", "running"),+ aicheck.SKIPPED: ("list-remove-symbolic", "off"), aicheck.UNTESTED: ("list-remove-symbolic", "off")}+++def recommended(app, kind: str) -> str | None:+ """The service's first recommended text or hear model, when it isn't the one in use."""+ c = app.ling.config()+ models = c.provider.text_models if kind == "text" else c.provider.hear_models+ current = c.text_model if kind == "text" else c.hear_model+ first = models[0].id if models else None+ return first if first and first != current else None+++def top_up_url(provider) -> str:+ return aicheck.TOP_UP if provider.id == "openrouter" else (provider.site or aicheck.TOP_UP)+++def actions(app, change_key, recheck_in_step: bool = True) -> list:+ """(title, run) for the failed step: one primary fix, at most one other."""+ from .settings_window import open_uri+ ling = app.ling+ f = ling.check_result.failure+ if f is None:+ return []+ p = ling.provider+ reason = f[1]+ recheck = [(L("重新检查"), app.recheck)] if recheck_in_step else []+ if reason == aicheck.UNREACHABLE:+ return [(L("怎么设置代理"), lambda: open_uri(aicheck.help_url(strings.language)))] + recheck+ if reason in (aicheck.INVALID_KEY, aicheck.MGMT_KEY):+ out = [(L("更换 key"), change_key)]+ if p.site:+ out.append((LF("打开 %@", p.name), lambda: open_uri(p.site)))+ return out+ if reason == aicheck.NO_CREDIT:+ return [(L("去充值"), lambda: open_uri(top_up_url(p)))] + recheck+ if reason in (aicheck.NO_MODEL, aicheck.DEAF):+ kind = "text" if reason == aicheck.NO_MODEL else "hear"+ rec = recommended(app, kind)+ if rec is None:+ return [(L("重新检查"), app.recheck)]+ return [(LF("换成推荐的 %@", rec), lambda: app.use_recommended(kind))]+ if reason == aicheck.SERVER_ERROR:+ return [(L("重新检查"), app.recheck)]+ return []+++def steps_widget(app, change_key, recheck_in_step: bool = True, width_chars: int = 46) -> Gtk.Widget:+ """The step list: a disc, the step's name and seconds; under the failed one, why, the proxy hint+ and its buttons (the first dark)."""+ ling = app.ling+ r = ling.check_result+ c = ling.config()+ host = ling.service_host+ box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)+ for i, step in enumerate(aicheck.STEPS):+ st = r[step]+ if i:+ sep = ui.panel(Gtk.Box(), "hair")+ sep.set_size_request(-1, 1)+ sep.set_margin_start(30)+ box.pack_start(sep, False, False, 0)+ icon_name, tone = ICONS[st.kind]+ img = ui.icon(icon_name, 11)+ img.set_halign(Gtk.Align.CENTER)+ img.set_valign(Gtk.Align.CENTER)+ disc = ui.panel(img, "stepdisc", tone)+ disc.set_size_request(20, 20)+ disc.set_valign(Gtk.Align.START)+ quiet = st.kind in (aicheck.SKIPPED, aicheck.UNTESTED)+ texts = ui.vbox(4, ui.text(aicheck.title(step, host), 13, "tertiary" if quiet else "ink", wrap=False))+ if st.kind == aicheck.OK and step in ("text", "hear"):+ texts.pack_start(ui.text(c.text_model if step == "text" else c.hear_model, 11, "tertiary", wrap=False), False, False, 0)+ if st.kind == aicheck.UNTESTED and r.passed:+ texts.pack_start(ui.text(L("开会用过一次后确认"), 11, "tertiary", wrap=False), False, False, 0)+ if st.kind in (aicheck.FAIL, aicheck.BUSY_STATE) and (st.kind == aicheck.BUSY_STATE or r.failure[0] == step):+ why = ling.message()+ if why:+ w = ui.text(why, 12, "stepwhy", width_chars=width_chars)+ if st.kind == aicheck.BUSY_STATE:+ ui.classes(w, "busy")+ texts.pack_start(w, False, False, 0)+ line = r.proxy_line(ling.service_name, host)+ if line:+ texts.pack_start(ui.panel(ui.pad(ui.text(line, 12, "", width_chars=width_chars), 7, 10), "proxybox"), False, False, 0)+ acts = actions(app, change_key, recheck_in_step) if st.kind == aicheck.FAIL else []+ if acts:+ row = ui.hbox(8)+ for j, (title, run) in enumerate(acts):+ row.pack_start(ui.button(title, run, "darkbtn" if j == 0 else "outline"), False, False, 0)+ texts.pack_start(ui.gap(row, 2), False, False, 0)+ row = ui.hbox(10, disc)+ row.pack_start(texts, True, True, 0)+ if st.kind == aicheck.OK and st.seconds is not None:+ secs = ui.text(LF("%@ 秒", "%.1f" % st.seconds), 11, "tertiary", wrap=False, ellipsize=False)+ secs.set_valign(Gtk.Align.START)+ row.pack_end(secs, False, False, 0)+ box.pack_start(ui.pad(row, 8, 0), False, False, 0)+ return box+++def show_steps(r) -> bool:+ """The list shows while something is wrong or being checked; all passed folds into one line."""+ return r.running or r.failure is not None or r.busy or (r.at is not None and not r.passed)+++def passed_line(app) -> str | None:+ """All passed, in one line: "文字 1.8 秒 · 听 2.1 秒", or "12 分钟前开会时用过" when the newest+ evidence came from a meeting."""+ r = app.ling.check_result+ if not r.passed or r.busy:+ return None+ if r.passive and r.at is not None:+ return aicheck.relative(r.at)+ parts = []+ text, hear = r["text"], r["hear"]+ if text.kind == aicheck.OK and text.seconds is not None:+ parts.append(LF("文字 %@ 秒", "%.1f" % text.seconds))+ if hear.kind == aicheck.OK and hear.seconds is not None:+ parts.append(LF("听 %@ 秒", "%.1f" % hear.seconds))+ return " · ".join(parts) or None+++def strip_words(app):+ """(title, detail) for the tray's first item and the checklist: only failures the user must fix+ (AIServiceStrip.swift). On Linux the service hears too, so nothing goes on without it."""+ ling = app.ling+ r = ling.check_result+ if not ling.has_key or not r.needs_user:+ return None+ name = ling.service_name+ f = r.failure+ if f is None:+ return r.balance_line(name), L("用完后纪要会停下")+ c = ling.config()+ reason = f[1]+ title = {aicheck.UNREACHABLE: lambda: LF("连不上 %@", name),+ aicheck.INVALID_KEY: lambda: LF("%@ 的 key 用不了", name),+ aicheck.MGMT_KEY: lambda: LF("%@ 的 key 用不了", name),+ aicheck.NO_CREDIT: lambda: LF("%@ 账户余额不足。", name),+ aicheck.NO_MODEL: lambda: LF("%@ 上找不到 %@ 这个模型。", name, c.text_model),+ aicheck.DEAF: lambda: LF("%@ 听不了声音。", c.hear_model)}.get(reason, lambda: L("AI 服务的设置要改一下"))()+ return title, ling.message() or ""+++def key_hint(app, key: str):+ """A pasted key that belongs elsewhere: (what it is, the service it fits or None), else None.+ A management key can't call models; another service's key goes there with one click."""+ owner = aicheck.owner(key)+ if owner is None:+ return None+ service, management = owner+ if management:+ return L("这是 ZenMux 的管理 key,不能用来调用模型。请粘贴 sk-payg 开头的 key。"), None+ if service != app.settings.aiProvider:+ from ..core.providers import named+ return LF("这是 %@ 的 key。", named(service).name), service+ return Nonediff --git a/linux/cicada/app/debug.py b/linux/cicada/app/debug.pyindex c2c793a..a037794 100644--- a/linux/cicada/app/debug.py+++ b/linux/cicada/app/debug.py@@ -9,6 +9,8 @@ per connection, one JSON line back. Never in release builds.calls <program=name,…>|none|real (meeting apps in a call) | endtimes <silence> <countdown> <grace>|off | endkeepnotes-tab notes|transcript | notes-search <text> | notes-wide on|off | onboarding-step <n> | settings-scroll <0-1>settings-models on|off (unfold 自己选模型)+ ai-check-sim <reason|lowBalance|off> (every check ends this way: screenshots of each state) | ai-check (check now)+ ask settings|fix|close (answer the 开始听 dialog a failed check put up) | settings-ai (设置 at AI 服务) | tray-menupill (the records window capsule's widget sizes)"""from __future__ import annotations@@ -130,7 +132,34 @@ def command(app, line: str) -> dict:"endTimes": list(app.end_times) if app.end_times else None,"inCall": dict(app.end_watch.in_call) if app.end_watch else None}if cmd == "start":- app.toggle_listening() if not listen.listening else None+ # Later, not here: 开始听 may ask first (a deaf hear model), and its dialog runs its own loop.+ if not listen.listening:+ GLib.idle_add(lambda: app.toggle_listening() and False)+ return {"ok": True}+ if cmd == "ai-check-sim":+ from ..core import aicheck+ if arg not in aicheck.REASONS + ("lowBalance", "off"):+ return {"ok": False, "error": "reason, lowBalance or off"}+ app.ling.simulate = None if arg == "off" else arg+ threading.Thread(target=app.ling.check, daemon=True).start()+ return {"ok": True, "simulate": app.ling.simulate}+ if cmd == "ai-check":+ threading.Thread(target=app.ling.check, daemon=True).start()+ return {"ok": True}+ if cmd == "ask":+ from gi.repository import Gtk+ d = getattr(app, "_asking", None)+ if d is None:+ return {"ok": False, "error": "no question open"}+ d.response({"settings": Gtk.ResponseType.CANCEL, "fix": Gtk.ResponseType.ACCEPT}.get(arg, Gtk.ResponseType.CLOSE))+ return {"ok": True}+ if cmd == "tray-menu":+ # The top-bar menu's items (opening it takes a real click on the top bar).+ if app.tray is None:+ return {"ok": False, "error": "no tray"}+ return {"ok": True, "items": [i.get_label() for i in app.tray.menu.get_children() if hasattr(i, "get_label")]}+ if cmd == "settings-ai":+ app.show_settings(ai=True)return {"ok": True}if cmd == "stop":app.stop_listening()@@ -295,5 +324,8 @@ def _ai(app) -> dict:"""The AI service in use and what its last check found (never the key itself)."""c, ling = app.ling.config(), app.lingreturn {"provider": c.provider.id, "base": c.base, "text": c.text_model, "hear": c.hear_model, "voice": c.voice_model,- "state": ling.key_state, "hears": ling.hears, "problem": list(ling.problem) if ling.problem else None,+ "state": ling.key_state, "hears": ling.hears, "check": ling.check_result.summary(), "message": ling.message(),+ "proxyLine": ling.check_result.proxy_line(ling.service_name, ling.service_host),+ "keyWorks": app.key_works, "asking": getattr(app, "_asking", None) is not None,+ "lastVoice": list(ling.last_voice) if ling.last_voice else None, "simulate": ling.simulate,"catalog": [len(ling.text_catalog), len(ling.hear_catalog)], "keyFile": os.path.basename(app.key.path)}diff --git a/linux/cicada/app/main.py b/linux/cicada/app/main.pyindex 1f79aa3..09103d0 100644--- a/linux/cicada/app/main.py+++ b/linux/cicada/app/main.py@@ -149,6 +149,7 @@ class Controller:refresh_autostart(self.launcher)if self.settings.onboarded and self.ling.has_key:threading.Thread(target=self.ling.check, daemon=True).start()+ self._watch_network()# Opened by hand, 知了 shows its window: a top-bar icon alone looks like nothing happened, and# plain GNOME has no top bar icon at all. Only a login start (--background) with an icon to be# reached through, set up already, stays out of the way. Not set up: the onboarding on top.@@ -203,13 +204,16 @@ class Controller:self.records_window.present()self.records_window.set_focus(None) # not the search box: its placeholder would vanish- def show_settings(self) -> None:+ def show_settings(self, ai: bool = False) -> None:+ """设置; `ai`: at AI 服务 (its first section), where every AI problem is fixed."""if self.settings_window is None:from .settings_window import SettingsWindowself.settings_window = SettingsWindow(self)self.application.add_window(self.settings_window)self.settings_window.show_all()self.settings_window.present()+ if ai:+ self.settings_window.scroll.get_vadjustment().set_value(0)# Setup (会议记录 › 还差几步 and the capsule)@@ -218,7 +222,14 @@ class Controller:"""The setup steps as the onboarding numbers them (key, computer sound, sample): done by whatreally happened, not by "the onboarding was finished" (Windows' SetupDone)."""s = self.settings- return self.ling.has_key, s.heardSystemAudio or s.onboarded, s.sampleSeen or s.onboarded+ return self.key_works, s.heardSystemAudio or s.onboarded, s.sampleSeen or s.onboarded++ @property+ def key_works(self) -> bool:+ """The key step is done: a key, and no failure only the user can fix (a check still running,+ or one not run yet, doesn't undo it; busy counts as passed)."""+ f = self.ling.check_result.failure+ return self.ling.has_key and (f is None or f[1] in ("busy", "serverError"))@propertydef setup_left(self) -> int:@@ -238,7 +249,8 @@ class Controller:def show_onboarding(self, step: int | None = None) -> None:"""The onboarding at `step`, or at the first step not done, over the records window."""from .onboarding import AUDIO, KEY, SAMPLE, Onboarding- key, audio, _ = self.setup_done+ _, audio, _ = self.setup_done+ key = self.ling.has_keyat = step if step is not None else KEY if not key else AUDIO if not audio else SAMPLEif self.onboarding is not None:if step is not None and self.onboarding.step != step:@@ -303,6 +315,46 @@ class Controller:if self.ling.has_key:threading.Thread(target=self.ling.check, daemon=True).start()+ def recheck(self) -> None:+ """重新检查: the AI service, step by step, off the main loop."""+ if self.ling.has_key and not self.ling.check_result.running:+ threading.Thread(target=self.ling.check, daemon=True).start()++ def use_recommended(self, kind: str) -> None:+ """换成推荐的: the service's first recommended text or hear model, then a fresh check. Only+ ever on the user's click: the app never changes a model by itself."""+ p = self.ling.provider+ models = p.text_models if kind == "text" else p.hear_models+ if models:+ self.set_ai_model(kind, models[0].id)++ def switch_service(self, provider: str, key: str) -> None:+ """改用 <服务>: a key pasted for another service goes there, then it is checked."""+ self.settings.aiProvider = provider+ self.settings.save()+ self.key.save(key)+ self.ai_changed()++ def _watch_network(self) -> None:+ """A change of route (Wi-Fi back, a proxy app's TUN) waits 3 s for the network to settle, then+ the service is looked at again if it was unreachable. No timer otherwise."""+ monitor = Gio.NetworkMonitor.get_default()+ self._net_wait = None++ def settled():+ self._net_wait = None+ self.ling.network_changed()+ return False++ def changed(_m, available):+ if not available:+ return+ if self._net_wait is not None:+ GLib.source_remove(self._net_wait)+ self._net_wait = GLib.timeout_add(3000, settled)+ monitor.connect("network-changed", changed)+ self._net_monitor = monitor+def set_view(self, view: str) -> None:if view not in ("notes", "subtitles") or view == self.settings.view:return@@ -374,12 +426,23 @@ class Controller:if answer == Gtk.ResponseType.ACCEPT and self.listen.listening and self.listen.session_id == sid:self.stop_listening()- def start_listening(self, source, kind: str) -> None:+ def start_listening(self, source, kind: str, checked: bool = False) -> None:if self.listen.listening:returnif not self.ling.has_key:self.show_onboarding()return+ # The service hears for us: a known failure stops here with the fix, not in an empty window.+ # Unknown or busy starts as usual; unreachable is looked at once more first.+ r = self.ling.check_result+ if r.reason == "unreachable" and not checked:+ def again():+ self.ling.check()+ GLib.idle_add(lambda: self.start_listening(source, kind, checked=True) and False)+ threading.Thread(target=again, daemon=True).start()+ return+ if r.reason in ("deaf", "unreachable") and not self._may_start(source, kind):+ returndef ended(reason):# A file that finished stops a little later, so its last sentence's pause is heard;@@ -400,6 +463,57 @@ class Controller:self.show_notes()self.changed()+ def _may_start(self, source, kind: str) -> bool:+ """开始听 when the last check found the hear model deaf or the service unreachable: say so,+ with 打开设置 and the one fix (换成推荐的并开始 / 重新检查并开始). False: not now."""+ from ..core import aicheck+ ling = self.ling+ r = ling.check_result+ name = ling.service_name+ if r.reason == aicheck.DEAF:+ model = ling.config().hear_model+ title, body, hint = LF("%@ 现在听不了声音", model), LF("%@ 只收文字。换成推荐的模型就能开始听。", model), None+ p = ling.provider+ fix = L("换成推荐的并开始") if p.hear_models and p.hear_models[0].id != model else None+ else:+ title, body = LF("连不上 %@", name), ling.message()+ hint = r.proxy_line(name, ling.service_host)+ fix = L("重新检查并开始")+ dialog = Gtk.Dialog(transient_for=self.records_window if self.records_window and self.records_window.get_visible() else None,+ modal=True)+ dialog.set_decorated(False)+ dialog.set_resizable(False)+ dialog.set_keep_above(True)+ ui.classes(dialog, "endask")+ texts = ui.vbox(6, ui.text(title, 15, "ink", bold=True, width_chars=36), ui.text(body or "", 12, "secondary", width_chars=36))+ if hint:+ texts.pack_start(ui.panel(ui.pad(ui.text(hint, 12, "", width_chars=36), 7, 10), "proxybox"), False, False, 0)+ row = ui.hbox(8)+ row.set_halign(Gtk.Align.END)+ settings = ui.button(L("打开设置"), lambda: dialog.response(Gtk.ResponseType.CANCEL), "outline")+ row.pack_start(settings, False, False, 0)+ if fix:+ row.pack_start(ui.button(fix, lambda: dialog.response(Gtk.ResponseType.ACCEPT), "darkbtn"), False, False, 0)+ dialog.connect("key-press-event", lambda _d, e: e.keyval == Gdk.KEY_Escape and dialog.response(Gtk.ResponseType.CLOSE))+ dialog.get_content_area().pack_start(ui.pad(ui.vbox(18, texts, row), 22, 22), True, True, 0)+ dialog.get_content_area().show_all()+ self._asking = dialog # debug: screenshots, and answering it from the control socket+ answer = dialog.run()+ self._asking = None+ dialog.destroy()+ if answer == Gtk.ResponseType.CANCEL:+ self.show_settings(ai=True)+ elif answer == Gtk.ResponseType.ACCEPT:+ if r.reason == aicheck.DEAF:+ self.use_recommended("hear") # checks again; the meeting starts now+ return True++ def again():+ self.ling.check()+ GLib.idle_add(lambda: self.start_listening(source, kind, checked=True) and False)+ threading.Thread(target=again, daemon=True).start()+ return False+# 结束会议def end_config(self) -> meeting_end.Config:diff --git a/linux/cicada/app/notes_window.py b/linux/cicada/app/notes_window.pyindex c47a4fd..d90990c 100644--- a/linux/cicada/app/notes_window.py+++ b/linux/cicada/app/notes_window.py@@ -781,7 +781,10 @@ class NotesWindow(Gtk.Window):if engine.status == notesmod.INVALID_KEY:text, tone = LF("key 已失效(令牌被删或免费额度用尽),纪要停留在 %@。", clock(last)), "error"elif engine.status == notesmod.RATE_LIMITED:- text, tone = LF("请求过于频繁,稍后会自动重试。纪要停留在 %@。", clock(last)), ""+ text, tone = LF("%@ 很忙,纪要稍后补上。字幕照常。", self.app.ling.service_name), "busy"+ elif engine.status == notesmod.FAILED and self.app.ling.check_result.reason == "unreachable":+ # The network or the proxy, not the notes: say which, and that it picks up by itself.+ text, tone = LF("连不上 %@,这段时间的纪要先停在 %@。网络恢复后自动继续。", self.app.ling.service_name, clock(last)), "error"elif engine.status == notesmod.FAILED:text, tone = L("这轮没整理好,下一轮会自动重试。"), ""else:@@ -789,7 +792,9 @@ class NotesWindow(Gtk.Window):row = ui.hbox(10)row.pack_start(ui.text(text, 12, "ink", width_chars=24), True, True, 0)if tone == "error":- b = ui.button(L("更换 key"), self.app.show_settings, "darkbtn")+ unreachable = engine.status == notesmod.FAILED+ b = ui.button(L("设置") if unreachable else L("更换 key"), lambda: self.app.show_settings(ai=True),+ "outline" if unreachable else "darkbtn")b.set_can_focus(False)b.set_valign(Gtk.Align.CENTER)row.pack_end(b, False, False, 0)diff --git a/linux/cicada/app/onboarding.py b/linux/cicada/app/onboarding.pyindex 8fabaca..16bedb2 100644--- a/linux/cicada/app/onboarding.py+++ b/linux/cicada/app/onboarding.py@@ -93,9 +93,12 @@ class Onboarding(Gtk.Window):self.resize(860, 640) # back to the fixed size if a step's content asked for moredef refresh(self) -> None:- """Engine changes (the sample being heard, 知了 麦克风 made): only the step that shows them."""+ """Engine changes (the sample being heard, 知了 麦克风 made, the key checked): only the step+ that shows them."""if self.step == SAMPLE:GLib.idle_add(lambda: self._fill_sample() and False)+ elif self.step == KEY:+ GLib.idle_add(lambda: self._fill_key_steps() and False)# Frame@@ -206,8 +209,9 @@ class Onboarding(Gtk.Window):n.get_child().set_halign(Gtk.Align.CENTER)n.set_valign(Gtk.Align.START)second.pack_start(n, False, False, 0)- second.pack_start(ui.vbox(10, ui.text(L("复制 sk- 开头的 key,回来粘贴"), 15, "ink", bold=True, width_chars=34), field, self.key_status),- True, True, 0)+ self._key_extras(36)+ second.pack_start(ui.vbox(10, ui.text(L("复制 sk- 开头的 key,回来粘贴"), 15, "ink", bold=True, width_chars=34), field, self.key_status,+ self.key_hint, self.key_steps), True, True, 0)steps = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)steps.pack_start(self._row(None, L("在 Ling 开放平台创建 key"), L("注册或登录后点“创建令牌”"), platform, number=1), False, False, 0)sep = ui.panel(Gtk.Box(), "hair")@@ -231,8 +235,7 @@ class Onboarding(Gtk.Window):row.pack_start(right, False, False, 0)self.page.pack_start(ui.gap(row, 24), False, False, 0)entry.connect("activate", lambda *_: self._save_key(entry.get_text()))- if self.app.ling.has_key and self.app.ling.key_state == lingmod.OK:- self._key_ok()+ self._fill_key_steps()hint = ui.text(L("只存在这台电脑上(只有你的账户能读),只发给 Ling(ant-ling.com)"), 13, "secondary", wrap=False)self.footer.pack_start(hint, True, True, 0)self.footer.pack_end(self._primary(L("继续"), self._key_next), False, False, 0)@@ -275,15 +278,70 @@ class Onboarding(Gtk.Window):ui.text(L("用你自己的声音"), 12, "ink", bold=True, wrap=False),ui.text(L("(只有 Ling 支持)"), 12, "secondary", wrap=False))lacks = ui.panel(ui.pad(lacks, 8, 10), "raised")- card = ui.panel(ui.pad(ui.vbox(14, top, field, self.key_status, lacks), 22), "bigcard")+ self._key_extras(60)+ card = ui.panel(ui.pad(ui.vbox(14, top, field, self.key_status, self.key_hint, self.key_steps, lacks), 22), "bigcard")self.page.pack_start(ui.gap(card, 24), False, False, 0)- if self.app.ling.has_key and self.app.ling.key_state == lingmod.OK:- self._key_ok()+ self._fill_key_steps()self.footer.pack_start(ui.link(L("‹ 还是用 Ling"), lambda: self._switch("ling")), False, False, 0)self.footer.pack_start(ui.text(LF("仅保存在本机当前账户下,仅发送至 %@", p.name), 13, "secondary", wrap=False), True, True, 0)self.footer.pack_end(self._primary(L("继续"), self._key_next), False, False, 0)GLib.idle_add(lambda: entry.grab_focus() and False)+ def _key_extras(self, width: int) -> None:+ """Under the key field: a pasted key that belongs elsewhere, and the check step by step."""+ self.key_hint = ui.hbox(8)+ self.key_hint.set_no_show_all(True) # no gap while empty+ self.key_status.set_no_show_all(True) # shown when it has something to say+ self.key_status.set_visible(False)+ self.key_steps = ui.vbox(0)+ self.key_steps_width = width+ self._steps_shown = None++ def _fill_key_steps(self) -> None:+ """Where it broke and the one thing that fixes it, as in the settings; 继续 stays open."""+ from . import aicheck_view+ ling = self.app.ling+ r = ling.check_result+ if getattr(self, "key_steps", None) is None or self.key_steps.get_parent() is None:+ return+ shown = (r.summary(), ling.has_key, ling.config().hear_model, ling.config().text_model)+ if shown == self._steps_shown:+ return+ self._steps_shown = shown+ ui.clear(self.key_steps)+ if ling.has_key and (r.running or r.failure is not None):+ ui.retext(self.key_status, "")+ self.key_status.set_visible(False)++ def again():+ self.key_entry.set_text("")+ self.key_entry.grab_focus()+ self.key_steps.pack_start(aicheck_view.steps_widget(self.app, again, width_chars=self.key_steps_width), False, False, 0)+ self.key_steps.show_all()+ elif ling.has_key and ling.key_state == lingmod.OK and r.passed:+ self.key_status.set_visible(True)+ self._key_ok()++ def _key_hint(self, hint, key: str) -> None:+ ui.clear(self.key_hint)+ self.key_hint.set_visible(hint is not None)+ if hint is None:+ return+ words, service = hint+ self.key_hint.pack_start(ui.text(words, 13, "stepwhy", width_chars=36), True, True, 0)+ if service:+ from ..core.providers import named++ def switch():+ ui.clear(self.key_hint)+ self.app.switch_service(service, key)+ self.render()+ b = ui.button(LF("改用 %@", named(service).name), switch, "darkbtn midbtn")+ b.set_valign(Gtk.Align.CENTER)+ self.key_hint.pack_end(b, False, False, 0)+ for w in self.key_hint.get_children():+ w.show_all()+def _key_next(self) -> None:text = self.key_entry.get_text().strip()if text:@@ -304,12 +362,14 @@ class Onboarding(Gtk.Window):self._save_key(text)def _key_problem(self, text: str) -> None:+ self.key_status.set_visible(True)ctx = self.key_status.get_style_context()ctx.remove_class("secondary")ctx.add_class("warn")ui.retext(self.key_status, text)def _key_ok(self) -> None:+ self.key_status.set_visible(True)ctx = self.key_status.get_style_context()ctx.remove_class("warn")ctx.add_class("ok")@@ -320,25 +380,30 @@ class Onboarding(Gtk.Window):if not text.startswith("sk-"):self._key_problem(L("复制 sk- 开头的 key,回来粘贴"))return+ # The prefix says whose key it is (AISettingsView.save does the same): never a silent switch.+ from . import aicheck_view+ hint = aicheck_view.key_hint(self.app, text)+ self._key_hint(hint, text)+ if hint is not None:+ ui.retext(self.key_status, "")+ returnself.app.key.save(text)self.app.ling.key_changed()ctx = self.key_status.get_style_context()ctx.remove_class("warn")+ self.key_status.set_visible(True)ui.retext(self.key_status, L("正在检查…"))def check():- state = self.app.ling.check()+ self.app.ling.check()def done():if self.step != KEY:return False- if state == lingmod.OK:- self._key_ok()+ self._fill_key_steps()+ ling = self.app.ling+ if ling.key_state == lingmod.OK and ling.check_result.failure is None:GLib.timeout_add(700, lambda: (self.step == KEY and self.go(AUDIO)) and False)- else:- name = self.app.ling.provider.name- self._key_problem(L("这个 key 无效,请检查是否复制完整,或重新创建一个") if state == lingmod.INVALID- else L("连不上 Ling,检查网络或代理") if name == "Ling" else LF("连不上 %@,请检查网络或代理", name))return FalseGLib.idle_add(done)threading.Thread(target=check, daemon=True).start()diff --git a/linux/cicada/app/records_window.py b/linux/cicada/app/records_window.pyindex 859c8a1..a8d3ed2 100644--- a/linux/cicada/app/records_window.py+++ b/linux/cicada/app/records_window.py@@ -176,7 +176,9 @@ class RecordsWindow(Gtk.Window):sep.set_valign(Gtk.Align.CENTER)b.add(inner)ui.classes(b, "listenpill")- b.connect("clicked", lambda *_: self.app.show_onboarding())+ # A key the check found failing is fixed in 设置 › AI 服务, not in the onboarding.+ b.connect("clicked", lambda *_: self.app.show_settings(ai=True) if self.app.ling.has_key and not self.app.key_works+ else self.app.show_onboarding())b.get_accessible().set_name(L("继续设置"))box.pack_start(b, False, False, 0)elif state in ("idle", "auto"):@@ -439,7 +441,11 @@ class RecordsWindow(Gtk.Window):speak = (LF("按 %@ 说话,对方听到翻译后的声音", SHORTCUTS["speak"][2].replace(" + Shift + ", " ⇧ "))if gnome_shortcut("speak") else L("点纪要窗的麦克风说话,对方听到翻译后的声音"))service = L("接上 Ling") if app.settings.aiProvider == "ling" else LF("接上 %@", app.ling.provider.name)- steps = ((service, L("只存在这台电脑上(只有你的账户能读)") if key else L("识别、翻译和纪要都靠它,约 1 分钟"), key),+ # A key that the check found failing: why, and 去修 opens 设置 › AI 服务 (not the onboarding).+ from . import aicheck_view+ broken = aicheck_view.strip_words(app) if app.ling.has_key and not key else None+ key_line = (broken[1] or broken[0]) if broken else (L("只存在这台电脑上(只有你的账户能读)") if key else L("识别、翻译和纪要都靠它,约 1 分钟"))+ steps = ((service, key_line, key),(L("听一下电脑里的声音"), L("放一段测试声音,看音量条动起来"), audio),(L("看看效果"), L("一段 9 秒的英文会议,字幕和纪要一句句出来"), sample),(L("同声传译"), L("以后在设置 › 同声传译里打开") if app.settings.speakLater and not app.settings.speakEnabled@@ -470,7 +476,10 @@ class RecordsWindow(Gtk.Window):row = ui.hbox(14, disc)row.pack_start(texts, True, True, 0) # filled, so the words start at the left of every rowaction = None- if now:+ if now and i == 0 and broken:+ action = ui.button(L("去修"), lambda: app.show_settings(ai=True), "darkbtn")+ sub.get_style_context().add_class("stepwhy")+ elif now:action = ui.button(L("继续设置"), lambda n=i: app.show_onboarding(n), "darkbtn")elif i == 3 and not done and not app.settings.speakLater:action = ui.button(L("以后再说"), self._speak_later, "outline")diff --git a/linux/cicada/app/settings_window.py b/linux/cicada/app/settings_window.pyindex 19bcaf3..3693315 100644--- a/linux/cicada/app/settings_window.py+++ b/linux/cicada/app/settings_window.py@@ -459,10 +459,11 @@ class SettingsWindow(Gtk.Window):self.key_status = ui.hbox(6)key_left = ui.vbox(4, self.key_line, self.key_status)self.change_button = ui.button(L("更换…"), self._toggle_entry, "outline")+ self.recheck_button = ui.button(L("重新检查"), app.recheck, "outline")self.remove_button = ui.button(L("删除"), self.remove_key, "dangertext")key_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)key_row.pack_start(key_left, True, True, 0)- for b in (self.change_button, self.remove_button):+ for b in (self.change_button, self.recheck_button, self.remove_button):b.set_valign(Gtk.Align.CENTER)key_row.pack_start(b, False, False, 0)key_row = ui.panel(ui.pad(key_row, 10, 14), "prow")@@ -476,7 +477,10 @@ class SettingsWindow(Gtk.Window):entry_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)entry_row.pack_start(self.key_entry, True, True, 0)entry_row.pack_start(ui.button(L("保存并检查"), self.save_key, "darkbtn"), False, False, 0)- self.entry_row = ui.panel(ui.pad(entry_row, 12, 16), "prow")+ # A pasted key that belongs elsewhere (AISettings.swift › keyHint): what it is, 改用 <服务>.+ self.key_hint = ui.hbox(8)+ self.key_hint.set_no_show_all(True) # no gap while empty+ self.entry_row = ui.panel(ui.pad(ui.vbox(8, entry_row, self.key_hint), 12, 16), "prow")# A custom service: its address and models come before a key can be checked.self.custom_base = self._field("https://api.example.com/v1", s.aiCustomBase)self.custom_text = self._field(L("例如 qwen3:14b"), s.aiModels.get("custom", ""))@@ -500,7 +504,15 @@ class SettingsWindow(Gtk.Window):title = ui.hbox(8, ui.pad(ui.text(L("AI 服务"), 12, "group-title", bold=True, wrap=False), 0, 0, 0, 2))title.pack_end(self.provider_menu, False, False, 0)self.lock_line = ui.text("", 11, "tertiary", width_chars=60)- page.pack_start(ui.vbox(6, title, self.custom_rows, self.key_group, ui.pad(self.lock_line, 0, 2, 0, 2)), False, False, 0)+ # The check, step by step, while something is wrong or being checked; OpenRouter's balance.+ self.steps = ui.vbox(0)+ self.steps_card = ui.panel(ui.pad(self.steps, 2, 14), "boxed")+ self.steps_card.set_no_show_all(True)+ self.balance_row = ui.hbox(8)+ self.balance_strip = ui.panel(ui.pad(self.balance_row, 10, 12), "warnstrip")+ self.balance_strip.set_no_show_all(True)+ page.pack_start(ui.vbox(6, title, self.custom_rows, self.key_group, self.steps_card, self.balance_strip,+ ui.pad(self.lock_line, 0, 2, 0, 2)), False, False, 0)# What works with it.self.uses = ui.vbox(0)page.pack_start(self._group(L("现在能用的"), self.uses), False, False, 0)@@ -561,28 +573,51 @@ class SettingsWindow(Gtk.Window):return cdef _uses_rows(self) -> list:- """现在能用的 (AISettings.swift › usage), with 听对方 first: on the ports the service hears."""+ """现在能用的 (AISettings.swift › usage), with 听对方 first: on the ports the service hears. Only+ what the last result supports: when the service can't be reached or the key fails, nothing+ says "用 ZenMux" in green."""+ from ..core import aicheckling = self.app.lingc = ling.config()+ r = ling.check_resultname = L(c.provider.name) if c.provider.id == "custom" else c.provider.name- on = ling.usable+ reason = r.reason+ down = ling.has_key and r.down+ on = ling.usable and not down+ text_on = on and reason != aicheck.NO_MODEL+ notes_on = text_on and reason != aicheck.NO_JSON+ hear_on = on and ling.hears is not Falseuses = LF("用 %@", name)+ later = ((LF("连上 %@ 后可用", name) if reason == aicheck.UNREACHABLE else L("换好 key 后可用")) if down+ else L("填好 key 后可用"))+ off = L("暂不可用") if ling.has_key else L("需要 key")rows = []- if not on:- hear = (L("需要 key"), "off", L("填好 key 后可用"))- elif ling.hears is False:- hear = (L("还不能用"), "off", L("这个模型听不了声音,换一个支持音频输入的"))- elif c.is_ling:- hear = (uses, "ok", L("Ming 一次识别并翻译"))+ if hear_on:+ hear = (uses, "ok", L("Ming 一次识别并翻译") if c.is_ling else c.hear_model + " · " + L("比 Ling 晚 1–2 秒出字"))+ elif on:+ hear = (off, "off", LF("%@ 听不了声音。", c.hear_model) if c.hear_model else L("换一个模型后可用"))else:- hear = (uses, "ok", c.hear_model + " · " + L("比 Ling 晚 1–2 秒出字"))+ hear = (off, "off", later)rows.append((L("听对方"),) + hear)- rows.append((L("实时纪要"),) + ((uses, "ok", L("会中每 45 秒更新")) if on else (L("需要 key"), "off", L("填好 key 后可用"))))- rows.append((L("翻译"),) + ((uses, "ok", L("整句用它;不行时换 Google")) if on else ("Google", "off", L("没有 key 时照常可用"))))- if ling.speaks:- rows.append((L("同传声音"), uses, "ok", L("Ming 的声音") if c.is_ling else c.voice_model))+ if notes_on and r.busy:+ rows.append((L("实时纪要"), L("很忙"), "warn", L("会自动重试,纪要可能晚一点")))else:- rows.append((L("同传声音"), L("用不了"), "off", L("这个服务不能出声音") if on else L("填好 key 后可用")))+ rows.append((L("实时纪要"),) + ((uses, "ok", L("会中每 45 秒更新")) if notes_on else+ (off, "off", L("这个服务不支持 JSON") if reason == aicheck.NO_JSON+ else L("换一个模型后可用") if reason == aicheck.NO_MODEL else later)))+ rows.append((L("翻译"),) + ((uses, "ok", L("整句用它;不行时换 Google")) if text_on else+ ("Google", "off", L("先用 Google 翻译") if ling.has_key else L("没有 key 时照常可用"))))+ if ling.speaks and hear_on:+ # 同传 hears me with the hear model first, then speaks with the voice model.+ if ling.last_voice is not None:+ note = L("上次同传时正常") if ling.last_voice[0] else L("上次同传没出声")+ else:+ note = L("Ming 的声音") if c.is_ling else c.voice_model+ rows.append((L("同传声音"), uses, "ok", note))+ elif ling.speaks:+ rows.append((L("同传声音"), off, "off", LF("%@ 听不了声音。", c.hear_model) if on else later))+ else:+ rows.append((L("同传声音"), L("用不了") if on else off, "off", L("这个服务不能出声音") if on else later))if not c.is_ling:rows.append((L("你自己的声音"), L("只有 Ling"), "ling", L("换用 Ling 才有")))out = []@@ -626,18 +661,23 @@ class SettingsWindow(Gtk.Window):have = k is not Noneui.retext(self.key_line, AIKey.masked(k) if k else (L("本机服务,不用 key") if have else(L("还没填好") if p.id == "custom" else L("还没填 API key"))))- problem = None- if app.ling.problem:- problem = LF(app.ling.problem[0], *[L(a) if isinstance(a, str) else a for a in app.ling.problem[1:]])- icon_name, cls, label = {- lingmod.OK: ("object-select-symbolic", "ok", L("已连接") +- " · " + LF("%@ · 响应约 %@ 秒", c.text_model, "%.1f" % (app.ling.seconds or 0))),- lingmod.CHECKING: ("content-loading-symbolic", "secondary", L("正在检查…")),- lingmod.INVALID: ("dialog-error-symbolic", "warn", LF("%@ 提示 key 无效,请检查是否复制完整,或重新创建一个", name)),- lingmod.UNREACHABLE: ("network-offline-symbolic", "warn", problem or LF("连不上 %@,请检查网络或代理", name)),- }.get(state, (None, "secondary", ""))- if state == lingmod.OK and problem:- icon_name, cls, label = "dialog-warning-symbolic", "warn", problem+ from ..core import aicheck+ from . import aicheck_view+ r = app.ling.check_result+ f = r.failure+ if r.running or state == lingmod.CHECKING:+ icon_name, cls, label = "content-loading-symbolic", "secondary", L("正在检查…")+ elif f is not None and f[1] != aicheck.BUSY:+ # Named after the step that failed: a missing model is not a connection problem.+ label = {"reach": L("暂时连不上"), "key": L("这个 key 用不了")}.get(f[0], L("模型用不了"))+ icon_name, cls = "dialog-warning-symbolic", "warn"+ elif r.busy:+ icon_name, cls, label = "dialog-warning-symbolic", "busyline", LF("%@ 现在很忙", name)+ elif state == lingmod.OK:+ line = aicheck_view.passed_line(app)+ icon_name, cls, label = "object-select-symbolic", "ok", L("已连接") + (" · " + line if line else "")+ else:+ icon_name, cls, label = None, "secondary", ""if have and label:if icon_name:img = ui.icon(icon_name, 14)@@ -647,8 +687,31 @@ class SettingsWindow(Gtk.Window):self.key_status.show_all()self.key_status.set_visible(have and bool(label))self.change_button.set_visible(bool(k))+ self.recheck_button.set_visible(have)+ self.recheck_button.set_sensitive(not r.running)self.remove_button.set_visible(bool(k))- self.entry_row.set_visible(not k or state == lingmod.INVALID)+ self.entry_row.set_visible(not k or state == lingmod.INVALID or (self.entry_row.get_visible() and bool(self.key_hint.get_children())))+ # The steps, rebuilt when they change.+ steps_key = (r.summary(), r.at is None, c.text_model, c.hear_model, have)+ if steps_key != getattr(self, "_steps_shown", None):+ self._steps_shown = steps_key+ ui.clear(self.steps)+ if have and aicheck_view.show_steps(r):+ self.steps.pack_start(aicheck_view.steps_widget(app, self._change_key, recheck_in_step=False), False, False, 0)+ self.steps.show_all()+ self.steps_card.get_child().show_all() # show_all stops at a no_show_all widget+ self.steps_card.set_visible(True)+ else:+ self.steps_card.set_visible(False)+ ui.clear(self.balance_row)+ low = r.balance_line(name) if have else None+ if low:+ self.balance_row.pack_start(ui.text(low, 12, "", width_chars=40), True, True, 0)+ b = ui.button(L("去充值"), lambda: open_uri(aicheck_view.top_up_url(p)), "outline")+ b.set_valign(Gtk.Align.CENTER)+ self.balance_row.pack_end(b, False, False, 0)+ self.balance_strip.get_child().show_all()+ self.balance_strip.set_visible(bool(low))self.custom_rows.set_visible(p.id == "custom")self.get_key.set_visible(p.site is not None and not k)ui.retext(self.get_key_label, L("获取 Ling key") if p.id == "ling" else LF("打开 %@", name))@@ -660,7 +723,7 @@ class SettingsWindow(Gtk.Window):else L("按所选模型计费。") + LF("听的时候,电脑里的声音会发给 %@。", sent))# The rows that depend on the service and what its check found.shown = (p.id, state, app.ling.hears, bool(k), c.text_model, c.hear_model, c.voice_model,- len(app.ling.text_catalog), len(app.ling.hear_catalog))+ len(app.ling.text_catalog), len(app.ling.hear_catalog), r.reason, r.busy, app.ling.last_voice)if shown != getattr(self, "ai_shown", None):self.ai_shown = shownui.clear(self.uses)@@ -691,12 +754,45 @@ class SettingsWindow(Gtk.Window):s.aiCustomVoiceBase = self.custom_voice_base.get_text().strip()s.save()text = self.key_entry.get_text().strip()+ self._show_key_hint(None)if text:+ # The prefix says whose key it is: a management key can't call models, and another+ # service's key goes there with one click (never a silent switch).+ from . import aicheck_view+ hint = aicheck_view.key_hint(app, text)+ if hint is not None:+ self._show_key_hint(hint, text)+ returnif not app.key.save(text):returnself.key_entry.set_text("")app.ai_changed()+ def _show_key_hint(self, hint, key: str = "") -> None:+ ui.clear(self.key_hint)+ self.key_hint.set_visible(hint is not None)+ if hint is None:+ return+ words, service = hint+ self.key_hint.pack_start(ui.text(words, 12, "stepwhy", width_chars=40), True, True, 0)+ if service:+ from ..core.providers import named++ def switch():+ self._show_key_hint(None)+ self.key_entry.set_text("")+ self.app.switch_service(service, key)+ b = ui.button(LF("改用 %@", named(service).name), switch, "darkbtn")+ b.set_valign(Gtk.Align.CENTER)+ self.key_hint.pack_end(b, False, False, 0)+ for w in self.key_hint.get_children():+ w.show_all()++ def _change_key(self) -> None:+ """更换 key from a failed step: the field opens, focused."""+ self.entry_row.set_visible(True)+ self.key_entry.grab_focus()+def remove_key(self) -> None:self.app.key.remove()self.app.ai_changed()diff --git a/linux/cicada/app/tray.py b/linux/cicada/app/tray.pyindex 7a049e5..9a5b4cf 100644--- a/linux/cicada/app/tray.py+++ b/linux/cicada/app/tray.py@@ -71,7 +71,14 @@ class Tray:i.set_sensitive(sensitive)menu.append(i)return i- # A new version first, with the accent dot the Mac's panel gives it; greyed while it downloads.+ # The AI service when only the user can fix it (AIServiceStrip.swift, the panel's top): what's+ # wrong, and a click opens 设置 › AI 服务. The icon stays as it is.+ from .aicheck_view import strip_words+ broken = strip_words(self.app)+ if broken:+ item("⚠ " + broken[0].rstrip("。.") + " · " + L("打开设置"), lambda: self.app.show_settings(ai=True))+ menu.append(Gtk.SeparatorMenuItem())+ # A new version, with the accent dot the Mac's panel gives it; greyed while it downloads.upd = self.app.updates.menu_label()if upd:item("● " + upd, self.app.updates.install, sensitive=self.app.updates.progress is Nonediff --git a/linux/cicada/app/ui.py b/linux/cicada/app/ui.pyindex af02ecc..523d10e 100644--- a/linux/cicada/app/ui.py+++ b/linux/cicada/app/ui.py@@ -123,6 +123,28 @@ button.iconbtn.on { background-color: #F3F4F6; color: #15171C; }.aitag.off label { color: #5A5F6B; }.aitag.ling { background-color: #FDEEE8; }.aitag.ling label { color: #B23A12; }+.aitag.warn { background-color: #FFF4D6; }+.aitag.warn label { color: #8A5A00; }+/* The AI service check (AICheckView.swift): a 20 px disc per step, the reason in red (busy in amber). */+.stepdisc { border-radius: 10px; min-width: 20px; min-height: 20px; }+.stepdisc.ok { background-color: #E3F3EA; }+.stepdisc.ok image { color: #1F6B3A; }+.stepdisc.fail { background-color: #FDECEA; }+.stepdisc.fail image { color: #B3261E; }+.stepdisc.busy { background-color: #FFF4D6; }+.stepdisc.busy image { color: #8A5A00; }+.stepdisc.running { background-color: #FDEEE8; }+.stepdisc.running image { color: #B33A14; }+.stepdisc.off { background-color: #F2F3F5; }+.stepdisc.off image { color: #6B7080; }+.stepwhy { color: #B3261E; }+.stepwhy.busy { color: #8A5A00; }+.proxybox { background-color: #F2F3F5; border-radius: 8px; }+.proxybox label { color: #3D4149; }+.warnstrip { background-color: #FFF4D6; border-radius: 10px; }+.warnstrip label { color: #8A5A00; }+.notice.busy { background-color: #FFF4D6; }+.busyline { color: #8A5A00; }.chip { background-color: #F2F3F5; border-radius: 5px; padding: 1px 6px; color: #15171C; }.chip.now { background-color: #E8552B; color: #FFFFFF; }.chip.time { background-color: transparent; padding: 0; color: #B33A14; }diff --git a/linux/cicada/core/aicheck.py b/linux/cicada/core/aicheck.pynew file mode 100644index 0000000..25856d5--- /dev/null+++ b/linux/cicada/core/aicheck.py@@ -0,0 +1,311 @@+"""What the last look at the AI service found, step by step (AICheck.swift, plus the ports' 听对方):+can this computer 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.++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 an extra request. A check runs+only when the service, a model or the key changes, at launch, on 重新检查, and when the network+changes while the service was unreachable. Stdlib only: the Mac runs these tests too."""+from __future__ import annotations++import copy+import time+from dataclasses import dataclass++from .jsonfmt import arr, obj, parse_object, string+from .strings import L, LF++STEPS = ("reach", "key", "text", "hear")++UNREACHABLE, BAD_ADDRESS, INVALID_KEY, MGMT_KEY, NO_CREDIT, NO_MODEL, NO_JSON, DEAF, BUSY, SERVER_ERROR = (+ "unreachable", "badAddress", "invalidKey", "mgmtKey", "noCredit", "noModel", "noJSON", "deaf", "busy", "serverError")+REASONS = (UNREACHABLE, BAD_ADDRESS, INVALID_KEY, MGMT_KEY, NO_CREDIT, NO_MODEL, NO_JSON, DEAF, BUSY, SERVER_ERROR)++RUNNING, OK, BUSY_STATE, FAIL, SKIPPED, UNTESTED = "running", "ok", "busy", "fail", "skipped", "untested"++# Below this many dollars left, OpenRouter's balance is worth a word.+LOW_BALANCE = 0.5+TOP_UP = "https://openrouter.ai/settings/credits"+++@dataclass(frozen=True)+class State:+ kind: str = UNTESTED+ seconds: float | None = None # ok: how long the request that proved it took (None: proved by another step's)+ reason: str | None = None # fail+ code: int | None = None # fail: the HTTP status, when there was one+++class AICheck:+ """The steps in order, when the newest result came in, whether it came from a real request+ (`passive`), the proxy hint after `unreachable`, and OpenRouter's balance. Replaced whole, never+ changed in place once shown: engine threads and the UI read it at the same time."""++ def __init__(self):+ self.steps = {s: State() for s in STEPS}+ self.at: float | None = None+ self.passive = False+ # ("system",) a proxy is on; ("app", port) a proxy app listens but the system proxy is off; ("none",).+ self.proxy: tuple | None = None+ self.balance: float | None = None++ def copy(self) -> "AICheck":+ return copy.deepcopy(self)++ def __getitem__(self, step: str) -> State:+ return self.steps[step]++ def __setitem__(self, step: str, state: State) -> None:+ self.steps[step] = state++ @property+ def failure(self):+ """(step, reason, code) of the first step that failed, else None."""+ for s in STEPS:+ st = self.steps[s]+ if st.kind == FAIL:+ return s, st.reason, st.code+ return None++ @property+ def reason(self) -> str | None:+ f = self.failure+ return f[1] if f else None++ @property+ def running(self) -> bool:+ return any(st.kind == RUNNING for st in self.steps.values())++ @property+ def busy(self) -> bool:+ return any(st.kind == BUSY_STATE for st in self.steps.values())++ @property+ def passed(self) -> bool:+ """Every step passed (busy counts; a step nothing has tested yet does not block)."""+ return self.at is not None and self.failure is None and not self.running++ @property+ def low_balance(self) -> bool:+ return self.balance is not None and self.balance < LOW_BALANCE++ @property+ def needs_user(self) -> bool:+ """Something only the user can fix (a busy service, or one that errs, fixes itself)."""+ f = self.failure+ if f is None:+ return self.low_balance+ return f[1] not in (BUSY, SERVER_ERROR)++ @property+ def down(self) -> bool:+ """Nothing AI works: the service can't be reached, or won't take the key."""+ return self.reason in (UNREACHABLE, BAD_ADDRESS, INVALID_KEY, MGMT_KEY, NO_CREDIT)++ def fail(self, step: str, reason: str, code: int | None = None, reached: bool = True) -> None:+ """`step` failed and the ones after it were never reached. `reached`: a reply came back, so+ the steps before it passed (False when nothing was sent, like a management key)."""+ after = False+ for s in STEPS:+ if s == step:+ self.steps[s] = State(FAIL, reason=reason, code=code)+ after = True+ elif after:+ self.steps[s] = State(SKIPPED)+ elif reached and self.steps[s].kind != OK:+ self.steps[s] = State(OK)+ if reason != UNREACHABLE:+ self.proxy = None++ def pass_up_to(self, step: str, seconds: float | None) -> None:+ """One request proved every step up to `step` (a chat proves the address, the key and the+ model). Clears what failed before; skipped steps after it are open again."""+ after = False+ for s in STEPS:+ if after:+ if self.steps[s].kind == SKIPPED:+ self.steps[s] = State(UNTESTED)+ elif s == step:+ self.steps[s] = State(OK, seconds)+ after = True+ elif self.steps[s].kind != OK:+ self.steps[s] = State(OK)+ self.proxy = None++ # Words++ def message(self, service: str, host: str, text_model: str, hear_model: str) -> str | None:+ """Why the failed step failed, in one sentence."""+ f = self.failure+ if f is None:+ return LF("%@ 现在很忙,key 没问题。开会时会自动重试。", service) if self.busy else None+ reason, code = f[1], f[2]+ return {+ UNREACHABLE: lambda: LF("这台电脑访问不到 %@。", host),+ BAD_ADDRESS: lambda: L("地址要用 https,只有 localhost 可以用 http。"),+ INVALID_KEY: lambda: LF("%@ 说这个 key 无效,可能没复制全,或已删除。", service),+ MGMT_KEY: lambda: L("这是 ZenMux 的管理 key,不能用来调用模型。请粘贴 sk-payg 开头的 key。"),+ NO_CREDIT: lambda: LF("%@ 账户余额不足。", service),+ NO_MODEL: lambda: LF("%@ 上找不到 %@ 这个模型。", service, text_model),+ NO_JSON: lambda: L("这个服务不支持 JSON,纪要写不了;翻译照常。"),+ DEAF: lambda: LF("%@ 听不了声音。", hear_model),+ BUSY: lambda: LF("%@ 现在很忙,key 没问题。开会时会自动重试。", service),+ SERVER_ERROR: lambda: LF("%@ 暂时出错(HTTP %lld),稍后再试。", service, code or 0),+ }[reason]()++ def proxy_line(self, service: str, host: str) -> str | None:+ """Under "can't reach": what this computer's proxy looks like, and what to do."""+ if self.reason != UNREACHABLE or self.proxy is None:+ return None+ if self.proxy[0] == "system":+ return LF("开了代理也连不上:换一个节点,或检查代理软件是否放过 %@。", host)+ if self.proxy[0] == "app":+ # As text: a number would be grouped ("7,890") on the Mac, which keys it this way.+ return LF("代理软件在运行(端口 %@),但没开系统代理。在代理软件里打开“系统代理”。", str(self.proxy[1]))+ return LF("这台电脑没开代理。在国内通常要开代理才能用 %@。", service)++ def balance_line(self, service: str) -> str | None:+ """"OpenRouter 余额快用完了(还剩 $0.40)" when it is."""+ if not self.low_balance:+ return None+ return LF("%@ 余额快用完了(还剩 $%@)", service, "%.2f" % max(0.0, self.balance))++ def summary(self) -> str:+ """Debug and logs: "reach=ok key=fail(invalidKey) text=skipped hear=skipped"."""+ out = []+ for s in STEPS:+ st = self.steps[s]+ if st.kind == OK:+ v = "ok" if st.seconds is None else "ok(%.1fs)" % st.seconds+ elif st.kind == FAIL:+ v = "fail(%s%s)" % (st.reason, "" if st.code is None else " %d" % st.code)+ else:+ v = st.kind+ out.append("%s=%s" % (s, v))+ if self.proxy is not None:+ out.append("proxy=" + ":".join(str(p) for p in self.proxy))+ if self.balance is not None:+ out.append("balance=%.2f" % self.balance)+ if self.passive:+ out.append("passive")+ return " ".join(out)+++def title(step: str, host: str) -> str:+ return {"reach": lambda: LF("连上 %@", host), "key": lambda: L("key 可以用"),+ "text": lambda: L("纪要和翻译"), "hear": lambda: L("听对方")}[step]()+++def classify(e: LingError, at: str, audio: bool = False):+ """(step, reason, code) a failed request stops at, or None when it says nothing about the+ service. `at` is the step the request was proving; `audio`: it carried audio for the hear model."""+ from .ling import LingError # here: ling.py imports this module+ k = e.kind+ if k in (LingError.NETWORK, LingError.TIMEOUT):+ return "reach", UNREACHABLE, None+ if k == LingError.INVALID_KEY:+ return "key", INVALID_KEY, None+ if k == LingError.RATE_LIMITED:+ return at, BUSY, None+ if k != LingError.HTTP:+ return None # no key, a search essay, an unreadable reply+ code = e.status+ if code == 402:+ return "key", NO_CREDIT, code+ if audio and code in (400, 404, 415, 422):+ return "hear", DEAF, code+ if code in (400, 404):+ return ("key", SERVER_ERROR, code) if at == "key" else ("text", NO_MODEL, code)+ return at, SERVER_ERROR, code+++def owner(key: str):+ """(service id, management) the prefix of a key says it belongs to: `sk-or-` OpenRouter,+ `sk-payg` ZenMux, `sk-mgmt` ZenMux's management key (it can't call models). None: can't tell."""+ k = (key or "").strip()+ if k.startswith("sk-or-"):+ return "openrouter", False+ if k.startswith("sk-payg"):+ return "zenmux", False+ if k.startswith("sk-mgmt"):+ return "zenmux", True+ return None+++def listed(data) -> tuple:+ """(every model id, the ids that take audio in) from a `/models` reply, as listed: unlike the+ menus' catalog, recommended models are not added, so one the service dropped shows. Either is+ None when the reply can't tell (no list; no model that declares its input modalities)."""+ root = parse_object(data) if isinstance(data, str) else data+ ids, hear, declared = set(), set(), False+ for m in arr((root or {}).get("data")):+ m = obj(m) or {}+ mid = string(m.get("id"))+ if not mid:+ continue+ ids.add(mid)+ ins = m.get("input_modalities")+ if ins is None:+ ins = (obj(m.get("architecture")) or {}).get("input_modalities")+ if isinstance(ins, list):+ declared = True+ if "audio" in ins:+ hear.add(mid)+ return (ids or None), (hear if declared and ids else None)+++def balance(key_info, credits) -> float | None:+ """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."""+ k = (obj((obj(key_info) or {}).get("data")) or {}).get("limit_remaining")+ k = float(k) if isinstance(k, (int, float)) and not isinstance(k, bool) else None+ d = obj((obj(credits) or {}).get("data")) or {}+ total, used = d.get("total_credits"), d.get("total_usage")+ c = float(total) - float(used) if all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in (total, used)) else None+ have = [v for v in (k, c) if v is not None]+ return min(have) if have else None+++def simulated(reason: str) -> AICheck:+ """A made-up result for `reason` (debug screenshots of every state)."""+ r = AICheck()+ if reason == BUSY:+ r.pass_up_to("hear", 1.4)+ r["text"] = State(OK, 1.2)+ r["hear"] = State(BUSY_STATE)+ elif reason in (UNREACHABLE, BAD_ADDRESS):+ r.fail("reach", reason, reached=False)+ elif reason in (INVALID_KEY, NO_CREDIT):+ r.fail("key", reason, 402 if reason == NO_CREDIT else None)+ elif reason == MGMT_KEY:+ r.fail("key", reason, reached=False)+ elif reason in (NO_MODEL, NO_JSON):+ r.fail("text", reason, 404)+ elif reason == DEAF:+ r.pass_up_to("text", 1.2)+ r.fail("hear", reason, 400)+ elif reason == SERVER_ERROR:+ r.fail("text", reason, 503)+ else: # lowBalance: everything passed+ r.pass_up_to("hear", 1.4)+ r["text"] = State(OK, 1.2)+ return r+++def relative(at: float, now: float | None = None) -> str:+ """"12 分钟前开会时用过", from when a meeting last proved the service."""+ ago = max(0, int((now if now is not None else time.time()) - at))+ if ago < 60:+ return L("刚刚开会时用过")+ if ago < 3600:+ return LF("%lld 分钟前开会时用过", ago // 60)+ if ago < 86400:+ return LF("%lld 小时前开会时用过", ago // 3600)+ return LF("%lld 天前开会时用过", ago // 86400)+++def help_url(language: str) -> str:+ """The website's proxy help, in the UI language."""+ prefix = next(("/" + p for p in ("en", "ja", "ko") if (language or "").startswith(p)), "")+ return "https://cicada.indaloop.app%s/start/#proxy" % prefixdiff --git a/linux/cicada/core/ling.py b/linux/cicada/core/ling.pyindex 9873e00..e0d0842 100644--- a/linux/cicada/core/ling.py+++ b/linux/cicada/core/ling.py@@ -8,10 +8,11 @@ import socketimport threadingimport timeimport urllib.error+import urllib.parseimport urllib.requestimport wave-from . import jsonfmt+from . import aicheck, jsonfmt, proxy, stringsfrom .jsonfmt import arr, obj, stringfrom .providers import LING, AIConfig, catalog, is_localfrom .support import Log, Paths@@ -203,20 +204,29 @@ class LingClient:self.transport = transportself.config = config or _ling_configself.key_state = NONE if self.current_key() is None else UNCHECKED- # Why the last check failed, shown under the key: a Mac string key and its arguments for LF()- # ("连不上 %@,请检查网络或代理", "ZenMux"); None when it didn't.- self.problem: tuple | None = None+ # Step by step, where the service stands (aicheck.py); `key_state` is its short form.+ self.check_result = aicheck.AICheck()self.seconds: float | None = None # how long the last good check took- # Whether the hear model takes audio: None until a check asked (always True on Ling).- self.hears: bool | None = None+ # The last time the room voice spoke (or failed to) through this service: (ok, time).+ self.last_voice: tuple | None = None+ # Reads this computer's proxy settings to word the "can't reach" hint (never used to connect).+ self.proxy_hint = proxy.hint+ # Debug control only: every check ends this way (a reason, or "lowBalance"), for screenshots.+ self.simulate: str | None = Noneself.text_catalog: list = []self.hear_catalog: list = []+ # Every model id the service lists, and those that take audio, to tell whether the chosen+ # ones still exist (None: the service can't tell).+ self._listed: tuple = (None, None)self.rate_limited_at = Noneself._listeners = []self._gate = threading.Condition()self._waiting = []self._last_start = 0.0self._seq = 0+ self._check_lock = threading.Lock()+ self._check_seq = 0+ self._checking = 0 # a check's own requests aren't real ones: they don't feed `observe`def on_change(self, listener) -> None:self._listeners.append(listener)@@ -250,83 +260,258 @@ class LingClient:"""Voices in the room from this service. Linux has no system voice to fall back on."""return self.usable and self.config().has_voices+ @property+ def hears(self) -> bool | None:+ """Whether the hear model takes audio: False when found deaf, True once proved (always on+ Ling, whose Ming hears by design), None until something asked."""+ st = self.check_result["hear"]+ if st.kind == aicheck.FAIL and st.reason == aicheck.DEAF:+ return False+ if st.kind in (aicheck.OK, aicheck.BUSY_STATE) or self.config().is_ling:+ return True+ return None+@propertydef can_hear(self) -> bool:"""Listening and 同声传译 can work: the hear model wasn't found to refuse audio."""return self.usable and self.hears is not False and bool(self.config().hear_model)+ @property+ def service_name(self) -> str:+ """The service's name for messages ("这个服务" for a custom address, localized)."""+ p = self.provider+ return p.name if p.id != "custom" else strings.L("这个服务")++ @property+ def service_host(self) -> str:+ c = self.config()+ return urllib.parse.urlsplit(c.base or c.provider.base or "").hostname or ""++ def message(self) -> str | None:+ """The failed step's sentence (or the busy note), in the UI language."""+ c = self.config()+ return self.check_result.message(self.service_name, self.service_host, c.text_model, c.hear_model)+def key_changed(self) -> None:"""The key, the service or its models changed: forget what the last check found."""self.key.reload()+ with self._check_lock:+ self._check_seq += 1 # a check still running for the old settings is dropped+ self.check_result = aicheck.AICheck()self.key_state = NONE if self.current_key() is None else UNCHECKED- self.problem = None- self.hears = True if self.config().is_ling else None+ self.last_voice = Noneself.text_catalog, self.hear_catalog = [], []+ self._listed = (None, None)self._changed()def check(self) -> str:- """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, then half a second of silence to the hear model (a 400 or 404 says it can't+ take audio). A custom service must also return JSON (the notes need it); OpenRouter's key+ and credits give the balance. The model list then tells whether the chosen models still+ exist. Returns the short form (`key_state`)."""+ with self._check_lock:+ self._check_seq += 1+ seq = self._check_seq+ k = self.current_key()+ c = self.config()+ if k is None:+ with self._check_lock:+ self.check_result = aicheck.AICheck()+ self.key_state = NONE+ self._changed()+ return NONE+ r = aicheck.AICheck()+ r["reach"] = aicheck.State(aicheck.RUNNING)+ with self._check_lock:+ self.check_result = r.copy()self.key_state = CHECKING- self.problem = Noneself._changed()- c = self.config()- name = c.provider.name if c.provider.id != "custom" else "这个服务"+ with self._check_lock:+ self._checking += 1+ try:+ r = self._run_check(r, c, k)+ finally:+ with self._check_lock:+ self._checking -= 1+ return self._finish_check(r, c, seq)++ def _run_check(self, r, c: AIConfig, k: str):+ if self.simulate:+ return aicheck.simulated(self.simulate)+ if c.provider.id == "custom" and c.base is None:+ r.fail("reach", aicheck.BAD_ADDRESS, reached=False)+ return r+ if (aicheck.owner(k) or ("", False))[1]:+ r.fail("key", aicheck.MGMT_KEY, reached=False)+ return rstarted = time.monotonic()- state = UNREACHABLEtry:if c.is_ling:self.chat("Reply with OK.", "Reply.", SPEAK, max_tokens=5, timeout=10.0, model="Ling-3.0-tiny")- self.seconds = time.monotonic() - started- self.hears = Trueelse:- if c.base is None or not c.text_model:- raise LingError(LingError.NO_KEY)self.chat("Reply with OK.", "Reply.", SPEAK, max_tokens=5, timeout=20.0)- self.seconds = time.monotonic() - started- if c.provider.id == "custom":- try:- self.chat("Reply with the JSON object {\"ok\": true}.", "Reply.", SPEAK, json=True, max_tokens=20, timeout=20.0)- except LingError as e:- if e.kind == LingError.HTTP:- self.problem = ("这个服务不支持 JSON(HTTP %lld),纪要用不了", e.status)- else:- raise- self.hears = self._hears(c)- state = OK+ self.seconds = time.monotonic() - started+ r.pass_up_to("text", self.seconds)+ if c.provider.id == "custom":+ try:+ self.chat("Reply with the JSON object {\"ok\": true}.", "Reply.", SPEAK, json=True, max_tokens=20, timeout=20.0)+ except LingError as e:+ if e.kind != LingError.HTTP:+ raise+ r.fail("text", aicheck.NO_JSON, e.status)except LingError as e:- state = {LingError.NO_KEY: NONE, LingError.INVALID_KEY: INVALID,- LingError.RATE_LIMITED: OK}.get(e.kind, UNREACHABLE) # a busy key is still a good key- if e.kind == LingError.HTTP and e.status in (400, 404):- self.problem = (("找不到模型,或地址不对(HTTP %lld)", e.status) if c.provider.id == "custom"- else ("%@ 拒绝了请求(HTTP %lld),请检查模型名", name, e.status))- elif state == UNREACHABLE:- self.problem = ("连不上 %@,请检查网络或代理", name)+ self._failed(r, aicheck.classify(e, "text"), "text")except Exception: # noqa: BLE001- state = UNREACHABLE- self.problem = ("连不上 %@,请检查网络或代理", name)- self.key_state = state- Log.d("ai %s: key check -> %s%s" % (c.provider.id, state, "" if self.hears is not False else " (hear model refuses audio)"))- self._changed()- if state == OK and not c.is_ling:+ r.fail("reach", aicheck.UNREACHABLE)+ if r.failure is not None or c.is_ling:+ return r # Ling's hearing is Ming: a meeting proves it, no probe+ if not c.hear_model:+ r.fail("hear", aicheck.DEAF)+ else:+ started = time.monotonic()+ try:+ self.chat("Transcribe the audio.", "Reply with what is said, or NONE.", SPEAK, max_tokens=10, timeout=20.0,+ model=c.hear_model, audio=silence_wav())+ r["hear"] = aicheck.State(aicheck.OK, time.monotonic() - started)+ except LingError as e:+ if e.kind == LingError.HIJACKED:+ r["hear"] = aicheck.State(aicheck.OK, time.monotonic() - started) # it answered: it took the audio+ else:+ self._failed(r, aicheck.classify(e, "hear", audio=True), "hear")+ except Exception: # noqa: BLE001+ r.fail("reach", aicheck.UNREACHABLE)+ if c.provider.id == "openrouter" and r.failure is None:+ r.balance = aicheck.balance(self._get_json("key", k), self._get_json("credits", k))+ if r.failure is None or r.failure[0] == "hear": # the menus want the models even when the hear one is deafself.fetch_catalog()- return state+ every, hear = self._listed+ # A model the service no longer lists fails here, before a meeting finds out.+ if every is not None and c.text_model and c.text_model not in every:+ r.fail("text", aicheck.NO_MODEL)+ elif hear is not None and c.hear_model not in hear and r.failure is None:+ r.fail("hear", aicheck.DEAF)+ return r- def _hears(self, c: AIConfig) -> bool | None:- """Whether the hear model takes audio: a 400 or 404 says no; anything else can't tell."""- if not c.hear_model:+ @staticmethod+ def _failed(r, classified, step: str) -> None:+ """A check's request failed: busy passes (the key works), anything else stops there."""+ if classified is None:+ r.pass_up_to(step, None) # a reply came (a search essay, odd JSON): the service answers+ return+ at, reason, code = classified+ if reason == aicheck.BUSY:+ r.pass_up_to(at, None)+ r[at] = aicheck.State(aicheck.BUSY_STATE)+ else:+ r.fail(at, reason, code)++ def _finish_check(self, r, c: AIConfig, seq: int) -> str:+ if r.reason == aicheck.UNREACHABLE and r.proxy is None:+ try:+ r.proxy = self.proxy_hint()+ except Exception: # noqa: BLE001 - it only words a hint+ r.proxy = None+ if self.simulate == "lowBalance":+ r.balance = 0.4+ r.at = time.time()+ with self._check_lock:+ if seq != self._check_seq:+ Log.d("ai %s: check result dropped (settings changed meanwhile)" % c.provider.id)+ return self.key_state+ self.check_result = r+ self._sync_key_state()+ Log.d("ai %s: check -> %s" % (c.provider.id, r.summary()))+ self._changed()+ return self.key_state++ def _sync_key_state(self) -> None:+ """The short form older callers read: invalid stops every request; a failure before the+ hear step is "unreachable" with a reason; a deaf hear model leaves notes and translation ok."""+ if not self.has_key:+ self.key_state = NONE+ return+ r = self.check_result+ f = r.failure+ if f is not None and f[1] in (aicheck.INVALID_KEY, aicheck.MGMT_KEY):+ self.key_state = INVALID+ elif f is not None and f[0] != "hear" and f[1] != aicheck.BUSY:+ self.key_state = UNREACHABLE+ elif r.at is not None and not r.running:+ self.key_state = OK+ for s in ("reach", "key", "text"):+ if r[s].kind == aicheck.OK and r[s].seconds is not None:+ self.seconds = r[s].seconds++ def observe(self, failure: LingError | None, seconds: float = 0.0, audio: bool = False) -> None:+ """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."""+ if self._checking or self.simulate or not self.has_key:+ return+ with self._check_lock:+ old = self.check_result+ if old.running:+ return+ r = old.copy()+ if failure is not None:+ cl = aicheck.classify(failure, "hear" if audio else "text", audio)+ if cl is None or cl[1] == aicheck.SERVER_ERROR:+ return+ step, reason, code = cl+ if reason == aicheck.BUSY:+ r.pass_up_to("key", None)+ r[step] = aicheck.State(aicheck.BUSY_STATE)+ else:+ r.fail(step, reason, code)+ elif audio:+ # Heard: says nothing about the text model, which keeps what it had.+ r.pass_up_to("key", None)+ r["hear"] = aicheck.State(aicheck.OK, seconds)+ else:+ r.pass_up_to("text", seconds)+ r.at = time.time()+ r.passive = True+ if r.reason != aicheck.UNREACHABLE:+ r.proxy = None+ if [r[s] for s in aicheck.STEPS] == [old[s] for s in aicheck.STEPS] and old.passive and old.at is not None:+ old.at = r.at # only the time: nothing worth repainting for+ return+ newly_unreachable = r.reason == aicheck.UNREACHABLE and old.reason != aicheck.UNREACHABLE+ self.check_result = r+ self._sync_key_state()+ Log.d("ai: from a real request -> %s" % r.summary())+ self._changed()+ if newly_unreachable:+ threading.Thread(target=self._word_proxy, daemon=True).start()++ def _word_proxy(self) -> None:+ hint = self.proxy_hint()+ with self._check_lock:+ if self.check_result.reason != aicheck.UNREACHABLE:+ return+ nxt = self.check_result.copy()+ nxt.proxy = hint+ self.check_result = nxt+ self._changed()++ def network_changed(self) -> bool:+ """The network came back (or changed) while the service was unreachable: look again.+ True when a check started."""+ r = self.check_result+ if not self.has_key or r.reason != aicheck.UNREACHABLE or r.running:return False+ Log.d("ai: network changed while unreachable, checking again")+ threading.Thread(target=self.check, daemon=True).start()+ return True++ def _get_json(self, path: str, k: str):+ """A GET under the service's address, as JSON; None when it fails (it only adds detail)."""+ c = self.config()try:- self.chat("Transcribe the audio.", "Reply with what is said, or NONE.", SPEAK, max_tokens=10, timeout=20.0,- model=c.hear_model, audio=silence_wav())- return True- except LingError as e:- if e.kind == LingError.HTTP and e.status in (400, 404, 415, 422):- return False- if e.kind == LingError.HIJACKED:- return True+ res = self.transport.send(c.base + path, "GET", None, self._headers(k), 15.0)+ except (OSError, TimeoutError):return None+ return jsonfmt.parse_object(res.body) if res.status == 200 else Nonedef fetch_catalog(self) -> None:"""The service's models, for the model menus: those that chat, and those that hear. Quietly@@ -343,6 +528,7 @@ class LingClient:returnself.text_catalog = catalog(res.body, [m.id for m in c.provider.text_models], hears=False)self.hear_catalog = catalog(res.body, [m.id for m in c.provider.hear_models], hears=True)+ self._listed = aicheck.listed(res.body)Log.d("ai %s: %d models, %d hear" % (c.provider.id, len(self.text_catalog), len(self.hear_catalog)))self._changed()@@ -394,8 +580,10 @@ class LingClient:if self.rate_limited_at is not None:self.rate_limited_at = Noneself._changed()+ self.observe(None, time.monotonic() - started, audio is not None)return trimmedexcept LingError as e:+ self.observe(e, audio=audio is not None)if e.kind != LingError.RATE_LIMITED:raiseif attempt > len(waits):@@ -408,6 +596,18 @@ class LingClient:attempt += 1def speech(self, text: str, voice: str | None = "UK_Charlotte", language: str | None = None, timeout: float = 20.0):+ """_speech, remembering how it went (现在能用的 › 同传声音 says so). Cut short on purpose (stop,+ a new press) is neither."""+ try:+ yield from self._speech(text, voice, language, timeout)+ except GeneratorExit:+ raise+ except Exception:+ self.last_voice = (False, time.time())+ raise+ self.last_voice = (True, time.time())++ def _speech(self, text: str, voice: str | None, language: str | None, timeout: float):"""The service's voice for `text`, as raw 24 kHz mono 16-bit PCM chunks while they arrive (agenerator). On Ling, `voice` is Ming's and `language` its language_id, needed for Japanese,Korean, German, French and Spanish (Ling.swift › speech); elsewhere the configured speechdiff --git a/linux/cicada/core/listen.py b/linux/cicada/core/listen.pyindex 23c9c94..0afba29 100644--- a/linux/cicada/core/listen.py+++ b/linux/cicada/core/listen.py@@ -234,7 +234,7 @@ class ListenEngine:heard = self.translator.hear(wav, seg.asked, lang)self.problem = self.problem_kind = Noneexcept LingError as e:- self.problem_kind, self.problem = problem(e, self.ling.provider.name)+ self.problem_kind, self.problem = problem(e, self.ling.provider.name, self.ling.config().hear_model)Log.d("listen: segment %d failed %s" % (seg.index, e))except Exception as e: # noqa: BLE001Log.d("listen: segment %d failed %s" % (seg.index, type(e).__name__))@@ -358,19 +358,20 @@ def join(a: str, b: str, lang: str) -> str:return a.rstrip() + b.lstrip() if cjk else a.rstrip() + " " + b.lstrip()-def problem(e: LingError, service: str):+def problem(e: LingError, service: str, hear_model: str = ""):"""(kind, what to say) for a stretch that couldn't be heard. Ling keeps its own words; another- service is named. A hear model that refuses audio (400 / 404) is a key-like problem: 设置 fixes it."""+ service is named. A hear model that refuses audio (400 / 404 / 415 / 422) is a key-like problem:+ 设置 fixes it, in the words of the settings' 听对方 step."""L, LF = strings.L, strings.LFling = service == "Ling"- if e.kind == LingError.HTTP and e.status in (400, 404) and not ling:- return "key", L("这个模型听不了声音,换一个支持音频输入的")+ if e.kind == LingError.HTTP and e.status in (400, 404, 415, 422) and not ling:+ return "key", LF("%@ 听不了声音。", hear_model or service)kind = {LingError.NO_KEY: "key", LingError.INVALID_KEY: "key", LingError.RATE_LIMITED: "busy",LingError.NETWORK: "network", LingError.TIMEOUT: "network"}.get(e.kind)if ling:text = {LingError.NO_KEY: L("需要 Ling key 才能听"), LingError.INVALID_KEY: L("Ling key 无效"),- LingError.RATE_LIMITED: L("Ling 太忙,稍后再试"), LingError.NETWORK: L("连不上 Ling,检查网络或代理"),- LingError.TIMEOUT: L("连不上 Ling,检查网络或代理")}.get(e.kind)+ LingError.RATE_LIMITED: L("Ling 太忙,稍后再试"), LingError.NETWORK: L("连不上 Ling"),+ LingError.TIMEOUT: L("连不上 Ling")}.get(e.kind)else:text = {LingError.NO_KEY: LF("需要 %@ 的 key 才能听", service), LingError.INVALID_KEY: LF("%@ 的 key 无效", service),LingError.RATE_LIMITED: LF("%@ 太忙,稍后再试", service), LingError.NETWORK: LF("连不上 %@", service),diff --git a/linux/cicada/core/proxy.py b/linux/cicada/core/proxy.pynew file mode 100644index 0000000..31f039f--- /dev/null+++ b/linux/cicada/core/proxy.py@@ -0,0 +1,48 @@+"""Words the "can't reach the AI service" hint (ProxyHint.swift). Read-only on purpose: the app never+sets or picks a proxy of its own (urllib already goes through `https_proxy` when it is set); it only+tells the user which of three situations they are in, so the hint says what to do."""+from __future__ import annotations++import os+import socket+import subprocess++# Ports common proxy apps listen on (Clash 7890, Clash Verge 7897, SOCKS 1080).+PORTS = (7890, 7897, 1080)+++def system_proxy_on(env=None, gsettings=None) -> bool:+ """A proxy in the environment (what urllib uses), else GNOME's 设置 › 网络 › 网络代理 set to+ manual or automatic."""+ env = os.environ if env is None else env+ if any((env.get(k) or "").strip() for k in ("https_proxy", "HTTPS_PROXY", "all_proxy", "ALL_PROXY")):+ return True+ mode = (gsettings or _gnome_mode)()+ return mode.strip().strip("'\"") in ("manual", "auto")+++def _gnome_mode() -> str:+ try:+ r = subprocess.run(["gsettings", "get", "org.gnome.system.proxy", "mode"], capture_output=True, text=True, timeout=2)+ return r.stdout if r.returncode == 0 else ""+ except (OSError, subprocess.SubprocessError):+ return "" # no gsettings (not GNOME, or the Mac running the tests)+++def listening(port: int, timeout: float = 0.3) -> bool:+ """Something accepts a TCP connection on 127.0.0.1:`port` within `timeout`. Nothing is sent."""+ try:+ with socket.create_connection(("127.0.0.1", port), timeout=timeout):+ return True+ except OSError:+ return False+++def hint(env=None, gsettings=None, probe=listening) -> tuple:+ """("system",), ("app", port) or ("none",): see AICheck.proxy_line."""+ if system_proxy_on(env, gsettings):+ return ("system",)+ for port in PORTS:+ if probe(port):+ return ("app", port)+ return ("none",)diff --git a/linux/strings/en.lproj/Linux.strings b/linux/strings/en.lproj/Linux.stringsindex 1b744e6..5a5989e 100644--- a/linux/strings/en.lproj/Linux.strings+++ b/linux/strings/en.lproj/Linux.strings@@ -5,11 +5,9 @@"句" = "lines";"重命名" = "Rename";"保存失败" = "Couldn't save";-"Ling key" = "Ling key";"只存在这台电脑上(只有你的账户能读),只发给 Ling(ant-ling.com)" = "Stored only on this computer (readable only by your account) and sent only to Ling (ant-ling.com)";"界面语言" = "App language";"关于" = "About";-"可以用" = "Works";"需要 Ling key 才能听" = "Listening needs a Ling key";"Ling key 无效" = "The Ling key is invalid";"Ling 太忙,稍后再试" = "Ling is busy; trying again shortly";@@ -49,8 +47,6 @@"正在听时" = "While listening";"悬浮窗" = "Floating window";"登录后在顶栏待命" = "Stand by in top bar after login";-"翻译与纪要模型" = "Translation & notes model";-"Ming(云端)" = "Ming (cloud)";"打开记录文件夹" = "Open meetings folder";"打开会议记录" = "Open meetings";"没能开始听" = "Couldn't start listening";@@ -154,8 +150,6 @@"例如 qwen3-omni" = "e.g. qwen3-omni";"听的模型" = "Listening model";"要能输入音频:听对方和“我说”都用它" = "Must take audio in: used for Listen and for Speak";-"还不能用" = "Not yet";-"这个模型听不了声音,换一个支持音频输入的" = "This model can't take audio. Choose one that accepts audio input";"Ming 一次识别并翻译" = "Ming recognizes and translates in one step";"比 Ling 晚 1–2 秒出字" = "Text appears 1–2 s later than with Ling";"用不了" = "Unavailable";@@ -169,3 +163,19 @@"%@ 的 key 无效" = "%@ key is invalid";"%@ 太忙,稍后再试" = "%@ is busy. Try again shortly";"仅保存在本机当前账户下,仅发送至 %@(%@)" = "Stored only for this account on this computer, sent only to %1$@ (%2$@)";+/* AI 服务检查 (aicheck.py): the steps, 开始听 when a check failed. */+"%@ 听不了声音。" = "%@ can't hear audio.";+"%@ 现在听不了声音" = "%@ can't hear audio right now";+"%@ 只收文字。换成推荐的模型就能开始听。" = "%@ only takes text. Switch to the recommended model to start listening.";+"换成推荐的并开始" = "Use Recommended and Start";+"重新检查并开始" = "Check Again and Start";+"去修" = "Fix";+"上次同传没出声" = "Silent last time it interpreted";+"仅保存在本机当前账户下,仅发送至 Ling(ant-ling.com)" = "Stored only for this account on this computer, sent only to Ling (ant-ling.com)";+"这台电脑访问不到 %@。" = "This computer can't reach %@.";+"刚刚开会时用过" = "used in a meeting just now";+"%lld 分钟前开会时用过" = "used in a meeting %lld min ago";+"%lld 小时前开会时用过" = "used in a meeting %lld h ago";+"%lld 天前开会时用过" = "used in a meeting %lld days ago";+"文字 %@ 秒" = "text %@ s";+"听 %@ 秒" = "hearing %@ s";diff --git a/linux/strings/ja.lproj/Linux.strings b/linux/strings/ja.lproj/Linux.stringsindex ba63ddb..d4a8617 100644--- a/linux/strings/ja.lproj/Linux.strings+++ b/linux/strings/ja.lproj/Linux.strings@@ -5,11 +5,9 @@"句" = "件";"重命名" = "名前を変更";"保存失败" = "保存できませんでした";-"Ling key" = "Ling キー";"只存在这台电脑上(只有你的账户能读),只发给 Ling(ant-ling.com)" = "このコンピュータにのみ保存され(あなたのアカウントだけが読めます)、Ling(ant-ling.com)にのみ送信されます";"界面语言" = "表示言語";"关于" = "情報";-"可以用" = "使用できます";"需要 Ling key 才能听" = "聞き取りには Ling キーが必要です";"Ling key 无效" = "Ling キーが無効です";"Ling 太忙,稍后再试" = "Ling が混み合っています。まもなく再試行します";@@ -49,8 +47,6 @@"正在听时" = "聞き取り中";"悬浮窗" = "フローティングウィンドウ";"登录后在顶栏待命" = "ログイン後、トップバーに常駐";-"翻译与纪要模型" = "翻訳・議事メモモデル";-"Ming(云端)" = "Ming(クラウド)";"打开记录文件夹" = "記録フォルダを開く";"打开会议记录" = "会議の記録を開く";"没能开始听" = "聞き取りを開始できませんでした";@@ -154,8 +150,6 @@"例如 qwen3-omni" = "例:qwen3-omni";"听的模型" = "聞き取りモデル";"要能输入音频:听对方和“我说”都用它" = "音声入力に対応している必要があります。相手の聞き取りと「話す」の両方で使います";-"还不能用" = "まだ使えません";-"这个模型听不了声音,换一个支持音频输入的" = "このモデルは音声を聞き取れません。音声入力に対応したモデルに変えてください";"Ming 一次识别并翻译" = "Ming が一度で認識と翻訳を行います";"比 Ling 晚 1–2 秒出字" = "Ling より文字が 1〜2 秒遅れて出ます";"用不了" = "使えません";@@ -169,3 +163,19 @@"%@ 的 key 无效" = "%@ の key が無効です";"%@ 太忙,稍后再试" = "%@ が混み合っています。しばらくしてからもう一度お試しください";"仅保存在本机当前账户下,仅发送至 %@(%@)" = "このコンピュータのこのアカウントにのみ保存され、%1$@(%2$@)にのみ送信されます";+/* AI 服务检查 (aicheck.py): the steps, 开始听 when a check failed. */+"%@ 听不了声音。" = "%@ は音声を聞き取れません。";+"%@ 现在听不了声音" = "%@ は今、音声を聞き取れません";+"%@ 只收文字。换成推荐的模型就能开始听。" = "%@ はテキストしか受け付けません。おすすめのモデルに切り替えると聞き取りを始められます。";+"换成推荐的并开始" = "おすすめに切り替えて開始";+"重新检查并开始" = "再確認して開始";+"去修" = "直す";+"上次同传没出声" = "前回の通訳では音が出ませんでした";+"仅保存在本机当前账户下,仅发送至 Ling(ant-ling.com)" = "このコンピュータのこのアカウントにのみ保存され、Ling(ant-ling.com)にのみ送信されます";+"这台电脑访问不到 %@。" = "このコンピュータから %@ にアクセスできません。";+"刚刚开会时用过" = "さっき会議で使用";+"%lld 分钟前开会时用过" = "%lld 分前に会議で使用";+"%lld 小时前开会时用过" = "%lld 時間前に会議で使用";+"%lld 天前开会时用过" = "%lld 日前に会議で使用";+"文字 %@ 秒" = "テキスト %@ 秒";+"听 %@ 秒" = "聞き取り %@ 秒";diff --git a/linux/strings/ko.lproj/Linux.strings b/linux/strings/ko.lproj/Linux.stringsindex 5fb856f..3743105 100644--- a/linux/strings/ko.lproj/Linux.strings+++ b/linux/strings/ko.lproj/Linux.strings@@ -5,11 +5,9 @@"句" = "줄";"重命名" = "이름 바꾸기";"保存失败" = "저장하지 못했습니다";-"Ling key" = "Ling 키";"只存在这台电脑上(只有你的账户能读),只发给 Ling(ant-ling.com)" = "이 컴퓨터에만 저장되며(내 계정만 읽을 수 있음) Ling(ant-ling.com)에만 전송됩니다";"界面语言" = "앱 언어";"关于" = "정보";-"可以用" = "사용 가능";"需要 Ling key 才能听" = "듣기에는 Ling 키가 필요합니다";"Ling key 无效" = "Ling 키가 유효하지 않습니다";"Ling 太忙,稍后再试" = "Ling이 바쁩니다. 잠시 후 다시 시도합니다";@@ -49,8 +47,6 @@"正在听时" = "듣는 중일 때";"悬浮窗" = "플로팅 창";"登录后在顶栏待命" = "로그인 후 상단 바에서 대기";-"翻译与纪要模型" = "번역 및 회의록 모델";-"Ming(云端)" = "Ming (클라우드)";"打开记录文件夹" = "기록 폴더 열기";"打开会议记录" = "회의 기록 열기";"没能开始听" = "듣기를 시작하지 못했습니다";@@ -154,8 +150,6 @@"例如 qwen3-omni" = "예: qwen3-omni";"听的模型" = "듣기 모델";"要能输入音频:听对方和“我说”都用它" = "오디오 입력을 지원해야 합니다. 상대방 듣기와 ‘말하기’에 모두 쓰입니다";-"还不能用" = "아직 안 됨";-"这个模型听不了声音,换一个支持音频输入的" = "이 모델은 오디오를 들을 수 없습니다. 오디오 입력을 지원하는 모델로 바꾸세요";"Ming 一次识别并翻译" = "Ming이 한 번에 인식하고 번역합니다";"比 Ling 晚 1–2 秒出字" = "Ling보다 글자가 1~2초 늦게 나옵니다";"用不了" = "사용 불가";@@ -169,3 +163,19 @@"%@ 的 key 无效" = "%@ key가 유효하지 않습니다";"%@ 太忙,稍后再试" = "%@이(가) 바쁩니다. 잠시 후 다시 시도하세요";"仅保存在本机当前账户下,仅发送至 %@(%@)" = "이 컴퓨터의 현재 계정에만 저장되고 %1$@(%2$@)에만 전송됩니다";+/* AI 服务检查 (aicheck.py): the steps, 开始听 when a check failed. */+"%@ 听不了声音。" = "%@ 모델은 소리를 들을 수 없습니다.";+"%@ 现在听不了声音" = "%@ 모델은 지금 소리를 들을 수 없습니다";+"%@ 只收文字。换成推荐的模型就能开始听。" = "%@ 모델은 텍스트만 받습니다. 추천 모델로 바꾸면 듣기를 시작할 수 있습니다.";+"换成推荐的并开始" = "추천 모델로 바꾸고 시작";+"重新检查并开始" = "다시 확인하고 시작";+"去修" = "고치기";+"上次同传没出声" = "지난번 통역 때 소리가 나지 않았습니다";+"仅保存在本机当前账户下,仅发送至 Ling(ant-ling.com)" = "이 컴퓨터의 현재 계정에만 저장되고 Ling(ant-ling.com)에만 전송됩니다";+"这台电脑访问不到 %@。" = "이 컴퓨터에서 %@에 접속할 수 없습니다.";+"刚刚开会时用过" = "방금 회의에서 사용함";+"%lld 分钟前开会时用过" = "%lld분 전 회의에서 사용함";+"%lld 小时前开会时用过" = "%lld시간 전 회의에서 사용함";+"%lld 天前开会时用过" = "%lld일 전 회의에서 사용함";+"文字 %@ 秒" = "텍스트 %@초";+"听 %@ 秒" = "듣기 %@초";diff --git a/linux/tests/test_aicheck.py b/linux/tests/test_aicheck.pynew file mode 100644index 0000000..343b8c5--- /dev/null+++ b/linux/tests/test_aicheck.py@@ -0,0 +1,358 @@+"""AI 服务检查 (AICheckTests.swift, plus the ports' 听对方 step): which step a failure stops at and+why, what passes, key prefixes, OpenRouter's balance, the models a service lists, the proxy hint,+and whole checks against a fake service, including results from real requests."""+from __future__ import annotations++import os+import sys+import unittest++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+sys.path.insert(0, os.path.dirname(HERE))++from test_providers import Base, Fake, reply # noqa: E402++from cicada.core import aicheck, jsonfmt, proxy # noqa: E402+from cicada.core.aicheck import AICheck, State # noqa: E402+from cicada.core.ling import INVALID, OK, TRANSLATE, UNREACHABLE, LingError, Response, silence_wav # noqa: E402++MODELS = {"data": [+ {"id": "inclusionai/ling-3.0-flash", "input_modalities": ["text"], "output_modalities": ["text"]},+ {"id": "qwen/qwen3.8-flash", "input_modalities": ["text"], "output_modalities": ["text"]},+ {"id": "qwen/qwen3.8-omni-flash", "input_modalities": ["text", "audio"], "output_modalities": ["text"]},+ {"id": "x/text-only", "input_modalities": ["text"], "output_modalities": ["text"]}]}+++def kinds(r: AICheck) -> list:+ return [r[s].kind for s in aicheck.STEPS]+++class Rules(unittest.TestCase):+ def test_classify(self):+ c = aicheck.classify+ self.assertEqual(("reach", "unreachable", None), c(LingError(LingError.NETWORK), "text"))+ self.assertEqual(("reach", "unreachable", None), c(LingError(LingError.TIMEOUT), "hear", True))+ self.assertEqual(("key", "invalidKey", None), c(LingError(LingError.INVALID_KEY), "text"))+ self.assertEqual(("text", "busy", None), c(LingError(LingError.RATE_LIMITED), "text"))+ self.assertEqual(("hear", "busy", None), c(LingError(LingError.RATE_LIMITED), "hear", True))+ self.assertEqual(("key", "noCredit", 402), c(LingError(LingError.HTTP, 402), "text"))+ self.assertEqual(("text", "noModel", 404), c(LingError(LingError.HTTP, 404), "text"))+ self.assertEqual(("key", "serverError", 400), c(LingError(LingError.HTTP, 400), "key"))+ self.assertEqual(("text", "serverError", 503), c(LingError(LingError.HTTP, 503), "text"))+ # The hear model: what says "this model takes no audio".+ for code in (400, 404, 415, 422):+ self.assertEqual(("hear", "deaf", code), c(LingError(LingError.HTTP, code), "hear", True))+ self.assertEqual(("hear", "serverError", 500), c(LingError(LingError.HTTP, 500), "hear", True))+ for kind in (LingError.NO_KEY, LingError.HIJACKED, LingError.PARSE):+ self.assertIsNone(c(LingError(kind), "text"))++ def test_a_failed_step_skips_the_rest(self):+ r = AICheck()+ r.fail("key", "invalidKey")+ self.assertEqual(["ok", "fail", "skipped", "skipped"], kinds(r))+ self.assertEqual(("key", "invalidKey", None), r.failure)+ # Nothing sent (a management key): the steps before it are not claimed.+ r = AICheck()+ r.fail("key", "mgmtKey", reached=False)+ self.assertEqual(["untested", "fail", "skipped", "skipped"], kinds(r))++ def test_passing_clears_a_failure_and_reopens_skipped_steps(self):+ r = AICheck()+ r.fail("reach", "unreachable")+ r.proxy = ("none",)+ r.pass_up_to("text", 1.5)+ self.assertEqual(["ok", "ok", "ok", "untested"], kinds(r))+ self.assertEqual(1.5, r["text"].seconds)+ self.assertIsNone(r.proxy)+ self.assertIsNone(r.failure)++ def test_busy_passes_and_needs_nobody(self):+ r = AICheck()+ r.pass_up_to("key", None)+ r["text"] = State(aicheck.BUSY_STATE)+ r.at = 1.0+ self.assertTrue(r.passed)+ self.assertTrue(r.busy)+ self.assertFalse(r.needs_user)+ self.assertIn("很忙", r.message("ZenMux", "zenmux.ai", "m", "h"))+ r.fail("text", "serverError", 503)+ self.assertFalse(r.needs_user)+ r.fail("hear", "deaf", 400)+ self.assertTrue(r.needs_user)+ self.assertFalse(r.down) # notes and translation still work++ def test_not_passed_until_a_result(self):+ r = AICheck()+ self.assertFalse(r.passed)+ r["reach"] = State(aicheck.RUNNING)+ r.at = 1.0+ self.assertFalse(r.passed)++ def test_key_prefixes(self):+ self.assertEqual(("openrouter", False), aicheck.owner("sk-or-v1-abc"))+ self.assertEqual(("zenmux", False), aicheck.owner(" sk-payg-abc\n"))+ self.assertEqual(("zenmux", True), aicheck.owner("sk-mgmt-abc"))+ self.assertIsNone(aicheck.owner("sk-abc"))++ def test_balance_is_the_smaller(self):+ b = aicheck.balance+ self.assertEqual(1.5, b({"data": {"limit_remaining": 1.5}}, {"data": {"total_credits": 10, "total_usage": 2}}))+ self.assertEqual(8.0, b({"data": {"limit_remaining": None}}, {"data": {"total_credits": 10, "total_usage": 2}}))+ self.assertEqual(0.3, b({"data": {"limit_remaining": 0.3}}, None))+ self.assertIsNone(b(None, None))+ r = AICheck()+ r.balance = 0.4+ self.assertTrue(r.low_balance)+ self.assertTrue(r.needs_user)+ self.assertEqual("OpenRouter 余额快用完了(还剩 $0.40)", r.balance_line("OpenRouter"))+ r.balance = 0.5+ self.assertIsNone(r.balance_line("OpenRouter"))++ def test_listed_models(self):+ every, hear = aicheck.listed(jsonfmt.write(MODELS))+ self.assertIn("x/text-only", every)+ self.assertEqual({"qwen/qwen3.8-omni-flash"}, hear)+ # OpenRouter keeps them under `architecture`.+ _, hear = aicheck.listed({"data": [{"id": "a", "architecture": {"input_modalities": ["audio", "text"]}}]})+ self.assertEqual({"a"}, hear)+ # Nothing about modalities: can't tell who hears.+ every, hear = aicheck.listed({"data": [{"id": "a"}]})+ self.assertEqual({"a"}, every)+ self.assertIsNone(hear)+ self.assertEqual((None, None), aicheck.listed("not json"))++ def test_messages(self):+ r = AICheck()+ r.fail("reach", "unreachable")+ self.assertEqual("这台电脑访问不到 zenmux.ai。", r.message("ZenMux", "zenmux.ai", "m", "h"))+ r = AICheck()+ r.fail("text", "noModel", 404)+ self.assertEqual("ZenMux 上找不到 x/y 这个模型。", r.message("ZenMux", "zenmux.ai", "x/y", "h"))+ r = AICheck()+ r.pass_up_to("text", 1.0)+ r.fail("hear", "deaf", 400)+ self.assertEqual("x/text-only 听不了声音。", r.message("ZenMux", "zenmux.ai", "m", "x/text-only"))+ r = AICheck()+ r.fail("text", "serverError", 502)+ self.assertEqual("ZenMux 暂时出错(HTTP 502),稍后再试。", r.message("ZenMux", "zenmux.ai", "m", "h"))++ def test_summary(self):+ r = AICheck()+ r.pass_up_to("text", 1.25)+ r.fail("hear", "deaf", 400)+ self.assertEqual("reach=ok key=ok text=ok(1.2s) hear=fail(deaf 400)", r.summary())++ def test_every_simulated_reason(self):+ for reason in aicheck.REASONS:+ r = aicheck.simulated(reason)+ if reason == "busy":+ self.assertTrue(r.busy)+ else:+ self.assertEqual(reason, r.reason)+ self.assertIsNone(aicheck.simulated("lowBalance").failure)+++class ProxyHint(unittest.TestCase):+ def test_three_cases(self):+ nothing = lambda: "" # noqa: E731+ self.assertEqual(("system",), proxy.hint({"https_proxy": "http://10.0.2.2:7890"}, nothing, lambda p: False))+ self.assertEqual(("system",), proxy.hint({}, lambda: "'manual'\n", lambda p: False))+ self.assertEqual(("system",), proxy.hint({}, lambda: "'auto'", lambda p: False))+ self.assertEqual(("app", 7897), proxy.hint({}, lambda: "'none'", lambda p: p == 7897))+ self.assertEqual(("none",), proxy.hint({"https_proxy": " "}, nothing, lambda p: False))++ def test_words(self):+ r = AICheck()+ r.fail("reach", "unreachable")+ for hint, words in ((("system",), "开了代理也连不上:换一个节点,或检查代理软件是否放过 zenmux.ai。"),+ (("app", 7890), "代理软件在运行(端口 7890),但没开系统代理。在代理软件里打开“系统代理”。"),+ (("none",), "这台电脑没开代理。在国内通常要开代理才能用 ZenMux。")):+ r.proxy = hint+ self.assertEqual(words, r.proxy_line("ZenMux", "zenmux.ai"))+ r.fail("key", "invalidKey")+ self.assertIsNone(r.proxy_line("ZenMux", "zenmux.ai")) # only after "can't reach"++ def test_help_url(self):+ self.assertEqual("https://cicada.indaloop.app/start/#proxy", aicheck.help_url("zh-Hans"))+ self.assertEqual("https://cicada.indaloop.app/ja/start/#proxy", aicheck.help_url("ja"))+++def service(text=200, hear=200, models=MODELS, json_ok=True, key_info=None, credits=None):+ """A fake service: the text model's status, the hear model's, its `/models`."""+ def respond(url, body):+ if url.endswith("/models"):+ return Response(200, jsonfmt.write(models)) if models is not None else Response(404, "")+ if url.endswith("/key"):+ return Response(200, jsonfmt.write(key_info or {"data": {"limit_remaining": None}}))+ if url.endswith("/credits"):+ return Response(200, jsonfmt.write(credits or {"data": {"total_credits": 5, "total_usage": 1}}))+ status = hear if "input_audio" in body else text+ if status != 200:+ return Response(status, "{}")+ if "json_object" in body and not json_ok:+ return Response(400, "{}")+ return reply("OK")+ return Fake(respond)+++class Checks(Base):+ def setUp(self):+ super().setUp()+ proxy_calls = []+ self.proxy_calls = proxy_calls++ def client(self, fake, provider="zenmux", key="sk-payg-test-000000", **kw):+ ling, s = super().client(fake, provider, key, **kw)+ ling.proxy_hint = lambda: (self.proxy_calls.append(1), ("none",))[1]+ return ling, s++ def test_zenmux_passes_every_step(self):+ ling, _ = self.client(service())+ self.assertEqual(OK, ling.check())+ r = ling.check_result+ self.assertEqual(["ok"] * 4, kinds(r))+ self.assertIsNotNone(r["text"].seconds)+ self.assertIsNotNone(r["hear"].seconds)+ self.assertTrue(r.passed)+ self.assertTrue(ling.hears)++ def test_a_missing_text_model(self):+ ling, _ = self.client(service(text=404), aiModels={"zenmux": "no/such"})+ self.assertEqual(UNREACHABLE, ling.check())+ self.assertEqual(("text", "noModel", 404), ling.check_result.failure)+ self.assertEqual(["ok", "ok", "fail", "skipped"], kinds(ling.check_result))+ self.assertTrue(ling.usable)+ # One the service answers but no longer lists.+ ling, _ = self.client(service(), aiModels={"zenmux": "old/model"})+ ling.check()+ self.assertEqual(("text", "noModel", None), ling.check_result.failure)++ def test_a_deaf_hear_model(self):+ ling, _ = self.client(service(hear=400), aiHearModels={"zenmux": "x/text-only"})+ self.assertEqual(OK, ling.check()) # notes and translation still work+ self.assertEqual(("hear", "deaf", 400), ling.check_result.failure)+ self.assertFalse(ling.hears)+ self.assertFalse(ling.can_hear)+ # It takes the request, but the service doesn't list it as taking audio.+ ling, _ = self.client(service(), aiHearModels={"zenmux": "x/text-only"})+ ling.check()+ self.assertEqual(("hear", "deaf", None), ling.check_result.failure)+ # A service that says nothing about modalities can't make it deaf.+ ling, _ = self.client(service(models={"data": [{"id": "inclusionai/ling-3.0-flash"}]}))+ ling.check()+ self.assertIsNone(ling.check_result.failure)++ def test_an_invalid_key_stops_there(self):+ ling, _ = self.client(service(text=401))+ self.assertEqual(INVALID, ling.check())+ self.assertEqual(["ok", "fail", "skipped", "skipped"], kinds(ling.check_result))+ self.assertEqual("ZenMux 说这个 key 无效,可能没复制全,或已删除。", ling.message())++ def test_no_credit(self):+ ling, _ = self.client(service(text=402))+ ling.check()+ self.assertEqual(("key", "noCredit", 402), ling.check_result.failure)++ def test_a_management_key_sends_nothing(self):+ fake = service()+ ling, _ = self.client(fake, key="sk-mgmt-000000")+ self.assertEqual(INVALID, ling.check())+ self.assertEqual(("key", "mgmtKey", None), ling.check_result.failure)+ self.assertEqual([], fake.sent)++ def test_busy_counts_as_passed(self):+ ling, _ = self.client(service(text=429))+ self.assertEqual(OK, ling.check())+ r = ling.check_result+ self.assertTrue(r.passed)+ self.assertEqual("busy", r["text"].kind)++ def test_unreachable_words_the_proxy(self):+ def down(url, body):+ raise OSError("no route")+ ling, _ = self.client(Fake(down))+ self.assertEqual(UNREACHABLE, ling.check())+ r = ling.check_result+ self.assertEqual(["fail", "skipped", "skipped", "skipped"], kinds(r))+ self.assertEqual(("none",), r.proxy)+ self.assertEqual("这台电脑访问不到 zenmux.ai。", ling.message())++ def test_custom_without_json(self):+ ling, _ = self.client(service(json_ok=False, models=None), "custom", key="sk-x",+ aiCustomBase="https://x.example/v1", aiModels={"custom": "m"}, aiHearModels={"custom": "h"})+ ling.check()+ self.assertEqual(("text", "noJSON", 400), ling.check_result.failure)+ ling, _ = self.client(service(), "custom", key="sk-x", aiCustomBase="http://x.example/v1")+ ling.check()+ self.assertEqual(("reach", "badAddress", None), ling.check_result.failure)++ def test_openrouter_reads_the_balance(self):+ ling, _ = self.client(service(key_info={"data": {"limit_remaining": 0.3}}), "openrouter", key="sk-or-v1-x",+ aiModels={"openrouter": "inclusionai/ling-3.0-flash"}, aiHearModels={"openrouter": "qwen/qwen3.8-omni-flash"})+ ling.check()+ self.assertEqual(0.3, ling.check_result.balance)+ self.assertTrue(ling.check_result.needs_user)++ def test_ling_proves_hearing_in_a_meeting(self):+ ling, _ = self.client(service(), "ling", key="sk-ling")+ ling.check()+ self.assertEqual(["ok", "ok", "ok", "untested"], kinds(ling.check_result))+ self.assertTrue(ling.hears)+ ling.chat("c", "i", TRANSLATE, audio=silence_wav())+ self.assertEqual("ok", ling.check_result["hear"].kind)+ self.assertTrue(ling.check_result.passive)++ def test_real_requests_update_the_steps(self):+ status = {"text": 200}+ ling, _ = self.client(Fake(lambda u, b: Response(status["text"], "{}") if status["text"] != 200 else reply("OK")))+ ling.check()+ self.assertIsNone(ling.check_result.failure)+ status["text"] = 401+ with self.assertRaises(LingError):+ ling.chat("c", "i", TRANSLATE)+ self.assertEqual(("key", "invalidKey", None), ling.check_result.failure)+ self.assertTrue(ling.check_result.passive)+ # A server error in a meeting changes nothing.+ status["text"] = 200+ ling.key_state = OK+ ling.chat("c", "i", TRANSLATE)+ self.assertIsNone(ling.check_result.failure)+ status["text"] = 503+ with self.assertRaises(LingError):+ ling.chat("c", "i", TRANSLATE)+ self.assertIsNone(ling.check_result.failure)+ # The hear model refusing audio in a meeting: deaf, the text model keeps its ok.+ status["text"] = 415+ with self.assertRaises(LingError):+ ling.chat("c", "i", TRANSLATE, audio=silence_wav())+ self.assertEqual(("hear", "deaf", 415), ling.check_result.failure)+ self.assertEqual("ok", ling.check_result["text"].kind)++ def test_network_change_rechecks_only_after_unreachable(self):+ ling, _ = self.client(service())+ ling.check()+ self.assertFalse(ling.network_changed())+ ling.check_result = aicheck.simulated("unreachable")+ self.assertTrue(ling.network_changed())++ def test_a_stale_check_is_dropped(self):+ ling, s = self.client(service())+ seq = ling._check_seq+ r = aicheck.simulated("invalidKey")+ ling.key_changed() # the settings changed while that check ran+ ling._finish_check(r, ling.config(), seq)+ self.assertIsNone(ling.check_result.failure)++ def test_simulated_check(self):+ ling, _ = self.client(service())+ ling.simulate = "deaf"+ ling.check()+ self.assertEqual(("hear", "deaf", 400), ling.check_result.failure)+ ling.simulate = "lowBalance"+ ling.check()+ self.assertTrue(ling.check_result.low_balance)+++if __name__ == "__main__":+ unittest.main()diff --git a/linux/tests/test_providers.py b/linux/tests/test_providers.pyindex a2bfa6e..0b84e37 100644--- a/linux/tests/test_providers.py+++ b/linux/tests/test_providers.py@@ -186,7 +186,8 @@ class Client(Base):def test_check_finds_a_hear_model_that_refuses_audio(self):def respond(url, body):if url.endswith("models"):- return Response(200, jsonfmt.write({"data": [{"id": "a/b", "input_modalities": ["text"], "output_modalities": ["text"]}]}))+ return Response(200, jsonfmt.write({"data": [{"id": "a/b", "input_modalities": ["text"], "output_modalities": ["text"]},+ {"id": "inclusionai/ling-3.0-flash"}]}))return Response(400, "{}") if "input_audio" in body else reply("OK")ling, s = self.client(Fake(respond), aiHearModels={"zenmux": "x/text-only"})self.assertEqual(OK, ling.check())@@ -203,7 +204,7 @@ class Client(Base):self.assertEqual(INVALID, ling.check())ling, _ = self.client(Fake(lambda u, b: Response(404, "")))ling.check()- self.assertEqual(("%@ 拒绝了请求(HTTP %lld),请检查模型名", "ZenMux", 404), ling.problem)+ self.assertEqual(("text", "noModel", 404), ling.check_result.failure)ling, _ = self.client(Fake(lambda u, b: Response(200, "")), "openrouter", key=None)self.assertEqual(NONE, ling.key_state)