知了 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(windows): 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
wquguru82c5b38197ec
diff --git a/windows/src/Cicada.Core/AICheck.cs b/windows/src/Cicada.Core/AICheck.csindex ad536a4..da770dc 100644--- a/windows/src/Cicada.Core/AICheck.cs+++ b/windows/src/Cicada.Core/AICheck.cs@@ -55,6 +55,19 @@ public sealed class AICheckpublic ProxyHint? Proxy { get; set; }/// OpenRouter only: dollars left (the smaller of the key's limit and the account's credits).public double? Balance { get; set; }+ /// A custom service: how long one real sentence took, and whether the model thought first.+ public Speed? Translate { get; set; }++ /// A sentence that takes `SlowAfter` seconds often misses the 6 s a translation is given+ /// (Translator) and falls back to Google; a model that thinks first does every time.+ public readonly record struct Speed(double Seconds, bool Thinks)+ {+ public const double SlowAfter = 3;+ public bool Slow => Thinks || Seconds >= SlowAfter;+ }++ /// Text works but every sentence is slow (a thinking model): translations will fall back.+ public bool Slow => Failure is null && Translate?.Slow == true;public const double LowBalance = 0.5;@@ -68,7 +81,7 @@ public sealed class AICheckpublic AICheck Clone(){- var c = new AICheck { At = At, Passive = Passive, Proxy = Proxy, Balance = Balance };+ var c = new AICheck { At = At, Passive = Passive, Proxy = Proxy, Balance = Balance, Translate = Translate };steps.CopyTo(c.steps, 0);return c;}@@ -145,8 +158,11 @@ public sealed class AICheck/// Which step a failed request stops at, and why. `step` is the step the request was proving/// (the text model for a chat, the hear model for audio). Null: says nothing about the service.- public static (StepId Step, Reason Why, int? Code)? Classify(LingException.Kind kind, int status, StepId step) => kind switch+ /// `hearElsewhere`: the hear model has an address of its own, so not reaching it says nothing+ /// about the service's address.+ public static (StepId Step, Reason Why, int? Code)? Classify(LingException.Kind kind, int status, StepId step, bool hearElsewhere = false) => kind switch{+ LingException.Kind.Network or LingException.Kind.Timeout when hearElsewhere && step == StepId.Hear => (StepId.Hear, Reason.Unreachable, null),LingException.Kind.Network or LingException.Kind.Timeout => (StepId.Reach, Reason.Unreachable, null),LingException.Kind.InvalidKey => (StepId.Key, Reason.InvalidKey, null),LingException.Kind.RateLimited => (step, Reason.Busy, null),@@ -231,7 +247,7 @@ public sealed class AICheckreturn f.Why switch{Reason.Unreachable => Strings.LF("这台电脑访问不到 %@。", host),- Reason.BadAddress => Strings.L("地址要用 https,只有 localhost 可以用 http。"),+ Reason.BadAddress => Strings.L("地址要用 https;这台电脑和局域网里的服务可以用 http。"),Reason.InvalidKey => Strings.LF("%@ 说这个 key 无效,可能没复制全,或已删除。", service),Reason.MgmtKey => Strings.L("这是 ZenMux 的管理 key,不能用来调用模型。请粘贴 sk-payg 开头的 key。"),Reason.NoCredit => Strings.LF("%@ 账户余额不足。", service),@@ -243,6 +259,16 @@ public sealed class AICheck};}+ /// Why translations are slow, and what to do (a custom service). The Mac's words: the+ /// translation timeout is the same 6 s here.+ public string? SlowLine()+ {+ if (!Slow || Translate is not { } t) return null;+ var secs = t.Seconds.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture);+ return t.Thinks ? Strings.LF("这个模型先思考再回答,翻一句要 %@ 秒,超过 6 秒会改用 Google。在服务端关掉思考,或换一个不思考的模型。", secs)+ : Strings.LF("翻一句要 %@ 秒,超过 6 秒会改用 Google。换一个更小的模型会快一些。", secs);+ }+/// The proxy line under "can't reach": what this computer's proxy looks like, and what to do.public string? ProxyLine(string service, string host){@@ -273,7 +299,8 @@ public sealed class AICheckvar k => Lower(k),});return string.Join(" ", parts) + (Proxy is { } p ? $" proxy={p}" : "")- + (Balance is { } b ? $" balance={b.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)}" : "") + (Passive ? " passive" : "");+ + (Balance is { } b ? $" balance={b.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)}" : "") + (Passive ? " passive" : "")+ + (Translate is { } t ? $" translate={t.Seconds.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture)}s{(t.Thinks ? " thinks" : "")}" : "");}}diff --git a/windows/src/Cicada.Core/AIProviders.cs b/windows/src/Cicada.Core/AIProviders.csindex e050ba7..797c223 100644--- a/windows/src/Cicada.Core/AIProviders.cs+++ b/windows/src/Cicada.Core/AIProviders.cs@@ -50,26 +50,49 @@ public sealed record AIProvider(string Id, string Name, string? Base, string? Si/// A service never named (or OpenAI, which the ports don't offer) is Ling.public static AIProvider Named(string? id) => All.FirstOrDefault(p => p.Id == id) ?? Ling;- public static bool IsLocal(string hostOrUrl)+ /// This computer: a key isn't needed.+ public static bool IsLocal(string hostOrUrl) => Host(hostOrUrl) is "localhost" or "127.0.0.1" or "::1";++ /// This computer or the local network (Ollama, LM Studio, a GPU box at home or work, a Tailscale+ /// address): 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.+ public static bool IsNearby(string hostOrUrl){- var u = hostOrUrl.Contains("://") ? hostOrUrl : "http://" + hostOrUrl;- var host = Uri.TryCreate(u, UriKind.Absolute, out var uri) ? uri.Host.Trim('[', ']') : hostOrUrl;- return host is "localhost" or "127.0.0.1" or "::1";+ var h = Host(hostOrUrl).ToLowerInvariant();+ if (IsLocal(h) || h.EndsWith(".local")) return true;+ var parts = h.Split('.');+ // Exactly four numbers: "10.0.0.5.evil.com" is a name, not a private address.+ if (parts.Length == 4 && parts.All(x => x.Length is > 0 and <= 3 && x.All(char.IsAsciiDigit) && int.Parse(x) <= 255))+ {+ int a = int.Parse(parts[0]), b = int.Parse(parts[1]);+ return a == 10 || a == 192 && b == 168 || a == 169 && b == 254 || a == 172 && b is >= 16 and <= 31 || a == 100 && b is >= 64 and <= 127;+ }+ if (h.Contains(':')) return h.StartsWith("fc") || h.StartsWith("fd") || h.StartsWith("fe80");+ return false;+ }++ static string Host(string hostOrUrl)+ {+ var s = hostOrUrl.Trim();+ var u = s.Contains("://") ? s : "http://" + s;+ return (Uri.TryCreate(u, UriKind.Absolute, out var uri) ? uri.Host : s).Trim('[', ']');}- /// 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; ends in "/".public static string? CustomBase(string? raw){var s = (raw ?? "").Trim();if (s.Length == 0) return null;- if (!s.Contains("://")) s = (IsLocal(s) ? "http://" : "https://") + s;+ if (!s.Contains("://")) s = (IsNearby(s) ? "http://" : "https://") + s;if (!s.EndsWith('/')) s += "/";if (!Uri.TryCreate(s, UriKind.Absolute, out var u) || u.Host.Length == 0) return null;if (u.Scheme == "https") return s;- return u.Scheme == "http" && IsLocal(u.Host) ? s : null;+ return u.Scheme == "http" && IsNearby(u.Host) ? s : null;}- static readonly Regex NotChat = new(@"(embed|whisper|tts|transcribe|dall-e|image|moderation|realtime|sora|search|video|seedance|wan\d)");+ static readonly Regex NotChat = new(@"(embed|whisper|tts|asr|transcribe|dall-e|image|moderation|realtime|sora|search|video|seedance|wan\d)");/// Model ids from a `/models` reply, recommended ones first: those that answer in text, and for/// `hears` only those that take audio in. ZenMux lists modalities at the top level, OpenRouter@@ -102,9 +125,10 @@ public sealed record AIProvider(string Id, string Name, string? Base, string? Si/// What one call needs to know about the service in use, resolved from settings each time/// (Settings.swift › aiConfig). `Base` is null for a custom service without a valid address yet;-/// `VoiceModel` null when the service can't speak here.+/// `VoiceModel` null when the service can't speak here. `HearBase` is where the hear model is+/// asked: the service's address, or a custom service's own one for it (null: not a valid address).public sealed record AIConfig(AIProvider Provider, string? Base, string TextModel, string HearModel,- string? VoiceModel = null, string? VoiceBase = null, string? CustomVoice = null)+ string? VoiceModel = null, string? VoiceBase = null, string? CustomVoice = null, string? HearBase = null){public bool IsLing => Provider.Id == "ling";public bool HasVoices => VoiceModel is not null && VoiceBase is not null;@@ -117,13 +141,31 @@ public sealed record AIConfig(AIProvider Provider, string? Base, string TextModepublic static AIConfig Default => From(new AppSettings());- /// Each service turns thinking off its own way (AIConfig.shape on the Mac).- public void Shape(JsonObject body, int maxTokens)+ /// The hear model has an address of its own (a custom service's speech server).+ public bool HearElsewhere => HearBase != Base;++ /// Each service turns thinking off its own way (AIConfig.shape on the Mac). A custom service+ /// gets `chat_template_kwargs` (vLLM, SGLang and llama.cpp pass it to the chat template, which+ /// is how Qwen3 turns thinking off); `templateKwargs` false leaves it out for a server that refused it.+ public void Shape(JsonObject body, int maxTokens, bool templateKwargs = true){body["max_tokens"] = maxTokens;body["temperature"] = 0.2;if (IsLing) body["thinking"] = new JsonObject { ["type"] = "disabled" };else if (Provider.Id is "openrouter" or "zenmux") body["reasoning"] = new JsonObject { ["enabled"] = false };+ else if (Provider.Id == "custom" && templateKwargs) body["chat_template_kwargs"] = new JsonObject { ["enable_thinking"] = false };+ }++ /// The model thought before answering, which makes every translation slow: a `reasoning_content`+ /// (or `reasoning`) field, reasoning tokens in the usage, or a `<think>` block in the answer.+ /// A server's reasoning parser may put the whole answer in `reasoning_content`, content empty.+ public static bool Thought(JsonNode? root)+ {+ var message = root?["choices"]?[0]?["message"];+ foreach (var k in new[] { "reasoning_content", "reasoning" })+ if (message?[k] is JsonValue v && v.TryGetValue<string>(out var r) && r.Trim().Length > 0) return true;+ if (root?["usage"]?["completion_tokens_details"]?["reasoning_tokens"] is JsonValue n && n.TryGetValue<int>(out var tokens) && tokens > 0) return true;+ return message?["content"] is JsonValue c && c.TryGetValue<string>(out var content) && content.Contains("<think>");}/// One WAV in a user message: Ming takes a data URL; the others the standard `input_audio`,@@ -143,7 +185,7 @@ public sealed record AIConfig(AIProvider Provider, string? Base, string TextModeif (p.Id == "ling"){var text = p.TextModels.Any(m => m.Id == s.Model) ? s.Model : p.TextModels[0].Id;- return new(p, p.Base, text, p.HearModels[0].Id, p.VoiceModels[0].Id, p.Base);+ return new(p, p.Base, text, p.HearModels[0].Id, p.VoiceModels[0].Id, p.Base, HearBase: p.Base);}string Pick(Dictionary<string, string> table) => table.TryGetValue(p.Id, out var v) ? v.Trim() : "";if (p.Id == "custom")@@ -152,10 +194,12 @@ public sealed record AIConfig(AIProvider Provider, string? Base, string TextModevar voice = Pick(s.AiVoiceModels);var voiceBase = s.AiCustomVoiceBase.Trim().Length > 0 ? AIProvider.CustomBase(s.AiCustomVoiceBase) : b;var name = s.AiCustomVoice.Trim();+ // The hear model may run as its own server; empty is the text model's address.+ var hearBase = s.AiCustomHearBase.Trim().Length > 0 ? AIProvider.CustomBase(s.AiCustomHearBase) : b;return new(p, b, Pick(s.AiModels), Pick(s.AiHearModels), voice.Length > 0 ? voice : null,- voice.Length > 0 ? voiceBase : null, name.Length > 0 ? name : null);+ voice.Length > 0 ? voiceBase : null, name.Length > 0 ? name : null, hearBase);}static string Or(string v, AIModel[] rec) => v.Length > 0 ? v : rec[0].Id;- return new(p, p.Base, Or(Pick(s.AiModels), p.TextModels), Or(Pick(s.AiHearModels), p.HearModels), Or(Pick(s.AiVoiceModels), p.VoiceModels), p.Base);+ return new(p, p.Base, Or(Pick(s.AiModels), p.TextModels), Or(Pick(s.AiHearModels), p.HearModels), Or(Pick(s.AiVoiceModels), p.VoiceModels), p.Base, HearBase: p.Base);}}diff --git a/windows/src/Cicada.Core/Ling.cs b/windows/src/Cicada.Core/Ling.csindex 38d83f9..b307f7b 100644--- a/windows/src/Cicada.Core/Ling.cs+++ b/windows/src/Cicada.Core/Ling.cs@@ -188,12 +188,12 @@ public sealed class LingClientpublic AIConfig Config => config();public AIProvider Provider => Config.Provider;- /// 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: "".public string? CurrentKey(){var c = Config;var k = key.Read();- if (k is null && c.Provider.Id == "custom" && c.Base is { } b && AIProvider.IsLocal(b)) return "";+ if (k is null && c.Provider.Id == "custom" && c.Base is { } b && AIProvider.IsNearby(b)) return "";return k;}@@ -203,11 +203,15 @@ public sealed class LingClientpublic bool Speaks => Usable && Config.HasVoices;/// Listening and 同声传译 can work: the hear model wasn't found to refuse audio.public bool CanHear => Usable && Hears != false && Config.HearModel.Length > 0;+ /// The addresses that refused `chat_template_kwargs` once (a custom service's text and hear+ /// models may be separate servers): left out there until settings change.+ readonly System.Collections.Concurrent.ConcurrentDictionary<string, bool> noTemplateKwargs = new();/// The key, the service or its models changed: forget what the last check found.public void KeyChanged(){key.Reload();+ noTemplateKwargs.Clear();Interlocked.Increment(ref generation);lock (healthGate) health = new AICheck();KeyState = CurrentKey() is null ? KeyState.None : KeyState.Unchecked;@@ -219,7 +223,10 @@ public sealed class LingClient/// What messages call the service ("这个服务" for a custom address) and its host.public string ServiceName => Config.Provider.Id == "custom" ? Strings.L("这个服务") : Config.Name;- public string ServiceHost => Config.Base is { } b && Uri.TryCreate(b, UriKind.Absolute, out var u) ? u.Host : "";+ public string ServiceHost => Host(Config.Base);+ /// Where the hear model is asked (a custom service's own address for it, else the service's).+ public string HearHost => Host(Config.HearBase ?? Config.Base);+ static string Host(string? b) => b is not null && Uri.TryCreate(b, UriKind.Absolute, out var u) ? u.Host : "";/// The hear model in messages; the service when none is named (a custom one not filled in).public string HearName => Config.HearModel.Length > 0 ? Config.HearModel : ServiceName;@@ -231,6 +238,9 @@ public sealed class LingClient{var started = DateTime.UtcNow;var c = Config;+ // Counted before anything else: a slower check still running (a custom service that thinks+ // for seconds) must not land on top of what this one finds, even "no key".+ var gen = Interlocked.Increment(ref generation);if (CurrentKey() is not { } k){lock (healthGate) health = new AICheck();@@ -239,7 +249,6 @@ public sealed class LingClientreturn (KeyState, 0);}Interlocked.Increment(ref checking);- var gen = Interlocked.Increment(ref generation);try{var r = new AICheck();@@ -263,18 +272,32 @@ public sealed class LingClientdouble Since(DateTime t) => (DateTime.UtcNow - t).TotalSeconds;void Failed(LingException e, AICheck.StepId step){- if (AICheck.Classify(e.Failure, e.Status, step) is not { } f) return;+ if (AICheck.Classify(e.Failure, e.Status, step, c.HearElsewhere) is not { } f) return;if (f.Why == AICheck.Reason.Busy) r.Busy(f.Step); else r.Fail(f.Step, f.Why, f.Code);}var t = DateTime.UtcNow;try{if (c.IsLing) await Chat("Reply with OK.", "Reply.", Priority.Speak, maxTokens: 5, timeout: 10, model: "Ling-3.0-tiny");- else await Chat("Reply with OK.", "Reply.", Priority.Speak, maxTokens: 5, timeout: 20);+ else if (c.Provider.Id != "custom") await Chat("Reply with OK.", "Reply.", Priority.Speak, maxTokens: 5, timeout: 20);+ else+ {+ // A real sentence, the way a meeting translates: one token says nothing about a+ // model that thinks for six seconds before every answer.+ JsonNode? root = null;+ try+ {+ await Chat("Translate the text into Simplified Chinese. Reply with the translation only.\n\nWe will ship the new version on Friday after the design review.",+ "Translate.", Priority.Speak, maxTokens: 120, timeout: 30, reply: n => root = n);+ }+ // A reasoning parser that put the whole answer in reasoning_content: it answered, by thinking.+ catch (LingException e) when (e.Failure == LingException.Kind.Parse && AIConfig.Thought(root)) { }+ r.Translate = new AICheck.Speed(Since(t), AIConfig.Thought(root));+ }r.Pass(AICheck.StepId.Text, Since(t));if (c.Provider.Id == "custom"){- try { await Chat("Reply with the JSON object {\"ok\": true}.", "Reply.", Priority.Speak, json: true, maxTokens: 20, timeout: 20); }+ try { await Chat("Reply with the JSON object {\"ok\": true}.", "Reply.", Priority.Speak, json: true, maxTokens: 20, timeout: 30); }catch (LingException e) when (e.Failure == LingException.Kind.Http) { r.Fail(AICheck.StepId.Text, AICheck.Reason.NoJSON, e.Status); }}}@@ -283,6 +306,7 @@ public sealed class LingClient// The address and the key work: hearing is its own question (the text model may be the one gone).if (c.IsLing || r.Failure is { Step: AICheck.StepId.Reach or AICheck.StepId.Key }) return;if (c.HearModel.Length == 0) r.Fail(AICheck.StepId.Hear, AICheck.Reason.Deaf);+ else if (c.HearBase is null) r.Fail(AICheck.StepId.Hear, AICheck.Reason.BadAddress);else{t = DateTime.UtcNow;@@ -301,7 +325,8 @@ public sealed class LingClient// A model the service no longer lists fails here, before a meeting finds out.if (listed is { } ids && c.TextModel.Length > 0 && r[AICheck.StepId.Text].Kind != AICheck.Kind.Fail && !ids.Contains(c.TextModel))r.Fail(AICheck.StepId.Text, AICheck.Reason.NoModel);- if (listedHearing is { } hearing && c.HearModel.Length > 0 && r[AICheck.StepId.Hear].Kind != AICheck.Kind.Fail && !hearing.Contains(c.HearModel))+ // The list is the text address's: it says nothing about a hear model served elsewhere.+ if (listedHearing is { } hearing && !c.HearElsewhere && c.HearModel.Length > 0 && r[AICheck.StepId.Hear].Kind != AICheck.Kind.Fail && !hearing.Contains(c.HearModel))r.Fail(AICheck.StepId.Hear, AICheck.Reason.Deaf);if (c.Provider.Id == "openrouter") r.Balance = AICheck.BalanceFrom(await GetText("key", k), await GetText("credits", k));}@@ -364,7 +389,7 @@ public sealed class LingClientr = old.Clone();if (failure is not null){- if (AICheck.Classify(failure.Failure, failure.Status, step) is not { } f || f.Why == AICheck.Reason.ServerError) return;+ if (AICheck.Classify(failure.Failure, failure.Status, step, Config.HearElsewhere) is not { } f || f.Why == AICheck.Reason.ServerError) return;if (f.Why == AICheck.Reason.Busy) r.Busy(f.Step); else r.Fail(f.Step, f.Why, f.Code);}else r.Pass(step, seconds);@@ -440,15 +465,17 @@ public sealed class LingClient/// with backoff (RetryWaits); the rest fail fast so the caller can fall back. `model` defaults to/// the service's text model. `patient` (the final notes) keeps retrying for about a minute. A 429/// holds every request start for a while (RateLimited), and a retry keeps its place in the- /// queue, so lines stay in order.+ /// queue, so lines stay in order. Audio goes to the hear model's address (a custom service's own+ /// one for it). `reply` sees the whole reply before its text is read (the check's thinking test).public async Task<string> Chat(string content, string instruction, Priority priority, bool json = false,int maxTokens = 1024, double timeout = 30, string? model = null, byte[]? audio = null, bool patient = false,- CancellationToken cancel = default)+ CancellationToken cancel = default, Action<JsonNode>? reply = null){var k = CurrentKey() ?? throw new LingException(LingException.Kind.NoKey);if (KeyState == KeyState.Invalid) throw new LingException(LingException.Kind.InvalidKey);var c = Config;- if (c.Base is null) throw new LingException(LingException.Kind.NoKey);+ var b = audio is null ? c.Base : c.Provider.Id == "custom" ? c.HearBase : c.HearBase ?? c.Base;+ if (b is null) throw new LingException(LingException.Kind.NoKey);model ??= c.TextModel;JsonNode user = audio is null ? JsonValue.Create(instruction)! : new JsonArray(c.AudioPart(audio, model), new JsonObject { ["type"] = "text", ["text"] = instruction });var body = new JsonObject@@ -459,10 +486,10 @@ public sealed class LingClientnew JsonObject { ["role"] = "user", ["content"] = user }),["stream"] = false,};- c.Shape(body, maxTokens);+ c.Shape(body, maxTokens, templateKwargs: !noTemplateKwargs.ContainsKey(b));if (json) body["response_format"] = new JsonObject { ["type"] = "json_object" };var payload = body.ToJsonString();- var url = new Uri(new Uri(c.Base), "chat/completions");+ var url = new Uri(new Uri(b), "chat/completions");var waits = RetryWaits(priority, audio is not null, patient);long? ticket = null;@@ -475,7 +502,19 @@ public sealed class LingClientif ((started - queued).TotalSeconds > 1) Log.Debug($"ling: {priority} waited {(started - queued).TotalMilliseconds:F0} ms at the gate");try{- var root = await Post(url, payload, k, timeout, cancel);+ JsonNode root;+ try { root = await Post(url, payload, k, timeout, cancel); }+ // A strict gateway answers 400 or 422 to a field it doesn't know: asked again+ // without it, and not sent it again until settings change.+ catch (LingException e) when (e.Failure == LingException.Kind.Http && e.Status is 400 or 422 && body.ContainsKey("chat_template_kwargs"))+ {+ Log.Debug($"ai custom: chat_template_kwargs refused (HTTP {e.Status}), sent without it from now on");+ noTemplateKwargs[b] = true;+ body.Remove("chat_template_kwargs");+ payload = body.ToJsonString();+ root = await Post(url, payload, k, timeout, cancel);+ }+ reply?.Invoke(root);var choice = root["choices"]?[0];var text = Str(choice?["message"]?["content"]) ?? throw new LingException(LingException.Kind.Parse);var finish = Str(choice?["finish_reason"]);diff --git a/windows/src/Cicada.Core/Settings.cs b/windows/src/Cicada.Core/Settings.csindex 1885ba6..d1d0d9a 100644--- a/windows/src/Cicada.Core/Settings.cs+++ b/windows/src/Cicada.Core/Settings.cs@@ -21,6 +21,8 @@ public sealed class AppSettings[JsonPropertyName("aiCustomBase")] public string AiCustomBase { get; set; } = "";[JsonPropertyName("aiCustomVoiceBase")] public string AiCustomVoiceBase { get; set; } = "";[JsonPropertyName("aiCustomVoice")] public string AiCustomVoice { get; set; } = "";+ /// A custom service's hear model at its own address (the Mac's key); empty: the same one.+ [JsonPropertyName("aiCustomHearBase")] public string AiCustomHearBase { get; set; } = "";/// 听哪里 (the Mac's key): "system" (电脑声音), "room" (会议室) or "both" (电脑和会议室).[JsonPropertyName("listenSource")] public string ListenSourceValue { get; set; } = ListenSource.System;[JsonIgnore] public string Listens => ListenSource.Parse(ListenSourceValue);diff --git a/windows/src/Cicada/AICheckView.cs b/windows/src/Cicada/AICheckView.csindex 867db00..4e42a17 100644--- a/windows/src/Cicada/AICheckView.cs+++ b/windows/src/Cicada/AICheckView.cs@@ -66,7 +66,9 @@ static class AICheckViewstatic void Problem(Controller app, AICheck check, StackPanel into, Action changeKey, bool recheckInStep){var ling = app.Ling;- if (check.Message(ling.ServiceName, ling.ServiceHost, ling.Config.TextModel, ling.HearName) is { } why)+ // A hear model at its own address: the one it couldn't reach is that one.+ var host = check.Failure?.Step == AICheck.StepId.Hear ? ling.HearHost : ling.ServiceHost;+ if (check.Message(ling.ServiceName, host, ling.Config.TextModel, ling.HearName) is { } why){var t = Ui.Text(why, 13, check.Failure is null ? Palette.WarnIcon : Palette.Danger);t.Margin = new Thickness(0, 4, 0, 0);diff --git a/windows/src/Cicada/App.cs b/windows/src/Cicada/App.csindex d5ab26b..4936dcd 100644--- a/windows/src/Cicada/App.cs+++ b/windows/src/Cicada/App.cs@@ -993,7 +993,7 @@ sealed class Controllervar c = Ling.Config;return new JsonObject{- ["provider"] = c.Provider.Id, ["base"] = c.Base, ["text"] = c.TextModel, ["hear"] = c.HearModel, ["voice"] = c.VoiceModel,+ ["provider"] = c.Provider.Id, ["base"] = c.Base, ["hearBase"] = c.HearBase, ["text"] = c.TextModel, ["hear"] = c.HearModel, ["voice"] = c.VoiceModel,["state"] = Ling.KeyState.ToString(), ["hears"] = Ling.Hears, ["seconds"] = Ling.Seconds is { } s ? Math.Round(s, 1) : null,["check"] = Ling.Health.Summary,["problem"] = Ling.Health.Message(Ling.ServiceName, Ling.ServiceHost, Ling.Config.TextModel, Ling.HearName),diff --git a/windows/src/Cicada/SettingsWindow.cs b/windows/src/Cicada/SettingsWindow.csindex af09d27..01f6312 100644--- a/windows/src/Cicada/SettingsWindow.cs+++ b/windows/src/Cicada/SettingsWindow.cs@@ -23,6 +23,8 @@ sealed class SettingsWindow : Windowstring? typing;// A custom service's address and models as typed, kept across re-renders until 保存并检查.readonly Dictionary<string, TextBox> customFields = [];+ // 其他(兼容 OpenAI): the per-use rows unfolded ("text", "voice", "hear"); null until the page first shows.+ HashSet<string>? open;/// A pasted key that belongs elsewhere: what it is, and (another service's key) where it fits.(string Text, string? Service, string Key)? keyHint;@@ -34,6 +36,7 @@ sealed class SettingsWindow : WindowBackground = Palette.Page; FontFamily = Palette.Font; Icon = AppIcon.Image;WindowStartupLocation = WindowStartupLocation.CenterScreen;System.Windows.Automation.AutomationProperties.SetName(keyBox, L("API key"));+ keyBox.PasswordChanged += (_, _) => KeyPlaceholder();var grid = new Grid();grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(200) });grid.ColumnDefinitions.Add(new ColumnDefinition());@@ -188,7 +191,7 @@ sealed class SettingsWindow : Windowif (id == "speak") h = Ui.Spread(h, Ui.Switch(app.Settings.Speak, v => { app.Settings.Speak = v; Save(); }, L("同声传译")));// The service menu in the page's header, Ling first and recommended.if (id == "ai") h = Ui.Spread(h, Ui.Choice(AIProvider.All.Select(p => (p.Id, p.Id == "ling" ? "Ling" + L("(推荐)") : L(p.Name))), app.Settings.AiProvider,- v => { editingKey = false; typing = null; keyHint = null; customFields.Clear(); app.SetAIProvider(v); }, 220));+ v => { editingKey = false; typing = null; keyHint = null; customFields.Clear(); open = null; app.SetAIProvider(v); }, 220));h.Margin = new Thickness(0, 0, 0, 20);sections[id] = h;page.Children.Add(h);@@ -296,12 +299,11 @@ sealed class SettingsWindow : Window{var c = app.Ling.Config;var p = c.Provider;- var s = app.Settings;if (p.Id == "custom")- yield return Group(- Card(null, L("地址"), null, CustomField("base", s.AiCustomBase, "https://api.example.com/v1")),- Card(null, L("文字模型"), L("纪要和整句翻译"), CustomField("text", s.AiModels.GetValueOrDefault("custom", ""), L("例如 qwen3:14b"))),- Card(null, L("听的模型"), L("要能输入音频:听对方和“我说”都用它"), CustomField("hear", s.AiHearModels.GetValueOrDefault("custom", ""), L("例如 qwen3-omni"))));+ {+ foreach (var e in CustomCards()) yield return e;+ yield break;+ }yield return KeyCard();var host = (c.Base ?? "").Split("//")[^1].Split('/')[0];if (host.Length == 0) host = L("你填的地址");@@ -377,15 +379,6 @@ sealed class SettingsWindow : Windowyield return Card(null, L("听的模型"), L("Ming 一次识别并翻译"), Ui.Text(c.HearModel, 13, Palette.Tertiary, wrap: false));yield break;}- if (p.Id == "custom")- {- var s = app.Settings;- yield return Card(null, L("声音模型"), L("需支持 /audio/speech;不填则同传用 Windows 的声音"), CustomField("voice", s.AiVoiceModels.GetValueOrDefault("custom", ""), L("例如 kokoro")));- yield return Card(null, L("声音"), null, CustomField("voiceName", s.AiCustomVoice, L("例如 af_heart")));- yield return Card(null, L("地址"), null, CustomField("voiceBase", s.AiCustomVoiceBase, L("跟上面一样")));- yield return Card(null, "", null, Ui.Button(L("保存并检查"), () => _ = SaveKey(), Ui.Kind.Primary, height: 32));- yield break;- }yield return Card(null, L("听的模型"), L("听对方和“我说”都用它"), ModelMenu("hear", c.HearModel, p.HearModels, app.Ling.HearCatalog));yield return Card(null, L("文字模型"), L("纪要和整句翻译"), ModelMenu("text", c.TextModel, p.TextModels, app.Ling.TextCatalog));if (p.HasVoices) yield return Card(null, L("声音模型"), L("同传念给对方"), ModelMenu("voice", c.VoiceModel ?? "", p.VoiceModels, []));@@ -430,6 +423,221 @@ sealed class SettingsWindow : Windowreturn frame;}+ // MARK: Own service++ /// 其他(兼容 OpenAI) (AISettings.swift › customPage): one card with a row per use, each at its+ /// own address if need be (a text model, a hear model and a speech model often run as separate+ /// servers), each saying whether it works and how fast. What isn't set up or doesn't work yet+ /// opens where it needs filling in.+ IEnumerable<FrameworkElement> CustomCards()+ {+ var ling = app.Ling;+ var c = ling.Config;+ var check = ling.Health;+ open ??= !check.Passed || check.Slow ? new HashSet<string> { "text" } : new HashSet<string>();+ var intro = Ui.Helper(L("每样可以接不同的机器;这台电脑和局域网里的服务可以用 http。"));+ intro.Margin = new Thickness(6, -8, 0, 0);+ yield return intro;+ yield return Group(TextSection(), VoiceSection(), HearSection());+ var host = ling.ServiceHost.Length > 0 ? ling.ServiceHost : L("你填的地址");+ var lockLine = Ui.Helper(LF("仅保存在本机当前账户下,仅发送至 %@", host));+ lockLine.Margin = new Thickness(6, -4, 0, 0);+ yield return lockLine;+ // What it costs depends on where it runs; what is sent where is the port's own line (it hears through the service).+ var cost = c.Base is { } b && AIProvider.IsNearby(b) ? L("跑在你自己的机器上,不按量计费。") : L("费用以这个服务为准。");+ var foot = Ui.Helper(cost + LF("听的时候,电脑里的声音会发给 %@。", ling.HearHost.Length > 0 ? ling.HearHost : L("你填的地址")));+ foot.Margin = new Thickness(6, 0, 0, 0);+ yield return foot;+ }++ /// A row that opens to its fields: a state dot, the use, what it runs on, and how it's doing.+ FrameworkElement SectionHeader(string id, string title, string detail, Brush dot, string? trailing, Brush? trailingColor = null)+ {+ var isOpen = open!.Contains(id);+ var dock = new DockPanel { MinHeight = 40, Margin = new Thickness(0, 10, 0, 10), Background = Brushes.Transparent, Cursor = System.Windows.Input.Cursors.Hand };+ var chevron = Ui.Text(isOpen ? "⌄" : "›", 15, Palette.Secondary, wrap: false);+ chevron.VerticalAlignment = VerticalAlignment.Center; chevron.Margin = new Thickness(12, 0, 0, 0);+ DockPanel.SetDock(chevron, Dock.Right);+ dock.Children.Add(chevron);+ if (trailing is not null)+ {+ var t = Ui.Text(trailing, 13, trailingColor ?? Palette.Tertiary, wrap: false);+ t.VerticalAlignment = VerticalAlignment.Center; t.Margin = new Thickness(12, 0, 0, 0);+ DockPanel.SetDock(t, Dock.Right);+ dock.Children.Add(t);+ }+ var d = Ui.Dot(dot);+ d.Margin = new Thickness(0, 0, 12, 0);+ DockPanel.SetDock(d, Dock.Left);+ dock.Children.Add(d);+ var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ text.Children.Add(Ui.Text(title, 14, Palette.Ink));+ var sub = Ui.Text(detail, 12, Palette.Secondary, wrap: false);+ sub.TextTrimming = TextTrimming.CharacterEllipsis; sub.Margin = new Thickness(0, 2, 0, 0);+ text.Children.Add(sub);+ dock.Children.Add(text);+ dock.MouseLeftButtonUp += (_, _) => { if (!open.Remove(id)) open.Add(id); Render(); };+ System.Windows.Automation.AutomationProperties.SetName(dock, title);+ return dock;+ }++ /// A row's fields, under its title.+ static FrameworkElement Body(params FrameworkElement[] parts)+ {+ var s = new StackPanel { Margin = new Thickness(20, 0, 0, 12) };+ foreach (var x in parts) s.Children.Add(x);+ return s;+ }++ static FrameworkElement Line(string text, Brush color)+ {+ var t = Ui.Text(text, 13, color);+ t.Margin = new Thickness(0, 4, 0, 4);+ return t;+ }++ FrameworkElement SaveButton()+ {+ var check = app.Ling.Health;+ var b = Ui.Button(check.IsRunning ? L("正在检查…") : L("保存并检查"), () => _ = SaveKey(), Ui.Kind.Primary, height: 32);+ b.IsEnabled = !check.IsRunning;+ return b;+ }++ static string Secs(double s) => s.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture);++ /// 翻译和纪要: the address, the text model (a menu once the service listed its models), the key,+ /// how long a sentence took and whether the model thinks; the steps when something failed.+ FrameworkElement TextSection()+ {+ var ling = app.Ling;+ var c = ling.Config;+ var s = app.Settings;+ var check = ling.Health;+ var textFailed = check.Failure is { Step: not AICheck.StepId.Hear };+ var detail = ling.ServiceHost.Length == 0 || c.TextModel.Length == 0 ? L("填上地址和模型") : $"{ling.ServiceHost} · {c.TextModel}";+ var trailing = check.IsRunning ? L("正在检查…")+ : textFailed && ling.HasKey ? AICheckView.Status(check)+ : check.Translate is { } sp ? LF("翻一句 %@ 秒", Secs(sp.Seconds)) : null;+ Brush dot = !ling.HasKey ? Palette.Toggle : check.IsRunning ? Palette.Live : textFailed ? Palette.Danger+ : check.Slow || check.IsBusy ? Palette.WarnIcon : check.Passed ? Palette.Success : Palette.Toggle;+ var header = SectionHeader("text", L("翻译和纪要"), detail, dot, trailing, check.Slow ? Palette.WarnIcon : textFailed ? Palette.Danger : null);+ if (!open!.Contains("text")) return header;+ FrameworkElement model;+ if (ling.TextCatalog.Count > 0)+ {+ // The models the service lists: picking one saves and checks it.+ customFields.Remove("text");+ model = ModelMenu("text", c.TextModel, [], ling.TextCatalog);+ }+ else model = CustomField("text", s.AiModels.GetValueOrDefault("custom", ""), L("例如 qwen3:14b"));+ var parts = new List<FrameworkElement>+ {+ Card(null, L("地址"), null, CustomField("base", s.AiCustomBase, "http://192.168.1.20:8000/v1")),+ Card(null, L("模型"), null, model),+ Card(null, "key", null, CustomKey()),+ };+ if (check.SlowLine() is { } slow) parts.Add(Line(slow, Palette.WarnIcon));+ var key = ling.CurrentKey();+ if (key is not null && (check.IsRunning || textFailed || check.IsBusy || check.At is not null && !check.Passed && check.Failure is null))+ parts.Add(AICheckView.Steps(app, ChangeKey, recheckInStep: false));+ else if (check.At is not null && !check.IsRunning && check.Failure is null or { Step: AICheck.StepId.Hear })+ {+ var facts = new List<string> { L("能写纪要") };+ if (check.Translate is { } t) facts.Add(t.Thinks ? L("会先思考") : L("不思考"));+ parts.Add(Line(string.Join(" · ", facts), Palette.Tertiary));+ }+ return new StackPanel { Children = { header, Body([.. parts]) } };+ }++ // The grey hint in a custom service's key field (a PasswordBox has none), shown while it's empty.+ TextBlock? keyPlaceholder;+ void KeyPlaceholder() { if (keyPlaceholder is { } h) h.Visibility = keyBox.Password.Length == 0 ? Visibility.Visible : Visibility.Collapsed; }++ /// The key of a custom service: optional on this computer and the local network.+ FrameworkElement CustomKey()+ {+ var saved = app.Key.Read();+ if (saved is { Length: > 0 } && !editingKey)+ return Ui.Row(8, Ui.Text(AIKey.Masked(saved), 13, Palette.Ink, wrap: false),+ Ui.Button(L("更换"), ChangeKey, height: 32),+ Ui.Button(L("删除"), () => { app.Key.Remove(); app.AIChanged(); }, height: 32),+ SaveButton());+ if (keyBox.Parent is Panel old) old.Children.Remove(keyBox);+ if (keyBox.Parent is Border oldBorder) oldBorder.Child = null;+ var typed = customFields.TryGetValue("base", out var b) ? b.Text : app.Settings.AiCustomBase;+ var hint = Ui.Text(AIProvider.IsNearby(typed) ? L("本机和局域网服务可不填") : "sk-…", 14, Palette.Tertiary, wrap: false);+ hint.IsHitTestVisible = false; hint.VerticalAlignment = VerticalAlignment.Center;+ keyPlaceholder = hint;+ KeyPlaceholder();+ Ui.StyleField(keyBox);+ var frame = Ui.FieldFrame(new Grid { Children = { keyBox, hint } }, keyBox);+ frame.Width = 200; frame.Height = 34;+ return Ui.Row(8, frame, SaveButton());+ }++ /// 同传声音: a speech model (`/audio/speech`), its voice and address; else Windows speaks.+ FrameworkElement VoiceSection()+ {+ var ling = app.Ling;+ var c = ling.Config;+ var s = app.Settings;+ var voiceModel = s.AiVoiceModels.GetValueOrDefault("custom", "").Trim();+ var host = c.VoiceBase is { } vb && Uri.TryCreate(vb, UriKind.Absolute, out var u) ? u.Host : ling.ServiceHost;+ var detail = voiceModel.Length == 0 ? L("没填,用 Windows 的声音")+ : string.Join(" · ", new[] { host, voiceModel, s.AiCustomVoice.Trim() }.Where(x => x.Length > 0));+ var last = ling.LastVoice;+ Brush dot = voiceModel.Length == 0 || last is null ? Palette.Toggle : last.Value.Ok ? Palette.Success : Palette.Danger;+ var trailing = voiceModel.Length == 0 ? L("本机") : last is { } l ? (l.Ok ? L("上次正常") : L("上次没出声")) : null;+ var header = SectionHeader("voice", L("同传声音"), detail, dot, trailing, last is { Ok: false } ? Palette.Danger : null);+ if (!open!.Contains("voice")) return header;+ return new StackPanel+ {+ Children =+ {+ header,+ Body(Line(L("需支持 /audio/speech;不填则同传用 Windows 的声音"), Palette.Tertiary),+ Card(null, L("模型"), null, CustomField("voice", voiceModel, L("例如 kokoro"))),+ Card(null, L("声音"), null, CustomField("voiceName", s.AiCustomVoice, L("例如 af_heart"))),+ Card(null, L("地址"), null, CustomField("voiceBase", s.AiCustomVoiceBase, L("跟上面一样"))),+ Card(null, "", null, SaveButton())),+ },+ };+ }++ /// 听对方: the hear model (it takes audio in: listening and 我说 both use it) and its own+ /// address if it runs elsewhere; the status is the check's hear step.+ FrameworkElement HearSection()+ {+ var ling = app.Ling;+ var c = ling.Config;+ var s = app.Settings;+ var check = ling.Health;+ var state = check[AICheck.StepId.Hear];+ var detail = c.HearModel.Length == 0 ? L("还没填好") : string.Join(" · ", new[] { ling.HearHost, c.HearModel }.Where(x => x.Length > 0));+ Brush dot = c.HearModel.Length == 0 ? Palette.Toggle : state.Kind switch+ {+ AICheck.Kind.Ok => Palette.Success,+ AICheck.Kind.Busy => Palette.WarnIcon,+ AICheck.Kind.Fail => Palette.Danger,+ AICheck.Kind.Running => Palette.Live,+ _ => Palette.Toggle,+ };+ var trailing = state is { Kind: AICheck.Kind.Ok, Seconds: { } sec } ? LF("听 %@ 秒", Secs(sec)) : state.Kind == AICheck.Kind.Fail ? L("听不了声音") : null;+ var header = SectionHeader("hear", L("听对方"), detail, dot, trailing, state.Kind == AICheck.Kind.Fail ? Palette.Danger : null);+ if (!open!.Contains("hear")) return header;+ var parts = new List<FrameworkElement>+ {+ Line(L("要能输入音频:听对方和“我说”都用它"), Palette.Tertiary),+ Card(null, L("模型"), null, CustomField("hear", s.AiHearModels.GetValueOrDefault("custom", ""), L("例如 qwen3-omni"))),+ Card(null, L("地址"), null, CustomField("hearBase", s.AiCustomHearBase, L("跟上面一样"))),+ };+ if (check.Failure is { Step: AICheck.StepId.Hear } && check.Message(ling.ServiceName, ling.HearHost, c.TextModel, ling.HearName) is { } why)+ parts.Add(Line(why, Palette.Danger));+ parts.Add(Card(null, "", null, SaveButton()));+ return new StackPanel { Children = { header, Body([.. parts]) } };+ }+FrameworkElement KeyCard(){var ling = app.Ling;@@ -508,6 +716,7 @@ sealed class SettingsWindow : Windows.AiVoiceModels["custom"] = F("voice", s.AiVoiceModels.GetValueOrDefault("custom", ""));s.AiCustomVoice = F("voiceName", s.AiCustomVoice);s.AiCustomVoiceBase = F("voiceBase", s.AiCustomVoiceBase);+ s.AiCustomHearBase = F("hearBase", s.AiCustomHearBase);s.Save();}var text = keyBox.Password.Trim();diff --git a/windows/src/Cicada/Strings/en.lproj/Windows.strings b/windows/src/Cicada/Strings/en.lproj/Windows.stringsindex 8fb6596..4e2e59e 100644--- a/windows/src/Cicada/Strings/en.lproj/Windows.strings+++ b/windows/src/Cicada/Strings/en.lproj/Windows.strings@@ -312,3 +312,6 @@"也听电脑" = "Hear the PC too";"电脑里放出来的" = "Played on the PC";"%@。点按去设置" = "%@. Click to open Settings";+"每样可以接不同的机器;这台电脑和局域网里的服务可以用 http。" = "Each can use a different machine; services on this PC or your local network can use http.";+"没填,用 Windows 的声音" = "Not set: the Windows voice";+"地址要用 https;这台电脑和局域网里的服务可以用 http。" = "The address must use https; services on this PC or your local network can use http.";diff --git a/windows/src/Cicada/Strings/ja.lproj/Windows.strings b/windows/src/Cicada/Strings/ja.lproj/Windows.stringsindex 62ac152..6a7a53d 100644--- a/windows/src/Cicada/Strings/ja.lproj/Windows.strings+++ b/windows/src/Cicada/Strings/ja.lproj/Windows.strings@@ -312,3 +312,6 @@"也听电脑" = "PC も聞く";"电脑里放出来的" = "PC で再生された音声";"%@。点按去设置" = "%@。クリックして設定を開く";+"每样可以接不同的机器;这台电脑和局域网里的服务可以用 http。" = "それぞれ別のマシンを使えます。この PC やローカルネットワークのサービスは http も使えます。";+"没填,用 Windows 的声音" = "未設定:Windows の音声";+"地址要用 https;这台电脑和局域网里的服务可以用 http。" = "アドレスは https にしてください。この PC やローカルネットワークのサービスは http も使えます。";diff --git a/windows/src/Cicada/Strings/ko.lproj/Windows.strings b/windows/src/Cicada/Strings/ko.lproj/Windows.stringsindex 35c4920..40400fb 100644--- a/windows/src/Cicada/Strings/ko.lproj/Windows.strings+++ b/windows/src/Cicada/Strings/ko.lproj/Windows.strings@@ -312,3 +312,6 @@"也听电脑" = "PC도 듣기";"电脑里放出来的" = "PC에서 재생된 소리";"%@。点按去设置" = "%@. 클릭하여 설정 열기";+"每样可以接不同的机器;这台电脑和局域网里的服务可以用 http。" = "기능마다 다른 컴퓨터를 쓸 수 있습니다. 이 PC나 로컬 네트워크의 서비스는 http도 쓸 수 있습니다.";+"没填,用 Windows 的声音" = "설정 안 함: Windows 음성";+"地址要用 https;这台电脑和局域网里的服务可以用 http。" = "주소는 https여야 합니다. 이 PC나 로컬 네트워크의 서비스는 http도 쓸 수 있습니다.";diff --git a/windows/tests/Cicada.Tests/Program.cs b/windows/tests/Cicada.Tests/Program.csindex c8cfda0..663b916 100644--- a/windows/tests/Cicada.Tests/Program.cs+++ b/windows/tests/Cicada.Tests/Program.cs@@ -1444,6 +1444,143 @@ static class TestsEqual(null, AIProvider.CustomBase(" "), "nothing");}+ public static void TheLocalNetworkMayUsePlainHttp()+ {+ foreach (var ok in new[] { "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://GPU.LOCAL/v1", "http://[fd12:3456::1]:8000/v1", "http://[fe80::1]/v1", "http://[::1]:8000/v1" })+ Check(AIProvider.CustomBase(ok)?.StartsWith("http://") == true, ok);+ foreach (var no in new[] { "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://[2001:db8::1]/v1" })+ Equal(null, AIProvider.CustomBase(no), no);+ Equal("http://192.168.1.20:8000/v1/", AIProvider.CustomBase("192.168.1.20:8000/v1"), "no scheme on the local network: http");+ Equal("https://10.0.0.5.evil.com/v1/", AIProvider.CustomBase("10.0.0.5.evil.com/v1"), "a name that looks like one: https");+ Check(AIProvider.IsNearby("http://192.168.1.20:8000/v1/") && !AIProvider.IsLocal("http://192.168.1.20:8000/v1/"), "nearby but not this computer");+ var (ling, s) = Using(new Service((_, _) => Reply("ok")), "custom", key: null, new AppSettings { AiCustomBase = "http://192.168.1.20:8000/v1" });+ Equal("", ling.CurrentKey(), "a service on the local network needs no key");+ }++ public static void ACustomHearModelMayHaveItsOwnAddress()+ {+ var s = new AppSettings { AiProvider = "custom", AiCustomBase = "http://192.168.1.20:8000/v1", AiHearModels = { ["custom"] = "qwen3-omni" } };+ Equal("http://192.168.1.20:8000/v1/", s.AIConfig().HearBase, "empty: the text model's address");+ Check(!s.AIConfig().HearElsewhere, "same address");+ s.AiCustomHearBase = "192.168.1.21:8001/v1";+ Equal("http://192.168.1.21:8001/v1/", s.AIConfig().HearBase, "its own");+ Check(s.AIConfig().HearElsewhere, "elsewhere");+ s.AiCustomHearBase = "http://example.com/v1";+ Equal(null, s.AIConfig().HearBase, "http off the local network is no address");+ Equal("https://zenmux.ai/api/v1/", new AppSettings { AiProvider = "zenmux" }.AIConfig().HearBase, "other services: theirs");+ Equal("https://api.ant-ling.com/v1/", new AppSettings().AIConfig().HearBase, "Ling");+ // Not reaching a hear server of its own says nothing about the text address.+ Equal((AICheck.StepId.Hear, AICheck.Reason.Unreachable, (int?)null), AICheck.Classify(LingException.Kind.Network, 0, AICheck.StepId.Hear, hearElsewhere: true), "hear elsewhere");+ Equal((AICheck.StepId.Reach, AICheck.Reason.Unreachable, (int?)null), AICheck.Classify(LingException.Kind.Timeout, 0, AICheck.StepId.Hear), "same address");+ }++ public static void ACustomServiceIsAskedNotToThink()+ {+ var c = new AppSettings { AiProvider = "custom", AiCustomBase = "https://x.example/v1" }.AIConfig();+ var body = new JsonObject();+ c.Shape(body, 50);+ Equal("{\"enable_thinking\":false}", body["chat_template_kwargs"]?.ToJsonString(), "Qwen3 on vLLM / SGLang / llama.cpp");+ var plain = new JsonObject();+ c.Shape(plain, 50, templateKwargs: false);+ Check(plain["chat_template_kwargs"] is null, "left out for a server that refused it");+ var zen = new JsonObject();+ new AppSettings { AiProvider = "zenmux" }.AIConfig().Shape(zen, 50);+ Check(zen["chat_template_kwargs"] is null, "only a custom service");+ }++ public static void AThinkingModelIsSeenFromItsReply()+ {+ static JsonNode R(string message, string? usage = null) => JsonNode.Parse($"{{\"choices\":[{{\"message\":{message}}}]{(usage is null ? "" : ",\"usage\":" + usage)}}}")!;+ Check(!AIConfig.Thought(R("{\"content\":\"周五发布。\"}")), "a plain answer");+ Check(AIConfig.Thought(R("{\"content\":\"周五发布。\",\"reasoning_content\":\"The user wants…\"}")), "reasoning_content");+ Check(AIConfig.Thought(R("{\"content\":null,\"reasoning_content\":\"周五发布。\"}")), "the answer in reasoning_content");+ Check(AIConfig.Thought(R("{\"content\":\"周五发布。\",\"reasoning\":\"hmm\"}")), "reasoning");+ Check(AIConfig.Thought(R("{\"content\":\"<think>hmm</think>周五发布。\"}")), "<think>");+ Check(AIConfig.Thought(R("{\"content\":\"周五发布。\"}", "{\"completion_tokens_details\":{\"reasoning_tokens\":212}}")), "reasoning tokens");+ Check(!AIConfig.Thought(R("{\"content\":\"周五发布。\",\"reasoning_content\":\" \"}", "{\"completion_tokens_details\":{\"reasoning_tokens\":0}}")), "blank and zero");+ Check(!AIConfig.Thought(null), "no reply");+ Check(!new AICheck.Speed(0.4, false).Slow && new AICheck.Speed(0.4, true).Slow && new AICheck.Speed(3.0, false).Slow, "slow: thinks, or 3 s and more");+ }++ public static async Task ACustomCheckTranslatesASentenceAndRetriesWithoutKwargs()+ {+ var old = LingClient.Spacing; LingClient.Spacing = 0;+ try+ {+ // A strict gateway refuses chat_template_kwargs; the model thinks, its answer in reasoning_content.+ var fake = new Service((url, body) =>+ body.Contains("chat_template_kwargs") ? Status(400)+ : url.EndsWith("/models") ? Status(404)+ : body.Contains("input_audio") ? Reply("NONE")+ : new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{\"choices\":[{\"message\":{\"content\":null,\"reasoning_content\":\"我们将在周五发布。\"},\"finish_reason\":\"stop\"}]}") });+ var (ling, s) = Using(fake, "custom", key: null, new AppSettings+ {+ AiCustomBase = "http://192.168.1.20:8000/v1", AiCustomHearBase = "http://192.168.1.21:8001/v1",+ AiModels = { ["custom"] = "qwen3" }, AiHearModels = { ["custom"] = "qwen3-omni" },+ });+ await ling.Check();+ var first = fake.Sent[0];+ Check(first.url == "http://192.168.1.20:8000/v1/chat/completions" && first.body.Contains("chat_template_kwargs") && first.body.Contains("design review"), "a real sentence, thinking off");+ Check(!fake.Sent[1].body.Contains("chat_template_kwargs") && fake.Sent[1].body.Contains("design review"), "asked again without it");+ const string text = "http://192.168.1.20:8000/v1/chat/completions", hear = "http://192.168.1.21:8001/v1/chat/completions";+ Check(fake.Sent.Skip(2).Where(x => x.url == text).All(x => !x.body.Contains("chat_template_kwargs")), "and not sent it again");+ var heard = fake.Sent.Where(x => x.url == hear).ToList();+ Check(heard.Count == 2 && heard[0].body.Contains("input_audio") && heard[0].body.Contains("chat_template_kwargs") && !heard[1].body.Contains("chat_template_kwargs"),+ "the hear model at its own address, which refused it on its own");+ Check(ling.Health.Translate is { Thinks: true } && ling.Health.Slow, ling.Health.Summary);+ Check(ling.Health.SlowLine()!.Contains("先思考"), "says why");+ Equal(AICheck.Kind.Ok, ling.Health[AICheck.StepId.Hear].Kind, "hears");+ ling.KeyChanged();+ fake.Sent.Clear();+ try { await ling.Chat("x", "Translate.", Priority.Translate); } catch (LingException) { } // its answer is all reasoning+ Check(fake.Sent[0].body.Contains("chat_template_kwargs"), "settings changed: tried again");+ }+ finally { LingClient.Spacing = old; }+ }++ public static async Task AHearServerRefusingKwargsLeavesTheTextServerAlone()+ {+ var old = LingClient.Spacing; LingClient.Spacing = 0;+ try+ {+ var fake = new Service((url, body) => url.Contains(":8001/") && body.Contains("chat_template_kwargs") ? Status(422) : url.EndsWith("/models") ? Status(404) : Reply("周五发布。"));+ var (ling, _) = Using(fake, "custom", key: null, new AppSettings+ {+ AiCustomBase = "http://192.168.1.20:8000/v1", AiCustomHearBase = "http://192.168.1.21:8001/v1",+ AiModels = { ["custom"] = "qwen3" }, AiHearModels = { ["custom"] = "qwen3-omni" },+ });+ await ling.Check();+ Equal(AICheck.Kind.Ok, ling.Health[AICheck.StepId.Hear].Kind, "heard on the retry");+ fake.Sent.Clear();+ await ling.Chat("x", "Translate.", Priority.Translate);+ Check(fake.Sent.Single().body.Contains("chat_template_kwargs"), "the text server still gets it");+ Check(ling.Health.Translate is { Thinks: false } && !ling.Health.Slow, ling.Health.Summary);+ }+ finally { LingClient.Spacing = old; }+ }++ public static async Task ANoKeyCheckOutranksAnOlderSlowOne()+ {+ var old = LingClient.Spacing; LingClient.Spacing = 0;+ try+ {+ var gate = new TaskCompletionSource();+ var fake = new Service((_, _) => { gate.Task.Wait(); return Reply("周五发布。"); });+ var (ling, s) = Using(fake, "custom", key: null, new AppSettings { AiCustomBase = "http://localhost:8000/v1", AiModels = { ["custom"] = "m" } });+ var slow = Task.Run(ling.Check);+ while (fake.Sent.Count == 0) await Task.Delay(5);+ s.AiCustomBase = "https://api.example.com/v1"; // remote now, and no key+ await ling.Check();+ gate.SetResult();+ await slow;+ Equal(KeyState.None, ling.KeyState, "the newer \"no key\" stays");+ Check(ling.Health.At is null, "the older check dropped");+ }+ finally { LingClient.Spacing = old; }+ }+public static void SettingsKeepTheServiceAcrossARestart(){new AppSettings { AiProvider = "zenmux", AiHearModels = { ["zenmux"] = "bytedance/doubao-seed-2.0-mini" } }.Save();