知了 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): when the AI service fails, Settings shows which step broke and how to fix it
wquguru1664a7409aeb
diff --git a/windows/scripts/cicadactl.ps1 b/windows/scripts/cicadactl.ps1index 48937d3..bc153ec 100644--- a/windows/scripts/cicadactl.ps1+++ b/windows/scripts/cicadactl.ps1@@ -1,6 +1,7 @@# Sends one debug command to a running dev build (Cicada.exe --dev) and prints its JSON state.# .\cicadactl.ps1 state | start | stop | end | notesproblem failed | sample | feed C:\clip.wav | view subtitles | capture on | show records | quit# AI 服务: provider ling|openrouter|zenmux|custom | ai-model hear|text|voice <id> | show settings ai models+# AI 服务检查: ai-check | ai-check-sim <unreachable|invalidKey|noCredit|mgmtKey|noModel|noJSON|deaf|busy|serverError|lowBalance|off> (state › ai.check: every step)# 结束会议: calls zoom.exe=Zoom|none|real | realcalls | endtimes <silence> <countdown> <grace>|off | endkeepparam([Parameter(ValueFromRemainingArguments = $true)][string[]]$Command)$pipe = New-Object System.IO.Pipes.NamedPipeClientStream(".", "cicada-dev", [System.IO.Pipes.PipeDirection]::InOut)diff --git a/windows/src/Cicada.Cli/Program.cs b/windows/src/Cicada.Cli/Program.csindex 93845d1..5cc62b3 100644--- a/windows/src/Cicada.Cli/Program.cs+++ b/windows/src/Cicada.Cli/Program.cs@@ -61,9 +61,12 @@ switch (args_[0]){var ling = Client();var (state, seconds) = await ling.Check();- var problem = ling.Problem is { } p ? Strings.LF(p.Key, p.Args) : "-";- Console.WriteLine($"{provider}: {state} in {seconds:F1} s, text {ling.Config.TextModel} {ling.Seconds:F1} s, hears={ling.Hears?.ToString() ?? "?"} ({ling.Config.HearModel}), catalog {ling.TextCatalog.Count}/{ling.HearCatalog.Count}, problem {problem}");- return state == KeyState.Ok ? 0 : 1;+ var h = ling.Health;+ var problem = h.Message(ling.ServiceName, ling.ServiceHost, ling.Config.TextModel, ling.HearName) ?? "-";+ Console.WriteLine($"{provider}: {state} in {seconds:F1} s, text {ling.Config.TextModel}, hear {ling.Config.HearModel}, catalog {ling.TextCatalog.Count}/{ling.HearCatalog.Count}");+ Console.WriteLine($" {h.Summary}");+ Console.WriteLine($" problem {problem}{(h.ProxyLine(ling.ServiceName, ling.ServiceHost) is { } px ? " / " + px : "")}");+ return h.Passed ? 0 : 1;}case "speak":{diff --git a/windows/src/Cicada.Core/AICheck.cs b/windows/src/Cicada.Core/AICheck.csnew file mode 100644index 0000000..a7afd47--- /dev/null+++ b/windows/src/Cicada.Core/AICheck.cs@@ -0,0 +1,312 @@+using System.Net.Sockets;+using System.Text.Json.Nodes;++namespace Cicada;++/// What the last look at the AI service found, step by step (the Mac's AICheck.swift): can this+/// computer reach it, does it take the key, does the text model answer, and, on the ports, does the+/// hear model take audio. A failed step stops the ones after it, so the settings can say exactly+/// where it broke and offer the one thing that fixes it.+///+/// Most of the time the answer comes from real requests (hearing, notes, translation): every call+/// reports back, so a meeting keeps the steps current without any extra request. An explicit check+/// runs only when the service, model or key changes, at launch, on 重新检查, before 开始听 when the+/// service was unreachable, and when the network changes after it was unreachable.+///+/// A value: LingClient changes a copy and swaps it in, since requests report from worker threads.+public sealed class AICheck+{+ /// In order. Hear is the ports' own: they hear through the service (the Mac recognizes on the device).+ public enum StepId { Reach, Key, Text, Hear }++ public enum Reason { Unreachable, BadAddress, InvalidKey, MgmtKey, NoCredit, NoModel, NoJSON, Deaf, Busy, ServerError }++ public enum Kind { Running, Ok, Busy, Fail, Skipped, Untested }++ /// One step's state. `Seconds`: the request that proved it (null when it came with another+ /// step's request). Busy (429): the service is busy but the key works; it counts as passed.+ public readonly record struct State(Kind Kind, double? Seconds = null, Reason? Why = null, int? Code = null)+ {+ public static State Ok(double? seconds = null) => new(Kind.Ok, seconds);+ public static State Fail(Reason why, int? code = null) => new(Kind.Fail, null, why, code);+ public static readonly State Busy = new(Kind.Busy);+ public static readonly State Skipped = new(Kind.Skipped);+ public static readonly State Running = new(Kind.Running);+ public static readonly State Untested = new(Kind.Untested);+ }++ public enum ProxyKind { SystemOn, AppRunning, None }++ /// Where the proxy stands when the service can't be reached: only read, to word the hint.+ /// SystemOn: a system proxy is on and it still can't connect; AppRunning: nothing in the system+ /// settings, but a proxy app listens on `Port`.+ public readonly record struct ProxyHint(ProxyKind Kind, int Port = 0)+ {+ public override string ToString() => Kind == ProxyKind.AppRunning ? $"appRunning({Port})" : Kind == ProxyKind.SystemOn ? "systemOn" : "none";+ }++ public static readonly StepId[] Order = [StepId.Reach, StepId.Key, StepId.Text, StepId.Hear];++ readonly State[] steps = [State.Untested, State.Untested, State.Untested, State.Untested];+ /// When the newest result came in.+ public DateTimeOffset? At { get; set; }+ /// The newest result came from a real request in a meeting, not from a check.+ public bool Passive { get; set; }+ public 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; }++ public const double LowBalance = 0.5;++ public State this[StepId id]+ {+ get => steps[(int)id];+ set => steps[(int)id] = value;+ }++ public IEnumerable<(StepId Id, State State)> Steps => Order.Select(id => (id, steps[(int)id]));++ public AICheck Clone()+ {+ var c = new AICheck { At = At, Passive = Passive, Proxy = Proxy, Balance = Balance };+ steps.CopyTo(c.steps, 0);+ return c;+ }++ /// The same states and reasons; how many seconds a request took doesn't count.+ public bool SameSteps(AICheck other) => steps.Zip(other.steps).All(p => p.First with { Seconds = null } == p.Second with { Seconds = null });++ /// The first step that failed, and why.+ public (StepId Step, Reason Why, int? Code)? Failure+ {+ get+ {+ foreach (var id in Order) if (steps[(int)id] is { Kind: Kind.Fail, Why: { } r } s) return (id, r, s.Code);+ return null;+ }+ }++ public bool IsRunning => steps.Any(s => s.Kind == Kind.Running);+ public bool IsBusy => steps.Any(s => s.Kind == Kind.Busy);+ /// Every step passed (busy counts; a step nothing has tested yet does not block).+ public bool Passed => At is not null && Failure is null && !IsRunning;+ public bool IsLowBalance => (Balance ?? double.PositiveInfinity) < LowBalance;++ /// Something only the user can fix (a busy service or a server error fixes itself).+ public bool NeedsUser => Failure is { } f ? f.Why is not (Reason.Busy or Reason.ServerError) : IsLowBalance;++ /// Whether a request to `later` must have got past `step`: the hear model's request proves the+ /// address and the key, not the text model, and the text model's says nothing about hearing.+ static bool Needs(StepId later, StepId step) => later == StepId.Hear ? step is StepId.Reach or StepId.Key : step < later;++ /// `step` failed and the steps that need it were never reached. `reached`: a reply came back,+ /// so the steps it needs passed (false when nothing was sent, like a management key).+ public void Fail(StepId step, Reason why, int? code = null, bool reached = true)+ {+ foreach (var id in Order)+ {+ if (id == step) steps[(int)id] = State.Fail(why, code);+ else if (Needs(id, step)) steps[(int)id] = State.Skipped;+ else if (reached && Needs(step, id) && steps[(int)id].Kind != Kind.Ok) steps[(int)id] = State.Ok();+ }+ if (why != Reason.Unreachable) Proxy = null;+ }++ /// One request proved `step` and the steps it needs (a chat proves the address, the key and+ /// the text model). Clears what failed before; steps that need it and were skipped are open again.+ public void Pass(StepId step, double? seconds)+ {+ foreach (var id in Order)+ {+ if (id == step) steps[(int)id] = State.Ok(seconds);+ else if (Needs(step, id) && steps[(int)id].Kind != Kind.Ok) steps[(int)id] = State.Ok();+ }+ // Skipped because a step it needs failed; now nothing it needs has failed.+ foreach (var id in Order)+ if (steps[(int)id].Kind == Kind.Skipped && !Order.Any(n => Needs(id, n) && steps[(int)n].Kind == Kind.Fail)) steps[(int)id] = State.Untested;+ Proxy = null;+ }++ /// A 429 on `step`: the steps it needs passed, and it is busy (not a failure).+ public void Busy(StepId step)+ {+ Pass(step, null);+ steps[(int)step] = State.Busy;+ }++ /// 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+ {+ 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),+ LingException.Kind.Http when status == 402 => (StepId.Key, Reason.NoCredit, 402),+ // A hear model that refuses audio answers 400, 404, 415 or 422 (HearsAudio).+ LingException.Kind.Http when step == StepId.Hear && status is 400 or 404 or 415 or 422 => (StepId.Hear, Reason.Deaf, status),+ LingException.Kind.Http when step == StepId.Text && status is 400 or 404 => (StepId.Text, Reason.NoModel, status),+ LingException.Kind.Http => (step, Reason.ServerError, status),+ _ => null,+ };++ /// The prefix of a key says whose it is: `sk-or-` OpenRouter, `sk-payg` ZenMux, `sk-mgmt` ZenMux's+ /// management key (it can't call models). Null: nothing to tell.+ public static (string Service, bool Management)? Owner(string key)+ {+ var k = key.Trim();+ if (k.StartsWith("sk-or-")) return ("openrouter", false);+ if (k.StartsWith("sk-payg")) return ("zenmux", false);+ if (k.StartsWith("sk-mgmt")) return ("zenmux", true);+ return null;+ }++ /// Model ids in a `/models` reply, as listed (null when the reply can't be read or lists none).+ public static HashSet<string>? ListedModels(string json)+ {+ JsonNode? root;+ try { root = JsonNode.Parse(json); } catch (System.Text.Json.JsonException) { return null; }+ if (root is not JsonObject o || o["data"] is not JsonArray data) return null;+ var ids = data.OfType<JsonObject>().Select(m => m["id"] is JsonValue v && v.TryGetValue<string>(out var s) ? s : null).OfType<string>().ToHashSet();+ return ids.Count == 0 ? null : ids;+ }++ /// The models in a `/models` reply that say they take audio in. Null when none says anything+ /// about its input (a custom service): then the list proves nothing about hearing.+ public static HashSet<string>? ListedHearing(string json)+ {+ JsonNode? root;+ try { root = JsonNode.Parse(json); } catch (System.Text.Json.JsonException) { return null; }+ if (root is not JsonObject o || o["data"] is not JsonArray data) return null;+ bool told = false;+ var ids = new HashSet<string>();+ foreach (var m in data.OfType<JsonObject>())+ {+ var ins = m["input_modalities"] ?? (m["architecture"] as JsonObject)?["input_modalities"];+ if (ins is not JsonArray a) continue;+ told = true;+ if (a.Any(x => x is JsonValue v && v.TryGetValue<string>(out var s) && s == "audio") && m["id"] is JsonValue idv && idv.TryGetValue<string>(out var id)) ids.Add(id);+ }+ return told ? ids : null;+ }++ /// OpenRouter: dollars left from `/key` (`limit_remaining`, null without a key limit) and+ /// `/credits` (bought minus used); the smaller one is what the next meeting can spend.+ public static double? BalanceFrom(string? key, string? credits)+ {+ static JsonObject? Data(string? json)+ {+ if (json is null) return null;+ try { return JsonNode.Parse(json)?["data"] as JsonObject; } catch (System.Text.Json.JsonException) { return null; }+ }+ static double? Num(JsonNode? n) => n is JsonValue v && v.TryGetValue<double>(out var d) ? d : null;+ var k = Num(Data(key)?["limit_remaining"]);+ double? c = null;+ if (Data(credits) is { } d && Num(d["total_credits"]) is { } total && Num(d["total_usage"]) is { } used) c = total - used;+ return k is { } a && c is { } b ? Math.Min(a, b) : k ?? c;+ }++ // MARK: Words (Chinese keys, localized here: the Mac's own strings, "这台电脑" for the ports)++ public static string Title(StepId id, string host) => id switch+ {+ StepId.Reach => Strings.LF("连上 %@", host),+ StepId.Key => Strings.L("key 可以用"),+ StepId.Text => Strings.L("纪要和翻译"),+ _ => Strings.L("听对方"),+ };++ /// Why the failed step failed, in one sentence. `model`: the text model, `hear`: the hear model.+ public string? Message(string service, string host, string model, string hear)+ {+ if (Failure is not { } f) return IsBusy ? Strings.LF("%@ 现在很忙,key 没问题。开会时会自动重试。", service) : null;+ return f.Why switch+ {+ Reason.Unreachable => Strings.LF("这台电脑访问不到 %@。", host),+ Reason.BadAddress => Strings.L("地址要用 https,只有 localhost 可以用 http。"),+ Reason.InvalidKey => Strings.LF("%@ 说这个 key 无效,可能没复制全,或已删除。", service),+ Reason.MgmtKey => Strings.L("这是 ZenMux 的管理 key,不能用来调用模型。请粘贴 sk-payg 开头的 key。"),+ Reason.NoCredit => Strings.LF("%@ 账户余额不足。", service),+ Reason.NoModel => Strings.LF("%@ 上找不到 %@ 这个模型。", service, model),+ Reason.NoJSON => Strings.L("这个服务不支持 JSON,纪要写不了;翻译照常。"),+ Reason.Deaf => Strings.LF("%@ 听不了声音。", hear),+ Reason.Busy => Strings.LF("%@ 现在很忙,key 没问题。开会时会自动重试。", service),+ _ => Strings.LF("%@ 暂时出错(HTTP %lld),稍后再试。", service, f.Code ?? 0),+ };+ }++ /// 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)+ {+ if (Failure?.Why != Reason.Unreachable || Proxy is not { } p) return null;+ return p.Kind switch+ {+ ProxyKind.SystemOn => Strings.LF("开了代理也连不上:换一个节点,或检查代理软件是否放过 %@。", host),+ // As text: a number would be grouped ("7,890").+ ProxyKind.AppRunning => Strings.LF("代理软件在运行(端口 %@),但没开系统代理。在代理软件里打开“系统代理”。", p.Port.ToString(System.Globalization.CultureInfo.InvariantCulture)),+ _ => Strings.LF("这台电脑没开代理。在国内通常要开代理才能用 %@。", service),+ };+ }++ /// "OpenRouter 余额快用完了(还剩 $0.40)" when it is.+ public string? BalanceLine(string service) =>+ IsLowBalance && Balance is { } b ? Strings.LF("%@ 余额快用完了(还剩 $%@)", service, Math.Max(0, b).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)) : null;++ /// Debug and logs: "reach=ok key=fail(invalidKey) text=skipped hear=skipped".+ public string Summary+ {+ get+ {+ static string Lower(object o) { var s = o.ToString()!; return char.ToLowerInvariant(s[0]) + s[1..]; }+ var parts = Steps.Select(s => $"{Lower(s.Id)}=" + s.State.Kind switch+ {+ Kind.Ok => s.State.Seconds is { } sec ? $"ok({sec.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture)}s)" : "ok",+ Kind.Fail => $"fail({(s.State.Why is { } w ? Lower(w) : "?")}{(s.State.Code is { } c ? $" {c}" : "")})",+ var 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" : "");+ }+ }++ /// The website's proxy help, in the UI language.+ public static string HelpUrl => "https://cicada.indaloop.app" + (Strings.Language is "en" or "ja" or "ko" ? "/" + Strings.Language : "") + "/start/#proxy";++ /// "12 分钟前": when the newest evidence came in, for "%@ 开会时用过".+ public static string Ago(DateTimeOffset at, DateTimeOffset now)+ {+ var minutes = (int)Math.Floor((now - at).TotalMinutes);+ if (minutes < 1) return Strings.L("刚刚");+ if (minutes < 60) return Strings.LF("%lld 分钟前", minutes);+ var hours = minutes / 60;+ if (hours < 24) return Strings.LF("%lld 小时前", hours);+ return Strings.LF("%lld 天前", hours / 24);+ }+}++/// Words the "can't reach the AI service" hint. Read-only on purpose: the app never sets or uses a+/// proxy of its own (HttpClient already goes through the system proxy); it only tells the user which+/// of three situations they are in. The system settings come from the app (the registry on Windows).+public static class ProxyProbe+{+ /// Ports common proxy apps listen on (Clash 7890, Clash Verge 7897, SOCKS 1080).+ public static readonly int[] Ports = [7890, 7897, 1080];++ public static async Task<AICheck.ProxyHint> Hint(Func<bool> systemOn)+ {+ if (systemOn() || EnvProxy()) return new(AICheck.ProxyKind.SystemOn);+ foreach (var port in Ports) if (await Listening(port)) return new(AICheck.ProxyKind.AppRunning, port);+ return new(AICheck.ProxyKind.None);+ }++ /// An HTTPS proxy set for programs started from here (HttpClient reads it too).+ static bool EnvProxy() => new[] { "HTTPS_PROXY", "https_proxy" }.Any(n => Environment.GetEnvironmentVariable(n) is { Length: > 0 });++ /// Something accepts a TCP connection on 127.0.0.1:`port` within 0.3 s. Nothing is sent.+ public static async Task<bool> Listening(int port)+ {+ using var tcp = new TcpClient();+ using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300));+ try { await tcp.ConnectAsync("127.0.0.1", port, cts.Token); return true; }+ catch { return false; }+ }+}diff --git a/windows/src/Cicada.Core/Ling.cs b/windows/src/Cicada.Core/Ling.csindex 185d2ec..6743571 100644--- a/windows/src/Cicada.Core/Ling.cs+++ b/windows/src/Cicada.Core/Ling.cs@@ -130,18 +130,39 @@ public sealed class LingClientreadonly AIKey key;readonly HttpClient http;readonly Func<AIConfig> config;+ /// The short form older callers read (Usable, the early stop of every request): derived from Health.public KeyState KeyState { get; private set; }public DateTimeOffset? RateLimitedAt { get; private set; }- /// Why the last check failed, shown under the key: a Mac string key and its arguments for LF()- /// ("连不上 %@,请检查网络或代理", "ZenMux"); null when it didn't.- public (string Key, object[] Args)? Problem { get; private set; }- /// How long the last good check took.- public double? Seconds { get; private set; }- /// Whether the hear model takes audio: null until a check asked (always true on Ling).- public bool? Hears { get; private set; }+ /// Step by step, where the service stands (AICheck). Swapped whole: requests report from worker threads.+ public AICheck Health { get { lock (healthGate) return health; } }+ AICheck health = new();+ readonly object healthGate = new();+ int checking;+ /// Which check is the newest: a check that started before a change (a model switched while+ /// one ran) finishes into nothing, so an old answer never lands over the new setting.+ int generation;+ /// How long the text model took in the last check that reached it.+ public double? Seconds => Health[AICheck.StepId.Text].Seconds;+ /// Whether the hear model takes audio: null until a check or a meeting found out.+ public bool? Hears => Health[AICheck.StepId.Hear] switch+ {+ { Kind: AICheck.Kind.Ok or AICheck.Kind.Busy } => true,+ { Kind: AICheck.Kind.Fail, Why: AICheck.Reason.Deaf } => false,+ _ => null,+ };+ /// The last time the room voice spoke (or failed to) through this service.+ public (bool Ok, DateTimeOffset At)? LastVoice { get; private set; }/// The service's models from `/models`, recommended first: all that chat, and those that hear.public IReadOnlyList<string> TextCatalog { get; private set; } = [];public IReadOnlyList<string> HearCatalog { get; private set; } = [];+ /// Every model id the service lists, and those it says take audio: whether the chosen ones still exist.+ HashSet<string>? listed, listedHearing;+ /// Reads this computer's proxy settings to word the "can't reach" hint (never used to connect).+ public Func<Task<AICheck.ProxyHint>>? ProxyHint { get; set; }+ /// Debug pipe only: the next checks end this way (screenshots of every state).+ public AICheck.Reason? SimulateCheck { get; set; }+ /// Debug pipe only: report this OpenRouter balance instead of the real one.+ public double? SimulateBalance { get; set; }public event Action? Changed;public LingClient(AIKey key, HttpMessageHandler? handler = null, Func<AIConfig>? config = null)@@ -152,7 +173,6 @@ public sealed class LingClienthttp.Timeout = Timeout.InfiniteTimeSpan; // per request belowhttp.DefaultRequestHeaders.UserAgent.ParseAdd("Cicada-Windows/0.1");KeyState = CurrentKey() is null ? KeyState.None : KeyState.Unchecked;- Hears = Config.IsLing ? true : null;}public AIConfig Config => config();@@ -178,78 +198,216 @@ public sealed class LingClientpublic void KeyChanged(){key.Reload();+ Interlocked.Increment(ref generation);+ lock (healthGate) health = new AICheck();KeyState = CurrentKey() is null ? KeyState.None : KeyState.Unchecked;- Problem = null;- Hears = Config.IsLing ? true : null;+ LastVoice = null;+ listed = listedHearing = null;TextCatalog = HearCatalog = [];Changed?.Invoke();}- /// The cheapest request that proves the key: Ling's tiny model, else one token from the text- /// model. The others' hear model must also take audio (half a second of silence), and a custom- /// service must return JSON (the notes need it).+ /// 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 : "";+ /// 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;++ /// The cheapest requests that prove each step: Ling's tiny model, else one token from the text+ /// model; the others' hear model must take audio (half a second of silence), a custom service+ /// must return JSON (the notes need it), and the model list must still have both models.+ /// OpenRouter also tells the balance. Ling's Ming isn't asked: a meeting records how it hears.public async Task<(KeyState state, double seconds)> Check(){- KeyState = KeyState.Checking; Problem = null; Changed?.Invoke();- var c = Config;- var name = c.Provider.Id == "custom" ? "这个服务" : c.Name;var started = DateTime.UtcNow;- var state = KeyState.Unreachable;+ var c = Config;+ if (CurrentKey() is not { } k)+ {+ lock (healthGate) health = new AICheck();+ KeyState = KeyState.None;+ Changed?.Invoke();+ return (KeyState, 0);+ }+ Interlocked.Increment(ref checking);+ var gen = Interlocked.Increment(ref generation);+ try+ {+ var r = new AICheck();+ r[AICheck.StepId.Reach] = AICheck.State.Running;+ lock (healthGate) health = r;+ KeyState = KeyState.Checking;+ Changed?.Invoke();+ r = new AICheck();+ if (SimulateCheck is { } sim) r = Simulated(sim);+ else if (c.Provider.Id == "custom" && c.Base is null) r.Fail(AICheck.StepId.Reach, AICheck.Reason.BadAddress, reached: false);+ else if (AICheck.Owner(k) is { Management: true }) r.Fail(AICheck.StepId.Key, AICheck.Reason.MgmtKey, reached: false);+ else await Probe(r, c, k);+ await Finish(r, c, gen);+ }+ finally { Interlocked.Decrement(ref checking); }+ return (KeyState, (DateTime.UtcNow - started).TotalSeconds);+ }++ async Task Probe(AICheck r, AIConfig c, string k)+ {+ double 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 (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)+ 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);+ r.Pass(AICheck.StepId.Text, Since(t));+ if (c.Provider.Id == "custom"){- await Chat("Reply with OK.", "Reply.", Priority.Speak, maxTokens: 5, timeout: 10, model: "Ling-3.0-tiny");- Seconds = (DateTime.UtcNow - started).TotalSeconds;- Hears = true;+ try { await Chat("Reply with the JSON object {\"ok\": true}.", "Reply.", Priority.Speak, json: true, maxTokens: 20, timeout: 20); }+ catch (LingException e) when (e.Failure == LingException.Kind.Http) { r.Fail(AICheck.StepId.Text, AICheck.Reason.NoJSON, e.Status); }}- else+ }+ catch (LingException e) { Failed(e, AICheck.StepId.Text); }+ catch (Exception) { r.Fail(AICheck.StepId.Reach, AICheck.Reason.Unreachable); }+ // 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+ {+ t = DateTime.UtcNow;+ try{- if (c.Base is null || c.TextModel.Length == 0) throw new LingException(LingException.Kind.NoKey);- await Chat("Reply with OK.", "Reply.", Priority.Speak, maxTokens: 5, timeout: 20);- Seconds = (DateTime.UtcNow - started).TotalSeconds;- if (c.Provider.Id == "custom")- {- try { await Chat("Reply with the JSON object {\"ok\": true}.", "Reply.", Priority.Speak, json: true, maxTokens: 20, timeout: 20); }- catch (LingException e) when (e.Failure == LingException.Kind.Http) { Problem = ("这个服务不支持 JSON(HTTP %lld),纪要用不了", [e.Status]); }- }- Hears = await HearsAudio(c);+ await Chat("Transcribe the audio.", "Reply with what is said, or NONE.", Priority.Speak, maxTokens: 10, timeout: 20,+ model: c.HearModel, audio: Wav.Bytes(new short[8000]));+ r.Pass(AICheck.StepId.Hear, Since(t));}- state = KeyState.Ok;+ // A made-up answer to silence still came from a model that took the audio.+ catch (LingException e) when (e.Failure == LingException.Kind.Hijacked) { r.Pass(AICheck.StepId.Hear, Since(t)); }+ catch (LingException e) { Failed(e, AICheck.StepId.Hear); }+ catch (Exception) { }}- catch (LingException e)+ await FetchCatalog();+ // 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))+ 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));+ }++ async Task Finish(AICheck r, AIConfig c, int gen)+ {+ if (gen != Volatile.Read(ref generation)) { Log.Debug($"ai {c.Provider.Id}: an older check -> {r.Summary}, dropped"); return; }+ if (r.Failure?.Why == AICheck.Reason.Unreachable && r.Proxy is null && ProxyHint is { } hint) r.Proxy = await hint();+ if (SimulateBalance is { } b) r.Balance = b;+ r.At = DateTimeOffset.Now;+ lock (healthGate) { if (gen != generation) return; health = r; }+ SyncKeyState();+ Log.Debug($"ai {c.Provider.Id}: check -> {r.Summary}");+ Changed?.Invoke();+ }++ /// A made-up result for `reason` (debug screenshots of every state).+ static AICheck Simulated(AICheck.Reason reason)+ {+ var r = new AICheck();+ switch (reason){- // A busy key is still a good key.- state = e.Failure switch { LingException.Kind.NoKey => KeyState.None, LingException.Kind.InvalidKey => KeyState.Invalid, LingException.Kind.RateLimited => KeyState.Ok, _ => KeyState.Unreachable };- if (e.Failure == LingException.Kind.Http && e.Status is 400 or 404)- Problem = c.Provider.Id == "custom" ? ("找不到模型,或地址不对(HTTP %lld)", [e.Status]) : ("%@ 拒绝了请求(HTTP %lld),请检查模型名", [name, e.Status]);- else if (state == KeyState.Unreachable) Problem = ("连不上 %@,请检查网络或代理", [name]);+ case AICheck.Reason.Busy: r.Pass(AICheck.StepId.Text, 1.2); r[AICheck.StepId.Text] = AICheck.State.Busy; r.Pass(AICheck.StepId.Hear, 0.9); break;+ case AICheck.Reason.Unreachable or AICheck.Reason.BadAddress: r.Fail(AICheck.StepId.Reach, reason, reached: false); break;+ case AICheck.Reason.InvalidKey: r.Fail(AICheck.StepId.Key, reason); break;+ case AICheck.Reason.NoCredit: r.Fail(AICheck.StepId.Key, reason, 402); break;+ case AICheck.Reason.MgmtKey: r.Fail(AICheck.StepId.Key, reason, reached: false); break;+ case AICheck.Reason.NoModel or AICheck.Reason.NoJSON: r.Fail(AICheck.StepId.Text, reason, 404); r.Pass(AICheck.StepId.Hear, 0.9); break;+ case AICheck.Reason.Deaf: r.Pass(AICheck.StepId.Text, 1.2); r.Fail(AICheck.StepId.Hear, reason, 400); break;+ default: r.Pass(AICheck.StepId.Text, 1.2); r.Fail(AICheck.StepId.Hear, reason, 503); break;}- catch (Exception)+ return r;+ }++ /// The short form older callers read: a refused key stops every request; a hear model that+ /// can't hear leaves the key good (notes and translation work).+ void SyncKeyState()+ {+ var h = Health;+ KeyState = !HasKey ? KeyState.None+ : h.IsRunning ? KeyState.Checking+ : h.Failure is { Why: AICheck.Reason.InvalidKey or AICheck.Reason.MgmtKey } ? KeyState.Invalid+ : h.Failure is { Step: AICheck.StepId.Reach or AICheck.StepId.Key } or { Why: AICheck.Reason.NoModel or AICheck.Reason.ServerError } ? KeyState.Unreachable+ : h.At is null ? KeyState.Unchecked+ : KeyState.Ok;+ }++ /// A real request (hearing, notes, translation) came back: keep the steps current without a+ /// check. One server error in a meeting isn't worth repainting the settings for, nor is the+ /// same good result again.+ void Observe(LingException? failure, double seconds, bool audio)+ {+ if (!HasKey || Volatile.Read(ref checking) > 0 || SimulateCheck is not null) return;+ var step = audio ? AICheck.StepId.Hear : AICheck.StepId.Text;+ AICheck r;+ bool wasUnreachable;+ lock (healthGate){- state = KeyState.Unreachable;- Problem = ("连不上 %@,请检查网络或代理", [name]);+ var old = health;+ r = 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 (f.Why == AICheck.Reason.Busy) r.Busy(f.Step); else r.Fail(f.Step, f.Why, f.Code);+ }+ else r.Pass(step, seconds);+ r.At = DateTimeOffset.Now;+ r.Passive = true;+ if (r.SameSteps(old) && old.Passive) { old.At = r.At; return; }+ wasUnreachable = old.Failure?.Why == AICheck.Reason.Unreachable;+ if (r.Failure?.Why == AICheck.Reason.Unreachable) r.Proxy = old.Proxy;+ health = r;}- KeyState = state;- Log.Debug($"ai {c.Provider.Id}: key check -> {state}{(Hears == false ? " (hear model refuses audio)" : "")}");+ SyncKeyState();+ Log.Debug($"ai: from a real request -> {r.Summary}");Changed?.Invoke();- if (state == KeyState.Ok && !c.IsLing) await FetchCatalog();- return (KeyState, (DateTime.UtcNow - started).TotalSeconds);+ if (r.Failure?.Why == AICheck.Reason.Unreachable && !wasUnreachable && ProxyHint is { } hint)+ _ = Task.Run(async () =>+ {+ var p = await hint();+ lock (healthGate) { if (health.Failure?.Why != AICheck.Reason.Unreachable) return; health = health.Clone(); health.Proxy = p; }+ Changed?.Invoke();+ });+ }++ /// The network changed while the service was unreachable: look again (never on a timer).+ public void NetworkChanged()+ {+ var h = Health;+ if (!HasKey || h.Failure?.Why != AICheck.Reason.Unreachable || h.IsRunning) return;+ Log.Debug("ai: network changed while unreachable, checking again");+ _ = Check();+ }++ /// One click on 换成推荐的: the model that was wrong is the service's first recommended one now.+ /// Null when there is none (a custom service), or the chosen one is it already.+ public string? Recommended(AICheck.StepId step)+ {+ var c = Config;+ var (models, current) = step == AICheck.StepId.Hear ? (c.Provider.HearModels, c.HearModel) : (c.Provider.TextModels, c.TextModel);+ return models.FirstOrDefault()?.Id is { } id && id != current ? id : null;}- /// Whether the hear model takes audio: a 400, 404, 415 or 422 says no; anything else can't tell.- async Task<bool?> HearsAudio(AIConfig c)+ /// One GET on the service's API (OpenRouter's key info and credits); null when it fails.+ async Task<string?> GetText(string path, string k){- if (c.HearModel.Length == 0) return false;+ if (Config.Base is not { } b) return null;try{- await Chat("Transcribe the audio.", "Reply with what is said, or NONE.", Priority.Speak, maxTokens: 10, timeout: 20,- model: c.HearModel, audio: Wav.Bytes(new short[8000]));- return true;+ using var req = new HttpRequestMessage(HttpMethod.Get, new Uri(new Uri(b), path));+ if (k.Length > 0) req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", k);+ using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15));+ using var res = await http.SendAsync(req, cts.Token);+ return res.StatusCode == HttpStatusCode.OK ? await res.Content.ReadAsStringAsync(cts.Token) : null;}- catch (LingException e) when (e.Failure == LingException.Kind.Http && e.Status is 400 or 404 or 415 or 422) { return false; }- catch (LingException e) when (e.Failure == LingException.Kind.Hijacked) { return true; }- catch (LingException) { return null; }+ catch (Exception e) when (e is HttpRequestException or OperationCanceledException) { return null; }}/// The service's models, for the model menus. Quietly just the recommended ones when the@@ -258,20 +416,13 @@ public sealed class LingClient{var c = Config;if (c.IsLing || CurrentKey() is not { } k || c.Base is null) return;- try- {- using var req = new HttpRequestMessage(HttpMethod.Get, new Uri(new Uri(c.Base), "models"));- if (k.Length > 0) req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", k);- using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(20));- using var res = await http.SendAsync(req, cts.Token);- if (res.StatusCode != HttpStatusCode.OK) return;- var body = await res.Content.ReadAsStringAsync(cts.Token);- TextCatalog = AIProvider.Catalog(body, c.Provider.TextModels.Select(m => m.Id), hears: false);- HearCatalog = AIProvider.Catalog(body, c.Provider.HearModels.Select(m => m.Id), hears: true);- Log.Debug($"ai {c.Provider.Id}: {TextCatalog.Count} models, {HearCatalog.Count} hear");- Changed?.Invoke();- }- catch (Exception e) when (e is HttpRequestException or OperationCanceledException) { }+ if (await GetText("models", k) is not { } body) return;+ TextCatalog = AIProvider.Catalog(body, c.Provider.TextModels.Select(m => m.Id), hears: false);+ HearCatalog = AIProvider.Catalog(body, c.Provider.HearModels.Select(m => m.Id), hears: true);+ listed = AICheck.ListedModels(body);+ listedHearing = AICheck.ListedHearing(body);+ Log.Debug($"ai {c.Provider.Id}: {TextCatalog.Count} models, {HearCatalog.Count} hear");+ Changed?.Invoke();}/// One chat completion. `content` goes in the system message, `instruction` is the fixed user@@ -324,10 +475,13 @@ public sealed class LingClientvar usage = root["usage"];Log.Debug($"ai {c.Provider.Id}: {priority} ok {(int)(DateTime.UtcNow - started).TotalMilliseconds} ms tokens={usage?["prompt_tokens"]}/{usage?["completion_tokens"]}");if (RateLimitedAt is not null) { RateLimitedAt = null; Changed?.Invoke(); }+ Observe(null, (DateTime.UtcNow - started).TotalSeconds, audio is not null);return trimmed;}- catch (LingException e) when (e.Failure == LingException.Kind.RateLimited)+ catch (LingException e){+ Observe(e, 0, audio is not null);+ if (e.Failure != LingException.Kind.RateLimited) throw;if (attempt > waits.Length) { RateLimitedAt = DateTimeOffset.Now; Changed?.Invoke(); throw; }var wait = waits[attempt - 1] + Random.Shared.NextDouble() * 0.5;Log.Debug($"ling: {priority} 429, retry in {wait:F1} s");@@ -389,7 +543,7 @@ public sealed class LingClient{case HttpStatusCode.OK: break;case HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden:- if (KeyState != KeyState.Invalid) { KeyState = KeyState.Invalid; Changed?.Invoke(); }+ Observe(new LingException(LingException.Kind.InvalidKey), 0, audio: false);throw new LingException(LingException.Kind.InvalidKey);case HttpStatusCode.TooManyRequests: throw new LingException(LingException.Kind.RateLimited);default: Log.Debug($"ai {c.Provider.Id}: voice HTTP {(int)res.StatusCode}"); throw new LingException(LingException.Kind.Http, (int)res.StatusCode);@@ -441,6 +595,13 @@ public sealed class LingClient}}+ /// The room voice spoke through this service, or failed and Windows spoke instead (现在能用的 says which).+ public void VoiceSpoke(bool ok)+ {+ LastVoice = (ok, DateTimeOffset.Now);+ Changed?.Invoke();+ }+/// One SSE line of a voice stream: the PCM it carries, or `done` at the end.public static byte[]? SpeechChunk(string line, out bool done){@@ -492,9 +653,8 @@ public sealed class LingClientswitch (res.StatusCode){case HttpStatusCode.OK: break;- case HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden:- if (KeyState != KeyState.Invalid) { KeyState = KeyState.Invalid; Changed?.Invoke(); }- throw new LingException(LingException.Kind.InvalidKey);+ // Chat reports it to the check (Observe), which stops every request after it.+ case HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden: throw new LingException(LingException.Kind.InvalidKey);case HttpStatusCode.TooManyRequests: throw new LingException(LingException.Kind.RateLimited);default:Log.Debug($"ling: HTTP {(int)res.StatusCode}");diff --git a/windows/src/Cicada.Core/ListenEngine.cs b/windows/src/Cicada.Core/ListenEngine.csindex 9a0d857..bc3c137 100644--- a/windows/src/Cicada.Core/ListenEngine.cs+++ b/windows/src/Cicada.Core/ListenEngine.cs@@ -50,19 +50,20 @@ public sealed class ListenEnginepublic int ProblemStatus { get; private set; }/// A stretch that couldn't be heard, in words: (title, what to do, whether 设置 fixes it). Ling- /// keeps its own words; another service is named. A hear model that refuses audio (400 / 404)- /// is a settings problem, not the network.- public static (string? Title, string Body, bool Settings) Words(LingException.Kind kind, int status, string service)+ /// keeps its own words; another service is named. A hear model that refuses audio (400, 404,+ /// 415, 422: AICheck's deaf) is a settings problem, not the network; `hear` names it. A lost+ /// connection needs nothing from the user: segments keep going out and pick up by themselves.+ public static (string? Title, string Body, bool Settings) Words(LingException.Kind kind, int status, string service, string? hear = null){var ling = service == "Ling";- if (kind == LingException.Kind.Http && status is 400 or 404 && !ling)- return (Strings.L("这个模型听不了声音,换一个支持音频输入的"), Strings.L("在 设置 › AI 服务 里换一个"), true);+ if (kind == LingException.Kind.Http && status is 400 or 404 or 415 or 422 && !ling)+ return (Strings.LF("%@ 听不了声音。", hear ?? service), Strings.L("在 设置 › AI 服务 里换一个"), true);return kind switch{LingException.Kind.RateLimited => ling ? (Strings.L("Ling 太忙"), Strings.L("稍后会自动重试。"), false) : (null, Strings.LF("%@ 太忙,稍后再试", service), false),LingException.Kind.InvalidKey => (ling ? Strings.L("Ling key 无效") : Strings.LF("%@ 的 key 无效", service), Strings.L("去设置里换一个 key。"), true),LingException.Kind.NoKey => (ling ? Strings.L("Ling key 无效") : Strings.LF("需要 %@ 的 key 才能听", service), Strings.L("去设置里换一个 key。"), true),- _ => (ling ? Strings.L("连不上 Ling") : Strings.LF("连不上 %@", service), Strings.L("这段时间的话没能识别。检查网络后点重试。"), false),+ _ => (ling ? Strings.L("连不上 Ling") : Strings.LF("连不上 %@", service), Strings.L("这段时间的话没能识别。网络恢复后自动继续。"), false),};}diff --git a/windows/src/Cicada.Core/Speak.cs b/windows/src/Cicada.Core/Speak.csindex 1b05d3e..831a6e8 100644--- a/windows/src/Cicada.Core/Speak.cs+++ b/windows/src/Cicada.Core/Speak.cs@@ -213,6 +213,7 @@ public sealed class SpeakEngine}}catch (LingException e) { Log.Debug($"speak: {config.Provider.Id} voice failed {e.Message}"); }+ ling.VoiceSpoke(chunks > 0);if (chunks > 0) { await sink.End(); LastVoice = config.IsLing ? "ming" : "cloud"; return true; }}var own = await systemVoice.Speak(text, language);diff --git a/windows/src/Cicada/AICheckView.cs b/windows/src/Cicada/AICheckView.csnew file mode 100644index 0000000..867db00--- /dev/null+++ b/windows/src/Cicada/AICheckView.cs@@ -0,0 +1,170 @@+using System.Diagnostics;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Media;+using static Cicada.Strings;++namespace Cicada.App;++/// The AI service's check, step by step (AICheck; the Mac's AICheckView.swift): settings and the+/// onboarding show the same list. Every step that ran shows its result; the one that failed says+/// why in one line and offers the one thing that fixes it (one dark button, at most one other).+static class AICheckView+{+ static readonly SolidColorBrush OkPale = Frozen(0xE3, 0xF1, 0xE8);++ static SolidColorBrush Frozen(byte r, byte g, byte b) { var x = new SolidColorBrush(Color.FromRgb(r, g, b)); x.Freeze(); return x; }++ /// `changeKey` opens the key field (settings: 更换; onboarding: back to pasting). The settings+ /// have 重新检查 beside the key already; the onboarding needs it in the failed step. `compact`+ /// (the onboarding, under two numbered rows): only the steps that have a result.+ public static FrameworkElement Steps(Controller app, Action changeKey, bool recheckInStep, bool compact = false)+ {+ var ling = app.Ling;+ var check = ling.Health;+ var list = new StackPanel();+ var steps = check.Steps.Where(s => !compact || s.State.Kind is not (AICheck.Kind.Skipped or AICheck.Kind.Untested)).ToList();+ for (int i = 0; i < steps.Count; i++)+ {+ var row = Row(app, check, steps[i].Id, steps[i].State, changeKey, recheckInStep);+ list.Children.Add(new Border { BorderBrush = Palette.Line, BorderThickness = new Thickness(0, i == 0 ? 0 : 1, 0, 0), Child = row });+ }+ return list;+ }++ static FrameworkElement Row(Controller app, AICheck check, AICheck.StepId id, AICheck.State state, Action changeKey, bool recheckInStep)+ {+ var ling = app.Ling;+ var c = ling.Config;+ var quiet = state.Kind is AICheck.Kind.Skipped or AICheck.Kind.Untested;+ var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ text.Children.Add(Ui.Text(AICheck.Title(id, ling.ServiceHost), 14, quiet ? Palette.Tertiary : Palette.Ink));+ string? sub = state.Kind == AICheck.Kind.Ok && id == AICheck.StepId.Text ? c.TextModel+ : state.Kind == AICheck.Kind.Ok && id == AICheck.StepId.Hear ? c.HearModel+ : state.Kind == AICheck.Kind.Untested && check.Passed ? L("开会用过一次后确认")+ : null;+ if (sub is not null) { var s = Ui.Text(sub, 12, Palette.Tertiary); s.Margin = new Thickness(0, 2, 0, 0); text.Children.Add(s); }+ if (state.Kind is AICheck.Kind.Fail or AICheck.Kind.Busy) Problem(app, check, text, changeKey, recheckInStep);++ var dock = new DockPanel { Margin = new Thickness(0, 10, 0, 10) };+ var disc = Disc(state.Kind);+ disc.Margin = new Thickness(0, 1, 12, 0);+ DockPanel.SetDock(disc, Dock.Left);+ dock.Children.Add(disc);+ if (state is { Kind: AICheck.Kind.Ok, Seconds: { } sec })+ {+ var t = Ui.Text(LF("%@ 秒", sec.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture)), 12, Palette.Tertiary, wrap: false);+ t.VerticalAlignment = VerticalAlignment.Top; t.Margin = new Thickness(12, 2, 0, 0);+ DockPanel.SetDock(t, Dock.Right);+ dock.Children.Add(t);+ }+ dock.Children.Add(text);+ return dock;+ }++ /// Why it failed, the proxy box when the network is the trouble, and what fixes it.+ static 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)+ {+ var t = Ui.Text(why, 13, check.Failure is null ? Palette.WarnIcon : Palette.Danger);+ t.Margin = new Thickness(0, 4, 0, 0);+ into.Children.Add(t);+ }+ if (check.ProxyLine(ling.ServiceName, ling.ServiceHost) is { } proxy)+ into.Children.Add(new Border { Background = Palette.Mica, CornerRadius = new CornerRadius(8), Padding = new Thickness(10, 7, 10, 7), Margin = new Thickness(0, 6, 0, 0), Child = Ui.Text(proxy, 13, Palette.Body) });+ var acts = Actions(app, check, changeKey, recheckInStep);+ if (acts.Count == 0) return;+ var row = new WrapPanel { Margin = new Thickness(0, 8, 0, 0) };+ for (int i = 0; i < acts.Count; i++)+ {+ var b = Ui.Button(acts[i].Title, acts[i].Run, i == 0 ? Ui.Kind.Primary : Ui.Kind.Standard, height: 30);+ b.Margin = new Thickness(0, 0, 8, 0);+ row.Children.Add(b);+ }+ into.Children.Add(row);+ }++ /// One primary fix and at most one other.+ static List<(string Title, Action Run)> Actions(Controller app, AICheck check, Action changeKey, bool recheckInStep)+ {+ if (check.Failure is not { } f) return [];+ var ling = app.Ling;+ var p = ling.Provider;+ var recheck = recheckInStep ? new List<(string, Action)> { (L("重新检查"), () => _ = ling.Check()) } : [];+ switch (f.Why)+ {+ case AICheck.Reason.Unreachable:+ return [(L("怎么设置代理"), () => Open(AICheck.HelpUrl)), .. recheck];+ case AICheck.Reason.InvalidKey or AICheck.Reason.MgmtKey:+ return p.Site is { } site ? [(L("更换 key"), changeKey), (LF("打开 %@", ling.ServiceName), () => Open(site))] : [(L("更换 key"), changeKey)];+ case AICheck.Reason.NoCredit:+ return [(L("去充值"), () => Open(TopUp(p))), .. recheck];+ case AICheck.Reason.NoModel or AICheck.Reason.Deaf:+ var step = f.Why == AICheck.Reason.Deaf ? AICheck.StepId.Hear : AICheck.StepId.Text;+ return ling.Recommended(step) is { } rec ? [(LF("换成推荐的 %@", rec), () => app.UseRecommended(step))] : recheck;+ case AICheck.Reason.ServerError:+ return recheck;+ default:+ return [];+ }+ }++ /// Where to add money: OpenRouter's credits page, else the service's own site.+ public static string TopUp(AIProvider p) => p.Id == "openrouter" ? "https://openrouter.ai/settings/credits" : p.Site ?? "https://zenmux.ai";++ public static void Open(string url)+ {+ try { Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); }+ catch (Exception e) { Log.Debug($"ai: open failed {e.GetType().Name}"); }+ }++ /// The round mark before a step: a tick, a cross, "!" for busy, "…" while running, "–" for the rest.+ static FrameworkElement Disc(AICheck.Kind kind)+ {+ var (bg, fg) = kind switch+ {+ AICheck.Kind.Ok => (OkPale, Palette.Success),+ AICheck.Kind.Fail => (Palette.ErrorBg, Palette.Danger),+ AICheck.Kind.Busy => (Palette.WarnBg, Palette.WarnIcon),+ AICheck.Kind.Running => (Palette.AccentPale, Palette.AccentText),+ _ => (Palette.Subtle, Palette.Tertiary),+ };+ var g = new Grid { Width = 20, Height = 20, VerticalAlignment = VerticalAlignment.Top };+ g.Children.Add(new System.Windows.Shapes.Ellipse { Fill = bg });+ FrameworkElement mark = kind switch+ {+ AICheck.Kind.Ok => Ui.Icon(Icons.Check, 12, fg, stroke: 2),+ AICheck.Kind.Fail => Ui.Icon(Icons.Close, 10, fg, stroke: 2),+ _ => Ui.Text(kind switch { AICheck.Kind.Busy => "!", AICheck.Kind.Running => "…", _ => "–" }, 11, fg, FontWeights.Bold, wrap: false),+ };+ mark.HorizontalAlignment = HorizontalAlignment.Center; mark.VerticalAlignment = VerticalAlignment.Center;+ g.Children.Add(mark);+ return g;+ }++ /// All passed, in one line: "已连接 · 文字 1.8 秒 · 听 2.1 秒", or when the newest evidence came+ /// from a meeting, "正常 · 12 分钟前开会时用过". Null otherwise.+ public static string? Summary(AICheck check)+ {+ if (!check.Passed || check.IsBusy) return null;+ if (check.Passive && check.At is { } at) return L("正常") + " · " + LF("%@ 开会时用过", AICheck.Ago(at, DateTimeOffset.Now));+ var parts = new List<string> { L("已连接") };+ static string S(double s) => s.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture);+ if (check[AICheck.StepId.Text].Seconds is { } t) parts.Add(LF("文字 %@ 秒", S(t)));+ if (check[AICheck.StepId.Hear].Seconds is { } h) parts.Add(LF("听 %@ 秒", S(h)));+ return string.Join(" · ", parts);+ }++ /// The settings' status line, named after the step that failed: a missing model is not a connection problem.+ public static string? Status(AICheck check) => check.IsRunning ? L("正在检查…")+ : check.Failure is { Why: not AICheck.Reason.Busy } f ? f.Step switch+ {+ AICheck.StepId.Reach => L("暂时连不上"),+ AICheck.StepId.Key => L("这个 key 用不了"),+ AICheck.StepId.Text => L("模型用不了"),+ _ => L("听不了声音"),+ }+ : null;+}diff --git a/windows/src/Cicada/App.cs b/windows/src/Cicada/App.csindex 469580e..8833c3d 100644--- a/windows/src/Cicada/App.cs+++ b/windows/src/Cicada/App.cs@@ -106,7 +106,8 @@ sealed class Controllervar ui = Settings.UiLanguage == "system" ? null : Settings.UiLanguage;Strings.Load(Bundled.Strings, ui);Key = new AIKey(new DpapiProtector(), service: () => Settings.AiProvider);- Ling = new LingClient(Key, config: Settings.AIConfig);+ Ling = new LingClient(Key, config: Settings.AIConfig) { ProxyHint = () => ProxyProbe.Hint(WinProxy.SystemOn) };+ Ling.Changed += Changed;SpeakerLabels.Voices = Settings.SpeakerVoices;Notes = new NotesEngine(Ling, Store);Translator = new Translator(Ling);@@ -140,6 +141,7 @@ sealed class Controllertalk.Released += () => Dispatch.BeginInvoke(PressEnded);Log.Debug($"audio: speakers {Endpoints.Default(Endpoints.Flow.Render)?.Name ?? "none"}, mic {Endpoints.Microphone()?.Name ?? "none"}, cable {(Endpoints.Cable() is null ? "absent" : "present")}");DebugServer.Start(this);+ WatchNetwork();// A dev build isn't what a release replaces: it checks only when pointed at a test feed.UpdateChecker.CleanDownloads();if (!Paths.Dev || Environment.GetEnvironmentVariable("CICADA_UPDATE_FEED") is { Length: > 0 }) { checksUpdates = true; Updates.Start(); }@@ -268,7 +270,16 @@ sealed class Controlleritem.Click += (_, _) => act();return item;}- // The Mac's status menu: where it stands, then what to do, then the windows, then 退出.+ // The Mac's status menu: what the AI service needs from the user, where it stands, then what+ // to do, then the windows, then 退出.+ if (AIProblem() is { } ai)+ {+ var (problem, detail) = ai;+ var first = new MenuItem { Header = Ui.Stack(1, Ui.Text(problem, 13, Palette.AccentText, Palette.Strong, wrap: false), Ui.Text(detail + " · " + L("打开设置"), 12, Palette.Secondary, wrap: false)) };+ first.Click += (_, _) => ShowAISettings();+ menu.Items.Add(first);+ menu.Items.Add(new Separator());+ }if (Listen.Listening && Listen.SessionId is { } sid && Store.Get(sid) is { } live){var head = new MenuItem { Header = Ui.Row(8, Ui.Dot(Palette.Live, 6), Ui.Text($"{L("正在听")} · {Languages.Clock((DateTimeOffset.Now - live.StartedAt).TotalSeconds)}", 13, Palette.Secondary, wrap: false)), IsEnabled = false };@@ -301,10 +312,62 @@ sealed class Controllerpublic async Task ToggleListening(){if (Listen.Listening) RequestStop();- else StartListening(new SystemAudioTap());- await Task.CompletedTask;+ else await StartChecked(() => new SystemAudioTap());+ }++ /// The user's 开始听: blocked only by a failure the last result knows of. A hear model that+ /// can't hear asks to switch to the recommended one; an unreachable service is looked at once+ /// more first. Unknown or busy starts as usual. A dialog comes after a yield, so the debug pipe+ /// that asked for the start replies first; a start that needs none has happened by then.+ public async Task StartChecked(Func<IAudioSource> source)+ {+ if (Listen.Listening || starting) return;+ if (!Ling.HasKey) { StartListening(source()); return; }+ starting = true;+ try+ {+ if (Ling.Health.Failure?.Why == AICheck.Reason.Unreachable) await Ling.Check();+ var f = Ling.Health.Failure;+ if (f?.Why == AICheck.Reason.Deaf)+ {+ var service = Ling.ServiceName;+ var recommended = Ling.Recommended(AICheck.StepId.Hear);+ await Task.Yield();+ var choice = Dialogs.Choose(VisibleWindow(), LF("%@ 现在听不了声音", service), LF("%@ 只收文字。换成推荐的模型就能开始听。", Ling.HearName),+ recommended is null ? null : L("换成推荐的并开始"), L("打开设置"));+ if (choice == 1 && recommended is not null)+ {+ UseRecommended(AICheck.StepId.Hear);+ StartListening(source());+ }+ else if (choice == 2) ShowAISettings();+ return;+ }+ if (f?.Why == AICheck.Reason.Unreachable)+ {+ var h = Ling.Health;+ var body = h.Message(Ling.ServiceName, Ling.ServiceHost, Ling.Config.TextModel, Ling.HearName) ?? "";+ if (h.ProxyLine(Ling.ServiceName, Ling.ServiceHost) is { } proxy) body += "\n" + proxy;+ await Task.Yield();+ var choice = Dialogs.Choose(VisibleWindow(), LF("连不上 %@", Ling.ServiceName), body, L("重新检查并开始"), L("打开设置"));+ if (choice == 2) ShowAISettings();+ else if (choice == 1)+ {+ starting = false;+ await StartChecked(source);+ }+ return;+ }+ StartListening(source());+ }+ finally { starting = false; }}+ bool starting;++ /// A window of ours to put a dialog over; null (the screen's centre) from the tray.+ Window? VisibleWindow() => new Window?[] { settingsWindow, mainWindow, onboarding }.FirstOrDefault(w => w?.IsVisible == true && w.WindowState != WindowState.Minimized);+/// The user's 结束 (buttons, menu, hotkey): a meeting with lines ends only after asking, in the/// notes window or subtitle bar, which never take focus, so no modal dialog fights them for it./// An empty one just stops.@@ -553,7 +616,11 @@ sealed class Controller/// The setup steps, as the onboarding numbers them: what is done, by what really happened/// rather than by "the onboarding was finished".- public (bool Key, bool Audio, bool Sample) SetupDone => (Ling.HasKey, Settings.HeardSystemAudio || Settings.Onboarded, Settings.SampleSeen || Settings.Onboarded);+ public (bool Key, bool Audio, bool Sample) SetupDone => (Ling.HasKey && !KeyStepFailed, Settings.HeardSystemAudio || Settings.Onboarded, Settings.SampleSeen || Settings.Onboarded);++ /// The AI service's last result is a failure only the user can fix (not "still checking", not+ /// busy, not a server error, not a balance running low): 还差几步 shows it as not done yet.+ public bool KeyStepFailed => Ling.Health is { NeedsUser: true, Failure: not null };/// Steps left before listening works; 0 once set up. 同声传译 is optional and never counted.public int SetupLeft@@ -562,6 +629,8 @@ sealed class Controller{var (k, a, sm) = SetupDone;if (Settings.Onboarded && k) return 0;+ // Set up once, and the service broke later: that one step is left.+ if (Settings.Onboarded && Ling.HasKey) return 1;return (k ? 0 : 1) + (a ? 0 : 1) + (sm ? 0 : 1);}}@@ -630,6 +699,62 @@ sealed class ControllerAIChanged();}+ /// 设置 › AI 服务, opened at its page (the fix for every AI problem the app names).+ public void ShowAISettings()+ {+ ShowSettings();+ SettingsPage("ai");+ }++ /// One click on 换成推荐的: the service's first recommended text or hear model, then a fresh check.+ public void UseRecommended(AICheck.StepId step)+ {+ if (Ling.Recommended(step) is not { } id) return;+ Log.Debug($"ai: {step} model -> the recommended {id}");+ SetAIModel(step == AICheck.StepId.Hear ? "hear" : "text", id);+ }++ /// A key pasted for one service that belongs to another (改用 OpenRouter): switch, keep it there, check.+ public void SwitchService(string provider, string key)+ {+ if (AIProvider.Named(provider).Id != provider) return;+ Settings.AiProvider = provider;+ Settings.Save();+ Key.Save(key);+ AIChanged();+ }++ /// What the tray says first when the AI service needs the user (title, detail); null otherwise.+ /// On Windows the service hears too, so a dead service means no subtitles either.+ public (string Title, string Detail)? AIProblem()+ {+ var h = Ling.Health;+ if (!Ling.HasKey || !h.NeedsUser) return null;+ var name = Ling.ServiceName;+ if (h.Failure is not { } f) return h.BalanceLine(name) is { } low ? (low, L("用完后就听不了对方")) : null;+ var stopped = L("听对方暂时用不了");+ return f.Why switch+ {+ AICheck.Reason.Unreachable => (LF("连不上 %@", name), stopped),+ AICheck.Reason.InvalidKey or AICheck.Reason.MgmtKey => (LF("%@ 的 key 用不了", name), stopped),+ AICheck.Reason.NoCredit => (LF("%@ 账户余额不足。", name), stopped),+ AICheck.Reason.NoModel => (LF("%@ 上找不到 %@ 这个模型。", name, Ling.Config.TextModel), L("纪要和整句翻译先停下")),+ AICheck.Reason.Deaf => (LF("%@ 听不了声音。", Ling.HearName), stopped),+ _ => (L("AI 服务的设置要改一下"), L("纪要和整句翻译先停下")),+ };+ }++ /// Network changes (Wi-Fi back, a proxy app's TUN, a cable): 3 s for it to settle, then the AI+ /// service is looked at again if it was unreachable. No timer: nothing is checked while it stays the same.+ void WatchNetwork()+ {+ var settle = new DispatcherTimer { Interval = TimeSpan.FromSeconds(3) };+ settle.Tick += (_, _) => { settle.Stop(); Ling.NetworkChanged(); };+ void Changed() => Dispatch.BeginInvoke(() => { settle.Stop(); settle.Start(); });+ System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged += (_, _) => Changed();+ System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged += (_, e) => { if (e.IsAvailable) Changed(); };+ }+/// The service, its address, models or key changed: forget the old check and check again.public void AIChanged(){@@ -646,7 +771,11 @@ sealed class Controller{["provider"] = c.Provider.Id, ["base"] = c.Base, ["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,- ["problem"] = Ling.Problem is { } p ? LF(p.Key, p.Args) : null,+ ["check"] = Ling.Health.Summary,+ ["problem"] = Ling.Health.Message(Ling.ServiceName, Ling.ServiceHost, Ling.Config.TextModel, Ling.HearName),+ ["proxy"] = Ling.Health.ProxyLine(Ling.ServiceName, Ling.ServiceHost),+ ["tray"] = AIProblem()?.Title,+ ["simulated"] = Ling.SimulateCheck?.ToString() ?? (Ling.SimulateBalance is null ? null : "lowBalance"),["catalog"] = new JsonArray(Ling.TextCatalog.Count, Ling.HearCatalog.Count), ["keyFile"] = Path.GetFileName(Key.File_),};}@@ -798,6 +927,7 @@ sealed class Controller/// updatefeed <url or file> | checkupdate/// calls <program=name,…>|none|real | realcalls | endtimes <silence> <countdown> <grace>|off | endkeep/// provider ling|openrouter|zenmux|custom | ai-model hear|text|voice <id> (设置 › AI 服务; no id: the recommended)+/// ai-check | ai-check-sim <reason|lowBalance|off> (unreachable, invalidKey, noCredit, noModel, deaf, busy…)static class DebugServer{static string Pipe => Paths.Dev ? "cicada-dev" : "cicada";@@ -846,11 +976,11 @@ static class DebugServer"quit" => Quitting(app),_ => Opened(app),};- case "start": app.StartListening(new SystemAudioTap()); break;+ case "start": _ = app.StartChecked(() => new SystemAudioTap()); break;case "stop": _ = app.StopListening(); break;case "end": app.RequestStop(); break; // the user's 结束: asks first when anything was saidcase "notesproblem": app.Notes.SimulateStatus(arg); break;- case "feed": app.StartListening(new FileAudioSource(arg)); break;+ case "feed": _ = app.StartChecked(() => new FileAudioSource(arg)); break;case "sample": _ = app.PlaySample(); break;case "view": app.SetView(arg == "subtitles" ? "subtitles" : "notes"); break;case "capture": app.Settings.ShowInCapture = arg == "on"; app.Settings.Save(); app.CaptureSettingChanged(); break;@@ -869,6 +999,15 @@ static class DebugServerelse _ = app.Speak.Speak(Wav.Bytes(Wav.Read(arg)), new DeviceSpeaker(Endpoints.Cable));break;case "provider": app.SetAIProvider(arg); break;+ case "ai-check":+ // ai-check: a check now; ai-check-sim <reason|lowBalance|off>: every check ends this way (screenshots).+ _ = app.Ling.Check();+ break;+ case "ai-check-sim":+ app.Ling.SimulateCheck = Enum.TryParse<AICheck.Reason>(arg, true, out var reason) ? reason : null;+ app.Ling.SimulateBalance = arg == "lowBalance" ? 0.4 : null;+ _ = app.Ling.Check();+ break;case "ai-model":{var kv = arg.Split(' ', 2);diff --git a/windows/src/Cicada/Dialogs.cs b/windows/src/Cicada/Dialogs.csindex 3e4c352..db38560 100644--- a/windows/src/Cicada/Dialogs.cs+++ b/windows/src/Cicada/Dialogs.cs@@ -20,6 +20,18 @@ static class Dialogs/// Something to know, with one button.public static void Tell(Window owner, string title, string body) => Show(owner, title, Ui.Text(body, 14, Palette.Body), L("知道了"), danger: false, null, single: true);+ /// Two ways on, both named (开始听 blocked: 换成推荐的并开始 / 打开设置): 1 for `primary`, 2 for+ /// `other`, 0 when closed. No `primary`: just `other` and 取消. No owner: the screen's centre.+ public static int Choose(Window? owner, string title, string body, string? primary, string other)+ {+ int chosen = 0;+ var text = Ui.Text(body, 14, Palette.Body);+ if (primary is null) return Show(owner, title, text, other, danger: false, null) is null ? 0 : 2;+ var second = Ui.Button(other, () => { chosen = 2; Window.GetWindow(text)?.Close(); });+ var r = Show(owner, title, text, primary, danger: false, null, secondary: second);+ return r is not null ? 1 : chosen;+ }+/// A one-line answer: the new text (maybe empty), or null when cancelled.public static string? Prompt(Window owner, string title, string value, string? hint, string ok){@@ -30,19 +42,21 @@ static class Dialogsreturn Show(owner, title, content, ok, danger: false, box);}- static string? Show(Window owner, string title, FrameworkElement content, string ok, bool danger, TextBox? field, bool single = false)+ static string? Show(Window? owner, string title, FrameworkElement content, string ok, bool danger, TextBox? field, bool single = false, Button? secondary = null){string? result = null;var dialog = new Window{Owner = owner, WindowStyle = WindowStyle.None, AllowsTransparency = true, Background = Brushes.Transparent,ResizeMode = ResizeMode.NoResize, ShowInTaskbar = false, SizeToContent = SizeToContent.Height, Width = 456 + 32,- WindowStartupLocation = WindowStartupLocation.CenterOwner, FontFamily = Palette.Font, Title = title,+ WindowStartupLocation = owner is null ? WindowStartupLocation.CenterScreen : WindowStartupLocation.CenterOwner, Topmost = owner is null, FontFamily = Palette.Font, Title = title,};void Accept() { result = field?.Text.Trim() ?? ""; dialog.Close(); }var primary = Ui.Button(ok, Accept, danger ? Ui.Kind.Danger : Ui.Kind.Primary);- var cancel = Ui.Button(L("取消"), dialog.Close);- primary.IsDefault = true; cancel.IsCancel = true;+ var cancel = secondary ?? Ui.Button(L("取消"), dialog.Close);+ // A named second way on isn't 取消: Esc just closes.+ primary.IsDefault = true; cancel.IsCancel = secondary is null;+ if (secondary is not null) dialog.KeyDown += (_, e) => { if (e.Key == Key.Escape) dialog.Close(); };var buttons = new Grid();buttons.ColumnDefinitions.Add(new ColumnDefinition());buttons.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(8) });diff --git a/windows/src/Cicada/MainWindow.cs b/windows/src/Cicada/MainWindow.csindex 9723402..adf6f92 100644--- a/windows/src/Cicada/MainWindow.cs+++ b/windows/src/Cicada/MainWindow.cs@@ -245,10 +245,14 @@ sealed class MainWindow : Window{var (key, audio, sample) = app.SetupDone;var first = !key ? 0 : !audio ? 1 : !sample ? 2 : 3;+ // The key is in but the service turned it down (or can't be reached, or can't hear): the+ // reason, and the settings page that fixes it.+ var ling = app.Ling;+ var broken = app.KeyStepFailed ? ling.Health.Message(ling.ServiceName, ling.ServiceHost, ling.Config.TextModel, ling.HearName) : null;(string title, string detail, bool done)[] steps =[- // Any service connected ticks it; another service is named (接上 ZenMux).- (app.Ling.Config.IsLing ? L("接上 Ling") : LF("接上 %@", app.Ling.Config.Name), key ? L("key 已加密存在这台电脑上") : L("识别、翻译和纪要都靠它,约 1 分钟"), key),+ // A service whose check passed ticks it; another service is named (接上 ZenMux).+ (ling.Config.IsLing ? L("接上 Ling") : LF("接上 %@", ling.Config.Name), broken ?? (key ? L("key 已加密存在这台电脑上") : L("识别、翻译和纪要都靠它,约 1 分钟")), key),(L("听一下电脑里的声音"), L("放一段测试声音,看音量条动起来"), audio),(L("看看效果"), L("一段 9 秒的英文会议,字幕和纪要一句句出来"), sample),(L("同声传译"), LF("按住%@说话,对方听到翻译后的声音", PushToTalk.Label), false),@@ -259,16 +263,20 @@ sealed class MainWindow : Windowvar (title, detail, done) = steps[i];var now = i == first;var n = i;+ var failed = i == 0 && broken is not null;var disc = new Border{Width = 26, Height = 26, CornerRadius = new CornerRadius(13), VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 14, 0),Background = done ? Palette.Ink : now ? Palette.Live : Palette.Surface, BorderBrush = done ? Palette.Ink : now ? Palette.Live : Palette.Line, BorderThickness = new Thickness(1),- Child = done ? Ui.Icon(Icons.Check, 13, Brushes.White, stroke: 2) : Center(Ui.Text((i + 1).ToString(), 12, now ? Brushes.White : Palette.Body, FontWeights.Bold, wrap: false)),+ Child = done ? Ui.Icon(Icons.Check, 13, Brushes.White, stroke: 2) : Center(Ui.Text(failed ? "!" : (i + 1).ToString(), 12, now ? Brushes.White : Palette.Body, FontWeights.Bold, wrap: false)),};var head = Ui.Row(8, Ui.Text(title, 14, done ? Palette.Secondary : Palette.Ink, done ? FontWeights.Normal : Palette.Strong, wrap: false));if (i == 3) ((StackPanel)head).Children.Add(Ui.Badge(L("可选"), Palette.Surface, Palette.Secondary));- var text = Ui.Stack(1, head, Ui.Helper(detail));- FrameworkElement? action = now ? Ui.Button(L("继续设置"), () => app.ShowOnboarding(n), Ui.Kind.Primary, height: 32)+ var line = Ui.Helper(detail);+ if (failed) line.Foreground = Palette.Danger;+ var text = Ui.Stack(1, head, line);+ FrameworkElement? action = failed ? Ui.Button(L("打开设置"), app.ShowAISettings, Ui.Kind.Primary, height: 32)+ : now ? Ui.Button(L("继续设置"), () => app.ShowOnboarding(n), Ui.Kind.Primary, height: 32): i == 3 && first == 3 ? Ui.Button(L("去设置"), () => app.ShowOnboarding(3), height: 32) : null;var row = new DockPanel { Margin = new Thickness(0, 14, 0, 14) };DockPanel.SetDock(disc, Dock.Left);@@ -313,7 +321,7 @@ sealed class MainWindow : Window? Ui.Row(9, AppIcon.Small(22), Ui.Text(L("知了"), 13, Palette.Ink, FontWeights.Heavy, wrap: false), sep, Ui.Text(LF("还差 %@ 步", left), 13, Palette.AccentText, Palette.Strong, wrap: false), Ui.Text(L("继续设置"), 11, Palette.Secondary, wrap: false)): Ui.Row(9, AppIcon.Small(22), Ui.Text(L("知了"), 13, Palette.Ink, FontWeights.Heavy, wrap: false), sep, Ui.Text(app.AutoEnded ? L("会议已自动结束") : L("开始听"), 13, Palette.Ink, Palette.Strong, wrap: false), Ui.Text(Hotkey.Label.Replace('+', ' '), 11, Palette.Secondary, wrap: false));return Capsule(content, Palette.Surface, Palette.Line, 32, new Thickness(5, 0, 12, 0),- left > 0 ? () => app.ShowOnboarding() : () => _ = app.ToggleListening(), left > 0 ? L("继续设置") : L("开始听"));+ left > 0 ? () => { if (app.KeyStepFailed && app.Ling.HasKey) app.ShowAISettings(); else app.ShowOnboarding(); } : () => _ = app.ToggleListening(), left > 0 ? L("继续设置") : L("开始听"));}FrameworkElement LivePill()diff --git a/windows/src/Cicada/NotesWindow.cs b/windows/src/Cicada/NotesWindow.csindex f8ef67d..3a523e6 100644--- a/windows/src/Cicada/NotesWindow.cs+++ b/windows/src/Cicada/NotesWindow.cs@@ -176,7 +176,7 @@ sealed class NotesWindow : Windowif (Subtitles) { live.Content = SubtitleLine(); return; }var ek = !app.Listen.Listening ? null : app.ConfirmingEnd ? "confirm" : app.Ending is { } p ? p.Reason.ToString() : null;if (ek != endingKey) { endingKey = ek; ending.Content = EndingStrip(); }- var bk = $"{app.Listen.Problem}|{(app.Listen.Listening && app.Notes.Status is NotesEngine.State.Failed or NotesEngine.State.RateLimited ? app.Notes.Status : null)}|{app.Settings.ShowInCapture}|{hiddenFromCapture}";+ var bk = $"{app.Listen.Problem}|{(app.Listen.Listening && app.Notes.Status is NotesEngine.State.Failed or NotesEngine.State.RateLimited ? app.Notes.Status : null)}|{app.Ling.Health.Failure?.Why}|{app.Ling.Health.Proxy}|{app.Settings.ShowInCapture}|{hiddenFromCapture}";if (bk != barsKey) { barsKey = bk; bars.Content = Bars(); }live.Content = LiveCard();var count = app.Listen.SessionId is { } sid ? app.Store.Get(sid)?.Lines.Count ?? 0 : 0;@@ -263,9 +263,13 @@ sealed class NotesWindow : Windowvoid Add(FrameworkElement bar) { bar.Margin = new Thickness(0, 0, 0, 8); stack.Children.Add(bar); }if (app.Listen.Problem is { } problem){- var (title, body, settings) = ListenEngine.Words(problem, app.Listen.ProblemStatus, app.Ling.Config.Name);+ var ling = app.Ling;+ var (title, body, settings) = ListenEngine.Words(problem, app.Listen.ProblemStatus, ling.Config.Name, ling.HearName);+ // Can't reach it: what this computer's proxy looks like says what to do.+ var offline = problem is LingException.Kind.Network or LingException.Kind.Timeout;+ if (offline && ling.Health.ProxyLine(ling.ServiceName, ling.ServiceHost) is { } proxy) body += "\n" + proxy;if (problem == LingException.Kind.RateLimited) Add(Ui.InfoBar(Ui.Severity.Warning, title, body));- else if (settings) Add(Ui.InfoBar(Ui.Severity.Error, title, body, Ui.Button(L("打开设置"), app.ShowSettings, height: 32)));+ else if (settings || offline) Add(Ui.InfoBar(Ui.Severity.Error, title, body, Ui.Button(L("设置"), app.ShowAISettings, height: 32)));else Add(Ui.InfoBar(Ui.Severity.Error, title, body, Ui.Button(L("重试"), () => { app.Listen.ClearProblem(); _ = app.Ling.Check(); }, height: 32)));}// The notes' own trouble (NotesWindow.swift › banner): the last round didn't land.@@ -273,7 +277,14 @@ sealed class NotesWindow : Windowswitch (app.Notes.Status){case NotesEngine.State.RateLimited:- Add(Ui.InfoBar(Ui.Severity.Warning, null, LF("请求过于频繁,稍后会自动重试。纪要停留在 %@。", NotesCoveredUntil())));+ Add(Ui.InfoBar(Ui.Severity.Warning, null, LF("%@ 很忙,纪要稍后补上。字幕照常。", app.Ling.ServiceName)));+ break;+ // The network or the proxy, not the notes: say which, and that it picks up by itself.+ // (When hearing failed too, its bar above says so already.)+ case NotesEngine.State.Failed when app.Ling.Health.Failure?.Why == AICheck.Reason.Unreachable:+ if (app.Listen.Problem is not (LingException.Kind.Network or LingException.Kind.Timeout))+ Add(Ui.InfoBar(Ui.Severity.Error, null, LF("连不上 %@,这段时间的纪要先停在 %@。网络恢复后自动继续。", app.Ling.ServiceName, NotesCoveredUntil()),+ Ui.Button(L("设置"), app.ShowAISettings, height: 32)));break;case NotesEngine.State.Failed:Add(Ui.InfoBar(Ui.Severity.Warning, null, L("这轮没整理好,下一轮会自动重试。")));diff --git a/windows/src/Cicada/Onboarding.cs b/windows/src/Cicada/Onboarding.csindex d1531ba..a39c9eb 100644--- a/windows/src/Cicada/Onboarding.cs+++ b/windows/src/Cicada/Onboarding.cs@@ -31,6 +31,8 @@ sealed class Onboarding : Windowreadonly TextBox keyText = new() { FontSize = 14, MinHeight = 34, VerticalContentAlignment = VerticalAlignment.Center, Visibility = Visibility.Collapsed };readonly ContentControl keyStatus = new();bool checking;+ // A pasted key's prefix said something (a management key, another service's): that stays until the next paste.+ bool hinting;/// Opened by the installer: step 1 says so, and 开机时启动知了 shows what the installer set.readonly bool installed;@@ -49,11 +51,14 @@ sealed class Onboarding : Windowvar dock = new DockPanel();DockPanel.SetDock(stepper, Dock.Top);DockPanel.SetDock(footer, Dock.Bottom);- dock.Children.Add(stepper); dock.Children.Add(footer); dock.Children.Add(page);+ // The page scrolls if it must (a failed check's reason and proxy hint under the key).+ dock.Children.Add(stepper); dock.Children.Add(footer);+ dock.Children.Add(new ScrollViewer { Content = page, VerticalScrollBarVisibility = ScrollBarVisibility.Auto });Content = Ui.Frameless(this, dock, resizable: false, captionHeight: 24);meter.Tick += (_, _) => { if (step == 1) Meter(); };app.Speak.Changed += SpeakChanged;- Closed += (_, _) => { StopTap(); app.Speak.Changed -= SpeakChanged; LeaveSpeak(keep: false); };+ app.Ling.Changed += LingChanged;+ Closed += (_, _) => { StopTap(); app.Speak.Changed -= SpeakChanged; app.Ling.Changed -= LingChanged; LeaveSpeak(keep: false); };System.Windows.Automation.AutomationProperties.SetName(keyBox, L("API key"));System.Windows.Automation.AutomationProperties.SetName(keyText, L("API key"));keyBox.PasswordChanged += (_, _) => { if (keyText.Text != keyBox.Password) keyText.Text = keyBox.Password; };@@ -97,7 +102,7 @@ sealed class Onboarding : Windowvoid Render(){- if (shownProvider != app.Settings.AiProvider) { shownProvider = app.Settings.AiProvider; keyBox.Clear(); keyStatus.Content = null; }+ if (shownProvider != app.Settings.AiProvider) { shownProvider = app.Settings.AiProvider; keyBox.Clear(); keyStatus.Content = null; hinting = false; }stepper.Content = Stepper();page.Content = step switch { 0 => Other ? OtherStep() : KeyStep(), 1 => AudioStep(), 2 => SampleStep(), 3 => SpeakStep(), _ => DoneStep() };footer.Content = Footer();@@ -242,7 +247,7 @@ sealed class Onboarding : Windowvar open = Ui.Button(L("打开"), () => Process.Start(new ProcessStartInfo("https://chat.ant-ling.com/platform/api") { UseShellExecute = true }), icon: Icons.OpenExternal, height: 36, iconAfter: true);open.MinWidth = 0;var row = KeyRow("sk-…");- if (app.Ling.HasKey && keyBox.Password.Length == 0 && keyStatus.Content is null) Status(true, AIKey.Masked(app.Ling.CurrentKey() ?? "") + " · " + L("已连接,可以用了"));+ if (keyBox.Password.Length == 0 && keyStatus.Content is null) ShowCheck();keyStatus.Margin = new Thickness(0, 12, 0, 0);var second = new StackPanel { Children = { row, keyStatus } };var card = StepCard(new StackPanel@@ -279,7 +284,7 @@ sealed class Onboarding : Windowvoid Switch(string provider){- keyBox.Clear(); keyStatus.Content = null;+ keyBox.Clear(); keyStatus.Content = null; hinting = false;app.SetAIProvider(provider);Render();}@@ -296,8 +301,7 @@ sealed class Onboarding : Windowopen.MinWidth = 0;top = Ui.Spread(choices, open);}- if (app.Ling.HasKey && app.Ling.KeyState == KeyState.Ok && keyBox.Password.Length == 0 && keyStatus.Content is null)- Status(true, AIKey.Masked(app.Ling.CurrentKey() ?? "") + " · " + L("已连接") + " · " + L("现在可以用了"));+ if (keyBox.Password.Length == 0 && keyStatus.Content is null) ShowCheck();var row = KeyRow(LF("粘贴 %@ 的 key", app.Ling.Config.Name));keyStatus.Margin = new Thickness(0, 12, 0, 0);row.Margin = new Thickness(0, 18, 0, 0);@@ -352,29 +356,57 @@ sealed class Onboarding : Windowasync Task SaveKey(){var text = keyBox.Password.Trim();+ // 继续 is always allowed once a key is in: a failed check stays in 还差几步 and the settings.if (text.Length == 0 && app.Ling.HasKey) { Go(1); return; }if (!text.StartsWith("sk-")) { Status(false, L("要粘贴 sk- 开头的那串")); return; }+ // The prefix says whose key it is (SettingsWindow.SaveKey does the same).+ if (AICheck.Owner(text) is { } whose)+ {+ var (owner, management) = whose;+ if (management) { hinting = true; Status(false, L("这是 ZenMux 的管理 key,不能用来调用模型。请粘贴 sk-payg 开头的 key。")); return; }+ if (owner != app.Settings.AiProvider)+ {+ hinting = true;+ var words = Ui.Text(LF("这是 %@ 的 key。", AIProvider.Named(owner).Name), 13, Palette.Danger);+ words.VerticalAlignment = VerticalAlignment.Center;+ keyStatus.Content = Ui.Spread(words, Ui.Button(LF("改用 %@", AIProvider.Named(owner).Name), () =>+ {+ hinting = false;+ keyBox.Clear();+ app.SwitchService(owner, text);+ Render();+ }, Ui.Kind.Primary, height: 32));+ return;+ }+ }+ hinting = false;checking = true; footer.Content = Footer();Status(null, L("正在检查…"));- var previous = app.Key.Read();app.Key.Save(text);+ keyBox.Clear();app.Ling.KeyChanged();- var (state, _) = await app.Ling.Check();+ await app.Ling.Check();checking = false; footer.Content = Footer();- // The key is good but the chosen model can't hear: listening would show nothing, so say so here.- if (state == KeyState.Ok && app.Ling.Hears == false) { Status(false, L("这个模型听不了声音,换一个支持音频输入的")); return; }- if (state == KeyState.Ok) { Status(true, L("已连接,可以用了")); await Task.Delay(600); Go(1); return; }- // A key Ling turned down isn't kept: the one that worked before, if any, comes back.- if (state == KeyState.Invalid)- {- if (previous is not null) app.Key.Save(previous); else app.Key.Remove();- app.Ling.KeyChanged();- }- var name = app.Ling.Config.Name;- Status(false, state == KeyState.Invalid ? L("这个 key 不能用,检查是否复制完整,或重新创建一个")- : app.Ling.Config.IsLing ? L("连不上 Ling,检查网络") : app.Ling.Problem is { } why ? LF(why.Key, why.Args) : LF("连不上 %@,请检查网络或代理", name));+ ShowCheck();+ if (app.Ling.Health.Passed) { await Task.Delay(600); if (step == 0) Go(1); }}+ /// What the last check found, under the key: a tick when it passed (busy too), else where it+ /// broke and the one thing that fixes it, as in the settings.+ void ShowCheck()+ {+ var ling = app.Ling;+ var h = ling.Health;+ if (!ling.HasKey || hinting) return;+ if (h.IsRunning) Status(null, L("正在检查…"));+ else if (h.Passed) Status(true, AIKey.Masked(ling.CurrentKey() ?? "") + " · " + (h.IsBusy ? LF("%@ 现在很忙,key 没问题。开会时会自动重试。", ling.ServiceName) : L("已连接,可以用了")));+ else if (h.At is null) keyStatus.Content = null;+ else keyStatus.Content = AICheckView.Steps(app, () => { keyBox.Clear(); keyStatus.Content = null; keyBox.Focus(); }, recheckInStep: true, compact: true);+ }++ /// A check finished or a meeting request reported back while the key page is open.+ void LingChanged() => Dispatcher.BeginInvoke(() => { if (step == 0 && !checking && keyBox.Password.Length == 0) ShowCheck(); });+// MARK: 2 · System audioreadonly ContentControl meterHost = new(), heardHost = new();diff --git a/windows/src/Cicada/Platform.cs b/windows/src/Cicada/Platform.csindex cb70bea..c6c9616 100644--- a/windows/src/Cicada/Platform.cs+++ b/windows/src/Cicada/Platform.cs@@ -164,3 +164,21 @@ static class MicReadersreturn MicUse.Calls(entries);}}++/// Windows' own proxy settings (Settings › Network & internet › Proxy, which proxy apps switch on as+/// "system proxy"): only read, to word the "can't reach" hint. Cicada never sets or uses one itself.+static class WinProxy+{+ const string Key = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";++ /// A manual proxy, or an auto-config (PAC) script, is on.+ public static bool SystemOn()+ {+ try+ {+ using var k = Registry.CurrentUser.OpenSubKey(Key);+ return k?.GetValue("ProxyEnable") is int on && on == 1 || k?.GetValue("AutoConfigURL") is string { Length: > 0 };+ }+ catch (Exception e) { Log.Debug($"proxy: unreadable ({e.GetType().Name})"); return false; }+ }+}diff --git a/windows/src/Cicada/SettingsWindow.cs b/windows/src/Cicada/SettingsWindow.csindex 89765cf..8d7e3d0 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 = [];+ /// A pasted key that belongs elsewhere: what it is, and (another service's key) where it fits.+ (string Text, string? Service, string Key)? keyHint;public SettingsWindow(Controller app){@@ -181,7 +183,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; customFields.Clear(); app.SetAIProvider(v); }, 220));+ v => { editingKey = false; typing = null; keyHint = null; customFields.Clear(); app.SetAIProvider(v); }, 220));h.Margin = new Thickness(0, 0, 0, 20);sections[id] = h;page.Children.Add(h);@@ -316,33 +318,45 @@ sealed class SettingsWindow : Window}/// 现在能用的 (AISettings.swift › usage), with 听对方 first: on the ports the service hears.- /// Windows has no voice of the user's own on any service, so that row isn't here.+ /// Only what the last result supports: when the service can't be reached (or the key fails)+ /// nothing says "用 ZenMux" in green. Windows has no voice of the user's own on any service.IEnumerable<FrameworkElement> UsesRows(){var ling = app.Ling;var c = ling.Config;- var on = ling.Usable;+ var check = ling.Health;+ var reason = check.Failure?.Why;+ var down = ling.HasKey && reason is AICheck.Reason.Unreachable or AICheck.Reason.BadAddress or AICheck.Reason.InvalidKey or AICheck.Reason.MgmtKey or AICheck.Reason.NoCredit;+ var on = ling.Usable && !down;+ var textOn = on && reason != AICheck.Reason.NoModel;+ var notesOn = textOn && reason != AICheck.Reason.NoJSON;var uses = LF("用 %@", c.Name);FrameworkElement Row(string title, string tag, string style, string note){var (bg, fg) = style switch{"ok" => ((Brush)new SolidColorBrush(Color.FromRgb(0xE3, 0xF1, 0xE8)), (Brush)Palette.Success),+ "warn" => (Palette.WarnBg, Palette.WarnIcon),"local" => (Palette.Mica, Palette.Body),_ => (Palette.Subtle, Palette.Tertiary),};return Card(null, title, note, Ui.Badge(tag, bg, fg));}- var needKey = (L("需要 key"), "off", L("填好 key 后可用"));- var hear = !on ? needKey- : ling.Hears == false ? (L("还不能用"), "off", L("这个模型听不了声音,换一个支持音频输入的"))+ var later = !ling.HasKey ? L("填好 key 后可用") : reason == AICheck.Reason.Unreachable ? LF("连上 %@ 后可用", ling.ServiceName) : L("换好 key 后可用");+ var off = ling.HasKey ? L("暂不可用") : L("需要 key");+ var hear = !on ? (off, "off", later)+ : ling.Hears == false ? (L("暂不可用"), "off", LF("%@ 听不了声音。", ling.HearName)): c.IsLing ? (uses, "ok", L("Ming 一次识别并翻译")): (uses, "ok", c.HearModel + " · " + L("比 Ling 晚 1–2 秒出字"));yield return Row(L("听对方"), hear.Item1, hear.Item2, hear.Item3);- yield return on ? Row(L("实时纪要"), uses, "ok", L("会中每 45 秒更新")) : Row(L("实时纪要"), needKey.Item1, needKey.Item2, needKey.Item3);- yield return on ? Row(L("翻译"), uses, "ok", L("整句用它;不行时换 Google")) : Row(L("翻译"), "Google", "off", L("没有 key 时照常可用"));+ yield return notesOn && check.IsBusy ? Row(L("实时纪要"), L("很忙"), "warn", L("会自动重试,纪要可能晚一点"))+ : notesOn ? Row(L("实时纪要"), uses, "ok", L("会中每 45 秒更新"))+ : Row(L("实时纪要"), off, "off", reason == AICheck.Reason.NoJSON ? L("这个服务不支持 JSON") : reason == AICheck.Reason.NoModel ? L("换一个模型后可用") : later);+ yield return textOn ? Row(L("翻译"), uses, "ok", L("整句用它;不行时换 Google")) : Row(L("翻译"), "Google", "off", ling.HasKey ? L("先用 Google 翻译") : L("没有 key 时照常可用"));// Windows speaks when the service can't, as the Mac does with its own voice.- yield return ling.Speaks ? Row(L("同传声音"), uses, "ok", c.IsLing ? L("Ming 的声音") : c.VoiceModel!)+ var speaks = ling.Speaks && !down;+ yield return speaks ? Row(L("同传声音"), uses, "ok", ling.LastVoice is { } last ? (last.Ok ? L("上次同传时正常") : L("上次同传没出声,用了 Windows 的声音")) : c.IsLing ? L("Ming 的声音") : c.VoiceModel!)+ : down ? Row(L("同传声音"), L("本机"), "local", L("先用 Windows 的声音")): on ? Row(L("同传声音"), L("本机"), "local", L("没填声音模型,用 Windows 的声音")): Row(L("同传声音"), L("本机"), "local", L("填好 key 前用 Windows 的声音"));}@@ -416,42 +430,66 @@ sealed class SettingsWindow : Windowvar ling = app.Ling;var c = ling.Config;var p = c.Provider;- var state = ling.KeyState;+ var check = ling.Health;var key = ling.CurrentKey();- var problem = ling.Problem is { } why ? LF(why.Key, why.Args.Select(a => a is string s ? L(s) : a).ToArray()) : null;var title = key is { Length: > 0 } ? AIKey.Masked(key) : key is not null ? L("本机服务,不用 key") : p.Id == "custom" ? L("还没填好") : L("还没填 API key");- string? desc = state switch+ // One line under the key: what failed (the steps below say why), busy, or all passed in short.+ string? desc = null;+ Brush color = Palette.Secondary;+ if (key is not null){- KeyState.None or KeyState.Unchecked => null,- KeyState.Checking => L("正在检查…"),- KeyState.Invalid => LF("%@ 提示 key 无效,请检查是否复制完整,或重新创建一个", c.Name),- KeyState.Unreachable => problem ?? LF("连不上 %@,请检查网络或代理", c.Name),- _ => problem ?? L("已连接") + " · " + LF("%@ · 响应约 %@ 秒", c.TextModel, (ling.Seconds ?? 0).ToString("0.0")),- };+ if (AICheckView.Status(check) is { } status) { desc = status; color = check.IsRunning ? Palette.Secondary : Palette.Danger; }+ else if (check.IsBusy) { desc = LF("%@ 现在很忙", ling.ServiceName); color = Palette.WarnIcon; }+ else if (AICheckView.Summary(check) is { } passed) { desc = passed; color = Palette.Success; }+ }FrameworkElement control;- if (editingKey || key is null || state == KeyState.Invalid)+ if (editingKey || key is null){if (keyBox.Parent is Panel old) old.Children.Remove(keyBox);if (keyBox.Parent is Border oldBorder) oldBorder.Child = null;var field = Ui.Field(keyBox); field.Width = 260; field.Height = 34;var buttons = new List<UIElement> { field, Ui.Button(L("保存并检查"), () => _ = SaveKey(), Ui.Kind.Primary, height: 34) };- if (editingKey) buttons.Add(Ui.Button(L("取消"), () => { editingKey = false; Render(); }, height: 34));+ if (editingKey) buttons.Add(Ui.Button(L("取消"), () => { editingKey = false; keyHint = null; Render(); }, height: 34));control = Ui.Row(8, [.. buttons]);}else{- var change = Ui.Button(L("更换"), () => { editingKey = true; keyBox.Clear(); Render(); keyBox.Focus(); }, height: 32);- control = key.Length == 0 ? change : Ui.Row(8, change, Ui.Button(L("删除"), () => { app.Key.Remove(); app.AIChanged(); }, height: 32));+ var change = Ui.Button(L("更换"), ChangeKey, height: 32);+ var recheck = Ui.Button(check.IsRunning ? L("正在检查…") : L("重新检查"), () => _ = ling.Check(), height: 32);+ recheck.IsEnabled = !check.IsRunning;+ control = key.Length == 0 ? Ui.Row(8, change, recheck) : Ui.Row(8, change, Ui.Button(L("删除"), () => { app.Key.Remove(); app.AIChanged(); }, height: 32), recheck);}var card = Card(Icons.Key, title, desc, control);if (desc is not null && card is DockPanel dock && dock.Children.OfType<StackPanel>().LastOrDefault() is { Children.Count: > 1 } text && text.Children[1] is TextBlock line)- line.Foreground = state == KeyState.Ok && problem is null ? Palette.Success : state is KeyState.Checking ? Palette.Secondary : Palette.Danger;+ line.Foreground = color;+ var rows = new List<FrameworkElement> { card };+ // A pasted key that belongs elsewhere, before it is saved: what it is, and where it fits.+ if (keyHint is { } kh)+ {+ var (hintText, service, pasted) = kh;+ var words = Ui.Text(hintText, 13, Palette.Danger);+ FrameworkElement hint = words;+ if (service is not null)+ hint = Ui.Spread(words, Ui.Button(LF("改用 %@", AIProvider.Named(service).Name), () => { keyHint = null; editingKey = false; keyBox.Clear(); app.SwitchService(service, pasted); }, Ui.Kind.Primary, height: 30));+ hint.Margin = new Thickness(0, 0, 0, 12);+ rows.Add(hint);+ }+ // Where it broke and the one thing that fixes it; all passed folds into the line above.+ if (key is not null && (check.IsRunning || check.Failure is not null || check.IsBusy || check.At is not null && !check.Passed))+ rows.Add(AICheckView.Steps(app, ChangeKey, recheckInStep: false));+ if (check.BalanceLine(ling.ServiceName) is { } low)+ {+ var strip = Ui.Spread(Ui.Text(low, 13, Palette.WarnIcon), Ui.Button(L("去充值"), () => AICheckView.Open(AICheckView.TopUp(p)), height: 30));+ rows.Add(new Border { Background = Palette.WarnBg, CornerRadius = new CornerRadius(10), Padding = new Thickness(12, 8, 8, 8), Margin = new Thickness(0, 4, 0, 12), Child = strip });+ }// Where to get one, while there is none.if (p.Site is { } site && key is null)- return Group(card, Card(null, LF("打开 %@", c.Name), new Uri(site).Host, Ui.IconButton(Icons.OpenExternal, LF("打开 %@", c.Name), () => Process.Start(new ProcessStartInfo(site) { UseShellExecute = true }), Palette.Secondary, 32, 16)));- return Group(card);+ rows.Add(Card(null, LF("打开 %@", c.Name), new Uri(site).Host, Ui.IconButton(Icons.OpenExternal, LF("打开 %@", c.Name), () => Process.Start(new ProcessStartInfo(site) { UseShellExecute = true }), Palette.Secondary, 32, 16)));+ return Group([.. rows]);}+ void ChangeKey() { editingKey = true; keyHint = null; keyBox.Clear(); Render(); keyBox.Focus(); }+async Task SaveKey(){var s = app.Settings;@@ -468,6 +506,16 @@ sealed class SettingsWindow : Windows.Save();}var text = keyBox.Password.Trim();+ keyHint = null;+ // The prefix says whose key it is: a management key can't call models, and another+ // service's key goes there with one click (never a silent switch). A custom address may+ // well take an aggregator's key.+ if (s.AiProvider != "custom" && AICheck.Owner(text) is { } whose)+ {+ var (owner, management) = whose;+ if (management) { keyHint = (L("这是 ZenMux 的管理 key,不能用来调用模型。请粘贴 sk-payg 开头的 key。"), null, ""); Render(); return; }+ if (owner != s.AiProvider) { keyHint = (LF("这是 %@ 的 key。", AIProvider.Named(owner).Name), owner, text); Render(); return; }+ }// Ling's and the aggregators' keys start with sk-; a company gateway's may not.if (text.Length > 0 && (s.AiProvider == "custom" || text.StartsWith("sk-"))){diff --git a/windows/src/Cicada/Strings/en.lproj/Windows.strings b/windows/src/Cicada/Strings/en.lproj/Windows.stringsindex c4d573c..a1490b7 100644--- a/windows/src/Cicada/Strings/en.lproj/Windows.strings+++ b/windows/src/Cicada/Strings/en.lproj/Windows.strings@@ -118,12 +118,9 @@"还没接上 Ling" = "Not connected to Ling";"还没有会议记录" = "No meeting records yet";"还没装虚拟麦克风,去设置里装一下" = "Virtual microphone isn't installed. Install it in Settings.";-"这个 key 不能用,检查是否复制完整,或重新创建一个" = "This key didn't work. Make sure you copied the whole key, or create a new one.";"这个快捷键被别的程序占用了" = "This shortcut is already in use by another app";"这台电脑没有这种语言的声音,没有发出去" = "This PC doesn't have a voice for this language. Nothing was sent.";-"这段时间的话没能识别。检查网络后点重试。" = "Some audio couldn't be transcribed. Check your network and try again.";"连不上 Ling" = "Can't connect to Ling";-"连不上 Ling,检查网络" = "Can't connect to Ling. Check your network.";"连不上 Ling,没有发出去" = "Couldn't connect to Ling. Nothing was sent.";"重命名" = "Rename";"重新打开知了后生效" = "Takes effect after you restart Cicada";@@ -254,7 +251,6 @@"接 AI 服务" = "AI service";"仅保存在本机当前账户下,仅发送至 %@" = "Stored only for this account on this computer, sent only to %@";"听、纪要和翻译都能用,模型已经选好。" = "Listening, notes and translation all work, with the models already chosen.";-"这个模型听不了声音,换一个支持音频输入的" = "This model can't take audio. Choose one that accepts audio input";"听的模型" = "Listening model";"要能输入音频:听对方和“我说”都用它" = "Must take audio in: used for Listen and for Speak";"例如 qwen3-omni" = "e.g. qwen3-omni";@@ -281,3 +277,25 @@"没人说话时不乱写" = "Writes nothing when no one speaks";"更快" = "Faster";"最快,偶尔把杂音写成字" = "Fastest; sometimes turns noise into words";++/* AI 服务检查 (AICheck): the ports' own words; the rest are the Mac's. */+"正常" = "Working";+"文字 %@ 秒" = "text %@ s";+"听 %@ 秒" = "hearing %@ s";+"听不了声音" = "Can't hear audio";+"%@ 现在听不了声音" = "%@ can't hear audio right now";+"%@ 只收文字。换成推荐的模型就能开始听。" = "%@ takes text only. Switch to the recommended model to start listening.";+"换成推荐的并开始" = "Switch and Start";+"重新检查并开始" = "Check Again and Start";+"用完后就听不了对方" = "When it runs out, listening stops";+"听对方暂时用不了" = "Listening is unavailable for now";+"纪要和整句翻译先停下" = "Notes and full-sentence translation pause";+"%@ 听不了声音。" = "%@ can't hear audio.";+"上次同传没出声,用了 Windows 的声音" = "Silent last time; the Windows voice spoke instead";+"先用 Windows 的声音" = "Using the Windows voice for now";+"这台电脑访问不到 %@。" = "This PC can't reach %@.";+"刚刚" = "just now";+"%lld 分钟前" = "%lld min ago";+"%lld 小时前" = "%lld hr ago";+"%lld 天前" = "%lld days ago";+"这段时间的话没能识别。网络恢复后自动继续。" = "Some audio couldn't be transcribed. It picks up again when the network is back.";diff --git a/windows/src/Cicada/Strings/ja.lproj/Windows.strings b/windows/src/Cicada/Strings/ja.lproj/Windows.stringsindex d6fb969..ad84a25 100644--- a/windows/src/Cicada/Strings/ja.lproj/Windows.strings+++ b/windows/src/Cicada/Strings/ja.lproj/Windows.strings@@ -118,12 +118,9 @@"还没接上 Ling" = "Ling に未接続";"还没有会议记录" = "会議の記録はまだありません";"还没装虚拟麦克风,去设置里装一下" = "仮想マイクがまだありません。設定からインストールしてください";-"这个 key 不能用,检查是否复制完整,或重新创建一个" = "このキーは使用できません。最後までコピーされているか確認するか、新しく作成してください。";"这个快捷键被别的程序占用了" = "このショートカットは他のアプリで使用されています";"这台电脑没有这种语言的声音,没有发出去" = "この PC にはこの言語の音声がないため、送信されませんでした";-"这段时间的话没能识别。检查网络后点重试。" = "この間の音声を認識できませんでした。ネットワークを確認して再試行してください。";"连不上 Ling" = "Ling に接続できません";-"连不上 Ling,检查网络" = "Ling に接続できません。ネットワークを確認してください。";"连不上 Ling,没有发出去" = "Ling に接続できなかったため、送信されませんでした";"重命名" = "名前を変更";"重新打开知了后生效" = "Cicada の再起動後に反映されます";@@ -254,7 +251,6 @@"接 AI 服务" = "AI サービス";"仅保存在本机当前账户下,仅发送至 %@" = "このコンピュータのこのアカウントにのみ保存され、%@ にのみ送信されます";"听、纪要和翻译都能用,模型已经选好。" = "聞き取り・議事メモ・翻訳がすべて使えます。モデルは選択済みです。";-"这个模型听不了声音,换一个支持音频输入的" = "このモデルは音声を聞き取れません。音声入力に対応したモデルに変えてください";"听的模型" = "聞き取りモデル";"要能输入音频:听对方和“我说”都用它" = "音声入力に対応している必要があります。相手の聞き取りと「話す」の両方で使います";"例如 qwen3-omni" = "例:qwen3-omni";@@ -281,3 +277,25 @@"没人说话时不乱写" = "誰も話していないときは何も書かない";"更快" = "より速い";"最快,偶尔把杂音写成字" = "最速。雑音を文字にすることがある";++/* AI 服务检查 (AICheck): the ports' own words; the rest are the Mac's. */+"正常" = "正常";+"文字 %@ 秒" = "テキスト %@ 秒";+"听 %@ 秒" = "聞き取り %@ 秒";+"听不了声音" = "音声を聞き取れません";+"%@ 现在听不了声音" = "%@ は今、音声を聞き取れません";+"%@ 只收文字。换成推荐的模型就能开始听。" = "%@ はテキストしか受け付けません。おすすめのモデルに切り替えると聞き取りを始められます。";+"换成推荐的并开始" = "切り替えて開始";+"重新检查并开始" = "再確認して開始";+"用完后就听不了对方" = "使い切ると相手の声を聞き取れなくなります";+"听对方暂时用不了" = "相手の声の聞き取りは一時的に使えません";+"纪要和整句翻译先停下" = "メモと文単位の翻訳は一時停止します";+"%@ 听不了声音。" = "%@ は音声を聞き取れません。";+"上次同传没出声,用了 Windows 的声音" = "前回の通訳では音声が出ず、Windows の音声を使いました";+"先用 Windows 的声音" = "当面は Windows の音声を使います";+"这台电脑访问不到 %@。" = "この PC から %@ にアクセスできません。";+"刚刚" = "たった今";+"%lld 分钟前" = "%lld 分前";+"%lld 小时前" = "%lld 時間前";+"%lld 天前" = "%lld 日前";+"这段时间的话没能识别。网络恢复后自动继续。" = "この間の音声を認識できませんでした。ネットワークが戻ると自動で再開します。";diff --git a/windows/src/Cicada/Strings/ko.lproj/Windows.strings b/windows/src/Cicada/Strings/ko.lproj/Windows.stringsindex 5c714e8..4f73b75 100644--- a/windows/src/Cicada/Strings/ko.lproj/Windows.strings+++ b/windows/src/Cicada/Strings/ko.lproj/Windows.strings@@ -118,12 +118,9 @@"还没接上 Ling" = "Ling에 연결되지 않음";"还没有会议记录" = "아직 회의 기록이 없습니다";"还没装虚拟麦克风,去设置里装一下" = "가상 마이크가 아직 설치되지 않았습니다. 설정에서 설치해 주세요";-"这个 key 不能用,检查是否复制完整,或重新创建一个" = "이 키는 사용할 수 없습니다. 전체를 복사했는지 확인하거나 새로 만들어 보세요.";"这个快捷键被别的程序占用了" = "이 단축키는 다른 프로그램에서 이미 사용 중입니다";"这台电脑没有这种语言的声音,没有发出去" = "이 PC에 해당 언어의 음성이 없어 전송하지 않았습니다";-"这段时间的话没能识别。检查网络后点重试。" = "이 구간의 음성을 인식하지 못했습니다. 네트워크를 확인한 후 다시 시도하세요.";"连不上 Ling" = "Ling에 연결할 수 없음";-"连不上 Ling,检查网络" = "Ling에 연결할 수 없습니다. 네트워크를 확인하세요.";"连不上 Ling,没有发出去" = "Ling에 연결할 수 없어 전송하지 않았습니다";"重命名" = "이름 바꾸기";"重新打开知了后生效" = "Cicada를 다시 시작하면 적용됩니다";@@ -254,7 +251,6 @@"接 AI 服务" = "AI 서비스";"仅保存在本机当前账户下,仅发送至 %@" = "이 컴퓨터의 현재 계정에만 저장되고 %@에만 전송됩니다";"听、纪要和翻译都能用,模型已经选好。" = "듣기, 회의록, 번역 모두 사용할 수 있고 모델은 이미 골라 두었습니다.";-"这个模型听不了声音,换一个支持音频输入的" = "이 모델은 오디오를 들을 수 없습니다. 오디오 입력을 지원하는 모델로 바꾸세요";"听的模型" = "듣기 모델";"要能输入音频:听对方和“我说”都用它" = "오디오 입력을 지원해야 합니다. 상대방 듣기와 ‘말하기’에 모두 쓰입니다";"例如 qwen3-omni" = "예: qwen3-omni";@@ -281,3 +277,25 @@"没人说话时不乱写" = "아무도 말하지 않을 때 아무것도 쓰지 않음";"更快" = "더 빠름";"最快,偶尔把杂音写成字" = "가장 빠름, 가끔 잡음을 글자로 씀";++/* AI 服务检查 (AICheck): the ports' own words; the rest are the Mac's. */+"正常" = "정상";+"文字 %@ 秒" = "텍스트 %@초";+"听 %@ 秒" = "듣기 %@초";+"听不了声音" = "오디오를 들을 수 없음";+"%@ 现在听不了声音" = "%@에서 지금 오디오를 들을 수 없습니다";+"%@ 只收文字。换成推荐的模型就能开始听。" = "%@은(는) 텍스트만 받습니다. 추천 모델로 바꾸면 듣기를 시작할 수 있습니다.";+"换成推荐的并开始" = "바꾸고 시작";+"重新检查并开始" = "다시 확인하고 시작";+"用完后就听不了对方" = "다 쓰면 상대방 말을 들을 수 없습니다";+"听对方暂时用不了" = "상대방 듣기를 잠시 사용할 수 없습니다";+"纪要和整句翻译先停下" = "메모와 문장 번역이 잠시 멈춥니다";+"%@ 听不了声音。" = "%@은(는) 오디오를 들을 수 없습니다.";+"上次同传没出声,用了 Windows 的声音" = "지난번 통역 때 소리가 나지 않아 Windows 음성을 사용했습니다";+"先用 Windows 的声音" = "당분간 Windows 음성을 사용합니다";+"这台电脑访问不到 %@。" = "이 PC에서 %@에 연결할 수 없습니다.";+"刚刚" = "방금";+"%lld 分钟前" = "%lld분 전";+"%lld 小时前" = "%lld시간 전";+"%lld 天前" = "%lld일 전";+"这段时间的话没能识别。网络恢复后自动继续。" = "이 구간의 음성을 인식하지 못했습니다. 네트워크가 돌아오면 자동으로 이어집니다.";diff --git a/windows/src/Cicada/TrayFlyout.cs b/windows/src/Cicada/TrayFlyout.csindex 3f22943..7c15535 100644--- a/windows/src/Cicada/TrayFlyout.cs+++ b/windows/src/Cicada/TrayFlyout.cs@@ -100,6 +100,19 @@ sealed class TrayFlyout : Windowstack.Children.Add(strip);}+ // The AI service needs the user (can't reach it, the key, money, a model gone or deaf; the+ // Mac's AIServiceStrip). On Windows the service hears too, so it comes before 开始听.+ if (app.AIProblem() is { } ai)+ {+ var text = Ui.Stack(2, Ui.Text(ai.Title, 13, Palette.AccentText, Palette.Strong), Ui.Text(ai.Detail, 11, Palette.Secondary));+ var open = Ui.Button(L("打开设置"), () => Do(app.ShowAISettings), Ui.Kind.Primary, height: 30);+ open.VerticalAlignment = VerticalAlignment.Center; open.Margin = new Thickness(10, 0, 0, 0);+ var dock = new DockPanel();+ DockPanel.SetDock(open, Dock.Right);+ dock.Children.Add(open); dock.Children.Add(text);+ stack.Children.Add(new Border { Background = Palette.AccentPale, CornerRadius = new CornerRadius(9), Padding = new Thickness(10), Margin = new Thickness(0, 14, 0, 0), Child = dock });+ }+// The one thing to dovar main = new StackPanel { Margin = new Thickness(0, 18, 0, 0) };if (listen.Listening && app.Ending is { } p)diff --git a/windows/tests/Cicada.Tests/Program.cs b/windows/tests/Cicada.Tests/Program.csindex 5a389b9..a6a49a1 100644--- a/windows/tests/Cicada.Tests/Program.cs+++ b/windows/tests/Cicada.Tests/Program.cs@@ -4,6 +4,7 @@using System.Net;using System.Reflection;using System.Text.Json.Nodes;+using System.Text.RegularExpressions;using Cicada;Environment.SetEnvironmentVariable("CICADA_HOME", Path.Combine(Path.GetTempPath(), "cicada-tests-" + Environment.ProcessId));@@ -1172,14 +1173,16 @@ static class Teststry{var (ling, s) = Using(new Service((url, body) =>- url.EndsWith("models") ? Status(200, "{\"data\":[{\"id\":\"a/b\",\"input_modalities\":[\"text\"],\"output_modalities\":[\"text\"]}]}")+ url.EndsWith("models") ? Status(200, "{\"data\":[{\"id\":\"inclusionai/ling-3.0-flash\",\"input_modalities\":[\"text\"],\"output_modalities\":[\"text\"]}]}"): body.Contains("input_audio") ? Status(400) : Reply("OK")),s: new AppSettings { AiHearModels = { ["zenmux"] = "x/text-only" } });var (state, _) = await ling.Check();Equal(KeyState.Ok, state, "the key is good");Equal(false, ling.Hears, "but the model can't hear");+ Equal("reach=ok key=ok text=ok(0.0s) hear=fail(deaf 400)", Regex.Replace(ling.Health.Summary, @"\d+\.\ds", "0.0s"), "the hear step failed");Check(!ling.CanHear && ling.Usable, "notes and translation still work");- Check(ling.TextCatalog.Contains("a/b"), "catalog fetched after a good check");+ Check(ling.TextCatalog.Contains("inclusionai/ling-3.0-flash"), "catalog fetched after a good check");+ Equal("qwen/qwen3.8-omni-flash", ling.Recommended(AICheck.StepId.Hear), "换成推荐的");s.AiHearModels.Clear();ling.KeyChanged();Equal(null, ling.Hears, "a new model is asked again");@@ -1194,15 +1197,230 @@ static class Tests{var (ling, _) = Using(new Service((_, _) => Status(401)));Equal(KeyState.Invalid, (await ling.Check()).state, "401");- (ling, _) = Using(new Service((_, _) => Status(404)));+ Equal("reach=ok key=fail(invalidKey) text=skipped hear=skipped", ling.Health.Summary, "401 stops at the key");+ (ling, _) = Using(new Service((url, body) => body.Contains("input_audio") || url.EndsWith("models") ? Status(200, "{\"data\":[]}") : Status(404)));await ling.Check();- Equal("%@ 拒绝了请求(HTTP %lld),请检查模型名 ZenMux 404", $"{ling.Problem?.Key} {string.Join(" ", ling.Problem?.Args ?? [])}", "404 names the service and the status");+ Equal(AICheck.Reason.NoModel, ling.Health.Failure?.Why, "a 404 on the text model");+ Equal("ZenMux 上找不到 inclusionai/ling-3.0-flash 这个模型。", ling.Health.Message(ling.ServiceName, ling.ServiceHost, ling.Config.TextModel, ling.HearName), "names the service and the model");+ (ling, _) = Using(new Service((_, _) => throw new HttpRequestException("no route")));+ ling.ProxyHint = () => Task.FromResult(new AICheck.ProxyHint(AICheck.ProxyKind.AppRunning, 7890));+ await ling.Check();+ Equal("reach=fail(unreachable) key=skipped text=skipped hear=skipped proxy=appRunning(7890)", ling.Health.Summary, "a network error stops at reach, with the proxy");+ (ling, _) = Using(new Service((url, _) => url.EndsWith("models") ? Status(404) : Status(429)));+ await ling.Check();+ Check(ling.Health.Passed && ling.Health.IsBusy && !ling.Health.NeedsUser, "429 passes as busy");+ (ling, _) = Using(new Service((_, _) => Reply("ok")), key: "sk-mgmt-0000");+ await ling.Check();+ Equal("reach=untested key=fail(mgmtKey) text=skipped hear=skipped", ling.Health.Summary, "a management key isn't sent");(ling, _) = Using(new Service((_, _) => Reply("ok")), "openrouter", key: null);Equal(KeyState.None, ling.KeyState, "no key");}finally { LingClient.Spacing = old; }}+ public static async Task CheckFindsModelsGoneFromTheList()+ {+ var old = LingClient.Spacing; LingClient.Spacing = 0;+ try+ {+ // ZenMux lists modalities at the top level: the text model is gone, and the hear model doesn't take audio.+ var (ling, _) = Using(new Service((url, _) => url.EndsWith("models")+ ? Status(200, "{\"data\":[{\"id\":\"qwen/qwen3.8-flash\",\"input_modalities\":[\"text\"]},{\"id\":\"qwen/qwen3.8-omni-flash\",\"input_modalities\":[\"text\"]},{\"id\":\"a/ears\",\"input_modalities\":[\"audio\",\"text\"]}]}")+ : Reply("OK")));+ await ling.Check();+ Equal(AICheck.Kind.Fail, ling.Health[AICheck.StepId.Text].Kind, "the text model is gone");+ Equal(AICheck.Reason.Deaf, ling.Health[AICheck.StepId.Hear].Why, "the hear model isn't listed as hearing");+ }+ finally { LingClient.Spacing = old; }+ }++ public static async Task CheckReadsOpenRouterBalance()+ {+ var old = LingClient.Spacing; LingClient.Spacing = 0;+ try+ {+ var (ling, _) = Using(new Service((url, _) =>+ url.EndsWith("/key") ? Status(200, "{\"data\":{\"limit_remaining\":0.3}}")+ : url.EndsWith("/credits") ? Status(200, "{\"data\":{\"total_credits\":10,\"total_usage\":3}}")+ : url.EndsWith("models") ? Status(404) : Reply("OK")), "openrouter");+ await ling.Check();+ Equal(0.3, ling.Health.Balance, "the key's limit is the smaller");+ Check(ling.Health.Passed && ling.Health.NeedsUser, "passed, but low");+ Equal("OpenRouter 余额快用完了(还剩 $0.30)", ling.Health.BalanceLine("OpenRouter"), "balance line");+ }+ finally { LingClient.Spacing = old; }+ }++ public static async Task RealRequestsKeepTheStepsCurrent()+ {+ var old = LingClient.Spacing; LingClient.Spacing = 0;+ try+ {+ int status = 200;+ var (ling, _) = Using(new Service((url, body) => status == 200 ? Reply("OK") : Status(status)));+ await ling.Chat("c", "i", Priority.Translate);+ Equal("reach=ok key=ok text=ok(0.0s) hear=untested passive", Regex.Replace(ling.Health.Summary, @"\d+\.\ds", "0.0s"), "a translation proves the text model");+ status = 404;+ try { await ling.Chat("c", "i", Priority.Translate, model: ling.Config.HearModel, audio: [1]); } catch (LingException) { }+ Equal(AICheck.Reason.Deaf, ling.Health.Failure?.Why, "a 404 on audio is the hear model, never the text model");+ Equal(AICheck.Kind.Ok, ling.Health[AICheck.StepId.Text].Kind, "the text model stays proven");+ status = 200;+ await ling.Chat("c", "i", Priority.Translate, model: ling.Config.HearModel, audio: [1]);+ Equal(null, ling.Health.Failure, "heard again: clear");+ int changes = 0;+ ling.Changed += () => changes++;+ await ling.Chat("c", "i", Priority.Translate);+ await ling.Chat("c", "i", Priority.Translate);+ Equal(0, changes, "the same good result again changes nothing");+ status = 503;+ try { await ling.Chat("c", "i", Priority.Translate); } catch (LingException) { }+ Equal(null, ling.Health.Failure, "one server error in a meeting is left alone");+ status = 401;+ try { await ling.Chat("c", "i", Priority.Translate); } catch (LingException) { }+ Equal(KeyState.Invalid, ling.KeyState, "a refused key stops every request");+ }+ finally { LingClient.Spacing = old; }+ }++ public static async Task AnOlderCheckNeverLandsOverANewerOne()+ {+ var old = LingClient.Spacing; LingClient.Spacing = 0;+ try+ {+ var (ling, s) = Using(new Service((url, body) =>+ {+ if (body.Contains("slow/gone")) { Thread.Sleep(400); return Status(404); }+ return url.EndsWith("models") ? Status(404) : Reply("OK");+ }), s: new AppSettings { AiModels = { ["zenmux"] = "slow/gone" } });+ var first = ling.Check();+ await Task.Delay(50);+ s.AiModels["zenmux"] = "fast/here";+ ling.KeyChanged();+ await ling.Check();+ await first;+ Equal(null, ling.Health.Failure, "the model chosen since is the one checked");+ }+ finally { LingClient.Spacing = old; }+ }++ // MARK: AI 服务检查 (the Mac's AICheckTests, case for case, plus hearing)++ public static void EachFailureStopsAtItsStep()+ {+ static string C(LingException.Kind k, int status, AICheck.StepId at) => AICheck.Classify(k, status, at)?.ToString() ?? "null";+ Equal("(Reach, Unreachable, )", C(LingException.Kind.Network, 0, AICheck.StepId.Text), "network");+ Equal("(Reach, Unreachable, )", C(LingException.Kind.Timeout, 0, AICheck.StepId.Key), "timeout");+ Equal("(Key, InvalidKey, )", C(LingException.Kind.InvalidKey, 0, AICheck.StepId.Text), "401");+ Equal("(Key, NoCredit, 402)", C(LingException.Kind.Http, 402, AICheck.StepId.Text), "402");+ Equal("(Text, NoModel, 404)", C(LingException.Kind.Http, 404, AICheck.StepId.Text), "404");+ Equal("(Text, NoModel, 400)", C(LingException.Kind.Http, 400, AICheck.StepId.Text), "400");+ Equal("(Text, Busy, )", C(LingException.Kind.RateLimited, 0, AICheck.StepId.Text), "429");+ Equal("(Key, ServerError, 503)", C(LingException.Kind.Http, 503, AICheck.StepId.Key), "5xx");+ Equal("null", C(LingException.Kind.Hijacked, 0, AICheck.StepId.Text), "hijacked says nothing");+ foreach (var code in new[] { 400, 404, 415, 422 })+ Equal($"(Hear, Deaf, {code})", C(LingException.Kind.Http, code, AICheck.StepId.Hear), $"{code} on audio");+ Equal("(Hear, Busy, )", C(LingException.Kind.RateLimited, 0, AICheck.StepId.Hear), "429 on audio");+ }++ public static void AFailedStepSkipsTheRestAndAReplyProvesTheOnesBefore()+ {+ var c = new AICheck();+ c.Fail(AICheck.StepId.Key, AICheck.Reason.InvalidKey);+ Equal("reach=ok key=fail(invalidKey) text=skipped hear=skipped", c.Summary, "key");+ Equal(AICheck.StepId.Key, c.Failure?.Step, "failure");+ var m = new AICheck();+ m.Fail(AICheck.StepId.Key, AICheck.Reason.MgmtKey, reached: false);+ Equal(AICheck.Kind.Untested, m[AICheck.StepId.Reach].Kind, "nothing sent");+ // Hearing doesn't need the text model, nor the other way round.+ var t = new AICheck();+ t.Fail(AICheck.StepId.Text, AICheck.Reason.NoModel, 404);+ Equal("reach=ok key=ok text=fail(noModel 404) hear=untested", t.Summary, "text");+ var h = new AICheck();+ h.Fail(AICheck.StepId.Hear, AICheck.Reason.Deaf, 400);+ Equal("reach=ok key=ok text=untested hear=fail(deaf 400)", h.Summary, "hear");+ }++ public static void ASuccessClearsAnEarlierFailure()+ {+ var c = new AICheck();+ c.Fail(AICheck.StepId.Reach, AICheck.Reason.Unreachable);+ c.Proxy = new AICheck.ProxyHint(AICheck.ProxyKind.None);+ c.Pass(AICheck.StepId.Text, 1.5);+ Equal(null, c.Failure, "cleared");+ Equal("reach=ok key=ok text=ok(1.5s) hear=untested", c.Summary, "a chat proves reach, key and text");+ Equal(null, c.Proxy, "proxy hint gone");+ }++ public static void BusyPassesAndNeedsNobody()+ {+ var c = new AICheck();+ c.Busy(AICheck.StepId.Text);+ c.At = DateTimeOffset.Now;+ Check(c.Passed && c.IsBusy && !c.NeedsUser, "busy passes");+ Equal("ZenMux 现在很忙,key 没问题。开会时会自动重试。", c.Message("ZenMux", "zenmux.ai", "m", "h"), "busy words");+ }++ public static void KeyPrefixesTellWhoseKeyItIs()+ {+ Equal(("openrouter", false), AICheck.Owner("sk-or-v1-abc"), "OpenRouter");+ Equal(("zenmux", false), AICheck.Owner(" sk-payg-abc\n"), "ZenMux");+ Equal(("zenmux", true), AICheck.Owner("sk-mgmt-abc"), "management");+ Equal(null, AICheck.Owner("sk-abc"), "nothing to tell");+ }++ public static void BalanceIsTheSmallerOfKeyLimitAndCredits()+ {+ const string key = "{\"data\":{\"limit_remaining\":1.72}}", credits = "{\"data\":{\"total_credits\":10.0,\"total_usage\":3.92}}";+ Equal(1.72, AICheck.BalanceFrom(key, credits), "both");+ Check(Math.Abs(AICheck.BalanceFrom("{\"data\":{\"limit_remaining\":null}}", credits)!.Value - 6.08) < 0.001, "no key limit: credits");+ Equal(1.72, AICheck.BalanceFrom(key, null), "key only");+ Equal(null, AICheck.BalanceFrom(null, null), "nothing");+ var c = new AICheck { Balance = 0.3 };+ Check(c.IsLowBalance && c.NeedsUser, "low");+ }++ public static void ListedModelsReadsEveryID()+ {+ var ids = AICheck.ListedModels("{\"data\":[{\"id\":\"inclusionai/ling-3.0-flash\"},{\"id\":\"qwen/qwen3.8-flash\"}]}");+ Equal("inclusionai/ling-3.0-flash,qwen/qwen3.8-flash", string.Join(",", ids!.Order()), "ids");+ Equal(null, AICheck.ListedModels("{}"), "no data");+ Equal(null, AICheck.ListedModels("{\"data\":[]}"), "empty");+ // OpenRouter says modalities under architecture; a list that says nothing proves nothing about hearing.+ var hearing = AICheck.ListedHearing("{\"data\":[{\"id\":\"a\",\"architecture\":{\"input_modalities\":[\"text\",\"audio\"]}},{\"id\":\"b\",\"architecture\":{\"input_modalities\":[\"text\"]}}]}");+ Equal("a", string.Join(",", hearing!), "hearing");+ Equal(null, AICheck.ListedHearing("{\"data\":[{\"id\":\"a\"}]}"), "nothing said");+ }++ public static void MessagesNameTheServiceAndTheProxyHintFollowsTheProxy()+ {+ var c = new AICheck();+ c.Fail(AICheck.StepId.Reach, AICheck.Reason.Unreachable);+ Equal("这台电脑访问不到 zenmux.ai。", c.Message("ZenMux", "zenmux.ai", "m", "h"), "unreachable");+ Equal(null, c.ProxyLine("ZenMux", "zenmux.ai"), "no hint yet");+ c.Proxy = new AICheck.ProxyHint(AICheck.ProxyKind.AppRunning, 7890);+ Check(c.ProxyLine("ZenMux", "zenmux.ai")!.Contains("7890"), "port, not 7,890");+ c.Proxy = new AICheck.ProxyHint(AICheck.ProxyKind.SystemOn);+ Check(c.ProxyLine("ZenMux", "zenmux.ai")!.Contains("zenmux.ai"), "system on names the host");+ c.Proxy = new AICheck.ProxyHint(AICheck.ProxyKind.None);+ Check(c.ProxyLine("ZenMux", "zenmux.ai")!.Contains("ZenMux"), "none names the service");+ var m = new AICheck();+ m.Fail(AICheck.StepId.Text, AICheck.Reason.NoModel, 404);+ Check(m.Message("ZenMux", "zenmux.ai", "x/y", "h")!.Contains("x/y"), "model named");+ var d = new AICheck();+ d.Fail(AICheck.StepId.Hear, AICheck.Reason.Deaf, 400);+ Equal("qwen3:14b 听不了声音。", d.Message("ZenMux", "zenmux.ai", "m", "qwen3:14b"), "deaf names the hear model");+ Check(d.NeedsUser, "deaf needs the user");+ }++ public static async Task ProxyProbeReadsTheSystemThenThePorts()+ {+ Equal(AICheck.ProxyKind.SystemOn, (await ProxyProbe.Hint(() => true)).Kind, "system proxy on");+ var listener = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0);+ listener.Start();+ try { Check(await ProxyProbe.Listening(((IPEndPoint)listener.LocalEndpoint).Port), "something listens"); }+ finally { listener.Stop(); }+ }+static async Task<string> Joined(IAsyncEnumerable<byte[]> chunks){var all = new List<byte>();