Skip to content

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

feat(linux): your own AI server can be set per job, on a LAN or Tailscale address over http with no key, and its check says when the model thinks before answering

wquguru6fbdcd088821
diff --git a/linux/cicada/app/debug.py b/linux/cicada/app/debug.py
index 35a8658..c32368b 100644
--- a/linux/cicada/app/debug.py
+++ b/linux/cicada/app/debug.py
@@ -4,7 +4,8 @@ per connection, one JSON line back. Never in release builds.
state | start | stop | feed <wav> | sample | view notes|subtitles | show records|notes|settings|onboarding
target <code> | key-reload | windows | select <record id> | append <record id> <n> (a growing meeting)
- provider ling|openrouter|zenmux|custom | ai-model hear|text|voice <id> (设置 › AI 服务; "" back to the recommended)
+ provider ling|openrouter|zenmux|custom | ai-model hear|text|voice <id> (设置 › AI 服务; "" back to the recommended) |
+ ai-base text|voice|hear <url> (其他(兼容 OpenAI)'s addresses; "" for voice/hear: the text one)
speak-enable on|off | speak on|off (同声传译) | quit
calls <program=name,…>|none|real (meeting apps in a call) | endtimes <silence> <countdown> <grace>|off | endkeep
notes-tab notes|transcript | notes-search <text> | notes-wide on|off | onboarding-step <n> | settings-scroll <0-1>
@@ -243,6 +244,16 @@ def command(app, line: str) -> dict:
if cmd == "provider":
app.set_ai_provider(arg)
return {"ok": True, "ai": _ai(app)}
+ if cmd == "ai-base":
+ # A custom service's addresses: text, voice or hear ("" for voice and hear: the text one).
+ kind, _, url = arg.partition(" ")
+ field = {"text": "aiCustomBase", "voice": "aiCustomVoiceBase", "hear": "aiCustomHearBase"}.get(kind)
+ if field is None:
+ return {"ok": False, "error": "ai-base text|voice|hear <url>"}
+ setattr(app.settings, field, url.strip())
+ app.settings.save()
+ app.ai_changed()
+ return {"ok": True, "ai": _ai(app)}
if cmd == "ai-model":
kind, _, model = arg.partition(" ")
app.set_ai_model(kind, model.strip())
@@ -368,7 +379,7 @@ def command(app, line: str) -> dict:
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.ling
- return {"provider": c.provider.id, "base": c.base, "text": c.text_model, "hear": c.hear_model, "voice": c.voice_model,
+ return {"provider": c.provider.id, "base": c.base, "hearBase": c.hear_url, "text": c.text_model, "hear": c.hear_model, "voice": c.voice_model,
"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,
diff --git a/linux/cicada/app/settings_window.py b/linux/cicada/app/settings_window.py
index f6f85eb..054c85e 100644
--- a/linux/cicada/app/settings_window.py
+++ b/linux/cicada/app/settings_window.py
@@ -7,6 +7,7 @@ import os
import subprocess
import threading
import time
+import urllib.parse
from gi.repository import Gdk, GLib, Gtk
@@ -523,14 +524,8 @@ class SettingsWindow(Gtk.Window):
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", ""))
- self.custom_hear = self._field(L("例如 qwen3-omni"), s.aiHearModels.get("custom", ""))
- self.custom_rows = ui.boxed([ui.prow(L("地址"), self.custom_base), ui.prow(L("文字模型"), self.custom_text, L("纪要和整句翻译")),
- ui.prow(L("听的模型"), self.custom_hear, L("要能输入音频:听对方和“我说”都用它"))])
- self.custom_rows.set_no_show_all(True)
- self.custom_rows.get_child().show_all()
+ # A custom service: one row per use instead of the key card (_custom_page).
+ self.custom_page = self._custom_page()
self.get_key = Gtk.Button()
self.get_key_label = ui.text("", 13, "ink", wrap=False)
self.get_key.add(ui.pad(ui.hbox(8, self.get_key_label), 10, 14))
@@ -555,11 +550,15 @@ class SettingsWindow(Gtk.Window):
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,
+ page.pack_start(ui.vbox(6, title, self.custom_page, 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.
+ # What works with it (a custom service says so in its own rows).
self.uses = ui.vbox(0)
- page.pack_start(self._group(L("现在能用的"), self.uses), False, False, 0)
+ self.uses_group = self._group(L("现在能用的"), self.uses)
+ self.uses_group.set_no_show_all(True)
+ for w in self.uses_group.get_children(): # show_all() stops at a no_show_all widget
+ w.show_all()
+ page.pack_start(self.uses_group, False, False, 0)
# Its models, folded away: the recommended ones are already chosen.
self.models = ui.vbox(0)
self.models.set_no_show_all(True)
@@ -570,8 +569,272 @@ class SettingsWindow(Gtk.Window):
fold.set_halign(Gtk.Align.START)
fold.connect("clicked", lambda *_: self._toggle_models())
self.footnote = ui.text("", 11, "tertiary", width_chars=60)
+ self.fold = fold
+ fold.set_no_show_all(True)
+ fold.get_child().show_all()
page.pack_start(ui.vbox(6, fold, self.models, ui.pad(self.footnote, 0, 2, 0, 2)), False, False, 0)
+ # 其他(兼容 OpenAI): AISettings.swift › customPage, on a port
+
+ def _custom_page(self) -> Gtk.Widget:
+ """One row per use, each opening to its fields and how it's doing, each at its own address if
+ need be (a text model, a speech model and an audio model often run as separate servers):
+ 翻译和纪要, 同传声音 and 听对方 (the hear model, which also hears what I say). The fields are
+ built once; show_key_state only rewrites the headers and the status under them."""
+ s = self.app.settings
+ self.custom_open: set = set()
+ self.custom_heads: dict = {}
+ self.custom_bodies: dict = {}
+ # 翻译和纪要
+ self.custom_base = self._field("http://192.168.1.20:8000/v1", s.aiCustomBase)
+ self.custom_base_bad = ui.text(L("地址要用 https;这台电脑和局域网里的服务可以用 http。"), 11, "stepwhy", width_chars=46)
+ self.custom_base_bad.set_no_show_all(True)
+ self.custom_base.connect("changed", lambda *_: self._custom_base_typed())
+ # The models the service lists, once fetched; a name can always be typed.
+ self.custom_text = Gtk.ComboBoxText.new_with_entry()
+ self.custom_text.get_child().set_text(s.aiModels.get("custom", ""))
+ self.custom_text.get_child().set_placeholder_text(L("例如 qwen3:14b"))
+ self.custom_text.get_child().set_width_chars(26)
+ self.custom_text.get_child().connect("activate", lambda *_: self.save_key())
+ self.custom_text.connect("changed", self._custom_model_picked)
+ self._custom_listed = None
+ self.custom_key_line = ui.text("", 13, "ink mono", wrap=False)
+ self.custom_key = Gtk.Entry()
+ self.custom_key.set_visibility(False)
+ self.custom_key.set_width_chars(26)
+ self.custom_key.connect("activate", lambda *_: self.save_key())
+ self.custom_change = ui.button(L("更换"), self._custom_change_key, "outline")
+ self.custom_remove = ui.button(L("移除 key"), self.remove_key, "dangertext")
+ self.custom_save = ui.button(L("保存并检查"), self.save_key, "darkbtn")
+ key_row = ui.hbox(8, self._label("key"), self.custom_key_line, self.custom_key)
+ for b in (self.custom_change, self.custom_remove, self.custom_save):
+ b.set_valign(Gtk.Align.CENTER)
+ key_row.pack_end(b, False, False, 0)
+ self.custom_key_hint = ui.hbox(8)
+ self.custom_key_hint.set_no_show_all(True)
+ self.custom_text_status = ui.vbox(6)
+ self.custom_editing = False
+ text_body = ui.vbox(8, ui.hbox(8, self._label(L("地址")), self.custom_base), self.custom_base_bad,
+ ui.hbox(8, self._label(L("模型")), self.custom_text), key_row, self.custom_key_hint,
+ self.custom_text_status)
+ # 同传声音: Linux has no voice of its own to fall back on.
+ self.custom_voice_model = self._field(L("例如 qwen3-tts"), s.aiVoiceModels.get("custom", ""))
+ self.custom_voice = self._field(L("例如 vivian"), s.aiCustomVoice)
+ self.custom_voice_base = self._field(L("跟上面一样"), s.aiCustomVoiceBase)
+ voice_body = ui.vbox(8, ui.text(L("需支持 /audio/speech;不填则同声传译用不了"), 11, "tertiary", width_chars=50),
+ ui.hbox(8, self._label(L("模型")), self.custom_voice_model),
+ ui.hbox(8, self._label(L("声音")), self.custom_voice),
+ ui.hbox(8, self._label(L("地址")), self.custom_voice_base))
+ # 听对方: the hear model, at the text model's address unless it has its own.
+ self.custom_hear = self._field(L("例如 qwen3-omni"), s.aiHearModels.get("custom", ""))
+ self.custom_hear_base = self._field(L("跟上面一样"), s.aiCustomHearBase)
+ self.custom_hear_status = ui.vbox(4)
+ hear_body = ui.vbox(8, ui.text(L("要能输入音频:听对方和“我说”都用它"), 11, "tertiary", width_chars=50),
+ ui.hbox(8, self._label(L("模型")), self.custom_hear),
+ ui.hbox(8, self._label(L("地址")), self.custom_hear_base), self.custom_hear_status)
+ rows = []
+ for sid, title, body in (("text", L("翻译和纪要"), text_body), ("voice", L("同传声音"), voice_body),
+ ("hear", L("听对方"), hear_body)):
+ rows.append(ui.vbox(0, self._custom_head(sid, title), self._custom_body(sid, body)))
+ hint = ui.text(L("每样可以接不同的机器;这台电脑和局域网里的服务可以用 http。"), 12, "tertiary", width_chars=60)
+ page = ui.vbox(6, ui.pad(hint, 0, 2, 0, 2), ui.boxed(rows))
+ page.set_no_show_all(True)
+ for w in page.get_children():
+ w.show_all()
+ self.custom_base_bad.set_visible(False)
+ self.custom_key_hint.set_visible(False)
+ for body in self.custom_bodies.values():
+ body.set_visible(False)
+ return page
+
+ @staticmethod
+ def _label(title: str) -> Gtk.Widget:
+ l = ui.text(title, 12, "secondary", wrap=False, ellipsize=False)
+ l.set_size_request(34, -1)
+ l.set_xalign(0)
+ return l
+
+ def _custom_head(self, sid: str, title: str) -> Gtk.Widget:
+ """A row that opens to its fields: a state dot, the use, what it runs on, and how it's doing."""
+ dot = Gtk.Box()
+ dot.set_valign(Gtk.Align.CENTER)
+ ui.classes(dot, "statedot")
+ detail = ui.text("", 11, "tertiary", wrap=False)
+ trailing = ui.text("", 12, "tertiary", wrap=False, ellipsize=False)
+ chevron = ui.icon("pan-end-symbolic", 12)
+ left = ui.vbox(2, ui.text(title, 13, "ink", wrap=False), detail)
+ row = ui.hbox(10, dot, left)
+ left.set_hexpand(True)
+ row.pack_end(chevron, False, False, 0)
+ row.pack_end(trailing, False, False, 0)
+ b = Gtk.Button()
+ b.add(ui.pad(row, 10, 14))
+ ui.classes(b, "linkrow")
+ b.connect("clicked", lambda *_: self._custom_toggle(sid))
+ self.custom_heads[sid] = (dot, detail, trailing, chevron)
+ return b
+
+ def _custom_body(self, sid: str, body: Gtk.Widget) -> Gtk.Widget:
+ box = ui.pad(body, 0, 16, 14, 32)
+ self.custom_bodies[sid] = box
+ return box
+
+ def _custom_toggle(self, sid: str, on: bool | None = None) -> None:
+ on = sid not in self.custom_open if on is None else on
+ if on:
+ self.custom_open.add(sid)
+ else:
+ self.custom_open.discard(sid)
+ self.custom_bodies[sid].set_visible(on)
+ self.custom_heads[sid][3].set_from_icon_name("pan-down-symbolic" if on else "pan-end-symbolic", Gtk.IconSize.MENU)
+
+ def _custom_base_typed(self) -> None:
+ from ..core import providers
+ typed = self.custom_base.get_text().strip()
+ self.custom_base_bad.set_visible(bool(typed) and providers.custom_base(typed) is None)
+ self.custom_key.set_placeholder_text(L("本机和局域网服务可不填") if typed and providers.is_nearby(typed) else "sk-…")
+
+ def _custom_model_picked(self, combo) -> None:
+ """A model picked from the service's list saves and checks it (typing waits for Enter)."""
+ mid = combo.get_active_id()
+ if mid is not None and mid != self.app.settings.aiModels.get("custom", ""):
+ combo.get_child().set_text(mid)
+ self.save_key()
+
+ def _custom_change_key(self) -> None:
+ self.custom_editing = True
+ self.custom_key.set_text("")
+ self._show_custom_key()
+ self.custom_key.grab_focus()
+
+ def _show_custom_key(self) -> None:
+ k = self.app.ling.current_key()
+ editing = not k or self.custom_editing
+ self.custom_key_line.set_visible(not editing)
+ ui.retext(self.custom_key_line, AIKey.masked(k) if k else "")
+ self.custom_key.set_visible(editing)
+ self.custom_change.set_visible(not editing)
+ self.custom_remove.set_visible(bool(k) and not editing)
+ self.custom_save.set_visible(True)
+
+ def _show_custom(self) -> None:
+ """The custom rows' headers and status, from the settings and the last check."""
+ from ..core import aicheck, providers
+ from . import aicheck_view
+ app = self.app
+ ling = app.ling
+ c = ling.config()
+ s = app.settings
+ r = ling.check_result
+ f = r.failure
+ have = ling.has_key
+ self._custom_base_typed()
+ self._show_custom_key()
+ sens = not r.running
+ self.custom_save.set_sensitive(sens)
+ self.custom_save.set_label(L("正在检查…") if r.running else L("保存并检查"))
+ # The model menu: what the service lists, once fetched.
+ listed = tuple(ling.text_catalog)
+ if listed != self._custom_listed:
+ self._custom_listed = listed
+ typed = self.custom_text.get_child().get_text()
+ self.custom_text.remove_all()
+ for mid in listed:
+ self.custom_text.append(mid, mid)
+ self.custom_text.get_child().set_text(typed)
+ self.custom_text.set_button_sensitivity(Gtk.SensitivityType.ON if listed else Gtk.SensitivityType.OFF)
+
+ def head(sid, state, detail, trailing, tone=""):
+ dot, d, t, _ = self.custom_heads[sid]
+ for cls in ("ok", "warn", "error", "live"):
+ dot.get_style_context().remove_class(cls)
+ if state:
+ dot.get_style_context().add_class(state)
+ ui.retext(d, detail)
+ ui.retext(t, trailing or "")
+ for cls in ("warn", "stepwhy", "tertiary"):
+ t.get_style_context().remove_class(cls)
+ t.get_style_context().add_class(tone or "tertiary")
+
+ # 翻译和纪要
+ host = urllib.parse.urlsplit(c.base or "").hostname or ""
+ text_failed = f is not None and f[0] != "hear"
+ if not have:
+ state = ""
+ elif r.running:
+ state = "live"
+ elif text_failed:
+ state = "error"
+ elif r.slow or r.busy:
+ state = "warn"
+ else:
+ state = "ok" if r.passed or (f is not None and f[0] == "hear") else ""
+ if r.running:
+ trailing = L("正在检查…")
+ elif text_failed and have:
+ trailing = {"reach": L("暂时连不上"), "key": L("这个 key 用不了")}.get(f[0], L("模型用不了"))
+ elif r.translate is not None:
+ trailing = LF("翻一句 %@ 秒", "%.1f" % r.translate.seconds)
+ else:
+ trailing = None
+ head("text", state, "%s · %s" % (host, c.text_model) if host and c.text_model else L("填上地址和模型"), trailing,
+ "warn" if r.slow else "stepwhy" if text_failed and have else "")
+ ui.clear(self.custom_text_status)
+ slow = r.slow_line()
+ if slow:
+ self.custom_text_status.pack_start(ui.text(slow, 12, "warn", width_chars=46), False, False, 0)
+ if have and aicheck_view.show_steps(r) and (text_failed or r.running or r.busy):
+ card = ui.panel(ui.pad(aicheck_view.steps_widget(app, self._custom_change_key, recheck_in_step=False,
+ width_chars=40), 2, 12), "boxed")
+ self.custom_text_status.pack_start(card, False, False, 0)
+ elif r.passed or (f is not None and f[0] == "hear"):
+ facts = [L("能写纪要")]
+ if r.translate is not None:
+ facts.append(L("会先思考") if r.translate.thinks else L("不思考"))
+ self.custom_text_status.pack_start(ui.text(" · ".join(facts), 11, "tertiary", wrap=False), False, False, 0)
+ elif r.reason == aicheck.NO_JSON:
+ self.custom_text_status.pack_start(ui.text(L("纪要写不了"), 11, "tertiary", wrap=False), False, False, 0)
+ self.custom_text_status.show_all()
+ # 同传声音
+ voice = (s.aiVoiceModels.get("custom") or "").strip()
+ vhost = urllib.parse.urlsplit(c.voice_base or "").hostname or host
+ last = ling.last_voice
+ head("voice", "" if not voice or last is None else "ok" if last[0] else "error",
+ " · ".join(x for x in (vhost, voice, s.aiCustomVoice.strip()) if x) if voice else L("没填,同声传译用不了"),
+ L("用不了") if not voice else (L("上次正常") if last[0] else L("上次没出声")) if last else None,
+ "stepwhy" if last is not None and not last[0] and voice else "")
+ # 听对方
+ hear_st = r["hear"]
+ hear_failed = f is not None and f[0] == "hear"
+ hhost = ling.hear_host
+ if not c.hear_model:
+ hstate, htrail = "", None
+ elif hear_failed:
+ hstate, htrail = "error", L("暂时连不上") if f[1] == aicheck.UNREACHABLE else L("模型用不了")
+ elif hear_st.kind == aicheck.OK:
+ hstate = "ok"
+ htrail = LF("%@ 秒", "%.1f" % hear_st.seconds) if hear_st.seconds is not None else None
+ elif hear_st.kind == aicheck.BUSY_STATE:
+ hstate, htrail = "warn", LF("%@ 现在很忙", ling.service_name)
+ else:
+ hstate, htrail = ("live", L("正在检查…")) if r.running else ("", None)
+ head("hear", hstate if have else "", "%s · %s" % (hhost, c.hear_model) if c.hear_model and hhost
+ else c.hear_model or L("填上听的模型"), htrail, "stepwhy" if hear_failed else "")
+ ui.clear(self.custom_hear_status)
+ if hear_failed and have:
+ why = ling.message()
+ if why:
+ self.custom_hear_status.pack_start(ui.text(why, 12, "stepwhy", width_chars=46), False, False, 0)
+ elif s.aiCustomHearBase.strip() and providers.custom_base(s.aiCustomHearBase) is None:
+ self.custom_hear_status.pack_start(ui.text(L("地址要用 https;这台电脑和局域网里的服务可以用 http。"), 12, "stepwhy",
+ width_chars=46), False, False, 0)
+ self.custom_hear_status.show_all()
+ # A service that isn't set up yet, or doesn't work, opens where it needs filling in.
+ if not getattr(self, "_custom_opened", False):
+ self._custom_opened = True
+ if not r.passed or r.slow:
+ self._custom_toggle("text", True)
+
def _field(self, placeholder: str, value: str) -> Gtk.Entry:
e = Gtk.Entry()
e.set_placeholder_text(placeholder)
@@ -682,11 +945,7 @@ class SettingsWindow(Gtk.Window):
return [ui.prow(L("文字模型"), menu, L("3.1 更准;3.0 更快、更省")),
ui.prow(L("听的模型"), ui.text(c.hear_model, 12, "tertiary", wrap=False), L("Ming 一次识别并翻译"))]
if p.id == "custom":
- self.custom_voice_model = self._field(L("例如 kokoro"), app.settings.aiVoiceModels.get("custom", ""))
- self.custom_voice = self._field(L("例如 af_heart"), app.settings.aiCustomVoice)
- self.custom_voice_base = self._field(L("跟上面一样"), app.settings.aiCustomVoiceBase)
- return [ui.prow(L("声音模型"), self.custom_voice_model, L("需支持 /audio/speech;不填则同声传译用不了")),
- ui.prow(L("声音"), self.custom_voice), ui.prow(L("地址"), self.custom_voice_base)]
+ return [] # its models are in its own rows (_custom_page)
rows = [ui.prow(L("听的模型"), self._model_menu("hear", c.hear_model, p.hear_models, app.ling.hear_catalog),
L("听对方和“我说”都用它")),
ui.prow(L("文字模型"), self._model_menu("text", c.text_model, p.text_models, app.ling.text_catalog), L("纪要和整句翻译"))]
@@ -756,15 +1015,29 @@ class SettingsWindow(Gtk.Window):
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")
+ custom = p.id == "custom"
+ self.custom_page.set_visible(custom)
+ self.key_group.set_visible(not custom)
+ self.uses_group.set_visible(not custom)
+ self.fold.set_visible(not custom)
+ if custom:
+ self.steps_card.set_visible(False) # under 翻译和纪要 instead
+ self.models.set_visible(False)
+ self._show_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))
host = (c.base or "").split("//")[-1].split("/")[0] or L("你填的地址")
ui.retext(self.lock_line, L("仅保存在本机当前账户下,仅发送至 Ling(ant-ling.com)") if p.id == "ling"
else LF("仅保存在本机当前账户下,仅发送至 %@", host) if p.id == "custom" else LF("仅保存在本机当前账户下,仅发送至 %@(%@)", name, host))
- sent = host if p.id == "custom" else name
- ui.retext(self.footnote, LF("听的时候,电脑里的声音会发给 %@。", sent) if p.id == "ling"
- else L("按所选模型计费。") + LF("听的时候,电脑里的声音会发给 %@。", sent))
+ if custom:
+ # The user's own machines aren't billed by use; the audio still leaves this computer
+ # for the hear model's address (never 声音不出本机 on a port).
+ from ..core.providers import is_nearby
+ cost = L("跑在你自己的机器上,不按量计费。") if c.base and is_nearby(c.base) else L("费用以这个服务为准。")
+ ui.retext(self.footnote, cost + LF("听的时候,电脑里的声音会发给 %@。", app.ling.hear_host or L("你填的地址")))
+ else:
+ ui.retext(self.footnote, LF("听的时候,电脑里的声音会发给 %@。", name) if p.id == "ling"
+ else L("按所选模型计费。") + LF("听的时候,电脑里的声音会发给 %@。", name))
# 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), r.reason, r.busy, app.ling.last_voice)
@@ -790,14 +1063,15 @@ class SettingsWindow(Gtk.Window):
if s.aiProvider == "custom":
# The address and models typed so far, kept even before a key.
s.aiCustomBase = self.custom_base.get_text().strip()
- s.aiModels["custom"] = self.custom_text.get_text().strip()
+ s.aiModels["custom"] = self.custom_text.get_child().get_text().strip()
s.aiHearModels["custom"] = self.custom_hear.get_text().strip()
- if hasattr(self, "custom_voice_model"):
- s.aiVoiceModels["custom"] = self.custom_voice_model.get_text().strip()
- s.aiCustomVoice = self.custom_voice.get_text().strip()
- s.aiCustomVoiceBase = self.custom_voice_base.get_text().strip()
+ s.aiCustomHearBase = self.custom_hear_base.get_text().strip()
+ s.aiVoiceModels["custom"] = self.custom_voice_model.get_text().strip()
+ s.aiCustomVoice = self.custom_voice.get_text().strip()
+ s.aiCustomVoiceBase = self.custom_voice_base.get_text().strip()
s.save()
- text = self.key_entry.get_text().strip()
+ entry = self.custom_key if s.aiProvider == "custom" else self.key_entry
+ text = 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
@@ -809,27 +1083,32 @@ class SettingsWindow(Gtk.Window):
return
if not app.key.save(text):
return
- self.key_entry.set_text("")
+ entry.set_text("")
+ self.custom_editing = False
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)
+ for box in (self.key_hint, self.custom_key_hint):
+ ui.clear(box)
+ box.set_visible(False)
if hint is None:
return
+ box = self.custom_key_hint if self.app.settings.aiProvider == "custom" else self.key_hint
+ box.set_visible(True)
words, service = hint
- self.key_hint.pack_start(ui.text(words, 12, "stepwhy", width_chars=40), True, True, 0)
+ box.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.custom_key.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():
+ box.pack_end(b, False, False, 0)
+ for w in box.get_children():
w.show_all()
def _change_key(self) -> None:
diff --git a/linux/cicada/app/ui.py b/linux/cicada/app/ui.py
index d40a6e2..a31596f 100644
--- a/linux/cicada/app/ui.py
+++ b/linux/cicada/app/ui.py
@@ -181,6 +181,12 @@ button.iconbtn.on { background-color: #F3F4F6; color: #15171C; }
.breathemark { border-radius: 6px; animation: breathe-mark 2.2s ease-out infinite; }
.breathemark.late { animation-delay: 1.1s; }
.idledot { background-color: #C9CCD3; border-radius: 4px; min-width: 7px; min-height: 7px; }
+/* The custom service's per-use rows: how each use is doing (AISettings.swift sectionHeader). */
+.statedot { background-color: #C9CCD3; border-radius: 4px; min-width: 8px; min-height: 8px; }
+.statedot.ok { background-color: #1F7A45; }
+.statedot.warn { background-color: #8A5A00; }
+.statedot.error { background-color: #B42318; }
+.statedot.live { background-color: #E8552B; }
.sidebar { background-color: #F3F4F6; border-right: 1px solid #E4E6EA; }
.sidebar list, .sidebar viewport { background-color: #F3F4F6; }
diff --git a/linux/cicada/core/aicheck.py b/linux/cicada/core/aicheck.py
index 37a3377..0e02f32 100644
--- a/linux/cicada/core/aicheck.py
+++ b/linux/cicada/core/aicheck.py
@@ -27,6 +27,20 @@ RUNNING, OK, BUSY_STATE, FAIL, SKIPPED, UNTESTED = "running", "ok", "busy", "fai
# Below this many dollars left, OpenRouter's balance is worth a word.
LOW_BALANCE = 0.5
TOP_UP = "https://openrouter.ai/settings/credits"
+# A custom service whose sentence takes this long often misses the 6 s a translation is given and
+# falls back to Google (AICheck.Speed.slowAfter).
+SLOW_AFTER = 3.0
+
+
+@dataclass(frozen=True)
+class Speed:
+ """A custom service: how long one real sentence took, and whether the model thought first."""
+ seconds: float
+ thinks: bool
+
+ @property
+ def slow(self) -> bool:
+ return self.thinks or self.seconds >= SLOW_AFTER
@dataclass(frozen=True)
@@ -50,6 +64,8 @@ class AICheck:
# GNOME's is automatic; ("app", port) a proxy app listens but no proxy is set; ("none",).
self.proxy: tuple | None = None
self.balance: float | None = None
+ # A custom service: the real sentence the check translated (Speed).
+ self.translate: Speed | None = None
def copy(self) -> "AICheck":
return copy.deepcopy(self)
@@ -87,6 +103,11 @@ class AICheck:
"""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 slow(self) -> bool:
+ """Text works but every sentence is slow (a thinking model): translations will fall back."""
+ return self.failure is None and self.translate is not None and self.translate.slow
+
@property
def low_balance(self) -> bool:
return self.balance is not None and self.balance < LOW_BALANCE
@@ -101,8 +122,10 @@ class AICheck:
@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)
+ """Nothing AI works: the service can't be reached, or won't take the key. A hear model at an
+ address of its own that can't be reached leaves the text model working."""
+ f = self.failure
+ return f is not None and f[0] != "hear" and f[1] 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
@@ -144,7 +167,7 @@ class AICheck:
reason, code = f[1], f[2]
return {
UNREACHABLE: lambda: LF("这台电脑访问不到 %@。", host),
- BAD_ADDRESS: lambda: L("地址要用 https,只有 localhost 可以用 http。"),
+ BAD_ADDRESS: lambda: L("地址要用 https;这台电脑和局域网里的服务可以用 http。"),
INVALID_KEY: lambda: LF("%@ 说这个 key 无效,可能没复制全,或已删除。", service),
MGMT_KEY: lambda: L("这是 ZenMux 的管理 key,不能用来调用模型。请粘贴 sk-payg 开头的 key。"),
NO_CREDIT: lambda: LF("%@ 账户余额不足。", service),
@@ -155,6 +178,16 @@ class AICheck:
SERVER_ERROR: lambda: LF("%@ 暂时出错(HTTP %lld),稍后再试。", service, code or 0),
}[reason]()
+ def slow_line(self) -> str | None:
+ """Why translations are slow, and what to do (a custom service). Linux falls back to Google
+ too (Translator.translate, 6 s), so the Mac's words hold."""
+ if not self.slow:
+ return None
+ secs = "%.1f" % self.translate.seconds
+ if self.translate.thinks:
+ return LF("这个模型先思考再回答,翻一句要 %@ 秒,超过 6 秒会改用 Google。在服务端关掉思考,或换一个不思考的模型。", secs)
+ return LF("翻一句要 %@ 秒,超过 6 秒会改用 Google。换一个更小的模型会快一些。", secs)
+
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:
@@ -196,6 +229,8 @@ class AICheck:
out.append("balance=%.2f" % self.balance)
if self.passive:
out.append("passive")
+ if self.translate is not None:
+ out.append("translate=%.1fs%s" % (self.translate.seconds, " thinks" if self.translate.thinks else ""))
return " ".join(out)
diff --git a/linux/cicada/core/ling.py b/linux/cicada/core/ling.py
index ad03381..bba1bb8 100644
--- a/linux/cicada/core/ling.py
+++ b/linux/cicada/core/ling.py
@@ -14,7 +14,7 @@ import wave
from . import aicheck, jsonfmt, proxy, strings
from .jsonfmt import arr, obj, string
-from .providers import LING, AIConfig, catalog, is_local
+from .providers import LING, AIConfig, catalog, is_nearby, thought
from .support import Log, Paths
@@ -208,6 +208,11 @@ AUDIO_MODEL = LING.hear_models[0].id
HIJACK_PREFIXES = ("根据现有检索证据", "暂未找到足够可靠的信息", "根据检索", "作为一个人工智能语言模型")
+# The custom service's check: one real sentence, timed (Ling.swift › check).
+CHECK_SENTENCE = ("Translate the text into Simplified Chinese. Reply with the translation only.\n\n"
+ "We will ship the new version on Friday after the design review.")
+
+
def silence_wav(seconds: float = 0.5) -> bytes:
"""A short quiet WAV (16 kHz mono 16-bit), to ask a model whether it takes audio at all."""
buf = io.BytesIO()
@@ -263,6 +268,9 @@ class LingClient:
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`
+ # Custom addresses that refused `chat_template_kwargs` (a strict gateway answers 400 or 422
+ # to a field it doesn't know): left out there until settings change.
+ self._plain_bases: set = set()
def on_change(self, listener) -> None:
self._listeners.append(listener)
@@ -276,10 +284,11 @@ class LingClient:
return self.config().provider
def current_key(self) -> str | None:
- """The key for the service in use. A custom service on this computer may need none: ""."""
+ """The key for the service in use. A custom service on this computer or the local network
+ may need none: ""."""
c = self.config()
k = self.key.read()
- if k is None and c.provider.id == "custom" and c.base and is_local(c.base):
+ if k is None and c.provider.id == "custom" and c.base and is_nearby(c.base):
return ""
return k
@@ -323,10 +332,26 @@ class LingClient:
c = self.config()
return urllib.parse.urlsplit(c.base or c.provider.base or "").hostname or ""
+ @property
+ def hear_host(self) -> str:
+ """Where the hear model is asked (a custom service's own hear address, else the service's)."""
+ c = self.config()
+ return urllib.parse.urlsplit(c.hear_url or "").hostname or self.service_host
+
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)
+ f = self.check_result.failure
+ host = self.hear_host if f is not None and f[0] == "hear" else self.service_host
+ return self.check_result.message(self.service_name, host, c.text_model, c.hear_model)
+
+ def _classify(self, e: LingError, at: str, audio: bool = False):
+ """aicheck.classify, except that a hear model at an address of its own that can't be reached
+ stops at the hear step: the text model's address may be fine."""
+ cl = aicheck.classify(e, at, audio)
+ if audio and cl is not None and cl[1] == aicheck.UNREACHABLE and self.config().own_hear_address:
+ return "hear", aicheck.UNREACHABLE, None
+ return cl
def key_changed(self) -> None:
"""The key, the service or its models changed: forget what the last check found."""
@@ -336,6 +361,7 @@ class LingClient:
self.check_result = aicheck.AICheck()
self.key_state = NONE if self.current_key() is None else UNCHECKED
self.last_voice = None
+ self._plain_bases = set()
self.text_catalog, self.hear_catalog = [], []
self._listed = (None, None)
self._changed()
@@ -385,13 +411,20 @@ class LingClient:
try:
if c.is_ling:
self.chat("Reply with OK.", "Reply.", SPEAK, max_tokens=5, timeout=10.0, model="Ling-3.0-tiny")
+ elif c.provider.id == "custom":
+ # A real sentence, the way a meeting translates: one token says nothing about a model
+ # that thinks for six seconds before every answer.
+ roots: list = []
+ asked = time.monotonic()
+ self.chat(CHECK_SENTENCE, "Translate.", SPEAK, max_tokens=120, timeout=30.0, reply=roots)
+ r.translate = aicheck.Speed(time.monotonic() - asked, bool(roots) and thought(roots[-1]))
else:
self.chat("Reply with OK.", "Reply.", SPEAK, max_tokens=5, timeout=20.0)
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)
+ self.chat("Reply with the JSON object {\"ok\": true}.", "Reply.", SPEAK, json=True, max_tokens=20, timeout=30.0)
except LingError as e:
if e.kind != LingError.HTTP:
raise
@@ -404,6 +437,8 @@ class LingClient:
return r # Ling's hearing is Ming: a meeting proves it, no probe
if not c.hear_model:
r.fail("hear", aicheck.DEAF)
+ elif c.hear_url is None:
+ r.fail("hear", aicheck.BAD_ADDRESS) # its own address, typed but not valid
else:
started = time.monotonic()
try:
@@ -414,9 +449,9 @@ class LingClient:
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")
+ self._failed(r, self._classify(e, "hear", audio=True), "hear")
except Exception: # noqa: BLE001
- r.fail("reach", aicheck.UNREACHABLE)
+ r.fail("hear" if c.own_hear_address else "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 deaf
@@ -425,7 +460,8 @@ class LingClient:
# 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:
+ # The list is the text address's: a hear model elsewhere isn't in it.
+ elif hear is not None and not c.own_hear_address and c.hear_model not in hear and r.failure is None:
r.fail("hear", aicheck.DEAF)
return r
@@ -490,7 +526,7 @@ class LingClient:
return
r = old.copy()
if failure is not None:
- cl = aicheck.classify(failure, "hear" if audio else "text", audio)
+ cl = self._classify(failure, "hear" if audio else "text", audio)
if cl is None or cl[1] == aicheck.SERVER_ERROR:
return
step, reason, code = cl
@@ -569,29 +605,31 @@ class LingClient:
self._changed()
def chat(self, content: str, instruction: str, priority: int, json: bool = False, max_tokens: int = 1024,
- timeout: float = 30.0, model: str | None = None, audio: bytes | None = None, patient: bool = False) -> str:
+ timeout: float = 30.0, model: str | None = None, audio: bytes | None = None, patient: bool = False,
+ reply: list | None = None) -> str:
"""One chat completion. `content` goes in the system message, `instruction` is the fixed user
message, `audio` (a WAV) goes before it for the hear model. Notes and heard audio retry 429s
with backoff (retry_waits); the rest fail fast so the caller can fall back. `patient` (the
final notes) keeps retrying for about a minute. A 429 holds every request start for a while
- (_rate_limited), and a retry keeps its place in the queue, so lines stay in order."""
+ (_rate_limited), and a retry keeps its place in the queue, so lines stay in order. Audio goes
+ to the hear model's address (`hear_url`). `reply`, when given, gets the whole JSON reply."""
k = self.current_key()
if k is None:
raise LingError(LingError.NO_KEY)
if self.key_state == INVALID:
raise LingError(LingError.INVALID_KEY)
c = self.config()
- if c.base is None:
+ base = c.base if audio is None else c.hear_url
+ if base is None:
raise LingError(LingError.NO_KEY)
model = model or c.text_model
user = instruction if audio is None else [c.audio_part(audio, model), {"type": "text", "text": instruction}]
body = {"model": model,
"messages": [{"role": "system", "content": content}, {"role": "user", "content": user}],
"stream": False}
- c.shape(body, max_tokens)
+ c.shape(body, max_tokens, template_kwargs=base not in self._plain_bases)
if json:
body["response_format"] = {"type": "json_object"}
- payload = jsonfmt.write(body, pretty=False)
waits = retry_waits(priority, audio is not None, patient)
attempt = 1
name = PRIORITY_NAMES[priority]
@@ -601,7 +639,7 @@ class LingClient:
ticket = self._acquire(priority, c.provider.spacing, ticket, fail_if_paused=not waits)
started = time.monotonic()
try:
- root = self._post(c.base + "chat/completions", payload, k, timeout)
+ root = self._post_chat(base, body, k, timeout)
choices = arr(root.get("choices"))
choice = obj(choices[0]) if choices else None
text = string((obj(choice.get("message")) or {}).get("content")) if choice else None
@@ -620,6 +658,8 @@ class LingClient:
self.rate_limited_at = None
self._changed()
self.observe(None, time.monotonic() - started, audio is not None)
+ if reply is not None:
+ reply.append(root)
return trimmed
except LingError as e:
self.observe(e, audio=audio is not None)
@@ -713,6 +753,22 @@ class LingClient:
h["Authorization"] = "Bearer " + k
return h
+ def _post_chat(self, base: str, body: dict, k: str, timeout: float) -> dict:
+ """A chat completion. A custom server that refuses `chat_template_kwargs` (400 or 422) is
+ asked again without it, and once that works it isn't sent there again until settings change
+ (Ling.swift › postChat). A 400 the plain request gets too is the model's or the audio's, not
+ the field's: that one is raised and nothing is remembered."""
+ try:
+ return self._post(base + "chat/completions", jsonfmt.write(body, pretty=False), k, timeout)
+ except LingError as e:
+ if not (e.kind == LingError.HTTP and e.status in (400, 422) and "chat_template_kwargs" in body):
+ raise
+ plain = {kk: v for kk, v in body.items() if kk != "chat_template_kwargs"}
+ root = self._post(base + "chat/completions", jsonfmt.write(plain, pretty=False), k, timeout)
+ Log.d("ai custom: chat_template_kwargs refused (HTTP %d), sent without it from now on" % e.status)
+ self._plain_bases.add(base)
+ return root
+
def _post(self, url: str, payload: str, k: str, timeout: float) -> dict:
try:
res = self.transport.send(url, "POST", payload, self._headers(k), timeout)
diff --git a/linux/cicada/core/providers.py b/linux/cicada/core/providers.py
index c6e8282..e675afa 100644
--- a/linux/cicada/core/providers.py
+++ b/linux/cicada/core/providers.py
@@ -82,27 +82,79 @@ def named(raw: str) -> Provider:
return next((p for p in ALL if p.id == raw), LING)
+def _host(host_or_url: str) -> str:
+ s = (host_or_url or "").strip()
+ if "://" not in s and s.count(":") > 1 and "/" not in s:
+ return s.strip("[]").lower() # a bare IPv6 address
+ try:
+ host = urllib.parse.urlsplit(s if "://" in s else "http://" + s).hostname
+ except ValueError:
+ host = None
+ return (host or s).strip("[]").lower()
+
+
def is_local(host_or_url: str) -> bool:
- u = host_or_url if "://" in host_or_url else "http://" + host_or_url
- host = urllib.parse.urlsplit(u).hostname or host_or_url
- return host in ("localhost", "127.0.0.1", "::1")
+ """This computer."""
+ return _host(host_or_url) in ("localhost", "127.0.0.1", "::1")
+
+
+def is_nearby(host_or_url: str) -> bool:
+ """This computer or the local network (AIProvider.isNearby): plain http is allowed and a key
+ isn't needed. Private IPv4 (10/8, 172.16/12, 192.168/16), link-local, Tailscale's 100.64/10,
+ IPv6 unique and link-local addresses, and `.local` names."""
+ h = _host(host_or_url)
+ if is_local(h) or h.endswith(".local"):
+ return True
+ parts = h.split(".")
+ if len(parts) == 4 and all(p.isdigit() for p in parts):
+ a, b = (int(p) for p in parts[:2])
+ if not all(0 <= int(p) <= 255 for p in parts):
+ return False
+ return a == 10 or (a, b) in ((192, 168), (169, 254)) or (a == 172 and 16 <= b <= 31) or (a == 100 and 64 <= b <= 127)
+ if ":" in h:
+ return h.startswith(("fc", "fd", "fe80"))
+ return False
def custom_base(raw: str) -> str | None:
- """The address as typed, normalized: https, or http only on this computer; ends in "/"."""
+ """The address as typed, normalized: https, or http only on this computer or the local network
+ (Ollama, LM Studio, a GPU box at home or work, a Tailscale address); ends in "/"."""
s = (raw or "").strip()
if not s:
return None
if "://" not in s:
- s = ("http://" if is_local(s) else "https://") + s
+ s = ("http://" if is_nearby(s) else "https://") + s
if not s.endswith("/"):
s += "/"
- parts = urllib.parse.urlsplit(s)
- if not parts.hostname:
+ try:
+ parts = urllib.parse.urlsplit(s)
+ host = parts.hostname
+ except ValueError:
+ return None
+ if not host:
return None
if parts.scheme == "https":
return s
- return s if parts.scheme == "http" and is_local(parts.hostname) else None
+ return s if parts.scheme == "http" and is_nearby(host) else None
+
+
+def thought(root: dict) -> bool:
+ """The model thought before answering, which makes every translation slow (AIConfig.thought):
+ a `reasoning_content` (or `reasoning`) field, reasoning tokens in the usage, or a `<think>`
+ block in the answer."""
+ choices = arr((root or {}).get("choices"))
+ message = obj((obj(choices[0]) or {}).get("message")) if choices else None
+ message = message or {}
+ for k in ("reasoning_content", "reasoning"):
+ r = message.get(k)
+ if isinstance(r, str) and r.strip():
+ return True
+ details = obj((obj((root or {}).get("usage")) or {}).get("completion_tokens_details")) or {}
+ n = details.get("reasoning_tokens")
+ if isinstance(n, (int, float)) and not isinstance(n, bool) and n > 0:
+ return True
+ content = message.get("content")
+ return isinstance(content, str) and "<think>" in content
@dataclass
@@ -116,6 +168,20 @@ class AIConfig:
voice_base: str | None = None
custom_voice: str | None = None
extra: dict = field(default_factory=dict)
+ # Where the hear model is asked: a custom service's own hear address (the text model and an
+ # audio model often run as separate servers). None: the text address; "" (only from
+ # config_from): an address typed that isn't valid.
+ hear_base: str | None = None
+
+ @property
+ def hear_url(self) -> str | None:
+ """The address every hear call (and the check's hear step) goes to."""
+ return self.base if self.hear_base is None else (self.hear_base or None)
+
+ @property
+ def own_hear_address(self) -> bool:
+ """The hear model is at an address of its own, not the text model's."""
+ return self.hear_base is not None and self.hear_base != self.base
@property
def is_ling(self) -> bool:
@@ -134,14 +200,19 @@ class AIConfig:
return (CloudVoice(self.custom_voice, ""),) if self.custom_voice else ()
return self.provider.voices
- def shape(self, body: dict, max_tokens: int) -> None:
- """Each service turns thinking off its own way (AIConfig.shape on the Mac)."""
+ def shape(self, body: dict, max_tokens: int, template_kwargs: bool = True) -> None:
+ """Each service turns thinking off its own way (AIConfig.shape on the Mac). A custom service
+ gets `chat_template_kwargs` (vLLM, SGLang and llama.cpp pass it to the chat template, which
+ is how Qwen3 turns thinking off); `template_kwargs` False leaves it out for a server that
+ refused it."""
body["max_tokens"] = max_tokens
body["temperature"] = 0.2
if self.is_ling:
body["thinking"] = {"type": "disabled"}
elif self.provider.id in ("openrouter", "zenmux"):
body["reasoning"] = {"enabled": False}
+ elif self.provider.id == "custom" and template_kwargs:
+ body["chat_template_kwargs"] = {"enable_thinking": False}
def audio_part(self, wav: bytes, model: str) -> dict:
"""One WAV in a user message: Ming takes a data URL; the others the standard `input_audio`,
@@ -166,13 +237,16 @@ def config_from(settings) -> AIConfig:
voice = (voices.get("custom") or "").strip()
voice_base = custom_base(settings.aiCustomVoiceBase) if settings.aiCustomVoiceBase.strip() else base
name = settings.aiCustomVoice.strip()
+ # The hear model's own address (empty: the text model's); "" marks one typed that isn't valid.
+ typed = (getattr(settings, "aiCustomHearBase", "") or "").strip()
+ hear_base = (custom_base(typed) or "") if typed else None
return AIConfig(p, base, (models.get("custom") or "").strip(), (hears.get("custom") or "").strip(),
- voice or None, voice_base if voice else None, name or None)
+ voice or None, voice_base if voice else None, name or None, hear_base=hear_base)
return AIConfig(p, p.base, models.get(p.id) or p.text_models[0].id, hears.get(p.id) or p.hear_models[0].id,
voices.get(p.id) or p.voice_models[0].id, p.base)
-_NOT_CHAT = re.compile(r"(embed|whisper|tts|transcribe|dall-e|image|moderation|realtime|sora|search|video|seedance|wan\d)")
+_NOT_CHAT = re.compile(r"(embed|whisper|tts|asr|transcribe|dall-e|image|moderation|realtime|sora|search|video|seedance|wan\d)")
def catalog(data: str | dict, recommended: list, hears: bool) -> list:
diff --git a/linux/cicada/core/settings.py b/linux/cicada/core/settings.py
index 46e9322..4f89b62 100644
--- a/linux/cicada/core/settings.py
+++ b/linux/cicada/core/settings.py
@@ -23,6 +23,9 @@ class AppSettings:
"aiCustomBase": "",
"aiCustomVoiceBase": "",
"aiCustomVoice": "",
+ # The custom service's hear model at an address of its own (the port's, like the Mac's
+ # aiCustomHearBase); empty: the same address as the text model.
+ "aiCustomHearBase": "",
"view": "notes", # "notes" (the notes window, default) or "subtitles" (the subtitle bar)
"showInCapture": False, # 共享屏幕时让对方看到 (Linux can't hide it; see NotesWindow)
"onboarded": False,
diff --git a/linux/strings/en.lproj/Linux.strings b/linux/strings/en.lproj/Linux.strings
index 4bbd96c..c4b8b80 100644
--- a/linux/strings/en.lproj/Linux.strings
+++ b/linux/strings/en.lproj/Linux.strings
@@ -197,3 +197,9 @@
"没能自动更新:%@。请在浏览器里打开 %@ 下载" = "Couldn’t update automatically: %@. Open %@ in a browser to download it";
/* The Mac's 改用%@重新整理 with spaces around the language (notes_window.py); same translations. */
"改用 %@ 重新整理" = "Rewrite in %@";
+/* 其他(兼容 OpenAI)on the local network and its per-use rows (settings_window.py › _custom_page): the Mac's say "this Mac". */
+"地址要用 https;这台电脑和局域网里的服务可以用 http。" = "The address must use https; services on this computer or your local network can use http.";
+"每样可以接不同的机器;这台电脑和局域网里的服务可以用 http。" = "Each can use a different machine; services on this computer or your local network can use http.";
+"没填,同声传译用不了" = "Not set: no voice for interpreting";
+"填上听的模型" = "Add a listening model";
+"本机和局域网服务可不填" = "Optional on this computer or your local network";
diff --git a/linux/strings/ja.lproj/Linux.strings b/linux/strings/ja.lproj/Linux.strings
index af2f16a..b623e5b 100644
--- a/linux/strings/ja.lproj/Linux.strings
+++ b/linux/strings/ja.lproj/Linux.strings
@@ -197,3 +197,9 @@
"没能自动更新:%@。请在浏览器里打开 %@ 下载" = "自動アップデートできませんでした:%@。ブラウザで %@ を開いてダウンロードしてください";
/* The Mac's 改用%@重新整理 with spaces around the language (notes_window.py); same translations. */
"改用 %@ 重新整理" = "%@で書き直す";
+/* 其他(兼容 OpenAI)on the local network and its per-use rows (settings_window.py › _custom_page): the Mac's say "this Mac". */
+"地址要用 https;这台电脑和局域网里的服务可以用 http。" = "アドレスは https にしてください。このコンピュータやローカルネットワークのサービスは http も使えます。";
+"每样可以接不同的机器;这台电脑和局域网里的服务可以用 http。" = "それぞれ別のマシンを使えます。このコンピュータやローカルネットワークのサービスは http も使えます。";
+"没填,同声传译用不了" = "未設定:同時通訳は話せません";
+"填上听的模型" = "聞き取りモデルを入力";
+"本机和局域网服务可不填" = "このコンピュータやローカルネットワークでは省略可";
diff --git a/linux/strings/ko.lproj/Linux.strings b/linux/strings/ko.lproj/Linux.strings
index 5780bb8..d9f95f8 100644
--- a/linux/strings/ko.lproj/Linux.strings
+++ b/linux/strings/ko.lproj/Linux.strings
@@ -197,3 +197,9 @@
"没能自动更新:%@。请在浏览器里打开 %@ 下载" = "자동 업데이트 실패: %@. 브라우저에서 %@을(를) 열어 다운로드하세요";
/* The Mac's 改用%@重新整理 with spaces around the language (notes_window.py); same translations. */
"改用 %@ 重新整理" = "%@로 다시 작성";
+/* 其他(兼容 OpenAI)on the local network and its per-use rows (settings_window.py › _custom_page): the Mac's say "this Mac". */
+"地址要用 https;这台电脑和局域网里的服务可以用 http。" = "주소는 https여야 합니다. 이 컴퓨터나 로컬 네트워크의 서비스는 http도 쓸 수 있습니다.";
+"每样可以接不同的机器;这台电脑和局域网里的服务可以用 http。" = "기능마다 다른 컴퓨터를 쓸 수 있습니다. 이 컴퓨터나 로컬 네트워크의 서비스는 http도 쓸 수 있습니다.";
+"没填,同声传译用不了" = "설정 안 함: 동시통역 음성을 낼 수 없음";
+"填上听的模型" = "듣기 모델을 입력하세요";
+"本机和局域网服务可不填" = "이 컴퓨터나 로컬 네트워크에서는 생략 가능";
diff --git a/linux/tests/test_custom.py b/linux/tests/test_custom.py
new file mode 100644
index 0000000..b2cf3eb
--- /dev/null
+++ b/linux/tests/test_custom.py
@@ -0,0 +1,237 @@
+"""其他(兼容 OpenAI)for self-hosted models (AIProviderTests.swift): plain http on the local network,
+thinking turned off through the chat template (and left out for a server that refuses it), the
+check's real sentence and what it says about a thinking model, and the hear model at an address of
+its own."""
+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, providers # noqa: E402
+from cicada.core.ling import OK, TRANSLATE, LingError, Response, silence_wav # noqa: E402
+from cicada.core.settings import AppSettings # noqa: E402
+
+
+def custom(**kw):
+ kw.setdefault("aiCustomBase", "http://192.168.1.20:8000/v1")
+ kw.setdefault("aiModels", {"custom": "qwen3:14b"})
+ kw.setdefault("aiHearModels", {"custom": "qwen3-omni"})
+ return dict(kw)
+
+
+def answer(content="周五发布。", **message):
+ m = {"content": content, **message}
+ return Response(200, jsonfmt.write({"choices": [{"message": m, "finish_reason": "stop"}]}, pretty=False))
+
+
+class Nearby(unittest.TestCase):
+ def test_the_local_network_may_use_plain_http(self):
+ for ok in ("http://192.168.1.20:8000/v1", "10.0.0.5:8000/v1", "http://172.20.1.1/v1", "http://100.101.102.103:8000/v1",
+ "http://169.254.3.4/v1", "http://gpu.local:30000/v1", "http://[fd12:3456::1]:8000/v1", "http://[::1]:8000/v1",
+ "http://[fe80::1]/v1", "http://localhost:11434/v1"):
+ self.assertTrue((providers.custom_base(ok) or "").startswith("http://"), ok)
+ for no in ("http://172.32.0.1/v1", "http://172.15.0.1/v1", "http://100.128.0.1/v1", "http://100.63.0.1/v1",
+ "http://8.8.8.8/v1", "http://192.169.1.1/v1", "http://gpu.example.com/v1", "http://10.0.0.5.evil.com/v1",
+ "http://10.0.0.256/v1", "http://[2001:db8::1]/v1"):
+ self.assertIsNone(providers.custom_base(no), no)
+ self.assertEqual("http://192.168.1.20:8000/v1/", providers.custom_base("192.168.1.20:8000/v1"))
+ self.assertEqual("https://10.0.0.5.evil.com/v1/", providers.custom_base("10.0.0.5.evil.com/v1"))
+ self.assertEqual("https://gpu.example.com/v1/", providers.custom_base("https://gpu.example.com/v1"))
+ self.assertTrue(providers.is_nearby("http://192.168.1.20:8000/v1/"))
+ self.assertFalse(providers.is_local("http://192.168.1.20:8000/v1/"))
+ self.assertIsNone(providers.custom_base(" "))
+
+ def test_a_nearby_service_needs_no_key(self):
+ from cicada.core.ling import AIKey, LingClient
+ s = AppSettings(aiProvider="custom", **custom())
+ ling = LingClient(AIKey(path=os.path.join(HERE, "no-such-key")), Fake(lambda u, b: answer()), config=s.ai_config)
+ self.assertEqual("", ling.current_key())
+ s.aiCustomBase = "https://gpu.example.com/v1"
+ self.assertIsNone(ling.current_key())
+
+
+class Shape(unittest.TestCase):
+ def test_custom_turns_thinking_off_through_the_template(self):
+ c = providers.AIConfig(providers.CUSTOM, "http://localhost/v1/", "m", "h")
+ body = {}
+ c.shape(body, 50)
+ self.assertEqual({"enable_thinking": False}, body["chat_template_kwargs"])
+ self.assertNotIn("thinking", body)
+ plain = {}
+ c.shape(plain, 50, template_kwargs=False)
+ self.assertNotIn("chat_template_kwargs", plain)
+ for p in (providers.LING, providers.ZENMUX, providers.OPENROUTER):
+ other = {}
+ providers.AIConfig(p, p.base, "m", "h").shape(other, 50)
+ self.assertNotIn("chat_template_kwargs", other, p.id)
+
+ def test_a_thinking_model_is_seen_from_its_reply(self):
+ def r(message, usage=None):
+ root = {"choices": [{"message": message}]}
+ if usage is not None:
+ root["usage"] = usage
+ return root
+ self.assertFalse(providers.thought(r({"content": "周五发布。"})))
+ self.assertTrue(providers.thought(r({"content": "周五发布。", "reasoning_content": "The user wants…"})))
+ # A reasoning parser on the server: the answer itself sits in reasoning_content.
+ self.assertTrue(providers.thought(r({"content": "", "reasoning_content": "周五发布。"})))
+ self.assertTrue(providers.thought(r({"content": "周五发布。", "reasoning": "hmm"})))
+ self.assertTrue(providers.thought(r({"content": "<think>hmm</think>周五发布。"})))
+ self.assertTrue(providers.thought(r({"content": "周五发布。"}, {"completion_tokens_details": {"reasoning_tokens": 212}})))
+ self.assertFalse(providers.thought(r({"content": "周五发布。", "reasoning_content": " "},
+ {"completion_tokens_details": {"reasoning_tokens": 0}})))
+ self.assertFalse(providers.thought({}))
+
+ def test_a_slow_sentence_is_flagged(self):
+ self.assertFalse(aicheck.Speed(0.4, False).slow)
+ self.assertTrue(aicheck.Speed(0.4, True).slow)
+ self.assertTrue(aicheck.Speed(3.0, False).slow)
+ self.assertTrue(aicheck.Speed(6.4, False).slow)
+ r = aicheck.AICheck()
+ r.pass_up_to("hear", 1.0)
+ r.translate = aicheck.Speed(4.2, True)
+ self.assertTrue(r.slow)
+ self.assertIn("4.2", r.slow_line())
+ self.assertIn("思考", r.slow_line())
+ r.translate = aicheck.Speed(3.5, False)
+ self.assertNotIn("思考", r.slow_line())
+ r.translate = aicheck.Speed(0.5, False)
+ self.assertIsNone(r.slow_line())
+ self.assertIn("translate=0.5s", r.summary())
+
+
+class TemplateKwargs(Base):
+ def test_a_server_that_refuses_it_is_asked_again_without(self):
+ def respond(url, body):
+ return Response(422, "{}") if "chat_template_kwargs" in body else answer()
+ fake = Fake(respond)
+ ling, s = self.client(fake, "custom", key=None, **custom())
+ self.assertEqual("周五发布。", ling.chat("x", "Translate.", TRANSLATE))
+ self.assertEqual(2, len(fake.sent))
+ self.assertIn("chat_template_kwargs", fake.sent[0][1])
+ self.assertNotIn("chat_template_kwargs", fake.sent[1][1])
+ # Not sent there again…
+ ling.chat("x", "Translate.", TRANSLATE)
+ self.assertEqual(3, len(fake.sent))
+ self.assertNotIn("chat_template_kwargs", fake.sent[2][1])
+ # …until settings change.
+ ling.key_changed()
+ ling.chat("x", "Translate.", TRANSLATE)
+ self.assertIn("chat_template_kwargs", fake.sent[3][1])
+ # A refused request never showed as a missing model.
+ self.assertIsNone(ling.check_result.failure)
+
+ def test_a_400_both_ways_is_not_the_field(self):
+ fake = Fake(lambda u, b: Response(400, "{}"))
+ ling, _ = self.client(fake, "custom", key=None, **custom())
+ with self.assertRaises(LingError) as e:
+ ling.chat("x", "Translate.", TRANSLATE)
+ self.assertEqual(400, e.exception.status)
+ self.assertEqual(2, len(fake.sent))
+ fake.respond = lambda u, b: answer()
+ ling.chat("x", "Translate.", TRANSLATE)
+ self.assertIn("chat_template_kwargs", fake.sent[-1][1]) # nothing remembered
+
+ def test_other_errors_are_not_retried(self):
+ fake = Fake(lambda u, b: Response(500, "{}"))
+ ling, _ = self.client(fake, "custom", key=None, **custom())
+ with self.assertRaises(LingError):
+ ling.chat("x", "Translate.", TRANSLATE)
+ self.assertEqual(1, len(fake.sent))
+
+
+class Check(Base):
+ def test_the_check_translates_a_real_sentence(self):
+ fake = Fake(lambda u, b: Response(404, "") if u.endswith("/models") else answer())
+ ling, _ = self.client(fake, "custom", key=None, **custom())
+ self.assertEqual(OK, ling.check())
+ first = jsonfmt.parse_object(fake.sent[0][1])
+ self.assertIn("We will ship the new version on Friday", first["messages"][0]["content"])
+ self.assertEqual("Translate.", first["messages"][1]["content"])
+ self.assertEqual(120, first["max_tokens"])
+ r = ling.check_result
+ self.assertIsNotNone(r.translate)
+ self.assertFalse(r.translate.thinks)
+ self.assertFalse(r.slow)
+ self.assertIn("translate=", r.summary())
+
+ def test_a_thinking_model_is_slow(self):
+ def respond(url, body):
+ if url.endswith("/models"):
+ return Response(404, "")
+ return answer(reasoning_content="Let me think…")
+ ling, _ = self.client(Fake(respond), "custom", key=None, **custom())
+ ling.check()
+ r = ling.check_result
+ self.assertTrue(r.translate.thinks)
+ self.assertTrue(r.slow)
+ self.assertIn("思考", r.slow_line())
+
+ def test_bad_address_words_the_local_network(self):
+ ling, _ = self.client(Fake(lambda u, b: answer()), "custom", key="sk-x", aiCustomBase="http://gpu.example.com/v1")
+ ling.check()
+ self.assertEqual(aicheck.BAD_ADDRESS, ling.check_result.reason)
+ self.assertIn("局域网", ling.message())
+
+
+class HearAddress(Base):
+ def test_the_hear_address_falls_back_to_the_text_one(self):
+ c = AppSettings(aiProvider="custom", **custom()).ai_config()
+ self.assertEqual("http://192.168.1.20:8000/v1/", c.hear_url)
+ self.assertFalse(c.own_hear_address)
+ c = AppSettings(aiProvider="custom", **custom(aiCustomHearBase="192.168.1.30:8001/v1")).ai_config()
+ self.assertEqual("http://192.168.1.30:8001/v1/", c.hear_url)
+ self.assertEqual("http://192.168.1.20:8000/v1/", c.base)
+ self.assertTrue(c.own_hear_address)
+ # Typed but not valid: nowhere to send audio (not the text address).
+ c = AppSettings(aiProvider="custom", **custom(aiCustomHearBase="http://gpu.example.com/v1")).ai_config()
+ self.assertIsNone(c.hear_url)
+ z = AppSettings(aiProvider="zenmux", aiCustomHearBase="http://192.168.1.30/v1").ai_config()
+ self.assertEqual(z.base, z.hear_url)
+
+ def test_hear_calls_and_the_check_go_to_the_hear_address(self):
+ def respond(url, body):
+ if url.endswith("/models"):
+ return Response(404, "")
+ return answer("NONE" if "input_audio" in body else "周五发布。")
+ fake = Fake(respond)
+ ling, _ = self.client(fake, "custom", key=None, **custom(aiCustomHearBase="http://192.168.1.30:8001/v1"))
+ self.assertEqual(OK, ling.check())
+ audio = [u for u, b in fake.sent if "input_audio" in b]
+ text = [u for u, b in fake.sent if "chat/completions" in u and "input_audio" not in b]
+ self.assertEqual(["http://192.168.1.30:8001/v1/chat/completions"], audio)
+ self.assertTrue(text and all(u.startswith("http://192.168.1.20:8000/v1/") for u in text))
+ self.assertEqual("ok", ling.check_result["hear"].kind)
+ ling.chat("x", "y", TRANSLATE, model="qwen3-omni", audio=silence_wav())
+ self.assertEqual("http://192.168.1.30:8001/v1/chat/completions", fake.sent[-1][0])
+
+ def test_an_unreachable_hear_address_leaves_text_working(self):
+ def respond(url, body):
+ if "192.168.1.30" in url:
+ raise OSError("no route")
+ return Response(404, "") if url.endswith("/models") else answer()
+ ling, _ = self.client(Fake(respond), "custom", key=None, **custom(aiCustomHearBase="http://192.168.1.30:8001/v1"))
+ self.assertEqual(OK, ling.check())
+ r = ling.check_result
+ self.assertEqual(("hear", aicheck.UNREACHABLE, None), r.failure)
+ self.assertFalse(r.down)
+ self.assertIn("192.168.1.30", ling.message())
+ self.assertEqual("192.168.1.30", ling.hear_host)
+
+ def test_an_invalid_hear_address_fails_the_hear_step(self):
+ fake = Fake(lambda u, b: Response(404, "") if u.endswith("/models") else answer())
+ ling, _ = self.client(fake, "custom", key=None, **custom(aiCustomHearBase="http://gpu.example.com/v1"))
+ ling.check()
+ self.assertEqual(("hear", aicheck.BAD_ADDRESS, None), ling.check_result.failure)
+ self.assertFalse(any("input_audio" in b for _u, b in fake.sent))
+
+
+if __name__ == "__main__":
+ unittest.main()