知了 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): notes can use their own model, or another OpenAI-compatible service with its own address and key
wquguru5acd003b144d
diff --git a/windows/scripts/cicadactl.ps1 b/windows/scripts/cicadactl.ps1index a2c50a1..8fdfe5a 100644--- a/windows/scripts/cicadactl.ps1+++ b/windows/scripts/cicadactl.ps1@@ -1,6 +1,6 @@# 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 | hide notes | quit-# AI 服务: provider ling|openrouter|zenmux|custom | switchtoling (a status line's 改用 Ling) | ai-model hear|text|voice <id> | ai-custom-only on|off | show settings ai models+# AI 服务: provider ling|openrouter|zenmux|custom | switchtoling (a status line's 改用 Ling) | ai-model hear|text|voice|notes <id> | ai-notes same|own [address] | ai-custom-only on|off | 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 | endkeep# 改正听错的词: silentlisten zh-CN | heard <text> | fixstate | fixanswer yes|no | fixlater | fixrevert <line> | fixedit <line>=<text>[|one][|keep0] | fixundo | vocabadd Morpho=莫拉 | vocabstate (… @<id> for another meeting)diff --git a/windows/src/Cicada.Core/AICheck.cs b/windows/src/Cicada.Core/AICheck.csindex cc46d22..122238b 100644--- a/windows/src/Cicada.Core/AICheck.cs+++ b/windows/src/Cicada.Core/AICheck.cs@@ -57,6 +57,13 @@ public sealed class AICheckpublic double? Balance { get; set; }/// A custom service: how long one real sentence took, and whether the model thought first.public Speed? Translate { get; set; }+ /// A custom service whose notes go to another model or server: how that one answered (Running,+ /// Ok with seconds, or Fail with why). Null while notes use the translation model (then the+ /// steps say it all). A notes failure doesn't stop translation: Failure and Passed stay about+ /// translation.+ public State? Notes { get; set; }+ /// Translation works but the notes' own model or server doesn't (a busy one fixes itself).+ public bool NotesFailed => Notes is { Kind: Kind.Fail, Why: not Reason.Busy };/// A sentence that takes `SlowAfter` seconds often misses the 6 s a translation is given/// (Translator) and falls back to Google; a model that thinks first does every time.@@ -81,7 +88,7 @@ public sealed class AICheckpublic AICheck Clone(){- var c = new AICheck { At = At, Passive = Passive, Proxy = Proxy, Balance = Balance, Translate = Translate };+ var c = new AICheck { At = At, Passive = Passive, Proxy = Proxy, Balance = Balance, Translate = Translate, Notes = Notes };steps.CopyTo(c.steps, 0);return c;}@@ -99,7 +106,7 @@ public sealed class AICheck}}- public bool IsRunning => steps.Any(s => s.Kind == Kind.Running);+ public bool IsRunning => steps.Any(s => s.Kind == Kind.Running) || Notes?.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;@@ -273,6 +280,24 @@ public sealed class AICheck: Strings.LF("翻一句要 %@ 秒,超过 6 秒会改用 Google。换一个更小的模型会快一些。", secs);}+ /// The notes' own model or server's problem, in one sentence. `sharedKey`: notes use the+ /// translation key, so a refused key wants one of their own.+ public string? NotesLine(string host, string model, bool sharedKey)+ {+ if (Notes is not { Kind: Kind.Fail, Why: { } why } n) return null;+ return why switch+ {+ Reason.InvalidKey or Reason.MgmtKey => sharedKey ? Strings.LF("%@ 不认上面的 key,给它单独填一个。", host) : Strings.LF("%@ 说这个 key 无效,可能没复制全,或已删除。", host),+ Reason.Unreachable => Strings.LF("这台电脑访问不到 %@。", host),+ Reason.BadAddress => Strings.L("地址要用 https;这台电脑和局域网里的服务可以用 http。"),+ Reason.NoCredit => Strings.LF("%@ 账户余额不足。", host),+ Reason.NoModel => Strings.LF("%@ 上找不到 %@ 这个模型。", host, model),+ Reason.NoJSON => Strings.L("这个模型没按要求返回 JSON,写不了纪要。换一个通用模型。"),+ Reason.Busy => null,+ _ => Strings.LF("%@ 暂时出错(HTTP %lld),稍后再试。", host, n.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){@@ -297,15 +322,17 @@ public sealed class AICheckget{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+ static string Step(State s) => s.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}" : "")})",+ Kind.Ok => s.Seconds is { } sec ? $"ok({sec.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture)}s)" : "ok",+ Kind.Fail => $"fail({(s.Why is { } w ? Lower(w) : "?")}{(s.Code is { } c ? $" {c}" : "")})",var k => Lower(k),- });+ };+ var parts = Steps.Select(s => $"{Lower(s.Id)}=" + Step(s.State));return string.Join(" ", parts) + (Proxy is { } p ? $" proxy={p}" : "")+ (Balance is { } b ? $" balance={b.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)}" : "") + (Passive ? " passive" : "")- + (Translate is { } t ? $" translate={t.Seconds.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture)}s{(t.Thinks ? " thinks" : "")}" : "");+ + (Translate is { } t ? $" translate={t.Seconds.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture)}s{(t.Thinks ? " thinks" : "")}" : "")+ + (Notes is { } n ? " notes=" + Step(n) : "");}}diff --git a/windows/src/Cicada.Core/AIProviders.cs b/windows/src/Cicada.Core/AIProviders.csindex 797c223..b0e90da 100644--- a/windows/src/Cicada.Core/AIProviders.cs+++ b/windows/src/Cicada.Core/AIProviders.cs@@ -127,9 +127,20 @@ public sealed record AIProvider(string Id, string Name, string? Base, string? Si/// (Settings.swift › aiConfig). `Base` is null for a custom service without a valid address yet;/// `VoiceModel` null when the service can't speak here. `HearBase` is where the hear model is/// asked: the service's address, or a custom service's own one for it (null: not a valid address).+///+/// A custom service's notes (实时纪要, 说话人): `NotesModel` another model, and with 另一个服务+/// (`NotesOwnService`) `NotesBase` another server with its own key; null: the same as translation.+/// `NotesBadAddress`: 另一个服务 with an address that can't be used (http to the internet).public sealed record AIConfig(AIProvider Provider, string? Base, string TextModel, string HearModel,- string? VoiceModel = null, string? VoiceBase = null, string? CustomVoice = null, string? HearBase = null)+ string? VoiceModel = null, string? VoiceBase = null, string? CustomVoice = null, string? HearBase = null,+ string? NotesModel = null, string? NotesBase = null, bool NotesOwnService = false, bool NotesBadAddress = false){+ /// Notes go somewhere translation doesn't: they get their own check, result, key and start gate.+ public bool NotesApart => Provider.Id == "custom" && (NotesModel is not null || NotesBase is not null || NotesOwnService);++ /// What a notes call is sent with: notes' model at notes' address, the rest as translation.+ public AIConfig ForNotes => !NotesApart ? this : this with { TextModel = NotesModel ?? TextModel, Base = NotesBase ?? Base };+public bool IsLing => Provider.Id == "ling";public bool HasVoices => VoiceModel is not null && VoiceBase is not null;/// What the UI and errors call it ("其他(兼容 OpenAI)" is a UI key, localized by the caller).@@ -196,8 +207,15 @@ public sealed record AIConfig(AIProvider Provider, string? Base, string TextModevar name = s.AiCustomVoice.Trim();// The hear model may run as its own server; empty is the text model's address.var hearBase = s.AiCustomHearBase.Trim().Length > 0 ? AIProvider.CustomBase(s.AiCustomHearBase) : b;- return new(p, b, Pick(s.AiModels), Pick(s.AiHearModels), voice.Length > 0 ? voice : null,- voice.Length > 0 ? voiceBase : null, name.Length > 0 ? name : null, hearBase);+ var textModel = Pick(s.AiModels);+ var notesModel = s.AiModels.TryGetValue("custom.notes", out var nm) ? nm.Trim() : "";+ var notesAddress = s.AiCustomNotesOwn ? s.AiCustomNotesBase.Trim() : "";+ var notesBase = notesAddress.Length == 0 ? null : AIProvider.CustomBase(notesAddress);+ return new(p, b, textModel, Pick(s.AiHearModels), voice.Length > 0 ? voice : null,+ voice.Length > 0 ? voiceBase : null, name.Length > 0 ? name : null, hearBase,+ NotesModel: notesModel.Length == 0 || notesModel == textModel ? null : notesModel,+ NotesBase: notesBase == b ? null : notesBase, NotesOwnService: s.AiCustomNotesOwn,+ NotesBadAddress: notesAddress.Length > 0 && notesBase is null);}static string Or(string v, AIModel[] rec) => v.Length > 0 ? v : rec[0].Id;return new(p, p.Base, Or(Pick(s.AiModels), p.TextModels), Or(Pick(s.AiHearModels), p.HearModels), Or(Pick(s.AiVoiceModels), p.VoiceModels), p.Base, HearBase: p.Base);diff --git a/windows/src/Cicada.Core/Ling.cs b/windows/src/Cicada.Core/Ling.csindex 5d1e2e3..ed0fc28 100644--- a/windows/src/Cicada.Core/Ling.cs+++ b/windows/src/Cicada.Core/Ling.cs@@ -61,10 +61,14 @@ public sealed class AIKey(IKeyProtector protector, string? file = null, Func<str}}- public bool Save(string key)+ public bool Save(string key) => SaveAt(File_, key);++ /// Another key file of this user's (a custom service's notes server, `custom-notes`).+ public bool Save(string key, string service) => file is null && SaveAt(Paths.KeyFile(service), key);++ bool SaveAt(string path, string key){key = key.Trim();- var path = File_;lock (gate){try@@ -86,9 +90,12 @@ public sealed class AIKey(IKeyProtector protector, string? file = null, Func<str}/// Removes the key of the service in use only.- public void Remove()+ public void Remove() => RemoveAt(File_);++ public void Remove(string service) { if (file is null) RemoveAt(Paths.KeyFile(service)); }++ void RemoveAt(string path){- var path = File_;lock (gate){try { File.Delete(path); } catch { }@@ -202,6 +209,25 @@ public sealed class LingClient}public bool HasKey => CurrentKey() is not null;++ /// The key file of a custom service's notes server (另一个服务), as on the Mac.+ public const string NotesKeyName = "custom-notes";++ /// The key notes are sent with: with 另一个服务, their own key file if there is one, else the+ /// translation key ("不填就用上面的 key").+ public string? NotesKey() => Config.NotesOwnService && key.Read(NotesKeyName) is { } own ? own : CurrentKey();++ /// Notes have a key file of their own (另一个服务 only).+ public bool NotesHasOwnKey => Config.NotesOwnService && key.Read(NotesKeyName) is not null;++ /// Notes' own key (另一个服务); the caller checks again (Controller.AIChanged).+ public bool SaveNotesKey(string raw) => raw.Trim().Length > 0 && key.Save(raw.Trim(), NotesKeyName);++ /// Notes go back to the translation key.+ public void RemoveNotesKey() => key.Remove(NotesKeyName);++ /// Notes' own server's text models from its `/models` (empty while notes share translation's address).+ public IReadOnlyList<string> NotesCatalog { get; private set; } = [];public bool Usable => HasKey && KeyState != KeyState.Invalid;/// Voices in the room from this service (else Windows' own voice speaks).public bool Speaks => Usable && Config.HasVoices;@@ -221,7 +247,7 @@ public sealed class LingClientKeyState = CurrentKey() is null ? KeyState.None : KeyState.Unchecked;LastVoice = null;listed = listedHearing = null;- TextCatalog = HearCatalog = [];+ TextCatalog = HearCatalog = NotesCatalog = [];Changed?.Invoke();}@@ -264,14 +290,14 @@ public sealed class LingClientif (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);+ else await Probe(r, c, k, gen);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)+ async Task Probe(AICheck r, AIConfig c, string k, int gen){double Since(DateTime t) => (DateTime.UtcNow - t).TotalSeconds;void Failed(LingException e, AICheck.StepId step)@@ -299,7 +325,15 @@ public sealed class LingClientr.Translate = new AICheck.Speed(Since(t), AIConfig.Thought(root));}r.Pass(AICheck.StepId.Text, Since(t));- if (c.Provider.Id == "custom")+ if (c.NotesApart)+ {+ // Notes at their own model or server: their failure is theirs, translation goes on.+ r.Notes = AICheck.State.Running;+ lock (healthGate) { if (gen == generation) health = r.Clone(); }+ Changed?.Invoke();+ r.Notes = await CheckNotes(c);+ }+ else if (c.Provider.Id == "custom"){const string ask = "Reply with the JSON object {\"ok\": true}.";try { await Chat(ask, "Reply.", Priority.Speak, json: true, maxTokens: 20, timeout: 30, jsonFallback: false); }@@ -334,8 +368,11 @@ public sealed class LingClientcatch (Exception) { }}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))+ // A model the service no longer lists fails here, before a meeting finds out. On a custom+ // service, one a real sentence just went through exists whatever the list says (an alias,+ // a name typed by hand).+ var proven = c.Provider.Id == "custom" && r.Translate is not null;+ if (listed is { } ids && c.TextModel.Length > 0 && !proven && r[AICheck.StepId.Text].Kind != AICheck.Kind.Fail && !ids.Contains(c.TextModel))r.Fail(AICheck.StepId.Text, AICheck.Reason.NoModel);// The list is the text address's: it says nothing about a hear model served elsewhere.if (listedHearing is { } hearing && !c.HearElsewhere && c.HearModel.Length > 0 && r[AICheck.StepId.Hear].Kind != AICheck.Kind.Fail && !hearing.Contains(c.HearModel))@@ -389,9 +426,30 @@ public sealed class LingClient/// 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)+ void Observe(LingException? failure, double seconds, bool audio, bool notes = false){if (!HasKey || Volatile.Read(ref checking) > 0 || SimulateCheck is not null) return;+ if (notes)+ {+ // Notes at their own model or server: theirs alone, translation's steps (and KeyState) are untouched.+ AICheck.State now;+ if (failure is not null)+ {+ if (AICheck.Classify(failure.Failure, failure.Status, AICheck.StepId.Text) is not { } f || f.Why == AICheck.Reason.ServerError) return;+ now = AICheck.State.Fail(f.Why, f.Code);+ }+ else now = AICheck.State.Ok(seconds);+ lock (healthGate)+ {+ if (health.Notes?.Kind == AICheck.Kind.Ok && now.Kind == AICheck.Kind.Ok) return;+ if (health.Notes is { } old && old with { Seconds = null } == now with { Seconds = null }) return;+ health = health.Clone();+ health.Notes = now;+ }+ Log.Debug($"ai: notes from a real request -> {health.Summary}");+ Changed?.Invoke();+ return;+ }var step = audio ? AICheck.StepId.Hear : AICheck.StepId.Text;AICheck r;bool wasUnreachable;@@ -443,9 +501,9 @@ public sealed class LingClient}/// 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)+ async Task<string?> GetText(string path, string k, string? at = null){- if (Config.Base is not { } b) return null;+ if ((at ?? Config.Base) is not { } b) return null;try{using var req = new HttpRequestMessage(HttpMethod.Get, new Uri(new Uri(b), path));@@ -472,6 +530,63 @@ public sealed class LingClientChanged?.Invoke();}+ /// Notes' own model or server (AIConfig.NotesApart): one JSON request the way a meeting's notes+ /// ask, sent straight (no gate, no retries: a check), then, at another address, its model list+ /// for the menu.+ async Task<AICheck.State> CheckNotes(AIConfig config)+ {+ if (config.NotesBadAddress) return AICheck.State.Fail(AICheck.Reason.BadAddress);+ var c = config.ForNotes;+ if (NotesKey() is not { } k || c.Base is not { } b) return AICheck.State.Fail(AICheck.Reason.InvalidKey);+ var url = new Uri(new Uri(b), "chat/completions");+ var body = new JsonObject+ {+ ["model"] = c.TextModel,+ ["messages"] = new JsonArray(+ new JsonObject { ["role"] = "system", ["content"] = "Reply with the JSON object {\"ok\": true}." },+ new JsonObject { ["role"] = "user", ["content"] = "Reply." }),+ ["stream"] = false,+ };+ c.Shape(body, 20, templateKwargs: !noTemplateKwargs.ContainsKey(b));+ body["response_format"] = new JsonObject { ["type"] = "json_object" };+ var asked = DateTime.UtcNow;+ AICheck.State result;+ try+ {+ await PostChat(url, body, b, k, 60, default);+ result = AICheck.State.Ok((DateTime.UtcNow - asked).TotalSeconds);+ }+ catch (LingException e) when (e.Failure == LingException.Kind.Http && e.Status is 400 or 422)+ {+ // JSON mode refused (some hosts of a model do): meetings then ask without it, so what+ // counts is whether the model still answers with a JSON object.+ body.Remove("response_format");+ string? said = null;+ try { said = Str((await PostChat(url, body, b, k, 60, default))["choices"]?[0]?["message"]?["content"]); } catch (LingException) { }+ result = AnswersJSON(said) ? AICheck.State.Ok((DateTime.UtcNow - asked).TotalSeconds) : AICheck.State.Fail(AICheck.Reason.NoJSON, e.Status);+ }+ catch (LingException e)+ {+ var f = AICheck.Classify(e.Failure, e.Status, AICheck.StepId.Text) ?? (AICheck.StepId.Text, AICheck.Reason.ServerError, null);+ result = AICheck.State.Fail(f.Why, f.Code);+ }+ catch (Exception) { result = AICheck.State.Fail(AICheck.Reason.Unreachable); }+ if (c.Base != config.Base) await FetchNotesCatalog();+ return result;+ }++ /// Notes' own address's text models, for its menu. Quietly empty when it has no `/models`.+ public async Task FetchNotesCatalog()+ {+ var c = Config;+ var b = c.ForNotes.Base;+ if (!c.NotesApart || b is null || b == c.Base || NotesKey() is not { } k) return;+ if (await GetText("models", k, b) is not { } body) return;+ NotesCatalog = AIProvider.Catalog(body, [], hears: false);+ Log.Debug($"ai notes: {NotesCatalog.Count} models");+ Changed?.Invoke();+ }+/// One chat completion. `content` goes in the system message, `instruction` is the fixed user/// message, `audio` (a WAV) goes before it for the hear model. Notes and heard audio retry 429s/// with backoff (RetryWaits); the rest fail fast so the caller can fall back. `model` defaults to@@ -480,14 +595,23 @@ public sealed class LingClient/// queue, so lines stay in order. Audio goes to the hear model's address (a custom service's own/// one for it). `reply` sees the whole reply before its text is read (the check's thinking test)./// A JSON request refused with 400 is asked again without JSON mode unless `jsonFallback` is- /// off (the check asks again itself).+ /// off (the check asks again itself). Notes (`notes`, by default the Notes priority) go to a+ /// custom service's notes model, address and key when they have their own (AIConfig.ForNotes);+ /// a live line's corrections ride at Notes priority but are translation's, as on the Mac.public async Task<string> Chat(string content, string instruction, Priority priority, bool json = false,int maxTokens = 1024, double timeout = 30, string? model = null, byte[]? audio = null, bool patient = false,- CancellationToken cancel = default, Action<JsonNode>? reply = null, bool jsonFallback = true)+ CancellationToken cancel = default, Action<JsonNode>? reply = null, bool jsonFallback = true, bool? notes = null){- var k = CurrentKey() ?? throw new LingException(LingException.Kind.NoKey);- if (KeyState == KeyState.Invalid) throw new LingException(LingException.Kind.InvalidKey);- var c = Config;+ var all = Config;+ var notesSide = (notes ?? priority == Priority.Notes) && audio is null && all.NotesApart;+ // 另一个服务 at an address that can't be used: never fall back to translation's server with+ // the notes' key (the Mac does; the check already says the address is wrong).+ if (notesSide && all.NotesBadAddress) throw new LingException(LingException.Kind.NoKey);+ var c = notesSide ? all.ForNotes : all;+ var k = (notesSide ? NotesKey() : CurrentKey()) ?? throw new LingException(LingException.Kind.NoKey);+ // A refused notes key stops notes only; a refused translation key stops everything else.+ if (notesSide ? Health.Notes?.Why is AICheck.Reason.InvalidKey or AICheck.Reason.MgmtKey : KeyState == KeyState.Invalid)+ throw new LingException(LingException.Kind.InvalidKey);var b = audio is null ? c.Base : c.Provider.Id == "custom" ? c.HearBase : c.HearBase ?? c.Base;if (b is null) throw new LingException(LingException.Kind.NoKey);model ??= c.TextModel;@@ -505,12 +629,13 @@ public sealed class LingClientvar url = new Uri(new Uri(b), "chat/completions");var waits = RetryWaits(priority, audio is not null, patient);+ var g = GateFor(b);long? ticket = null;for (int attempt = 1; ; attempt++){var queued = DateTime.UtcNow;// One that wouldn't retry fails at once while the service is cooling down: its caller falls back.- ticket = await Acquire(priority, c.Provider.Spacing, cancel, ticket, failIfPaused: waits.Length == 0);+ ticket = await Acquire(g, priority, c.Provider.Spacing, cancel, ticket, failIfPaused: waits.Length == 0);var started = DateTime.UtcNow;if ((started - queued).TotalSeconds > 1) Log.Debug($"ling: {priority} waited {(started - queued).TotalMilliseconds:F0} ms at the gate");try@@ -539,14 +664,14 @@ 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);+ Observe(null, (DateTime.UtcNow - started).TotalSeconds, audio is not null, notesSide);return trimmed;}catch (LingException e){- Observe(e, 0, audio is not null);+ Observe(e, 0, audio is not null, notesSide);if (e.Failure != LingException.Kind.RateLimited) throw;- var wait = RateLimited(waits.Length > 0 ? waits[Math.Min(attempt, waits.Length) - 1] : 1, e.RetryAfter);+ var wait = RateLimited(g, waits.Length > 0 ? waits[Math.Min(attempt, waits.Length) - 1] : 1, e.RetryAfter);if (attempt > waits.Length || wait is null) { RateLimitedAt = DateTimeOffset.Now; Changed?.Invoke(); throw; }Log.Debug($"ling: {priority} 429, retry in {wait:F1} s");}@@ -572,13 +697,13 @@ public sealed class LingClient/// (Retry-After; Ling sends none), plus a little jitter. The queue waits at the gate instead of/// each request spending its retries on the same limit. Null when that is over MaxPause (the/// gate still holds for MaxPause).- double? RateLimited(double backoff, double? retryAfter)+ double? RateLimited(StartGate g, double backoff, double? retryAfter){var wait = Math.Max(backoff, retryAfter ?? 0) + Random.Shared.NextDouble() * 0.5;lock (gate){var until = clock.UtcNow.AddSeconds(Math.Min(wait, MaxPause));- if (until > pausedUntil) pausedUntil = until;+ if (until > g.PausedUntil) g.PausedUntil = until;}return wait <= MaxPause ? wait : null;}@@ -615,7 +740,7 @@ public sealed class LingClientvar ids = c.Voices.Select(v => v.Id).ToList();body["voice"] = voice is not null && ids.Contains(voice) ? voice : ids.FirstOrDefault() ?? c.CustomVoice ?? "Kore";}- await Acquire(Priority.Speak, c.Provider.Spacing, cancel);+ await Acquire(GateFor(c.VoiceBase), Priority.Speak, c.Provider.Spacing, cancel);var started = DateTime.UtcNow;using var req = new HttpRequestMessage(HttpMethod.Post, new Uri(new Uri(c.VoiceBase!), "audio/speech")){@@ -801,37 +926,55 @@ public sealed class LingClient}// Start gate: request starts ≥ the service's spacing apart, the most urgent waiting one first,- // none while the service is cooling down after a 429.+ // none while the server is cooling down after a 429. One per server (by host): notes or a hear+ // model on another server don't wait behind translation, and a 429 there doesn't hold it back./// Tests only: overrides the service's spacing.public static double? Spacing { get; set; }readonly GateClock clock;+ /// Guards every StartGate and the shared ticket counter.readonly object gate = new();- DateTime lastStart = DateTime.MinValue;- DateTime pausedUntil = DateTime.MinValue;- readonly List<(Priority priority, long seq, TaskCompletionSource ready)> waiting = [];+ readonly Dictionary<string, StartGate> gates = [];long seq;- bool pumping;- double spacing = 0.6;++ sealed class StartGate+ {+ public DateTime LastStart = DateTime.MinValue;+ public DateTime PausedUntil = DateTime.MinValue;+ public readonly List<(Priority priority, long seq, TaskCompletionSource ready)> Waiting = [];+ public bool Pumping;+ public double Spacing = 0.6;+ }++ /// The gate of the server at `address` (its host; the service's when there is none).+ StartGate GateFor(string? address)+ {+ var host = Host(address ?? Config.Base);+ lock (gate)+ {+ if (!gates.TryGetValue(host, out var g)) gates[host] = g = new StartGate();+ return g;+ }+ }/// Waits for this request's turn to start. `ticket` is a retry's first one, which keeps its/// place ahead of requests queued after it. Returns the ticket.- Task<long> Acquire(Priority priority, double serviceSpacing, CancellationToken cancel, long? ticket = null, bool failIfPaused = false)+ Task<long> Acquire(StartGate g, Priority priority, double serviceSpacing, CancellationToken cancel, long? ticket = null, bool failIfPaused = false){lock (gate){- spacing = Spacing ?? serviceSpacing;+ g.Spacing = Spacing ?? serviceSpacing;var now = clock.UtcNow;- if (failIfPaused && pausedUntil > now) throw new LingException(LingException.Kind.RateLimited);+ if (failIfPaused && g.PausedUntil > now) throw new LingException(LingException.Kind.RateLimited);var me = ticket ?? ++seq;- if (waiting.Count == 0 && !pumping && Wait(now) <= Slack)+ if (g.Waiting.Count == 0 && !g.Pumping && Wait(g, now) <= Slack){- lastStart = now;+ g.LastStart = now;return Task.FromResult(me);}var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);- waiting.Add((priority, me, ready));- if (!pumping) { pumping = true; _ = Pump(); }+ g.Waiting.Add((priority, me, ready));+ if (!g.Pumping) { g.Pumping = true; _ = Pump(g); }return ready.Task.WaitAsync(cancel).ContinueWith(t => { t.GetAwaiter().GetResult(); return me; }, TaskScheduler.Default);}}@@ -840,23 +983,23 @@ public sealed class LingClientconst double Slack = 0.001;/// Seconds until the next start may go (gate held).- double Wait(DateTime now) => Math.Max(spacing - (now - lastStart).TotalSeconds, (pausedUntil - now).TotalSeconds);+ static double Wait(StartGate g, DateTime now) => Math.Max(g.Spacing - (now - g.LastStart).TotalSeconds, (g.PausedUntil - now).TotalSeconds);- async Task Pump()+ async Task Pump(StartGate g){while (true){double wait;lock (gate){- if (waiting.Count == 0) { pumping = false; return; }+ if (g.Waiting.Count == 0) { g.Pumping = false; return; }var now = clock.UtcNow;- wait = Wait(now);+ wait = Wait(g, now);if (wait <= Slack){- var next = waiting.MinBy(w => ((int)w.priority, w.seq));- waiting.Remove(next);- lastStart = now;+ var next = g.Waiting.MinBy(w => ((int)w.priority, w.seq));+ g.Waiting.Remove(next);+ g.LastStart = now;next.ready.TrySetResult();continue;}diff --git a/windows/src/Cicada.Core/Settings.cs b/windows/src/Cicada.Core/Settings.csindex db8e5bb..85ad271 100644--- a/windows/src/Cicada.Core/Settings.cs+++ b/windows/src/Cicada.Core/Settings.cs@@ -26,6 +26,11 @@ public sealed class AppSettings/// 语音和文字只发给你的服务 (the Mac's key): with the custom service, Google Translate is never/// asked. Kept when another service is picked, but only acts on the custom one (GoogleOff).[JsonPropertyName("aiCustomOnly")] public bool AiCustomOnly { get; set; }+ /// A custom service's notes (the Mac's keys): 另一个服务 (its own address, empty: the same one, and+ /// its own key in the `custom-notes` key file). Off keeps the address, so switching back and+ /// forth loses nothing. The notes model is AiModels["custom.notes"] (empty: the translation model).+ [JsonPropertyName("aiCustomNotesOwn")] public bool AiCustomNotesOwn { get; set; }+ [JsonPropertyName("aiCustomNotesBase")] public string AiCustomNotesBase { get; set; } = "";[JsonIgnore] public bool GoogleOff => AiProvider == "custom" && AiCustomOnly;/// 打开麦克风: "both" while the mic is on, else "system" (the Mac's listenSource values; "room",/// the mic alone, is the Mac's on macOS 14/15). Not saved: every launch starts with the mic off.diff --git a/windows/src/Cicada.Core/Translator.cs b/windows/src/Cicada.Core/Translator.csindex 52ea99f..be838ac 100644--- a/windows/src/Cicada.Core/Translator.cs+++ b/windows/src/Cicada.Core/Translator.cs@@ -250,7 +250,8 @@ public sealed class Translator(LingClient ling, HttpMessageHandler? google = nulprompt += "\nSubtitle: " + text;try{- var out_ = await ling.Chat(prompt, "JSON only.", priority, maxTokens: 600, timeout: 6);+ // A live line's translation, even at Notes priority: it goes to translation's model and server.+ var out_ = await ling.Chat(prompt, "JSON only.", priority, maxTokens: 600, timeout: 6, notes: false);if (out_.Length == 0) return null;if (Correction.Parse(out_, text) is not { } parsed){diff --git a/windows/src/Cicada/App.cs b/windows/src/Cicada/App.csindex 33facc1..f88cc6d 100644--- a/windows/src/Cicada/App.cs+++ b/windows/src/Cicada/App.cs@@ -1054,6 +1054,11 @@ sealed class Controller{var p = Settings.AiProvider;if (kind == "text" && p == "ling") Settings.Model = model.Length > 0 ? model : LingClient.DefaultModel;+ // A custom service's notes model: "" is the translation model's.+ else if (kind == "notes")+ {+ if (model.Length > 0) Settings.AiModels["custom.notes"] = model; else Settings.AiModels.Remove("custom.notes");+ }else{var table = kind switch { "text" => Settings.AiModels, "hear" => Settings.AiHearModels, "voice" => Settings.AiVoiceModels, _ => null };@@ -1175,6 +1180,7 @@ sealed class Controllerreturn new JsonObject{["provider"] = c.Provider.Id, ["base"] = c.Base, ["hearBase"] = c.HearBase, ["text"] = c.TextModel, ["hear"] = c.HearModel, ["voice"] = c.VoiceModel,+ ["notesBase"] = c.NotesApart ? c.ForNotes.Base : null, ["notesModel"] = c.NotesApart ? c.ForNotes.TextModel : null, ["notesOwnKey"] = Ling.NotesHasOwnKey,["state"] = Ling.KeyState.ToString(), ["hears"] = Ling.Hears, ["seconds"] = Ling.Seconds is { } s ? Math.Round(s, 1) : null,["check"] = Ling.Health.Summary,["problem"] = Ling.Health.Message(Ling.ServiceName, Ling.ServiceHost, Ling.Config.TextModel, Ling.HearName),@@ -1442,6 +1448,15 @@ static class DebugServer_ = app.Ling.Check();break;case "ai-custom-only": app.Settings.AiCustomOnly = arg == "on"; app.Settings.Save(); app.AIChanged(); break;+ // 纪要 on a custom service: "ai-notes same|own [address]" (the notes model: ai-model notes <id>).+ case "ai-notes":+ {+ var p = arg.Split(' ', 2);+ app.Settings.AiCustomNotesOwn = p[0] == "own";+ if (p.Length > 1) app.Settings.AiCustomNotesBase = p[1].Trim();+ app.Settings.Save(); app.AIChanged();+ break;+ }case "ai-model":{var kv = arg.Split(' ', 2);diff --git a/windows/src/Cicada/ModelPicker.cs b/windows/src/Cicada/ModelPicker.csnew file mode 100644index 0000000..19c72cd--- /dev/null+++ b/windows/src/Cicada/ModelPicker.cs@@ -0,0 +1,121 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using System.Windows.Documents;+using System.Windows.Input;+using System.Windows.Media;+using static Cicada.Strings;++namespace Cicada.App;++/// A custom service's model once its `/models` listed some (AISettings.swift › ModelPicker): a+/// button that opens the list with a search box on top. A name the service doesn't list can be+/// typed (an alias, a model it hides): 用 X(列表里没有). Return takes the only match, else what+/// was typed. `sameLabel` is a first choice that clears the value (和翻译模型一样). Without a list+/// the settings show a plain field instead (SettingsWindow.ModelField).+static class ModelPicker+{+ public static FrameworkElement Make(string value, string? sameLabel, IReadOnlyList<string> catalog, string host,+ Action refetch, Action<string> onPick, double width = 260)+ {+ var shown = value.Length > 0 ? value : sameLabel ?? L("选一个");+ var label = Ui.Text(shown, 14, value.Length > 0 ? Palette.Ink : Palette.Secondary, wrap: false);+ label.TextTrimming = TextTrimming.CharacterEllipsis;+ label.HorizontalAlignment = HorizontalAlignment.Left;+ var chevron = Ui.Icon(Icons.Chevron, 14, Palette.Secondary, stroke: 1.8);+ chevron.Margin = new Thickness(8, 0, 0, 0);+ DockPanel.SetDock(chevron, Dock.Right);+ // Ui.Choice's look; its own menu would open beside the popup.+ var button = new Button+ {+ Content = new DockPanel { LastChildFill = true, Children = { chevron, label } }, Width = width, Height = 34,+ Padding = new Thickness(12, 0, 10, 0), Background = Palette.Mica, BorderThickness = new Thickness(0), Cursor = Cursors.Hand,+ HorizontalContentAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Center,+ Template = Ui.Template(plain: true, radius: 10, soft: true),+ };+ System.Windows.Automation.AutomationProperties.SetName(button, shown);++ var search = new TextBox();+ var hint = Ui.Text(L("搜索或输入模型"), 13, Palette.Tertiary, wrap: false);+ hint.IsHitTestVisible = false; hint.VerticalAlignment = VerticalAlignment.Center;+ Ui.StyleField(search);+ search.FontSize = 13;+ var field = Ui.FieldFrame(new Grid { Children = { search, hint } }, search);+ field.Height = 32; field.Margin = new Thickness(8, 8, 8, 4);+ var rows = new StackPanel { Margin = new Thickness(4) };+ var count = Ui.Text(LF("%@ 列出 %lld 个模型", host, catalog.Count), 12, Palette.Tertiary, wrap: false);+ count.VerticalAlignment = VerticalAlignment.Center;+ var popup = new Popup { PlacementTarget = button, Placement = PlacementMode.Bottom, StaysOpen = false, AllowsTransparency = true };+ var again = Ui.LinkText(L("重新获取"), () => { popup.IsOpen = false; refetch(); }, 12);+ var footer = Ui.Spread(count, again);+ footer.Margin = new Thickness(12, 6, 12, 8);+ var list = new ScrollViewer { VerticalScrollBarVisibility = ScrollBarVisibility.Auto, MaxHeight = 280, Content = rows };+ var body = new DockPanel { Width = Math.Max(width, 320) };+ TextElement.SetFontFamily(body, Palette.Font);+ DockPanel.SetDock(field, Dock.Top);+ DockPanel.SetDock(footer, Dock.Bottom);+ body.Children.Add(field);+ body.Children.Add(footer);+ body.Children.Add(list);+ popup.Child = new Border+ {+ Background = Palette.Surface, BorderBrush = Palette.Line, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(10),+ Margin = new Thickness(0, 4, 0, 0), Child = body,+ };++ void Pick(string id)+ {+ popup.IsOpen = false;+ if (id != value) onPick(id);+ }+ List<string> Matches()+ {+ var q = search.Text.Trim();+ return q.Length == 0 ? [.. catalog] : catalog.Where(m => m.Contains(q, StringComparison.OrdinalIgnoreCase)).ToList();+ }+ FrameworkElement Row(string text, bool selected, bool mono, string pick)+ {+ var t = Ui.Text(text, 13, Palette.Ink, wrap: false);+ t.TextTrimming = TextTrimming.CharacterEllipsis;+ if (mono) t.FontFamily = new FontFamily("Cascadia Mono, Consolas");+ var check = Ui.Text("✓", 12, Palette.Ink, wrap: false);+ check.Opacity = selected ? 1 : 0; check.Margin = new Thickness(0, 0, 8, 0);+ var row = new Border+ {+ Background = selected ? Palette.Subtle : Brushes.Transparent, CornerRadius = new CornerRadius(6), Padding = new Thickness(8, 5, 8, 5),+ Cursor = Cursors.Hand, Child = Ui.Row(0, check, t),+ };+ row.MouseEnter += (_, _) => row.Background = Palette.Selected;+ row.MouseLeave += (_, _) => row.Background = selected ? Palette.Subtle : Brushes.Transparent;+ row.MouseLeftButtonUp += (_, _) => Pick(pick);+ return row;+ }+ void Fill()+ {+ hint.Visibility = search.Text.Length == 0 ? Visibility.Visible : Visibility.Collapsed;+ var q = search.Text.Trim();+ rows.Children.Clear();+ if (q.Length > 0 && !catalog.Contains(q)) rows.Children.Add(Row(LF("用 %@(列表里没有)", q), false, false, q));+ if (sameLabel is not null && q.Length == 0) rows.Children.Add(Row(sameLabel, value.Length == 0, false, ""));+ foreach (var id in Matches()) rows.Children.Add(Row(id, id == value, true, id));+ }+ search.TextChanged += (_, _) => Fill();+ search.KeyDown += (_, e) =>+ {+ if (e.Key == Key.Escape) { popup.IsOpen = false; e.Handled = true; }+ if (e.Key != Key.Enter) return;+ e.Handled = true;+ var m = Matches();+ var q = search.Text.Trim();+ if (m.Count == 1) Pick(m[0]); else if (q.Length > 0) Pick(q);+ };+ button.Click += (_, _) =>+ {+ search.Text = "";+ Fill();+ popup.IsOpen = true;+ search.Dispatcher.BeginInvoke(() => search.Focus(), System.Windows.Threading.DispatcherPriority.Input);+ };+ return button;+ }+}diff --git a/windows/src/Cicada/SettingsWindow.cs b/windows/src/Cicada/SettingsWindow.csindex 25ec946..688081b 100644--- a/windows/src/Cicada/SettingsWindow.cs+++ b/windows/src/Cicada/SettingsWindow.cs@@ -17,6 +17,9 @@ sealed partial class SettingsWindow : Windowreadonly Dictionary<string, FrameworkElement> sections = [];readonly PasswordBox keyBox = new();bool editingKey;+ // A custom service's notes key (另一个服务), typed until 保存并检查; 更换 shows the field again.+ readonly PasswordBox notesKeyBox = new();+ bool editingNotesKey;string current = "ai";// AI 服务: 自己选模型 unfolded, and a model being typed by hand ("hear", "text", "voice").bool modelsOpen;@@ -37,6 +40,8 @@ sealed partial class SettingsWindow : WindowWindowStartupLocation = WindowStartupLocation.CenterScreen;System.Windows.Automation.AutomationProperties.SetName(keyBox, L("API key"));keyBox.PasswordChanged += (_, _) => KeyPlaceholder();+ System.Windows.Automation.AutomationProperties.SetName(notesKeyBox, L("纪要") + " key");+ notesKeyBox.PasswordChanged += (_, _) => { if (notesKeyPlaceholder is { } h) h.Visibility = notesKeyBox.Password.Length == 0 ? Visibility.Visible : Visibility.Collapsed; };var grid = new Grid();grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(200) });grid.ColumnDefinitions.Add(new ColumnDefinition());@@ -196,7 +201,7 @@ sealed partial class SettingsWindow : Windowif (id == "speak") h = Ui.Spread(h, Ui.Switch(app.Settings.Speak, v => { app.Settings.Speak = v; Save(); }, L("同声传译")));// The service menu in the page's header, Ling first and recommended.if (id == "ai") h = Ui.Spread(h, Ui.Choice(AIProvider.All.Select(p => (p.Id, p.Id == "ling" ? "Ling" + L("(推荐)") : L(p.Name))), app.Settings.AiProvider,- v => { editingKey = false; typing = null; keyHint = null; customFields.Clear(); open = null; app.SetAIProvider(v); }, 220));+ v => { editingKey = false; editingNotesKey = false; notesKeyBox.Clear(); typing = null; keyHint = null; customFields.Clear(); open = null; app.SetAIProvider(v); }, 220));h.Margin = new Thickness(0, 0, 0, 20);sections[id] = h;page.Children.Add(h);@@ -541,14 +546,13 @@ sealed partial class SettingsWindow : Windowvar ling = app.Ling;var c = ling.Config;var check = ling.Health;- open ??= !check.Passed || check.Slow ? new HashSet<string> { "text" } : new HashSet<string>();+ open ??= !check.Passed || check.Slow || check.NotesFailed ? new HashSet<string> { "text" } : new HashSet<string>();var intro = Ui.Helper(L("每样可以接不同的机器;这台电脑和局域网里的服务可以用 http。"));intro.Margin = new Thickness(6, -8, 0, 0);yield return intro;yield return Group(TextSection(), VoiceSection(), HearSection());yield return Group(OnlyRow());- var host = ling.ServiceHost.Length > 0 ? ling.ServiceHost : L("你填的地址");- var lockLine = Ui.Helper(LF("仅保存在本机当前账户下,仅发送至 %@", host));+ var lockLine = Ui.Helper(LF("仅保存在本机当前账户下,仅发送至 %@", KeyHosts()));lockLine.Margin = new Thickness(6, -4, 0, 0);yield return lockLine;// What it costs depends on where it runs; what is sent where is the port's own line (it hears through the service).@@ -574,17 +578,26 @@ sealed partial class SettingsWindow : WindowUi.Switch(s.AiCustomOnly, v => { s.AiCustomOnly = v; s.Save(); app.AIChanged(); Render(); }, L("语音和文字只发给你的服务")));}- /// Where the custom service's audio and text go: one host when text, hearing and voice share it.- string CustomHosts()+ /// Where the custom service's audio and text go: one host when text, hearing, voice and notes+ /// share it, two by name.+ string CustomHosts() => Hosts(notes: true);++ /// Where the custom service's key is sent: every use's address, the notes' only while they share it.+ string KeyHosts() => Hosts(notes: !app.Ling.NotesHasOwnKey);++ string Hosts(bool notes){var ling = app.Ling;var c = ling.Config;var hosts = new List<string> { ling.ServiceHost, ling.HearHost };- if (c.HasVoices && Uri.TryCreate(c.VoiceBase, UriKind.Absolute, out var v)) hosts.Add(v.Host);+ if (notes && c.NotesApart) hosts.Add(HostOf(c.ForNotes.Base));+ if (c.HasVoices) hosts.Add(HostOf(c.VoiceBase));var set = hosts.Where(h => h.Length > 0).Distinct().ToList();- return set.Count == 1 ? set[0] : L("你填的地址");+ return set.Count switch { 1 => set[0], 2 => LF("%@ 和 %@", set[0], set[1]), _ => L("你填的地址") };}+ static string HostOf(string? url) => url is not null && Uri.TryCreate(url, UriKind.Absolute, out var u) ? u.Host : "";+/// A row that opens to its fields: a state dot, the use, what it runs on, and how it's doing.FrameworkElement SectionHeader(string id, string title, string detail, Brush dot, string? trailing, Brush? trailingColor = null){@@ -641,8 +654,9 @@ sealed partial class SettingsWindow : Windowstatic string Secs(double s) => s.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture);- /// 翻译和纪要: the address, the text model (a menu once the service listed its models), the key,- /// how long a sentence took and whether the model thinks; the steps when something failed.+ /// 翻译和纪要 (AISettings.swift › textSection): 翻译's address, key and model; then 纪要, the+ /// same service (another model at most) or another one with its own address and key; how long+ /// a sentence took and whether the model thinks; the steps when something failed.FrameworkElement TextSection(){var ling = app.Ling;@@ -650,53 +664,177 @@ sealed partial class SettingsWindow : Windowvar s = app.Settings;var check = ling.Health;var textFailed = check.Failure is { Step: not AICheck.StepId.Hear };- var detail = ling.ServiceHost.Length == 0 || c.TextModel.Length == 0 ? L("填上地址和模型") : $"{ling.ServiceHost} · {c.TextModel}";+ // Translation works, the notes' own model or server doesn't.+ var notesDown = !textFailed && check.NotesFailed;var trailing = check.IsRunning ? L("正在检查…"): textFailed && ling.HasKey ? AICheckView.Status(check)+ : notesDown ? L("纪要写不了"): check.Translate is { } sp ? LF("翻一句 %@ 秒", Secs(sp.Seconds)) : null;Brush dot = !ling.HasKey ? Palette.Toggle : check.IsRunning ? Palette.Live : textFailed ? Palette.Danger- : check.Slow || check.IsBusy ? Palette.WarnIcon : check.Passed ? Palette.Success : Palette.Toggle;- var header = SectionHeader("text", L("翻译和纪要"), detail, dot, trailing, check.Slow ? Palette.WarnIcon : textFailed ? Palette.Danger : null);+ : check.Slow || check.IsBusy || check.NotesFailed ? Palette.WarnIcon : check.Passed ? Palette.Success : Palette.Toggle;+ var header = SectionHeader("text", L("翻译和纪要"), TextDetail(), dot, trailing, textFailed || notesDown ? Palette.Danger : check.Slow ? Palette.WarnIcon : null);if (!open!.Contains("text")) return header;- FrameworkElement model;- if (ling.TextCatalog.Count > 0)- {- // The models the service lists: picking one saves and checks it.- customFields.Remove("text");- model = ModelMenu("text", c.TextModel, [], ling.TextCatalog);- }- else model = CustomField("text", s.AiModels.GetValueOrDefault("custom", ""), L("例如 qwen3:14b"));+ var model = ModelField("text", s.AiModels.GetValueOrDefault("custom", ""), L("例如 qwen3:14b"), null, ling.TextCatalog, ling.ServiceHost,+ () => _ = ling.FetchCatalog(), v => app.SetAIModel("text", v));var address = CustomField("base", s.AiCustomBase, "http://192.168.1.20:8000/v1");- // As typed (AISettings.swift › textSection): an http address out on the internet is refused,- // and without a key no check runs to say so.- var badAddress = Line(L("地址要用 https;这台电脑和局域网里的服务可以用 http。"), Palette.Danger);- var baseBox = customFields["base"];- void Bad() => badAddress.Visibility = baseBox.Text.Trim().Length > 0 && AIProvider.CustomBase(baseBox.Text) is null ? Visibility.Visible : Visibility.Collapsed;- baseBox.TextChanged += (_, _) => Bad();- Bad();var parts = new List<FrameworkElement>{+ GroupTitle(L("翻译")),Card(null, L("地址"), null, address),- badAddress,- Card(null, L("模型"), null, model),+ BadAddressLine(customFields["base"]),Card(null, "key", null, CustomKey()),+ Card(null, L("模型"), null, model),+ new Border { Height = 1, Background = Palette.Line, Margin = new Thickness(0, 6, 0, 6) },};+ parts.AddRange(NotesGroup());+ parts.Add(Card(null, "", null, SaveButton()));if (check.SlowLine(app.Settings.GoogleOff) is { } slow) parts.Add(Line(slow, Palette.WarnIcon));var key = ling.CurrentKey();if (key is not null && (check.IsRunning || textFailed || check.IsBusy || check.At is not null && !check.Passed && check.Failure is null))parts.Add(AICheckView.Steps(app, ChangeKey, recheckInStep: false));else if (check.At is not null && !check.IsRunning && check.Failure is null or { Step: AICheck.StepId.Hear }){- var facts = new List<string> { L("能写纪要") };- if (check.Translate is { } t) facts.Add(t.Thinks ? L("会先思考") : L("不思考"));- parts.Add(Line(string.Join(" · ", facts), Palette.Tertiary));+ if (c.NotesApart && check.Translate is { } t) parts.Add(CheckRows(t));+ else+ {+ var facts = new List<string> { L("能写纪要") };+ if (check.Translate is { } t2) facts.Add(t2.Thinks ? L("会先思考") : L("不思考"));+ parts.Add(Line(string.Join(" · ", facts), Palette.Tertiary));+ }}return new StackPanel { Children = { header, Body([.. parts]) } };}+ /// "192.168.1.20 · qwen-mt-turbo", then the notes' model, or their own server after a bar.+ string TextDetail()+ {+ var ling = app.Ling;+ var c = ling.Config;+ if (ling.ServiceHost.Length == 0 || c.TextModel.Length == 0) return L("填上地址和模型");+ var line = $"{ling.ServiceHost} · {c.TextModel}";+ if (!c.NotesApart) return line;+ var n = c.ForNotes;+ if (n.Base != c.Base && HostOf(n.Base) is { Length: > 0 } host) return line + $" | {host} · {n.TextModel}";+ return n.TextModel == c.TextModel ? line : line + $" · {n.TextModel}";+ }++ /// 纪要: the same service as translation, or another one with its own address and key (switching+ /// back keeps what was typed); then the notes' model, 和翻译模型一样 first. The grey line says what+ /// it's for, or in red why notes can't be written.+ IEnumerable<FrameworkElement> NotesGroup()+ {+ var ling = app.Ling;+ var c = ling.Config;+ var s = app.Settings;+ var own = s.AiCustomNotesOwn;+ var notesHost = HostOf(c.ForNotes.Base) is { Length: > 0 } h ? h : ling.ServiceHost;+ var elsewhere = c.ForNotes.Base != c.Base;+ yield return GroupTitle(L("纪要"), Ui.Segmented([("same", L("同一个服务")), ("own", L("另一个服务"))], own ? "own" : "same",+ v => { s.AiCustomNotesOwn = v == "own"; s.Save(); app.AIChanged(); Render(); }));+ if (own)+ {+ var address = CustomField("notesBase", s.AiCustomNotesBase, L("跟上面一样"));+ yield return Card(null, L("地址"), null, address);+ yield return BadAddressLine(customFields["notesBase"]);+ yield return Card(null, "key", null, NotesKey());+ }+ yield return Card(null, L("模型"), null, ModelField("notesModel", s.AiModels.GetValueOrDefault("custom.notes", ""), L("和翻译模型一样"), L("和翻译模型一样"),+ elsewhere ? ling.NotesCatalog : ling.TextCatalog, notesHost,+ () => _ = elsewhere ? ling.FetchNotesCatalog() : ling.FetchCatalog(), v => app.SetAIModel("notes", v)));+ yield return ling.Health.NotesLine(notesHost, c.ForNotes.TextModel, sharedKey: !ling.NotesHasOwnKey) is { } why+ ? Line(why, Palette.Danger)+ : Line(L("用来写实时纪要、识别说话人,默认和翻译用同一个"), Palette.Tertiary);+ }++ /// A group's name in the 翻译和纪要 row (翻译, 纪要), with its control on the right.+ static FrameworkElement GroupTitle(string text, FrameworkElement? control = null)+ {+ var title = Ui.Text(text, 14, Palette.Ink, FontWeights.SemiBold, wrap: false);+ title.VerticalAlignment = VerticalAlignment.Center;+ FrameworkElement row = control is null ? title : Ui.Spread(title, control);+ row.Margin = new Thickness(0, 8, 0, 2);+ return row;+ }++ /// As typed (AISettings.swift › textSection): an http address out on the internet is refused,+ /// and without a key no check runs to say so.+ static FrameworkElement BadAddressLine(TextBox box)+ {+ var bad = Line(L("地址要用 https;这台电脑和局域网里的服务可以用 http。"), Palette.Danger);+ void Bad() => bad.Visibility = box.Text.Trim().Length > 0 && AIProvider.CustomBase(box.Text) is null ? Visibility.Visible : Visibility.Collapsed;+ box.TextChanged += (_, _) => Bad();+ Bad();+ return bad;+ }++ /// A custom service's model: the names its `/models` lists (ModelPicker, picking saves and+ /// checks), or without a list a field saved by 保存并检查, with 重新获取 to ask for the list again.+ FrameworkElement ModelField(string name, string value, string hint, string? sameLabel, IReadOnlyList<string> catalog, string host,+ Action refetch, Action<string> pick)+ {+ if (catalog.Count > 0)+ {+ customFields.Remove(name);+ return ModelPicker.Make(value, sameLabel, catalog, host, refetch, pick);+ }+ var field = CustomField(name, value, hint);+ field.ToolTip = L("这个地址没列出模型,直接填名字");+ return host.Length == 0 ? field : Ui.Row(8, field, Ui.Button(L("重新获取"), refetch, height: 34));+ }++ /// After a check with notes apart: one row each, what it runs and how it did.+ FrameworkElement CheckRows(AICheck.Speed t)+ {+ var c = app.Ling.Config;+ var notes = app.Ling.Health.Notes;+ var notesText = notes switch+ {+ { Kind: AICheck.Kind.Ok, Seconds: { } secs } => LF("能写纪要 · %@ 秒", Secs(secs)),+ { Kind: AICheck.Kind.Ok } => L("能写纪要"),+ { Kind: AICheck.Kind.Fail, Why: AICheck.Reason.InvalidKey or AICheck.Reason.MgmtKey } => L("key 不对"),+ { Kind: AICheck.Kind.Fail } => L("纪要写不了"),+ { Kind: AICheck.Kind.Running } => L("正在检查…"),+ _ => "",+ };+ static FrameworkElement Row(string use, string model, bool ok, string result)+ {+ var color = ok ? Palette.Success : Palette.Danger;+ var dock = new DockPanel { MinHeight = 36 };+ var r = Ui.Text(result, 13, color, wrap: false);+ r.VerticalAlignment = VerticalAlignment.Center; r.Margin = new Thickness(8, 0, 0, 0);+ DockPanel.SetDock(r, Dock.Right);+ var d = Ui.Dot(color, 6);+ d.Margin = new Thickness(0, 0, 10, 0);+ DockPanel.SetDock(d, Dock.Left);+ var u = Ui.Text(use, 13, Palette.Ink, wrap: false);+ u.MinWidth = 40; u.VerticalAlignment = VerticalAlignment.Center; u.Margin = new Thickness(0, 0, 8, 0);+ DockPanel.SetDock(u, Dock.Left);+ var m = Ui.Text(model, 13, Palette.Secondary, wrap: false);+ m.TextTrimming = TextTrimming.CharacterEllipsis; m.VerticalAlignment = VerticalAlignment.Center;+ m.FontFamily = new FontFamily("Cascadia Mono, Consolas");+ dock.Children.Add(r); dock.Children.Add(d); dock.Children.Add(u); dock.Children.Add(m);+ return dock;+ }+ return new Border+ {+ BorderBrush = Palette.Line, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(10), Padding = new Thickness(12, 0, 12, 0),+ Margin = new Thickness(0, 4, 0, 4),+ Child = new StackPanel+ {+ Children =+ {+ Row(L("翻译"), c.TextModel, true, LF("翻一句 %@ 秒", Secs(t.Seconds)) + " · " + (t.Thinks ? L("会先思考") : L("不思考"))),+ new Border { Height = 1, Background = Palette.Line },+ Row(L("纪要"), c.ForNotes.TextModel, notes?.Kind != AICheck.Kind.Fail, notesText),+ },+ },+ };+ }+// The grey hint in a custom service's key field (a PasswordBox has none), shown while it's empty.TextBlock? keyPlaceholder;void KeyPlaceholder() { if (keyPlaceholder is { } h) h.Visibility = keyBox.Password.Length == 0 ? Visibility.Visible : Visibility.Collapsed; }+ TextBlock? notesKeyPlaceholder;/// The key of a custom service: optional on this computer and the local network.FrameworkElement CustomKey()@@ -705,8 +843,7 @@ sealed partial class SettingsWindow : Windowif (saved is { Length: > 0 } && !editingKey)return Ui.Row(8, Ui.Text(AIKey.Masked(saved), 13, Palette.Ink, wrap: false),Ui.Button(L("更换"), ChangeKey, height: 32),- Ui.Button(L("删除"), () => { app.Key.Remove(); app.AIChanged(); }, height: 32),- SaveButton());+ Ui.Button(L("删除"), () => { app.Key.Remove(); app.AIChanged(); }, height: 32));if (keyBox.Parent is Panel old) old.Children.Remove(keyBox);if (keyBox.Parent is Border oldBorder) oldBorder.Child = null;var typed = customFields.TryGetValue("base", out var b) ? b.Text : app.Settings.AiCustomBase;@@ -718,7 +855,29 @@ sealed partial class SettingsWindow : Windowvar frame = Ui.FieldFrame(new Grid { Children = { keyBox, hint } }, keyBox);// Wide enough for the hint in English, Japanese and Korean ("Optional on this PC or your local network").frame.Width = 340; frame.Height = 34;- return Ui.Row(8, frame, SaveButton());+ return frame;+ }++ /// The notes' own key (另一个服务): empty, the key above is used; saved by 保存并检查, sent only+ /// to the notes' address. A refused one is framed red.+ FrameworkElement NotesKey()+ {+ var ling = app.Ling;+ var saved = ling.NotesHasOwnKey ? app.Key.Read(LingClient.NotesKeyName) : null;+ if (saved is { Length: > 0 } && !editingNotesKey)+ return Ui.Row(8, Ui.Text(AIKey.Masked(saved), 13, Palette.Ink, wrap: false),+ Ui.Button(L("更换"), () => { editingNotesKey = true; notesKeyBox.Clear(); Render(); notesKeyBox.Focus(); }, height: 32),+ Ui.Button(L("移除"), () => { ling.RemoveNotesKey(); editingNotesKey = false; app.AIChanged(); }, height: 32));+ if (notesKeyBox.Parent is Panel old) old.Children.Remove(notesKeyBox);+ var hint = Ui.Text(L("不填就用上面的 key"), 14, Palette.Tertiary, wrap: false);+ hint.IsHitTestVisible = false; hint.VerticalAlignment = VerticalAlignment.Center;+ hint.Visibility = notesKeyBox.Password.Length == 0 ? Visibility.Visible : Visibility.Collapsed;+ notesKeyPlaceholder = hint;+ Ui.StyleField(notesKeyBox);+ var frame = Ui.FieldFrame(new Grid { Children = { notesKeyBox, hint } }, notesKeyBox);+ frame.Width = 340; frame.Height = 34;+ if (ling.Health.Notes?.Why is AICheck.Reason.InvalidKey or AICheck.Reason.MgmtKey) frame.BorderBrush = Palette.Danger;+ return frame;}/// 同传声音: a speech model (`/audio/speech`), its voice and address; else Windows speaks.@@ -862,7 +1021,19 @@ sealed partial class SettingsWindow : Windows.AiCustomVoice = F("voiceName", s.AiCustomVoice);s.AiCustomVoiceBase = F("voiceBase", s.AiCustomVoiceBase);s.AiCustomHearBase = F("hearBase", s.AiCustomHearBase);+ s.AiCustomNotesBase = F("notesBase", s.AiCustomNotesBase);+ // The notes model typed by hand (no list): empty is the translation model.+ if (customFields.TryGetValue("notesModel", out var nm))+ {+ if (nm.Text.Trim().Length > 0) s.AiModels["custom.notes"] = nm.Text.Trim(); else s.AiModels.Remove("custom.notes");+ }s.Save();+ // Notes' own key (另一个服务): saved here too; it goes only to the notes' address.+ if (s.AiCustomNotesOwn && notesKeyBox.Password.Trim().Length > 0 && app.Ling.SaveNotesKey(notesKeyBox.Password))+ {+ notesKeyBox.Clear();+ editingNotesKey = false;+ }}var text = keyBox.Password.Trim();keyHint = null;diff --git a/windows/src/Cicada/Ui.cs b/windows/src/Cicada/Ui.csindex 606f859..fd7a183 100644--- a/windows/src/Cicada/Ui.cs+++ b/windows/src/Cicada/Ui.cs@@ -246,7 +246,7 @@ static class Uistatic void AutomationName(UIElement e, string name) => System.Windows.Automation.AutomationProperties.SetName(e, name);/// Rounded, no Windows 7 chrome. Plain buttons get a grey wash on hover; filled ones dim a little.- static ControlTemplate Template(bool plain, bool onDark = false, Type? target = null, double radius = 10, bool soft = false)+ public static ControlTemplate Template(bool plain, bool onDark = false, Type? target = null, double radius = 10, bool soft = false){var t = new ControlTemplate(target ?? typeof(Button));var border = new FrameworkElementFactory(typeof(Border), "bg");diff --git a/windows/tests/Cicada.Tests/Program.cs b/windows/tests/Cicada.Tests/Program.csindex 8681d00..609e7b8 100644--- a/windows/tests/Cicada.Tests/Program.cs+++ b/windows/tests/Cicada.Tests/Program.cs@@ -1982,11 +1982,13 @@ static class Testssealed class Service(Func<string, string, HttpResponseMessage> respond) : HttpMessageHandler{public readonly List<(string url, string body)> Sent = [];+ /// The key each request carried ("Bearer …"), in the order of Sent.+ public readonly List<string?> Auth = [];protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancel){var body = request.Content is null ? "" : await request.Content.ReadAsStringAsync(cancel);var url = request.RequestUri!.ToString();- lock (Sent) Sent.Add((url, body));+ lock (Sent) { Sent.Add((url, body)); Auth.Add(request.Headers.Authorization?.ToString()); }return respond(url, body);}}@@ -2280,6 +2282,148 @@ static class Testsfinally { LingClient.Spacing = old; }}+ // MARK: Notes apart (LingTests.swift › Notes apart)++ /// A custom service whose notes use "big"; with `own`, at notes.example with 另一个服务.+ static (LingClient ling, AppSettings settings, Service fake) NotesClient(bool own, Func<string, string, HttpResponseMessage> respond, string? notesKey = null, GateClock? clock = null)+ {+ var s = new AppSettings+ {+ AiProvider = "custom", AiCustomBase = "https://main.example/v1", AiModels = { ["custom"] = "mt", ["custom.notes"] = "big" },+ AiCustomNotesOwn = own, AiCustomNotesBase = own ? "https://notes.example/v1" : "",+ };+ var k = new AIKey(new PlainProtector(), service: () => s.AiProvider);+ k.Remove(); k.Remove(LingClient.NotesKeyName);+ k.Save("sk-main-1111111111");+ if (notesKey is not null) k.Save(notesKey, LingClient.NotesKeyName);+ var fake = new Service(respond);+ return (new LingClient(k, fake, s.AIConfig, clock), s, fake);+ }++ public static async Task NotesGoToTheirModelAndServerTranslationStays()+ {+ var old = LingClient.Spacing; LingClient.Spacing = 0;+ try+ {+ var (ling, _, fake) = NotesClient(true, (_, _) => Reply("{}"), notesKey: "sk-notes-222222222");+ await ling.Chat("x", "Notes.", Priority.Notes, json: true);+ await ling.Chat("y", "Translate.", Priority.Translate);+ Equal("big,mt", string.Join(",", fake.Sent.Select(x => JsonNode.Parse(x.body)!["model"]!.GetValue<string>())), "models");+ Equal("https://notes.example/v1/chat/completions,https://main.example/v1/chat/completions", string.Join(",", fake.Sent.Select(x => x.url)), "servers");+ Equal("Bearer sk-notes-222222222,Bearer sk-main-1111111111", string.Join(",", fake.Auth), "keys");+ // A live line's corrections ride at Notes priority but are translation's.+ await ling.Chat("z", "JSON only.", Priority.Notes, notes: false);+ Check(fake.Sent[^1].url.StartsWith("https://main.example/") && fake.Auth[^1] == "Bearer sk-main-1111111111", "corrections stay with translation");+ }+ finally { LingClient.Spacing = old; }+ }++ public static async Task NotesWithoutTheirOwnKeyUseTheTranslationKey()+ {+ var old = LingClient.Spacing; LingClient.Spacing = 0;+ try+ {+ var (ling, _, fake) = NotesClient(true, (_, _) => Reply("{}"));+ await ling.Chat("x", "Notes.", Priority.Notes);+ Equal("Bearer sk-main-1111111111", fake.Auth[0], "不填就用上面的 key");+ Check(!ling.NotesHasOwnKey, "no key of their own");+ // The same service, another model: same address and key, even with a notes key file left over.+ var (same, _, f2) = NotesClient(false, (_, _) => Reply("{}"), notesKey: "sk-notes-222222222");+ await same.Chat("x", "Notes.", Priority.Notes);+ Check(f2.Sent[0].url.StartsWith("https://main.example/") && f2.Auth[0] == "Bearer sk-main-1111111111", "same service: its key");+ Equal("big", JsonNode.Parse(f2.Sent[0].body)!["model"]!.GetValue<string>(), "the notes model");+ Check(!same.NotesHasOwnKey, "同一个服务 has no key of its own");+ // 另一个服务 at an http address on the internet: notes aren't sent anywhere else instead.+ var (bad, s3, f3) = NotesClient(true, (_, _) => Reply("{}"), notesKey: "sk-notes-222222222");+ s3.AiCustomNotesBase = "http://notes.example/v1";+ try { await bad.Chat("x", "Notes.", Priority.Notes); Check(false, "not sent"); } catch (LingException) { }+ Equal(0, f3.Sent.Count, "nothing sent with a bad notes address");+ }+ finally { LingClient.Spacing = old; }+ }++ public static async Task ARefusedNotesKeyLeavesTranslationWorking()+ {+ var old = LingClient.Spacing; LingClient.Spacing = 0;+ try+ {+ var (ling, _, _) = NotesClient(true, (_, body) => body.Contains("\"big\"") ? Status(401) : Reply("好"));+ try { await ling.Chat("x", "Notes.", Priority.Notes); Check(false, "notes refused"); }+ catch (LingException e) { Equal(LingException.Kind.InvalidKey, e.Failure, "refused"); }+ Check(ling.KeyState != KeyState.Invalid, "translation's key isn't marked bad");+ Equal(AICheck.Reason.InvalidKey, ling.Health.Notes?.Why, "the notes' result says so");+ Check(ling.Health.Failure is null, "translation's steps untouched");+ Equal("好", await ling.Chat("y", "Translate.", Priority.Translate), "translation still works");+ Equal("%@ 不认上面的 key,给它单独填一个。".Replace("%@", "notes.example"), ling.Health.NotesLine("notes.example", "big", sharedKey: true), "wants a key of its own");+ }+ finally { LingClient.Spacing = old; }+ }++ public static async Task ANotesServerBusyDoesNotHoldTranslationBack()+ {+ var old = LingClient.Spacing; LingClient.Spacing = 0;+ try+ {+ var clock = new FakeClock();+ var (ling, _, fake) = NotesClient(true, (url, _) => url.Contains("notes.example") ? Busy("20") : Reply("好"), clock: clock);+ try { await ling.Chat("x", "Notes.", Priority.Notes); Check(false, "busy"); }+ catch (LingException e) { Equal(LingException.Kind.RateLimited, e.Failure, "notes gave up"); }+ Check(clock.Now > clock.Start, "notes waited at their own gate");+ // A translation fails at once while its server cools down; this one isn't.+ Equal("好", await ling.Chat("y", "Translate.", Priority.Translate), "translation's gate isn't paused");+ Check(ling.Health.Failure is null && !ling.Health.NotesFailed, "busy is no failure: " + ling.Health.Summary);+ }+ finally { LingClient.Spacing = old; }+ }++ public static void NotesFallBackToTranslationUntilSet()+ {+ const string b = "https://main.example/v1/";+ var plain = new AIConfig(AIProvider.Custom, b, "mt", "");+ Check(!plain.NotesApart && plain.ForNotes == plain, "nothing set: translation's");+ var model = new AIConfig(AIProvider.Custom, b, "mt", "", NotesModel: "big");+ Check(model.NotesApart && model.ForNotes.TextModel == "big" && model.ForNotes.Base == b, "another model, same address");+ // Only the custom service splits.+ var ling = new AIConfig(AIProvider.Ling, AIProvider.Ling.Base, "x", "", NotesModel: "big");+ Check(!ling.NotesApart && ling.ForNotes.TextModel == "x", "Ling doesn't");+ // From settings: the translation model named again is no model of its own; 另一个服务 off keeps+ // the address but doesn't use it; an http address on the internet can't be used.+ var s = new AppSettings { AiProvider = "custom", AiCustomBase = "https://main.example/v1", AiModels = { ["custom"] = "mt", ["custom.notes"] = "mt" } };+ Check(!s.AIConfig().NotesApart, "same model: not apart");+ s.AiCustomNotesBase = "https://notes.example/v1";+ Check(!s.AIConfig().NotesApart && s.AIConfig().ForNotes.Base == b, "同一个服务: the address is kept, not used");+ s.AiCustomNotesOwn = true;+ Equal("https://notes.example/v1/", s.AIConfig().ForNotes.Base, "另一个服务");+ Equal("mt", s.AIConfig().ForNotes.TextModel, "with the translation model");+ s.AiCustomNotesBase = "http://notes.example/v1";+ Check(s.AIConfig().NotesBadAddress && s.AIConfig().ForNotes.Base == b, "http to the internet");+ s.AiCustomNotesBase = "";+ Check(s.AIConfig().NotesApart && s.AIConfig().ForNotes.Base == b && !s.AIConfig().NotesBadAddress, "另一个服务, no address: the same one, its own key");+ }++ public static async Task ACheckTestsNotesApartWithoutFailingTranslation()+ {+ var old = LingClient.Spacing; LingClient.Spacing = 0;+ try+ {+ // The notes model is gone from the notes server; translation's model, typed by hand, isn't listed but answers.+ var (ling, _, fake) = NotesClient(true, (url, body) =>+ url == "https://main.example/v1/models" ? Status(200, "{\"data\":[{\"id\":\"other\"}]}")+ : url == "https://notes.example/v1/models" ? Status(200, "{\"data\":[{\"id\":\"n1\"},{\"id\":\"n2\"}]}")+ : url.StartsWith("https://notes.example/") ? Status(404)+ : Reply("周五发布。"), notesKey: "sk-notes-222222222");+ await ling.Check();+ var h = ling.Health;+ Check(h[AICheck.StepId.Text].Kind == AICheck.Kind.Ok && h.Failure?.Step == AICheck.StepId.Hear, "translation passes (no hear model here): " + h.Summary);+ Equal(AICheck.Reason.NoModel, h.Notes?.Why, "the notes fail on their own: " + h.Summary);+ Check(h.NotesFailed && h.Summary.Contains("notes=fail(noModel 404)"), h.Summary);+ Equal("n1,n2", string.Join(",", ling.NotesCatalog), "the notes server's models, for its menu");+ Check(!fake.Sent.Any(x => x.url == "https://main.example/v1/chat/completions" && x.body.Contains("JSON object")), "no JSON test against translation");+ Equal(KeyState.Ok, ling.KeyState, "translation's key is fine");+ }+ finally { LingClient.Spacing = old; }+ }+public static async Task ANoKeyCheckOutranksAnOlderSlowOne(){var old = LingClient.Spacing; LingClient.Spacing = 0;