知了 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): use OpenRouter, ZenMux or any OpenAI-compatible service when Ling isn't an option
wquguru222f8f9e87bd
diff --git a/windows/AGENTS.md b/windows/AGENTS.mdindex 6f28e2d..1a53cda 100644--- a/windows/AGENTS.md+++ b/windows/AGENTS.md@@ -3,7 +3,7 @@The Windows port: listening only. The root `AGENTS.md` applies too (Ling key, `LingClient`, no third-party dependencies, the Mac app as the reference, one `VERSION`). Commands, layout and how to verify are in `README.md`; the plan is `docs/windows-plan.md`.- .NET 10, WPF with the UI in code (no XAML), no NuGet packages. `src/Cicada.Core` is UI-free and must build and test on the Mac.-- The key: `AIKey` in `Cicada.Core/Ling.cs`, the `ling-api-key` file only; every Ling or Ming call goes through `LingClient`.+- Keys: `AIKey` in `Cicada.Core/Ling.cs`, one DPAPI-sealed file per AI service (`ling-api-key`, `ai-key-<service>`, as on the Mac). The services and their recommended models are `Cicada.Core/AIProviders.cs`; every AI call goes through `LingClient`, which reads the service from settings each time.- The notes window never takes focus (`WS_EX_NOACTIVATE`) and stays out of captures (`WDA_EXCLUDEFROMCAPTURE`) unless 共享屏幕时让对方看到 is on.- Shared UI text comes from `Resources/*.lproj/Localizable.strings`; Windows-only text is in `src/Cicada/Strings/`. Run `python3 scripts/strings.py` after changing either.- Verify with `scripts/test.sh`, then in the VM (`vm/`) with `cicadactl.ps1`. Real x64 hardware, Bluetooth and real screen sharing need a person.diff --git a/windows/README.md b/windows/README.mdindex 7ace360..0bd06a0 100644--- a/windows/README.md+++ b/windows/README.md@@ -3,7 +3,7 @@Cicada 的 Windows 版:把电脑播放的声音变成双语字幕和实时纪要,存成和 Mac 版同一格式的会议记录;同声传译(按住右 Ctrl 说话,翻译后的声音经 VB-Cable 虚拟麦克风进会议);说话人识别(按声音标出说话人 1、2…,声纹模型是 WeSpeaker ResNet34-LM,CC BY 4.0,用 `scripts/compress-voiceprint.py` 压成 int8,6.7 MB,由系统自带的 Windows ML 在本机运行)。方案和取舍见 [docs/windows-plan.md](../docs/windows-plan.md)。- 抓声音:WASAPI 进程回环,排除知了自己(Windows 10 2004 起)。-- 识别:Ming(`Ming-3.0-audio-flash`)分段识别,一次请求同时返回语言、原文和译文;需要 Ling key。+- 识别:Ming(`Ming-3.0-audio-flash`)分段识别,一次请求同时返回语言、原文和译文;需要 Ling key。用不了 Ling 的可以在 设置 › AI 服务 换成 OpenRouter、ZenMux 或兼容 OpenAI 的地址:听交给它能输入音频的模型(同样的提示词,字幕晚 1–2 秒),纪要和翻译用它的文字模型,同传声音用它的声音模型,没有时用 Windows 的声音。- 纪要、记录格式、提示词、多语言文案都和 Mac 版一致;文案的英日韩翻译直接用 `Resources/*.lproj/Localizable.strings`,Windows 独有的在 `src/Cicada/Strings/`。- 新版本:启动时和每 4 小时查一次 GitHub Releases(`UpdateChecker`),只认带 Windows 安装包的发布;有新版本时托盘图标出现红点、每个版本发一次通知(正在听时等会议结束),托盘面板和设置 › 关于也会提示。点“安装”由知了自己下载这台电脑对应架构的 `Cicada-<版本>-Windows-x64.exe` / `-ARM64.exe`(1.1.0 只认 `Cicada-Setup.exe` 这两个旧名字,发布时一并附上)、对照 `checksums.txt` 校验后安装并重新打开,不经过浏览器,所以 SmartScreen 不拦。开发版只在设了 `CICADA_UPDATE_FEED` 或用 `updatefeed` 调试命令时才查。@@ -34,7 +34,7 @@ DOTNET_ROOT=~/.dotnet build/cli/cicada-cli listen spike/clips/en.wav --target zhDOTNET_ROOT=~/.dotnet build/cli/cicada-cli roundtrip ~/Library/Application\ Support/LiveSubs/Sessions/*/session.json```-先 `scripts/dotnet.sh build src/Cicada.Cli -o build/cli` 编译命令行工具;它读 Mac 版的 key 文件,不打印 key。+先 `scripts/dotnet.sh build src/Cicada.Cli -o build/cli` 编译命令行工具;它读 Mac 版的 key 文件,不打印 key。`--provider zenmux`(或 openrouter)换服务,`check` 检查 key 和听的模型,`speak <文字> <out.wav>` 试声音模型。## 在 Windows 里验证diff --git a/windows/scripts/cicadactl.ps1 b/windows/scripts/cicadactl.ps1index 19baa00..48937d3 100644--- a/windows/scripts/cicadactl.ps1+++ b/windows/scripts/cicadactl.ps1@@ -1,5 +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 | quit+# AI 服务: provider ling|openrouter|zenmux|custom | ai-model hear|text|voice <id> | show settings ai models# 结束会议: 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 e25e5e4..93845d1 100644--- a/windows/src/Cicada.Cli/Program.cs+++ b/windows/src/Cicada.Cli/Program.cs@@ -4,11 +4,14 @@// Plays the file into ListenEngine as if the PC were playing it, prints each line as it is// recorded, then the record's folder. --speed 0 feeds it as fast as it can; --notes waits// for the final notes and prints them.+// cicada-cli check the AI service's key check: state, hears, catalog sizes+// cicada-cli speak <text> <out.wav> the service's voice for <text>, as a 24 kHz WAV// cicada-cli segments <file.wav> where the segmenter cuts (compare with ming_asr.py)// cicada-cli roundtrip <session.json>… reads and writes records, says if anything changed//-// Records go to CICADA_HOME (default: a temp folder). The key comes from CICADA_KEY_FILE, else-// the Mac app's dev or release key file; it is never printed.+// --provider ling|openrouter|zenmux|custom (default ling) and --hear / --text <model> pick the AI+// service. Records go to CICADA_HOME (default: a temp folder). The key comes from CICADA_KEY_FILE,+// else the Mac app's dev or release key file for that service; it is never printed.using System.Text.Json.Nodes;using Cicada;@@ -16,6 +19,14 @@ var args_ = args.ToList();if (args_.Count == 0) { Console.WriteLine("usage: cicada-cli listen|segments|roundtrip …"); return 2; }string Opt(string name, string fallback) { int i = args_.IndexOf(name); return i >= 0 && i + 1 < args_.Count ? args_[i + 1] : fallback; }Strings.Load(Path.Combine(AppContext.BaseDirectory, "Resources"), Opt("--ui", "zh-Hans"));+var provider = Opt("--provider", "ling");+var cliSettings = new AppSettings { Target = Opt("--target", "zh-CN"), AiProvider = provider };+if (Opt("--hear", "") is { Length: > 0 } hearModel) cliSettings.AiHearModels[provider] = hearModel;+if (Opt("--text", "") is { Length: > 0 } textModel) cliSettings.AiModels[provider] = textModel;+var keyFile = Environment.GetEnvironmentVariable("CICADA_KEY_FILE")+ ?? new[] { "LiveSubs Dev", "LiveSubs" }.Select(d => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library/Application Support", d,+ provider == "ling" ? "ling-api-key" : "ai-key-" + provider)).FirstOrDefault(File.Exists);+LingClient Client() => new(new AIKey(new PlainProtector(), keyFile), config: cliSettings.AIConfig);switch (args_[0]){@@ -46,15 +57,33 @@ switch (args_[0])}return changed == 0 ? 0 : 1;}+ case "check":+ {+ 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;+ }+ case "speak":+ {+ var ling = Client();+ var pcm = new List<byte>();+ var started = DateTime.UtcNow;+ await foreach (var chunk in ling.Speech(args_[1], Opt("--voice", "") is { Length: > 0 } v ? v : null)) pcm.AddRange(chunk);+ var samples = new short[pcm.Count / 2];+ Buffer.BlockCopy(pcm.ToArray(), 0, samples, 0, samples.Length * 2);+ File.WriteAllBytes(args_[2], Wav.Bytes(samples, 24000));+ Console.WriteLine($"{provider}: {ling.Config.VoiceModel} {samples.Length / 24000.0:F1} s of audio in {(DateTime.UtcNow - started).TotalSeconds:F1} s");+ return samples.Length > 0 ? 0 : 1;+ }case "hear":{- // One file to Ming, raw reply printed: for checking the prompt.- var keyFile = Environment.GetEnvironmentVariable("CICADA_KEY_FILE")- ?? new[] { "LiveSubs Dev", "LiveSubs" }.Select(d => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library/Application Support", d, "ling-api-key")).FirstOrDefault(File.Exists);- var ling = new LingClient(new AIKey(new PlainProtector(), keyFile));+ // One file to the hear model (Ming on Ling), raw reply printed: for checking the prompt.+ var ling = Client();var target = Opt("--target", "zh-CN");var reply = await ling.Chat(Translator.HearPrompt(target, null, []), Translator.HearInstruction(target), Priority.Translate,- maxTokens: 800, timeout: 20, model: LingClient.AudioModel, audio: Wav.Bytes(Wav.Read(args_[1])));+ maxTokens: 800, timeout: 20, model: ling.Config.HearModel, audio: Wav.Bytes(Wav.Read(args_[1])));Console.WriteLine(reply);Console.WriteLine($"-> {Translator.ParseHeard(reply, target, null)}");return 0;@@ -64,12 +93,10 @@ switch (args_[0])if (Environment.GetEnvironmentVariable("CICADA_HOME") is null)Environment.SetEnvironmentVariable("CICADA_HOME", Path.Combine(Path.GetTempPath(), "cicada-cli"));Log.Echo = args_.Contains("--log");- var keyFile = Environment.GetEnvironmentVariable("CICADA_KEY_FILE")- ?? new[] { "LiveSubs Dev", "LiveSubs" }.Select(d => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library/Application Support", d, "ling-api-key")).FirstOrDefault(File.Exists);- var key = new AIKey(new PlainProtector(), keyFile);- if (key.Read() is null) { Console.WriteLine("no Ling key (set CICADA_KEY_FILE)"); return 2; }- var settings = new AppSettings { Target = Opt("--target", "zh-CN") };- var ling = new LingClient(key);+ var settings = cliSettings;+ var ling = Client();+ if (!ling.HasKey) { Console.WriteLine($"no {provider} key (set CICADA_KEY_FILE)"); return 2; }+ Console.WriteLine($"{provider}: hear {ling.Config.HearModel}, text {ling.Config.TextModel}");var store = new SessionStore();var notes = new NotesEngine(ling, store);var engine = new ListenEngine(ling, new Translator(ling), store, notes, settings);diff --git a/windows/src/Cicada.Core/AIProviders.cs b/windows/src/Cicada.Core/AIProviders.csnew file mode 100644index 0000000..e050ba7--- /dev/null+++ b/windows/src/Cicada.Core/AIProviders.cs@@ -0,0 +1,161 @@+using System.Text.Json.Nodes;+using System.Text.RegularExpressions;++namespace Cicada;++/// A model a service recommends, and why: `Note` is a Chinese UI key, localized where shown.+public sealed record AIModel(string Id, string Note = "");++/// One of a service's speech voices; `Gender` is "女" / "男" (a UI key) or "".+public sealed record CloudVoice(string Id, string Gender);++/// The AI services the port can use (the Mac's AIProviders.swift, plus what hears audio). Ling is+/// the reference: Ming hears each stretch of audio and answers language, original and translation+/// in one call, and only Ling clones the user's voice. The others are OpenAI-compatible and hear+/// through an audio-input chat model with the same prompt (tools/audio-probe measured them against+/// Ming, 2026-11: about as accurate, 0.5–2 s slower). OpenAI itself is left out: a port needs a+/// model that hears, and its audio models are untested.+///+/// Recommended models come first in every menu and are the defaults. For hearing, the first is the+/// one that wrote nothing for a clip without speech: a made-up line ends up in the notes and, when+/// interpreting, in the room.+public sealed record AIProvider(string Id, string Name, string? Base, string? Site,+ AIModel[] TextModels, AIModel[] HearModels, AIModel[] VoiceModels, CloudVoice[] Voices, bool Clones = false, double Spacing = 0.1)+{+ public bool HasVoices => VoiceModels.Length > 0;++ static readonly CloudVoice[] Gemini = [new("Kore", "女"), new("Aoede", "女"), new("Charon", "男"), new("Puck", "男")];++ // Ling allows ~2 request starts a second; the aggregators far more.+ public static readonly AIProvider Ling = new("ling", "Ling", "https://api.ant-ling.com/v1/", "https://chat.ant-ling.com/platform/api",+ [new("Ling-3.1-flash", "更准"), new("Ling-3.0-flash", "更快、更省")], [new("Ming-3.0-audio-flash")], [new("Ming-3.0-tts-0.5B")], [],+ Clones: true, Spacing: 0.6);++ public static readonly AIProvider OpenRouter = new("openrouter", "OpenRouter", "https://openrouter.ai/api/v1/", "https://openrouter.ai/settings/keys",+ [new("inclusionai/ling-3.1-flash", "和 Ling 同款"), new("qwen/qwen3.8-flash", "中文好")],+ [new("qwen/qwen3.8-omni-flash", "没人说话时不乱写"), new("google/gemini-3.1-flash-lite", "最快,偶尔把杂音写成字")],+ [new("google/gemini-3.8-flash-tts", "效果和价格最均衡"), new("google/gemini-3.8-flash-lite-tts", "更省")], Gemini);++ public static readonly AIProvider ZenMux = new("zenmux", "ZenMux", "https://zenmux.ai/api/v1/", "https://zenmux.ai/settings/keys",+ [new("inclusionai/ling-3.0-flash", "和 Ling 同款"), new("qwen/qwen3.8-flash", "中文好")],+ [new("qwen/qwen3.8-omni-flash", "没人说话时不乱写"), new("bytedance/doubao-seed-2.0-mini", "更快"), new("google/gemini-3.1-flash-lite", "最快,偶尔把杂音写成字")],+ [new("google/gemini-3.8-flash-tts", "效果和价格最均衡"), new("google/gemini-3.8-flash-lite-tts", "更省")], Gemini);++ /// Any OpenAI-compatible address (a company gateway, Ollama…). Its hear model must take audio+ /// in; voices only when the user names a speech model, else Windows speaks.+ public static readonly AIProvider Custom = new("custom", "其他(兼容 OpenAI)", null, null, [], [], [], []);++ public static readonly AIProvider[] All = [Ling, OpenRouter, ZenMux, Custom];++ /// A service never named (or OpenAI, which the ports don't offer) is Ling.+ public static AIProvider Named(string? id) => All.FirstOrDefault(p => p.Id == id) ?? Ling;++ public static bool IsLocal(string hostOrUrl)+ {+ var u = hostOrUrl.Contains("://") ? hostOrUrl : "http://" + hostOrUrl;+ var host = Uri.TryCreate(u, UriKind.Absolute, out var uri) ? uri.Host.Trim('[', ']') : hostOrUrl;+ return host is "localhost" or "127.0.0.1" or "::1";+ }++ /// The address as typed, normalized: https, or http only on this computer; ends in "/".+ public static string? CustomBase(string? raw)+ {+ var s = (raw ?? "").Trim();+ if (s.Length == 0) return null;+ if (!s.Contains("://")) s = (IsLocal(s) ? "http://" : "https://") + s;+ if (!s.EndsWith('/')) s += "/";+ if (!Uri.TryCreate(s, UriKind.Absolute, out var u) || u.Host.Length == 0) return null;+ if (u.Scheme == "https") return s;+ return u.Scheme == "http" && IsLocal(u.Host) ? s : null;+ }++ static readonly Regex NotChat = new(@"(embed|whisper|tts|transcribe|dall-e|image|moderation|realtime|sora|search|video|seedance|wan\d)");++ /// Model ids from a `/models` reply, recommended ones first: those that answer in text, and for+ /// `hears` only those that take audio in. ZenMux lists modalities at the top level, OpenRouter+ /// under `architecture`; a service that says nothing keeps everything but obvious non-chat names.+ public static List<string> Catalog(string json, IEnumerable<string> recommended, bool hears)+ {+ JsonNode? root;+ try { root = JsonNode.Parse(json); } catch (System.Text.Json.JsonException) { root = null; }+ var ids = new List<string>();+ if (root is JsonObject o && o["data"] is JsonArray data)+ foreach (var m in data.OfType<JsonObject>())+ {+ if (Str(m["id"]) is not { Length: > 0 } id || id.EndsWith(":batch")) continue;+ var arch = m["architecture"] as JsonObject;+ var ins = Strs(m["input_modalities"] ?? arch?["input_modalities"]);+ var outs = Strs(m["output_modalities"] ?? arch?["output_modalities"]);+ if (outs.Count > 0 && !outs.Contains("text")) continue;+ if (ins is ["audio"]) continue; // speech-to-text only: no prompt, no translation+ if (hears && !ins.Contains("audio")) continue;+ if (outs.Count == 0 && NotChat.IsMatch(id)) continue;+ ids.Add(id);+ }+ var rec = recommended.ToList();+ return [.. rec, .. ids.Where(i => !rec.Contains(i)).Distinct().Order(StringComparer.Ordinal)];+ }++ static string? Str(JsonNode? n) => n is JsonValue v && v.TryGetValue<string>(out var s) ? s : null;+ static List<string> Strs(JsonNode? n) => n is JsonArray a ? a.Select(Str).OfType<string>().ToList() : [];+}++/// What one call needs to know about the service in use, resolved from settings each time+/// (Settings.swift › aiConfig). `Base` is null for a custom service without a valid address yet;+/// `VoiceModel` null when the service can't speak here.+public sealed record AIConfig(AIProvider Provider, string? Base, string TextModel, string HearModel,+ string? VoiceModel = null, string? VoiceBase = null, string? CustomVoice = null)+{+ 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).+ public string Name => Provider.Id == "custom" ? Strings.L(Provider.Name) : Provider.Name;++ /// The voices the room can pick from with this service (Ling's are Ming's, in VoiceCatalog).+ public IReadOnlyList<CloudVoice> Voices =>+ !HasVoices || IsLing ? [] : Provider.Id == "custom" ? (CustomVoice is { } v ? [new CloudVoice(v, "")] : []) : Provider.Voices;++ public static AIConfig Default => From(new AppSettings());++ /// Each service turns thinking off its own way (AIConfig.shape on the Mac).+ public void Shape(JsonObject body, int maxTokens)+ {+ body["max_tokens"] = maxTokens;+ body["temperature"] = 0.2;+ if (IsLing) body["thinking"] = new JsonObject { ["type"] = "disabled" };+ else if (Provider.Id is "openrouter" or "zenmux") body["reasoning"] = new JsonObject { ["enabled"] = false };+ }++ /// One WAV in a user message: Ming takes a data URL; the others the standard `input_audio`,+ /// except that Qwen's omni models want the data URL inside it (DashScope's form).+ public JsonObject AudioPart(byte[] wav, string model)+ {+ var b64 = Convert.ToBase64String(wav);+ if (IsLing) return new JsonObject { ["type"] = "audio_url", ["audio_url"] = new JsonObject { ["url"] = "data:audio/wav;base64," + b64 } };+ if (model.Split('/')[^1].StartsWith("qwen")) b64 = "data:audio/wav;base64," + b64;+ return new JsonObject { ["type"] = "input_audio", ["input_audio"] = new JsonObject { ["data"] = b64, ["format"] = "wav" } };+ }++ /// The service, its address and models from the app's settings.+ public static AIConfig From(AppSettings s)+ {+ var p = AIProvider.Named(s.AiProvider);+ if (p.Id == "ling")+ {+ var text = p.TextModels.Any(m => m.Id == s.Model) ? s.Model : p.TextModels[0].Id;+ return new(p, p.Base, text, p.HearModels[0].Id, p.VoiceModels[0].Id, p.Base);+ }+ string Pick(Dictionary<string, string> table) => table.TryGetValue(p.Id, out var v) ? v.Trim() : "";+ if (p.Id == "custom")+ {+ var b = AIProvider.CustomBase(s.AiCustomBase);+ var voice = Pick(s.AiVoiceModels);+ var voiceBase = s.AiCustomVoiceBase.Trim().Length > 0 ? AIProvider.CustomBase(s.AiCustomVoiceBase) : b;+ var name = s.AiCustomVoice.Trim();+ 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);+ }+ 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);+ }+}diff --git a/windows/src/Cicada.Core/Ling.cs b/windows/src/Cicada.Core/Ling.csindex 439e34e..5bc6140 100644--- a/windows/src/Cicada.Core/Ling.cs+++ b/windows/src/Cicada.Core/Ling.cs@@ -22,63 +22,79 @@ public sealed class PlainProtector : IKeyProtectorpublic byte[] Unprotect(byte[] data) => data;}-/// The user's Ling key, only ever in the `ling-api-key` file under the app folder (as on the Mac):-/// never in settings, the registry, logs or exports. On Windows the file holds DPAPI-sealed bytes,-/// "dpapi:" + base64, readable only by this Windows user.-public sealed class AIKey(IKeyProtector protector, string? file = null)+/// The user's AI keys, one file per service under the app folder, named as on the Mac+/// (`ling-api-key`, `ai-key-<service>`): never in settings, the registry, logs or exports. On+/// Windows each file holds DPAPI-sealed bytes, "dpapi:" + base64, readable only by this Windows+/// user. `service` says which one is in use, so switching services never deletes another's key;+/// `file` pins one file (the CLI reads the Mac app's in place).+public sealed class AIKey(IKeyProtector protector, string? file = null, Func<string>? service = null){- /// The CLI reads the Mac app's key file in place; the app always uses Paths.KeyFile.- string File_ => file ?? Paths.KeyFile;+ readonly Func<string> service = service ?? (() => "ling");+ public string File_ => file ?? Paths.KeyFile(service());- string? cached;- bool loaded;+ readonly Dictionary<string, string?> cache = [];+ readonly object gate = new();public string? Read(){- if (loaded) return cached;- loaded = true;- try- {- if (!File.Exists(File_)) return cached = null;- var text = File.ReadAllText(File_).Trim();- if (text.StartsWith("dpapi:"))- text = Encoding.UTF8.GetString(protector.Unprotect(Convert.FromBase64String(text["dpapi:".Length..])));- cached = text.Length == 0 ? null : text.Trim();- }- catch (Exception e)+ var path = File_;+ lock (gate){- Log.Debug($"ai key: read failed {e.GetType().Name}");- cached = null;+ if (cache.TryGetValue(path, out var cached)) return cached;+ string? value = null;+ try+ {+ if (File.Exists(path))+ {+ var text = File.ReadAllText(path).Trim();+ if (text.StartsWith("dpapi:"))+ text = Encoding.UTF8.GetString(protector.Unprotect(Convert.FromBase64String(text["dpapi:".Length..])));+ value = text.Trim().Length == 0 ? null : text.Trim();+ }+ }+ catch (Exception e) { Log.Debug($"ai key: read failed {e.GetType().Name}"); }+ return cache[path] = value;}- return cached;}public bool Save(string key){key = key.Trim();- try- {- Directory.CreateDirectory(Paths.Root);- var body = protector.Tag == "plain" ? key- : "dpapi:" + Convert.ToBase64String(protector.Protect(Encoding.UTF8.GetBytes(key)));- File.WriteAllText(File_, body);- if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(File_, UnixFileMode.UserRead | UnixFileMode.UserWrite);- cached = key; loaded = true;- return true;- }- catch (Exception e)+ var path = File_;+ lock (gate){- Log.Debug($"ai key: save failed {e.GetType().Name}");- return false;+ try+ {+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);+ var body = protector.Tag == "plain" ? key+ : "dpapi:" + Convert.ToBase64String(protector.Protect(Encoding.UTF8.GetBytes(key)));+ File.WriteAllText(path, body);+ if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite);+ cache[path] = key;+ return true;+ }+ catch (Exception e)+ {+ Log.Debug($"ai key: save failed {e.GetType().Name}");+ return false;+ }}}+ /// Removes the key of the service in use only.public void Remove(){- try { File.Delete(File_); } catch { }- cached = null; loaded = true;+ var path = File_;+ lock (gate)+ {+ try { File.Delete(path); } catch { }+ cache[path] = null;+ }}+ /// Forget what was read: a file may have changed behind the app.+ public void Reload() { lock (gate) cache.Clear(); }+/// "sk-••••••••••••3f9a" for display.public static string Masked(string key) => key.Length <= 8 ? "sk-…" : key[..3] + new string('•', 12) + key[^4..];}@@ -91,96 +107,197 @@ public sealed class LingException(LingException.Kind kind, int status = 0) : Exc{public enum Kind { NoKey, InvalidKey, RateLimited, Hijacked, Timeout, Http, Network, Parse }public Kind Failure { get; } = kind;+ /// The HTTP status for Kind.Http.+ public int Status { get; } = status;}-/// Ling (ant-ling.com), OpenAI-compatible. One instance for the app: the account allows about 2-/// requests per second across every model, so request *starts* go through one gate (≥ 0.6 s apart,-/// overlapping is fine) in priority order. Two gateway quirks shape every call (see Ling.swift):-/// thinking is always disabled, and the content goes in the system message with a fixed user-/// instruction, because a question-like user message gets a search essay back; such replies are dropped.+/// The AI service: Ling (ant-ling.com) by default, or another OpenAI-compatible one (AIProviders.cs),+/// read from `config` on every call. One instance for the app. Request *starts* go through one gate+/// in priority order: Ling allows about 2 a second across every model (≥ 0.6 s apart, overlapping+/// is fine), the aggregators far more. Ling's gateway shapes every call (see Ling.swift): thinking+/// is always disabled, and the content goes in the system message with a fixed user instruction,+/// because a question-like user message gets a search essay back; such replies are dropped. The+/// other services get the same messages.public sealed class LingClient{- public static readonly Uri Base = new("https://api.ant-ling.com/v1/");+ public static readonly Uri Base = new(AIProvider.Ling.Base!);public const string DefaultModel = "Ling-3.1-flash";public const string AudioModel = "Ming-3.0-audio-flash";+ public const string VoiceModel = "Ming-3.0-tts-0.5B";// Search essays (Ling.swift), and the canned refusal some audio prompts get.static readonly string[] HijackPrefixes = ["根据现有检索证据", "暂未找到足够可靠的信息", "根据检索", "作为一个人工智能语言模型"];readonly AIKey key;readonly HttpClient http;- public string Model { get; set; } = DefaultModel;+ readonly Func<AIConfig> config;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; }+ /// 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; } = [];public event Action? Changed;- public LingClient(AIKey key, HttpMessageHandler? handler = null)+ public LingClient(AIKey key, HttpMessageHandler? handler = null, Func<AIConfig>? config = null){this.key = key;+ this.config = config ?? (() => AIConfig.Default);http = handler is null ? new HttpClient() : new HttpClient(handler);http.Timeout = Timeout.InfiniteTimeSpan; // per request belowhttp.DefaultRequestHeaders.UserAgent.ParseAdd("Cicada-Windows/0.1");- KeyState = key.Read() is null ? KeyState.None : KeyState.Unchecked;+ KeyState = CurrentKey() is null ? KeyState.None : KeyState.Unchecked;+ Hears = Config.IsLing ? true : null;+ }++ public AIConfig Config => config();+ public AIProvider Provider => Config.Provider;++ /// The key for the service in use. A custom service on this computer may need none: "".+ public string? CurrentKey()+ {+ var c = Config;+ var k = key.Read();+ if (k is null && c.Provider.Id == "custom" && c.Base is { } b && AIProvider.IsLocal(b)) return "";+ return k;}- public bool HasKey => key.Read() is not null;+ public bool HasKey => CurrentKey() is not null;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;+ /// Listening and 同声传译 can work: the hear model wasn't found to refuse audio.+ public bool CanHear => Usable && Hears != false && Config.HearModel.Length > 0;+ /// The key, the service or its models changed: forget what the last check found.public void KeyChanged(){- KeyState = key.Read() is null ? KeyState.None : KeyState.Unchecked;+ key.Reload();+ KeyState = CurrentKey() is null ? KeyState.None : KeyState.Unchecked;+ Problem = null;+ Hears = Config.IsLing ? true : null;+ TextCatalog = HearCatalog = [];Changed?.Invoke();}- /// A tiny request that says whether the key works (and how fast).+ /// 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).public async Task<(KeyState state, double seconds)> Check(){- KeyState = KeyState.Checking; Changed?.Invoke();+ 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;try{- await Chat("Reply with OK.", "Reply.", Priority.Speak, maxTokens: 5, timeout: 10, model: "Ling-3.0-tiny");- KeyState = KeyState.Ok;- }- catch (LingException e) when (e.Failure is LingException.Kind.InvalidKey or LingException.Kind.NoKey)- {- KeyState = e.Failure == LingException.Kind.NoKey ? KeyState.None : KeyState.Invalid;+ if (c.IsLing)+ {+ await Chat("Reply with OK.", "Reply.", Priority.Speak, maxTokens: 5, timeout: 10, model: "Ling-3.0-tiny");+ Seconds = (DateTime.UtcNow - started).TotalSeconds;+ Hears = true;+ }+ else+ {+ 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);+ }+ state = KeyState.Ok;}- catch (LingException e) when (e.Failure == LingException.Kind.RateLimited)+ catch (LingException e){- KeyState = KeyState.Ok; // a busy key is still a good key+ // 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]);}- catch+ catch (Exception){- KeyState = KeyState.Unreachable;+ state = KeyState.Unreachable;+ Problem = ("连不上 %@,请检查网络或代理", [name]);}+ KeyState = state;+ Log.Debug($"ai {c.Provider.Id}: key check -> {state}{(Hears == false ? " (hear model refuses audio)" : "")}");Changed?.Invoke();+ if (state == KeyState.Ok && !c.IsLing) await FetchCatalog();return (KeyState, (DateTime.UtcNow - started).TotalSeconds);}+ /// 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)+ {+ if (c.HearModel.Length == 0) return false;+ 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;+ }+ 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; }+ }++ /// The service's models, for the model menus. Quietly just the recommended ones when the+ /// service has no `/models`.+ public async Task FetchCatalog()+ {+ 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) { }+ }+/// One chat completion. `content` goes in the system message, `instruction` is the fixed user- /// message, `audio` (a WAV) goes before it for Ming. Notes retry 429s with backoff; the rest- /// fail fast so the caller can fall back.+ /// message, `audio` (a WAV) goes before it for the hear model. Notes retry 429s with backoff;+ /// the rest fail fast so the caller can fall back. `model` defaults to the service's text model.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, CancellationToken cancel = default){- var k = key.Read() ?? throw new LingException(LingException.Kind.NoKey);+ var k = CurrentKey() ?? throw new LingException(LingException.Kind.NoKey);if (KeyState == KeyState.Invalid) throw new LingException(LingException.Kind.InvalidKey);- JsonNode user = audio is null ? JsonValue.Create(instruction)! : new JsonArray(- new JsonObject { ["type"] = "audio_url", ["audio_url"] = new JsonObject { ["url"] = "data:audio/wav;base64," + Convert.ToBase64String(audio) } },- new JsonObject { ["type"] = "text", ["text"] = instruction });+ var c = Config;+ if (c.Base is null) throw new LingException(LingException.Kind.NoKey);+ model ??= c.TextModel;+ JsonNode user = audio is null ? JsonValue.Create(instruction)! : new JsonArray(c.AudioPart(audio, model), new JsonObject { ["type"] = "text", ["text"] = instruction });var body = new JsonObject{- ["model"] = model ?? Model,+ ["model"] = model,["messages"] = new JsonArray(new JsonObject { ["role"] = "system", ["content"] = content },new JsonObject { ["role"] = "user", ["content"] = user }),- ["max_tokens"] = maxTokens,- ["temperature"] = 0.2,- ["thinking"] = new JsonObject { ["type"] = "disabled" },["stream"] = false,};+ c.Shape(body, maxTokens);if (json) body["response_format"] = new JsonObject { ["type"] = "json_object" };var payload = body.ToJsonString();+ var url = new Uri(new Uri(c.Base), "chat/completions");// Notes can wait; heard audio gets one retry, since on Windows a lost reply loses the words// (on the Mac recognition is local and only the translation is lost); the rest fail fast.@@ -189,23 +306,24 @@ public sealed class LingClientfor (int attempt = 1; ; attempt++){var queued = DateTime.UtcNow;- await Acquire(priority, cancel);+ await Acquire(priority, c.Provider.Spacing, cancel);var started = DateTime.UtcNow;if ((started - queued).TotalSeconds > 1) Log.Debug($"ling: {priority} waited {(started - queued).TotalMilliseconds:F0} ms at the gate");try{- var root = await Post("chat/completions", payload, k, timeout, cancel);+ var root = await Post(url, payload, k, timeout, cancel);var choice = root["choices"]?[0];- var text = choice?["message"]?["content"]?.GetValue<string>() ?? throw new LingException(LingException.Kind.Parse);- var finish = choice?["finish_reason"]?.GetValue<string>();+ var text = Str(choice?["message"]?["content"]) ?? throw new LingException(LingException.Kind.Parse);+ var finish = Str(choice?["finish_reason"]);var trimmed = text.Trim();- if (finish is null || HijackPrefixes.Any(trimmed.StartsWith))+ // Ling's search essays come without a finish reason; other services may simply omit it.+ if (finish is null && c.IsLing || HijackPrefixes.Any(trimmed.StartsWith)){Log.Debug($"ling: {priority} search-style reply dropped");throw new LingException(LingException.Kind.Hijacked);}var usage = root["usage"];- Log.Debug($"ling: {priority} ok {(int)(DateTime.UtcNow - started).TotalMilliseconds} ms tokens={usage?["prompt_tokens"]}/{usage?["completion_tokens"]}");+ 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(); }return trimmed;}@@ -220,28 +338,39 @@ public sealed class LingClient}}- public const string VoiceModel = "Ming-3.0-tts-0.5B";-- /// Ming's voice for `text`: raw 24 kHz mono 16-bit PCM, chunk by chunk as it streams (SSE).- /// `languageId` is Ming's `language_id`, needed for ja, ko, de, fr and es. Ling.swift › speech.- public async IAsyncEnumerable<byte[]> Speech(string text, string voice, string? languageId = null,+ /// The service's voice for `text`: raw 24 kHz mono 16-bit PCM, chunk by chunk as it arrives.+ /// On Ling, `voice` is Ming's and `languageId` its `language_id`, needed for ja, ko, de, fr and+ /// es (Ling.swift › speech); elsewhere the configured speech model, and a voice not in the+ /// service's list becomes its first. Replies come three ways and all are read: server-sent+ /// base64 chunks (Ling, ZenMux), raw PCM (OpenRouter), or one JSON `{"audio": <WAV>}`.+ public async IAsyncEnumerable<byte[]> Speech(string text, string? voice, string? languageId = null,[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancel = default){- var k = key.Read() ?? throw new LingException(LingException.Kind.NoKey);+ var k = CurrentKey() ?? throw new LingException(LingException.Kind.NoKey);if (KeyState == KeyState.Invalid) throw new LingException(LingException.Kind.InvalidKey);- var body = new JsonObject+ var c = Config;+ if (!c.HasVoices) throw new LingException(LingException.Kind.NoKey);+ var body = new JsonObject { ["model"] = c.VoiceModel, ["input"] = text, ["response_format"] = "pcm" };+ if (c.IsLing){- ["model"] = VoiceModel, ["input"] = text, ["voice"] = voice,- ["response_format"] = "pcm", ["sample_rate"] = 24000, ["stream"] = true, ["stream_format"] = "sse",- };- if (languageId is not null) body["language_id"] = languageId;- await Acquire(Priority.Speak, cancel);+ body["voice"] = voice ?? "UK_Charlotte";+ body["sample_rate"] = 24000; body["stream"] = true; body["stream_format"] = "sse";+ if (languageId is not null) body["language_id"] = languageId;+ }+ else+ {+ // OpenRouter documents no `stream` (it streams the bytes anyway); ZenMux needs it.+ if (c.Provider.Id != "openrouter") body["stream"] = true;+ var 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);var started = DateTime.UtcNow;- using var req = new HttpRequestMessage(HttpMethod.Post, new Uri(Base, "audio/speech"))+ using var req = new HttpRequestMessage(HttpMethod.Post, new Uri(new Uri(c.VoiceBase!), "audio/speech")){Content = new StringContent(body.ToJsonString(), Encoding.UTF8, "application/json"),};- req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", k);+ if (k.Length > 0) req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", k);using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancel);cts.CancelAfter(TimeSpan.FromSeconds(20));HttpResponseMessage res;@@ -257,44 +386,91 @@ public sealed class LingClientif (KeyState != KeyState.Invalid) { KeyState = KeyState.Invalid; Changed?.Invoke(); }throw new LingException(LingException.Kind.InvalidKey);case HttpStatusCode.TooManyRequests: throw new LingException(LingException.Kind.RateLimited);- default: Log.Debug($"ling: voice HTTP {(int)res.StatusCode}"); throw new LingException(LingException.Kind.Http, (int)res.StatusCode);+ default: Log.Debug($"ai {c.Provider.Id}: voice HTTP {(int)res.StatusCode}"); throw new LingException(LingException.Kind.Http, (int)res.StatusCode);}- using var reader = new StreamReader(await res.Content.ReadAsStreamAsync(cts.Token));+ var kind = res.Content.Headers.ContentType?.MediaType ?? "";+ var stream = await res.Content.ReadAsStreamAsync(cts.Token);int chunks = 0;- while (true)+ if (kind.Contains("event-stream") || c.IsLing){- string? line;- try { line = await reader.ReadLineAsync(cts.Token); }+ using var reader = new StreamReader(stream);+ while (true)+ {+ string? line;+ try { line = await reader.ReadLineAsync(cts.Token); }+ catch (OperationCanceledException) when (!cancel.IsCancellationRequested) { throw new LingException(LingException.Kind.Timeout); }+ if (line is null) break;+ var pcm = SpeechChunk(line, out var done);+ if (done) break;+ if (pcm is null) continue;+ if (chunks++ == 0) Log.Debug($"ai {c.Provider.Id}: Speak first audio {(int)(DateTime.UtcNow - started).TotalMilliseconds} ms");+ yield return pcm;+ }+ }+ else if (kind.Contains("json"))+ {+ string all;+ try { all = await new StreamReader(stream).ReadToEndAsync(cts.Token); }catch (OperationCanceledException) when (!cancel.IsCancellationRequested) { throw new LingException(LingException.Kind.Timeout); }- if (line is null) break;- var pcm = SpeechChunk(line, out var done);- if (done) break;- if (pcm is null) continue;- if (chunks++ == 0) Log.Debug($"ling: Speak first audio {(int)(DateTime.UtcNow - started).TotalMilliseconds} ms");- yield return pcm;+ byte[] wav;+ try { wav = Convert.FromBase64String(JsonNode.Parse(all)?["audio"]?.GetValue<string>() ?? throw new LingException(LingException.Kind.Parse)); }+ catch (Exception e) when (e is JsonException or FormatException or InvalidOperationException) { throw new LingException(LingException.Kind.Parse); }+ Log.Debug($"ai {c.Provider.Id}: Speak audio {(int)(DateTime.UtcNow - started).TotalMilliseconds} ms");+ yield return PcmFromWav(wav);+ }+ else+ {+ // Raw PCM: handed on in 0.1 s pieces at 24 kHz, so playback starts early.+ var buffer = new byte[4800];+ while (true)+ {+ int n;+ try { n = await stream.ReadAsync(buffer, cts.Token); }+ catch (OperationCanceledException) when (!cancel.IsCancellationRequested) { throw new LingException(LingException.Kind.Timeout); }+ if (n == 0) break;+ if (chunks++ == 0) Log.Debug($"ai {c.Provider.Id}: Speak first audio {(int)(DateTime.UtcNow - started).TotalMilliseconds} ms");+ yield return buffer[..n];+ }}}}- /// One SSE line of Ming's voice stream: the PCM it carries, or `done` at the end.+ /// 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){done = false;if (!line.StartsWith("data:")) return null;JsonNode? obj;try { obj = JsonNode.Parse(line[5..]); } catch (JsonException) { return null; }- if (obj?["type"]?.GetValue<string>() == "speech.audio.done") { done = true; return null; }- if (obj?["audio"]?.GetValue<string>() is not { Length: > 0 } b64) return null;+ if (obj is not JsonObject) return null;+ if (Str(obj["type"]) == "speech.audio.done") { done = true; return null; }+ if (Str(obj["audio"]) is not { Length: > 0 } b64) return null;try { return Convert.FromBase64String(b64); } catch (FormatException) { return null; }}- async Task<JsonNode> Post(string path, string payload, string k, double timeout, CancellationToken cancel)+ static string? Str(JsonNode? n) => n is JsonValue v && v.TryGetValue<string>(out var s) ? s : null;++ /// The samples of a WAV (its `data` chunk); the bytes themselves when there's no header.+ public static byte[] PcmFromWav(byte[] wav)+ {+ if (wav.Length < 12 || Encoding.ASCII.GetString(wav, 0, 4) != "RIFF") return wav;+ int at = 12;+ while (at + 8 <= wav.Length)+ {+ int size = BitConverter.ToInt32(wav, at + 4);+ if (Encoding.ASCII.GetString(wav, at, 4) == "data") return wav[(at + 8)..Math.Min(wav.Length, at + 8 + size)];+ at += 8 + size + (size & 1);+ }+ return [];+ }++ async Task<JsonNode> Post(Uri url, string payload, string k, double timeout, CancellationToken cancel){- using var req = new HttpRequestMessage(HttpMethod.Post, new Uri(Base, path))+ using var req = new HttpRequestMessage(HttpMethod.Post, url){Content = new StringContent(payload, Encoding.UTF8, "application/json"),};- req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", k);+ if (k.Length > 0) req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", k);using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancel);cts.CancelAfter(TimeSpan.FromSeconds(timeout));HttpResponseMessage res;@@ -328,20 +504,23 @@ public sealed class LingClient}}- // Start gate: request starts ≥ 0.6 s apart, the most urgent waiting one first.+ // Start gate: request starts ≥ the service's spacing apart, the most urgent waiting one first.- public static double Spacing { get; set; } = 0.6;+ /// Tests only: overrides the service's spacing.+ public static double? Spacing { get; set; }readonly object gate = new();DateTime lastStart = DateTime.MinValue;readonly List<(Priority priority, long seq, TaskCompletionSource ready)> waiting = [];long seq;bool pumping;+ double spacing = 0.6;- Task Acquire(Priority priority, CancellationToken cancel)+ Task Acquire(Priority priority, double serviceSpacing, CancellationToken cancel){lock (gate){- if (waiting.Count == 0 && (DateTime.UtcNow - lastStart).TotalSeconds >= Spacing)+ spacing = Spacing ?? serviceSpacing;+ if (waiting.Count == 0 && (DateTime.UtcNow - lastStart).TotalSeconds >= spacing){lastStart = DateTime.UtcNow;return Task.CompletedTask;@@ -358,7 +537,7 @@ public sealed class LingClientwhile (true){double wait;- lock (gate) wait = Math.Max(0, Spacing - (DateTime.UtcNow - lastStart).TotalSeconds);+ lock (gate) wait = Math.Max(0, spacing - (DateTime.UtcNow - lastStart).TotalSeconds);if (wait > 0) await Task.Delay(TimeSpan.FromSeconds(wait));lock (gate){diff --git a/windows/src/Cicada.Core/ListenEngine.cs b/windows/src/Cicada.Core/ListenEngine.csindex e48bc3e..9a0d857 100644--- a/windows/src/Cicada.Core/ListenEngine.cs+++ b/windows/src/Cicada.Core/ListenEngine.cs@@ -2,8 +2,8 @@ using System.Threading.Channels;namespace Cicada;-/// Listening end to end: system audio → segments → Ming (language, original, translation in one-/// call) → lines in the record, plus live notes. UI-free; the app shows `Lines` and listens to+/// Listening end to end: system audio → segments → the AI service's hear model (Ming on Ling:+/// language, original, translation in one call) → lines in the record, plus live notes. UI-free; the app shows `Lines` and listens to/// `Changed` (raised on worker threads: marshal to the UI thread).////// Ming takes ~2.2 s whatever the segment's length, so segments overlap in flight: request starts@@ -43,14 +43,40 @@ public sealed class ListenEngine/// Segments sent and not yet back: the UI shows "…" while this is above zero.public int Pending { get { lock (gate) return segments.Count; } }/// The last error worth showing ("key 无效", "网络不通"), cleared by the next good reply.- /// What last went wrong talking to Ling (null once a segment gets through); the windows word it.+ /// What last went wrong talking to the AI service (null once a segment gets through); the+ /// windows word it with Words().public LingException.Kind? Problem { get; private set; }+ /// The HTTP status behind Problem == Http.+ public 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)+ {+ var ling = service == "Ling";+ if (kind == LingException.Kind.Http && status is 400 or 404 && !ling)+ return (Strings.L("这个模型听不了声音,换一个支持音频输入的"), 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),+ };+ }/// The user pressed 重试: hide the bar until the next failure says otherwise.public void ClearProblem() { Problem = null; Changed?.Invoke(); }/// Debug pipe only: show a failure's bar without breaking the network ("network", "ratelimited"…).- public void SimulateProblem(string kind) { Problem = Enum.TryParse<LingException.Kind>(kind, true, out var k) ? k : null; Changed?.Invoke(); }+ public void SimulateProblem(string kind)+ {+ var parts = kind.Split(' ');+ Problem = Enum.TryParse<LingException.Kind>(parts[0], true, out var k) ? k : null;+ ProblemStatus = parts.Length > 1 && int.TryParse(parts[1], out var s) ? s : 0;+ Changed?.Invoke();+ }public double Level { get; private set; }public event Action? Changed;@@ -149,6 +175,7 @@ public sealed class ListenEnginecatch (LingException e){Problem = e.Failure is LingException.Kind.Hijacked or LingException.Kind.Parse ? null : e.Failure;+ ProblemStatus = e.Status;Log.Debug($"listen: segment {seg.Index} failed {e.Message}");}Log.Debug($"listen: segment {seg.Index} {seg.Seconds:F1}s -> {(heard is null ? "nothing" : heard.Lang)} in {(DateTime.UtcNow - started).TotalMilliseconds:F0} ms");diff --git a/windows/src/Cicada.Core/Settings.cs b/windows/src/Cicada.Core/Settings.csindex bc58c5c..9408b0d 100644--- a/windows/src/Cicada.Core/Settings.cs+++ b/windows/src/Cicada.Core/Settings.cs@@ -3,14 +3,24 @@ using System.Text.Json.Serialization;namespace Cicada;-/// The app's settings, in settings.json beside the records (never the Ling key: that has its own file).+/// The app's settings, in settings.json beside the records (never an AI key: each has its own file).public sealed class AppSettings{/// What subtitles translate into; "system" follows the Windows display language.[JsonPropertyName("target")] public string Target { get; set; } = "system";/// 纪要语言: the notes' language code; "system" is the same as the subtitles'.[JsonPropertyName("notesLanguage")] public string NotesLanguage { get; set; } = "system";+ /// Ling's text model (the other services' are in AiModels).[JsonPropertyName("model")] public string Model { get; set; } = LingClient.DefaultModel;+ /// AI 服务 (the Mac's keys): the service, and per service the models chosen over its recommended+ /// ones. aiHearModels is the ports' own: what hears the audio (Ming on Ling).+ [JsonPropertyName("aiProvider")] public string AiProvider { get; set; } = "ling";+ [JsonPropertyName("aiModels")] public Dictionary<string, string> AiModels { get; set; } = [];+ [JsonPropertyName("aiHearModels")] public Dictionary<string, string> AiHearModels { get; set; } = [];+ [JsonPropertyName("aiVoiceModels")] public Dictionary<string, string> AiVoiceModels { get; set; } = [];+ [JsonPropertyName("aiCustomBase")] public string AiCustomBase { get; set; } = "";+ [JsonPropertyName("aiCustomVoiceBase")] public string AiCustomVoiceBase { get; set; } = "";+ [JsonPropertyName("aiCustomVoice")] public string AiCustomVoice { get; set; } = "";/// "notes" (the notes window, default) or "subtitles" (the subtitle bar).[JsonPropertyName("view")] public string View { get; set; } = "notes";/// Whether 知了还在任务栏右下角 was shown, after the first × on a window.@@ -48,6 +58,8 @@ public sealed class AppSettings[JsonPropertyName("updateNotified")] public string? UpdateNotified { get; set; }[JsonIgnore] public string TargetCode => Target == "system" ? Languages.FromSystem(CultureInfo.CurrentUICulture.Name) : Target;+ /// The AI service in use, its address and models (what LingClient calls with).+ public AIConfig AIConfig() => Cicada.AIConfig.From(this);[JsonIgnore] public string NotesCode => NotesLanguage == "system" ? TargetCode : NotesLanguage;public static AppSettings Load()diff --git a/windows/src/Cicada.Core/Speak.cs b/windows/src/Cicada.Core/Speak.csindex ced5935..1b05d3e 100644--- a/windows/src/Cicada.Core/Speak.cs+++ b/windows/src/Cicada.Core/Speak.cs@@ -12,7 +12,7 @@ public interface ISpeechSinkTask End();}-/// Windows' own voice, for when Ming's can't speak: 16-bit mono PCM, or null.+/// Windows' own voice, for when the AI service's can't speak: 16-bit mono PCM, or null.public interface ISystemVoice{Task<(byte[] pcm, int rate)?> Speak(string text, string language);@@ -20,20 +20,27 @@ public interface ISystemVoicebool Has(string language);}-/// A voice the room can hear: one of Ming's (through the Ling key) or Windows' own.+/// A voice the room can hear: one of Ming's ("ming:…", through the Ling key), one of another+/// service's speech model ("cloud:…"), or Windows' own.public sealed record VoiceOption(string Id, string Name, string Tags);-/// Which voices to offer for each language the room may hear: Ming's hand-picked natural ones, as-/// on the Mac (Voices.swift › VoiceCatalog), then Windows' voice so there is always one.+/// Which voices to offer for each language the room may hear, by the AI service in use: on Ling+/// Ming's hand-picked natural ones, as on the Mac (Voices.swift › VoiceCatalog); on another service+/// its speech model's voices, the same in every language, or none without a speech model; then+/// Windows' voice so there is always one.public static class VoiceCatalog{- public const string SystemId = "system";+ public const string SystemId = "system", MingPrefix = "ming:", CloudPrefix = "cloud:";public static string Key(string code) { var b = code.Split('-')[0]; return b.Length == 0 ? "en" : b; }/// Ming's `language_id` for languages that need it (zh and en work without).public static string? MingLanguage(string code) => Key(code) is "ja" or "ko" or "de" or "fr" or "es" ? Key(code) : null;+ /// The service's own voices for a language (Ming's on Ling).+ public static IReadOnlyList<VoiceOption> Cloud(string language, AIConfig config) =>+ config.IsLing ? Ming(language) : config.Voices.Select(v => new VoiceOption(CloudPrefix + v.Id, v.Id, v.Gender)).ToList();+public static IReadOnlyList<VoiceOption> Ming(string language) => Key(language) switch{"en" => [new("ming:US_Emma", "Emma", "女 · 美式 · 自然对话"), new("ming:UK_George", "George", "男 · 英式 · 稳重"), new("ming:UK_Charlotte", "Charlotte", "女 · 英式 · 平稳")],@@ -42,11 +49,17 @@ public static class VoiceCatalog_ => [],};- public static IReadOnlyList<VoiceOption> Options(string language, bool windowsHasIt = true) =>- windowsHasIt ? [.. Ming(language), new(SystemId, "Windows", "本机")] : Ming(language);+ public static IReadOnlyList<VoiceOption> Options(string language, AIConfig config, bool windowsHasIt = true) =>+ windowsHasIt ? [.. Cloud(language, config), new(SystemId, "Windows", "本机")] : Cloud(language, config);++ /// What a language uses until the user picks: the service's first voice once it can speak,+ /// else Windows'.+ public static string DefaultId(string language, AIConfig config, bool speaks) => speaks && Cloud(language, config) is [var first, ..] ? first.Id : SystemId;- /// What a language uses until the user picks: Ming's first voice with a key, else Windows'.- public static string DefaultId(string language, bool hasKey) => hasKey && Ming(language).Count > 0 ? Ming(language)[0].Id : SystemId;+ /// The voice chosen for a language, if this service still offers it: a Ming voice saved+ /// before switching to ZenMux is not sent there.+ public static string Chosen(AppSettings settings, string language, AIConfig config, bool speaks) =>+ settings.SpeakVoices.TryGetValue(Key(language), out var id) && Options(language, config).Any(v => v.Id == id) ? id : DefaultId(language, config, speaks);/// A short line to try a voice with, in the language it will speak.public static string Sample(string language) => Key(language) switch@@ -62,8 +75,8 @@ public static class VoiceCatalog};}-/// Hold to talk, the Mac's SpeakEngine: what I said (a 16 kHz WAV) → Ming hears and translates it in-/// one call → a voice speaks the translation into the virtual mic, so the meeting hears it in the+/// Hold to talk, the Mac's SpeakEngine: what I said (a 16 kHz WAV) → the AI service's hear model+/// (Ming on Ling) hears and translates it in one call → a voice speaks the translation into the virtual mic, so the meeting hears it in the/// room's language. Never speaks anything untranslated: no translation, no sound.public sealed class SpeakEngine{@@ -84,7 +97,7 @@ public sealed class SpeakEnginepublic string? Said { get; private set; }public string? Heard { get; private set; }public string? Problem { get; private set; }- /// "ming" or "system": how the last sentence was voiced.+ /// "ming", "cloud" (another service's speech model) or "system": how the last sentence was voiced.public string? LastVoice { get; private set; }public event Action? Changed;@@ -135,7 +148,7 @@ public sealed class SpeakEngineChanged?.Invoke();Heard? heard = null;try { heard = await translator.Hear(wav, to, MyLanguage, Priority.Speak); }- catch (LingException e) { Log.Debug($"speak: hear failed {e.Message}"); return Fail(e.Failure is LingException.Kind.Network or LingException.Kind.Timeout ? Strings.L("连不上 Ling,没有发出去") : Strings.L("没翻译成功,没有发出去")); }+ catch (LingException e) { Log.Debug($"speak: hear failed {e.Message}"); return Fail(e.Failure is LingException.Kind.Network or LingException.Kind.Timeout ? (ling.Config.IsLing ? Strings.L("连不上 Ling,没有发出去") : Strings.LF("连不上 %@,没有发出去", ling.Config.Name)) : Strings.L("没翻译成功,没有发出去")); }if (heard is null) return Fail(Strings.L("没听清,没有发出去"));Said = heard.Original;var text = heard.Translation;@@ -182,23 +195,25 @@ public sealed class SpeakEnginestore.Append(m.id, line);}- /// Ming's voice, else Windows'. True once some sound went out.+ /// The service's voice (Ming's on Ling), else Windows'. True once some sound went out.public async Task<bool> Voice(string text, string language, ISpeechSink sink){- var id = settings.SpeakVoices.TryGetValue(VoiceCatalog.Key(language), out var chosen) ? chosen : VoiceCatalog.DefaultId(language, ling.HasKey);- if (id.StartsWith("ming:") && ling.HasKey)+ var config = ling.Config;+ var id = VoiceCatalog.Chosen(settings, language, config, ling.Speaks);+ var prefix = config.IsLing ? VoiceCatalog.MingPrefix : VoiceCatalog.CloudPrefix;+ if (id.StartsWith(prefix) && ling.Speaks){int chunks = 0;try{- await foreach (var pcm in ling.Speech(text, id["ming:".Length..], VoiceCatalog.MingLanguage(language)))+ await foreach (var pcm in ling.Speech(text, id[prefix.Length..], config.IsLing ? VoiceCatalog.MingLanguage(language) : null)){if (chunks++ == 0) sink.Begin(24000);sink.Write(pcm);}}- catch (LingException e) { Log.Debug($"speak: ming voice failed {e.Message}"); }- if (chunks > 0) { await sink.End(); LastVoice = "ming"; return true; }+ catch (LingException e) { Log.Debug($"speak: {config.Provider.Id} voice failed {e.Message}"); }+ if (chunks > 0) { await sink.End(); LastVoice = config.IsLing ? "ming" : "cloud"; return true; }}var own = await systemVoice.Speak(text, language);if (own is not { } v || v.pcm.Length == 0) { LastVoice = null; return false; }diff --git a/windows/src/Cicada.Core/Support.cs b/windows/src/Cicada.Core/Support.csindex 204780d..0383ad5 100644--- a/windows/src/Cicada.Core/Support.cs+++ b/windows/src/Cicada.Core/Support.cs@@ -22,7 +22,8 @@ public static class Pathspublic static string Sessions => Path.Combine(Root, "Sessions");public static string Settings => Path.Combine(Root, "settings.json");- public static string KeyFile => Path.Combine(Root, "ling-api-key");+ /// One key file per AI service, named as on the Mac.+ public static string KeyFile(string service = "ling") => Path.Combine(Root, service == "ling" ? "ling-api-key" : "ai-key-" + service);public static string Log => Path.Combine(Path.GetTempPath(), Dev ? "cicada-dev-debug.log" : "cicada-debug.log");}diff --git a/windows/src/Cicada.Core/Translator.cs b/windows/src/Cicada.Core/Translator.csindex 7088607..034d65a 100644--- a/windows/src/Cicada.Core/Translator.cs+++ b/windows/src/Cicada.Core/Translator.cs@@ -2,13 +2,14 @@ using System.Text.Json;namespace Cicada;-/// What Ming heard in one stretch of audio.+/// What the hear model (Ming on Ling) heard in one stretch of audio.public sealed record Heard(string Lang, string Original, string? Translation);/// Translation and recognition through the cloud, in place of the Mac's on-device recognizer and-/// Apple translation. Listening sends each stretch of audio to Ming's audio model, which returns-/// the language, the original and the translation in one call (as the Mac's speak-back does).-/// Text translation is Ling first, then Google; Google is also the only one that sees drafts.+/// Apple translation. Listening sends each stretch of audio to the AI service's hear model (Ming on+/// Ling), which returns the language, the original and the translation in one call (as the Mac's+/// speak-back does). Text translation is the AI service first, then Google; Google is also the only+/// one that sees drafts.public sealed class Translator(LingClient ling, HttpMessageHandler? google = null){static readonly HttpClient Shared = MakeHttp(null);@@ -38,11 +39,16 @@ public sealed class Translator(LingClient ling, HttpMessageHandler? google = nul// 16 kHz mono 16-bit after the 44-byte header: the length caps the reply and catches a runaway one.var seconds = Math.Max(0, wav.Length - 44) / 32000.0;var prompt = HearPrompt(target, hint, Glossary());- var reply = await ling.Chat(prompt, HearInstruction(target), priority, maxTokens: HearTokens(seconds), timeout: 12,- model: LingClient.AudioModel, audio: wav, cancel: cancel);+ var config = ling.Config;+ var reply = await ling.Chat(prompt, HearInstruction(target), priority, maxTokens: HearTokens(seconds), timeout: HearTimeout(config),+ model: config.HearModel, audio: wav, cancel: cancel);return ParseHeard(reply, target, hint, seconds);}+ /// Ming answers in ~2 s; the other services' hear models in 3–4 s, but now and then over 12 s+ /// (Qwen on ZenMux, 2026-11), and a stretch given up on is words lost.+ public static double HearTimeout(AIConfig config) => config.IsLing ? 12 : 20;+/// Room for a reply to `seconds` of audio: a fast talker's original and translation fit; a/// reply that runs on repeating itself ("滴答" ×800 from typing) stops early. 0: unknown.public static int HearTokens(double seconds) => seconds <= 0 ? 800 : Math.Min(800, (int)(60 + 40 * seconds));@@ -56,6 +62,8 @@ public sealed class Translator(LingClient ling, HttpMessageHandler? google = nul{var text = Annotation.Replace(original.ToLowerInvariant(), " ");if (NoSpeech.Any(text.Contains)) return true;+ // A clock instead of words ("00:00"): what some of the other services' models write for a beep.+ if (Clock.IsMatch(text.Trim())) return true;var words = new List<string>();var word = new System.Text.StringBuilder();foreach (var c in text)@@ -77,6 +85,7 @@ public sealed class Translator(LingClient ling, HttpMessageHandler? google = nul/// Ming describing the audio instead of transcribing it: "(无语音内容)", "[Music]", "这段音频是一段/// 旋律,没有说话声。". A bracketed note beside real words ("(笑)好的") keeps the words.static readonly System.Text.RegularExpressions.Regex Annotation = new("[((\\[【][^))\\]】]*[))\\]】]|♪");+ static readonly System.Text.RegularExpressions.Regex Clock = new(@"^\d{1,2}(:\d{2}){1,2}[.。]?$");static readonly string[] NoSpeech = ["没有说话", "无语音", "没有语音", "没有人声", "无人声", "没有人说话", "无人说话","no speech", "no spoken", "no one is speaking", "nobody is speaking", "no audible speech", "no dialogue",@@ -155,7 +164,7 @@ public sealed class Translator(LingClient ling, HttpMessageHandler? google = nulpublic enum Kind { Draft, Sentence }- /// Ling (finished sentences only) → Google. Null when both fail.+ /// The AI service (finished sentences only) → Google. Null when both fail.public async Task<string?> Translate(string text, string source, string target, Kind kind, Priority priority = Priority.Translate){if (source == target) return text;diff --git a/windows/src/Cicada/App.cs b/windows/src/Cicada/App.csindex 462a32a..469580e 100644--- a/windows/src/Cicada/App.cs+++ b/windows/src/Cicada/App.cs@@ -49,7 +49,8 @@ sealed class Controller{readonly Application application;public readonly AppSettings Settings = AppSettings.Load();- public readonly AIKey Key = new(new DpapiProtector());+ /// The key of the AI service in use (one file per service).+ public readonly AIKey Key;public readonly LingClient Ling;public readonly SessionStore Store = new();public readonly NotesEngine Notes;@@ -104,7 +105,8 @@ sealed class Controllerthis.application = application;var ui = Settings.UiLanguage == "system" ? null : Settings.UiLanguage;Strings.Load(Bundled.Strings, ui);- Ling = new LingClient(Key) { Model = Settings.Model };+ Key = new AIKey(new DpapiProtector(), service: () => Settings.AiProvider);+ Ling = new LingClient(Key, config: Settings.AIConfig);SpeakerLabels.Voices = Settings.SpeakerVoices;Notes = new NotesEngine(Ling, Store);Translator = new Translator(Ling);@@ -496,7 +498,7 @@ sealed class Controllervoid PressBegan(){if (!Settings.Speak || Speak.State is SpeakEngine.Phase.Recording or SpeakEngine.Phase.Translating) return;- if (!Ling.HasKey) { Speak.Report(L("需要 Ling key 才能说")); return; }+ if (!Ling.HasKey) { Speak.Report(Ling.Config.IsLing ? L("需要 Ling key 才能说") : LF("需要 %@ 的 key 才能说", Ling.Config.Name)); return; }if (Endpoints.Cable() is null) { Speak.Report(L("还没装虚拟麦克风,去设置里装一下")); return; }if (fakeMic is null){@@ -602,6 +604,53 @@ sealed class Controllerpublic void SettingsPage(string id) => settingsWindow?.Show(id);+ // MARK: AI 服务++ /// 设置 › AI 服务: another service, with its own key file and models; checked again.+ public void SetAIProvider(string provider)+ {+ if (AIProvider.Named(provider).Id != provider || provider == Settings.AiProvider) return;+ Settings.AiProvider = provider;+ Settings.Save();+ AIChanged();+ }++ /// A model chosen over the recommended one ("text", "hear" or "voice"; "" goes back to it).+ public void SetAIModel(string kind, string model)+ {+ var p = Settings.AiProvider;+ if (kind == "text" && p == "ling") Settings.Model = model.Length > 0 ? model : LingClient.DefaultModel;+ else+ {+ var table = kind switch { "text" => Settings.AiModels, "hear" => Settings.AiHearModels, "voice" => Settings.AiVoiceModels, _ => null };+ if (table is null) return;+ if (model.Length > 0) table[p] = model; else table.Remove(p);+ }+ Settings.Save();+ AIChanged();+ }++ /// The service, its address, models or key changed: forget the old check and check again.+ public void AIChanged()+ {+ Ling.KeyChanged();+ if (Ling.HasKey) _ = Ling.Check();+ Changed();+ }++ /// For the debug pipe: the AI service in use and what its last check found (never the key).+ public JsonObject AIState()+ {+ var c = Ling.Config;+ return new JsonObject+ {+ ["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,+ ["catalog"] = new JsonArray(Ling.TextCatalog.Count, Ling.HearCatalog.Count), ["keyFile"] = Path.GetFileName(Key.File_),+ };+ }+public void SetView(string view){Settings.View = view;@@ -717,6 +766,7 @@ sealed class Controller["notes"] = Notes.Status.ToString(),["topics"] = Notes.Notes.Topics.Count,["key"] = Ling.KeyState.ToString(),+ ["ai"] = AIState(),["view"] = Settings.View,["showInCapture"] = Settings.ShowInCapture,["sessions"] = Store.All().Count,@@ -747,6 +797,7 @@ sealed class Controller/// show notes|records|settings [page]|flyout|menu | quit/// 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)static class DebugServer{static string Pipe => Paths.Dev ? "cicada-dev" : "cicada";@@ -817,6 +868,13 @@ static class DebugServerif (arg == "on" || arg == "off") { app.Settings.Speak = arg == "on"; app.Settings.Save(); app.SettingsChanged(); }else _ = app.Speak.Speak(Wav.Bytes(Wav.Read(arg)), new DeviceSpeaker(Endpoints.Cable));break;+ case "provider": app.SetAIProvider(arg); break;+ case "ai-model":+ {+ var kv = arg.Split(' ', 2);+ app.SetAIModel(kv[0], kv.Length > 1 ? kv[1].Trim() : "");+ break;+ }case "speakers": app.Settings.SpeakerVoices = arg == "on"; app.Settings.Save(); app.SettingsChanged(); break;case "fakemic": app.SetFakeMic(arg == "off" ? null : arg); break;case "record": _ = app.RecordCable(arg); break;diff --git a/windows/src/Cicada/MainWindow.cs b/windows/src/Cicada/MainWindow.csindex 1a47e46..9723402 100644--- a/windows/src/Cicada/MainWindow.cs+++ b/windows/src/Cicada/MainWindow.cs@@ -247,7 +247,8 @@ sealed class MainWindow : Windowvar first = !key ? 0 : !audio ? 1 : !sample ? 2 : 3;(string title, string detail, bool done)[] steps =[- (L("接上 Ling"), key ? L("key 已加密存在这台电脑上") : L("识别、翻译和纪要都靠它,约 1 分钟"), key),+ // 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),(L("听一下电脑里的声音"), L("放一段测试声音,看音量条动起来"), audio),(L("看看效果"), L("一段 9 秒的英文会议,字幕和纪要一句句出来"), sample),(L("同声传译"), LF("按住%@说话,对方听到翻译后的声音", PushToTalk.Label), false),diff --git a/windows/src/Cicada/NotesWindow.cs b/windows/src/Cicada/NotesWindow.csindex 7d2027c..f8ef67d 100644--- a/windows/src/Cicada/NotesWindow.cs+++ b/windows/src/Cicada/NotesWindow.cs@@ -256,23 +256,17 @@ sealed class NotesWindow : Windowreturn row;}- /// What needs the user: Ling failing, or the window being visible to others.+ /// What needs the user: the AI service failing, or the window being visible to others.FrameworkElement Bars(){var stack = new StackPanel { Margin = new Thickness(12, 0, 12, 0) };void Add(FrameworkElement bar) { bar.Margin = new Thickness(0, 0, 0, 8); stack.Children.Add(bar); }- switch (app.Listen.Problem)+ if (app.Listen.Problem is { } problem){- case LingException.Kind.Network or LingException.Kind.Timeout or LingException.Kind.Http:- Add(Ui.InfoBar(Ui.Severity.Error, L("连不上 Ling"), L("这段时间的话没能识别。检查网络后点重试。"),- Ui.Button(L("重试"), () => { app.Listen.ClearProblem(); _ = app.Ling.Check(); }, height: 32)));- break;- case LingException.Kind.RateLimited:- Add(Ui.InfoBar(Ui.Severity.Warning, L("Ling 太忙"), L("稍后会自动重试。")));- break;- case LingException.Kind.InvalidKey or LingException.Kind.NoKey:- Add(Ui.InfoBar(Ui.Severity.Error, L("Ling key 无效"), L("去设置里换一个 key。"), Ui.Button(L("打开设置"), app.ShowSettings, height: 32)));- break;+ var (title, body, settings) = ListenEngine.Words(problem, app.Listen.ProblemStatus, app.Ling.Config.Name);+ 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 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.if (app.Listen.Listening)diff --git a/windows/src/Cicada/Onboarding.cs b/windows/src/Cicada/Onboarding.csindex 43b53c2..d1531ba 100644--- a/windows/src/Cicada/Onboarding.cs+++ b/windows/src/Cicada/Onboarding.cs@@ -10,8 +10,9 @@ namespace Cicada.App;/// First run, as the Mac's setup window without Windows' title bar: the logo and a bar per step/// along the top, a big heading with one grey line, the task in white cards, Back / Continue at the-/// bottom. Windows needs no permission for system audio and listening needs the Ling key-/// (recognition is Ming's), so: 接 Ling → 听声音 → 看效果 → 同声传译, then where the tray icon lives.+/// bottom. Windows needs no permission for system audio and listening needs an AI key (recognition+/// is Ming's, or another service's hear model behind 用不了 Ling?), so: 接 Ling → 听声音 → 看效果 →+/// 同声传译, then where the tray icon lives.sealed class Onboarding : Window{readonly Controller app;@@ -53,8 +54,8 @@ sealed class Onboarding : Windowmeter.Tick += (_, _) => { if (step == 1) Meter(); };app.Speak.Changed += SpeakChanged;Closed += (_, _) => { StopTap(); app.Speak.Changed -= SpeakChanged; LeaveSpeak(keep: false); };- System.Windows.Automation.AutomationProperties.SetName(keyBox, L("Ling key"));- System.Windows.Automation.AutomationProperties.SetName(keyText, L("Ling key"));+ 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; };keyText.TextChanged += (_, _) => { if (keyBox.Password != keyText.Text) keyBox.Password = keyText.Text; };step = app.Ling.HasKey ? 1 : 0;@@ -91,10 +92,14 @@ sealed class Onboarding : WindowspeakBefore = null;}+ // The service the key page was last shown for: another one's status and key don't carry over.+ string? shownProvider;+void Render(){+ if (shownProvider != app.Settings.AiProvider) { shownProvider = app.Settings.AiProvider; keyBox.Clear(); keyStatus.Content = null; }stepper.Content = Stepper();- page.Content = step switch { 0 => KeyStep(), 1 => AudioStep(), 2 => SampleStep(), 3 => SpeakStep(), _ => DoneStep() };+ page.Content = step switch { 0 => Other ? OtherStep() : KeyStep(), 1 => AudioStep(), 2 => SampleStep(), 3 => SpeakStep(), _ => DoneStep() };footer.Content = Footer();}@@ -108,7 +113,7 @@ sealed class Onboarding : Windowlogo.Margin = new Thickness(0, 0, 14, 0); logo.VerticalAlignment = VerticalAlignment.Top;grid.Children.Add(logo);if (step >= Steps) return grid;- string[] names = [L("接 Ling"), L("听声音"), L("看效果"), L("同声传译")];+ string[] names = [Other ? L("接 AI 服务") : L("接 Ling"), L("听声音"), L("看效果"), L("同声传译")];for (int i = 0; i < names.Length; i++) grid.ColumnDefinitions.Add(new ColumnDefinition());for (int i = 0; i < names.Length; i++){@@ -195,8 +200,19 @@ sealed class Onboarding : Windowback.MinWidth = 0; back.HorizontalAlignment = HorizontalAlignment.Left; back.Padding = new Thickness(0);((TextBlock)((StackPanel)back.Content).Children[0]).Foreground = Palette.Secondary;UIElement left = back;- if (step == 0)- left = Ui.Row(8, Ui.Icon(Icons.Lock, 14, Palette.Secondary), Ui.Text(L("key 加密存在这台电脑上,只发给 Ling"), 13, Palette.Secondary, wrap: false));+ if (step == 0 && Other)+ {+ var ling = Ui.LinkText(L("‹ 还是用 Ling"), () => Switch("ling"));+ ling.Foreground = Palette.Secondary;+ left = Ui.Row(16, ling, Ui.Row(8, Ui.Icon(Icons.Lock, 14, Palette.Secondary), Ui.Text(LF("仅保存在本机当前账户下,仅发送至 %@", app.Ling.Config.Name), 13, Palette.Secondary, wrap: false)));+ }+ else if (step == 0)+ {+ // A grey link, as on the Mac: Ling stays first and recommended.+ var other = Ui.LinkText(L("用不了 Ling?"), () => Switch("openrouter"));+ other.Foreground = Palette.Secondary;+ left = Ui.Row(16, Ui.Row(8, Ui.Icon(Icons.Lock, 14, Palette.Secondary), Ui.Text(L("key 加密存在这台电脑上,只发给 Ling"), 13, Palette.Secondary, wrap: false)), other);+ }var next = step switch{0 => Ui.Button(L("继续"), () => _ = SaveKey(), Ui.Kind.Primary, Icons.Arrow, height: 44, iconAfter: true),@@ -225,6 +241,73 @@ sealed class Onboarding : Window{var 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("已连接,可以用了"));+ keyStatus.Margin = new Thickness(0, 12, 0, 0);+ var second = new StackPanel { Children = { row, keyStatus } };+ var card = StepCard(new StackPanel+ {+ Children =+ {+ Numbered(Disc(1), L("在 Ling 开放平台创建 key"), L("国内直接注册,不用代理;登录后点“创建令牌”"), open),+ Divider(),+ Numbered(Disc(2), L("复制 sk- 开头的 key,回来粘贴"), null, below: second),+ },+ });+ FrameworkElement Benefit(string title, string detail) => new StackPanel { Margin = new Thickness(0, 14, 0, 0), Children = { Ui.Text(title, 14, Palette.Ink), Gap(Ui.Text(detail, 12, Palette.Secondary), 2) } };+ var side = StepCard(new StackPanel+ {+ Children =+ {+ Ui.Text(L("Ling 每月赠送 ¥10 额度"), 16, Palette.Ink, FontWeights.Bold),+ Gap(Ui.Text(L("约够 10–50 小时会议"), 13, Palette.Secondary), 4),+ new Border { Height = 1, Background = Palette.Line, Margin = new Thickness(0, 14, 0, 0) },+ Benefit(L("实时纪要"), L("会中每 45 秒更新")),+ Benefit(L("更准的翻译"), L("人名、术语前后一致")),+ Benefit(L("自然人声"), L("同传约 2 秒出声")),+ },+ }, new Thickness(20, 20, 20, 20));+ return Page(L("接上 Ling"), L("识别、翻译和纪要都靠它,约 1 分钟。"), Columns(card, side));+ }++ // MARK: 1 · 用其他服务 (OnboardingKey.swift › otherEntry)++ /// Another service than Ling is chosen (用不了 Ling?): step 1 asks for its key instead.+ bool Other => app.Settings.AiProvider != "ling";+ /// What the page offers; a custom address is set up in 设置 › AI 服务.+ static readonly string[] Others = ["openrouter", "zenmux"];++ void Switch(string provider)+ {+ keyBox.Clear(); keyStatus.Content = null;+ app.SetAIProvider(provider);+ Render();+ }++ FrameworkElement OtherStep()+ {+ var p = app.Ling.Provider;+ var choices = Ui.Segmented(Others.Select(id => (id, AIProvider.Named(id).Name)), Others.Contains(p.Id) ? p.Id : Others[0],+ v => { if (v != app.Settings.AiProvider) Switch(v); });+ UIElement top = choices;+ if (p.Site is { } site)+ {+ var open = Ui.Button(LF("打开 %@", app.Ling.Config.Name), () => Process.Start(new ProcessStartInfo(site) { UseShellExecute = true }), icon: Icons.OpenExternal, height: 36, iconAfter: true);+ open.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("现在可以用了"));+ 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);+ var card = StepCard(new StackPanel { Children = { top, row, keyStatus } });+ return Page(L("用其他服务"), L("听、纪要和翻译都能用,模型已经选好。"), card);+ }++ /// The key field with its reveal button, and 粘贴并检查.+ DockPanel KeyRow(string placeholder)+ {var reveal = Ui.IconButton(Icons.Eye, L("显示 key"), () =>{var show = keyText.Visibility != Visibility.Visible;@@ -232,7 +315,7 @@ sealed class Onboarding : WindowkeyBox.Visibility = show ? Visibility.Collapsed : Visibility.Visible;}, Palette.Secondary, 32, 16);Detach(keyBox); Detach(keyText); Detach(keyStatus);- var hint = Ui.Text("sk-…", 14, Palette.Tertiary, wrap: false);+ var hint = Ui.Text(placeholder, 14, Palette.Tertiary, wrap: false);hint.IsHitTestVisible = false; hint.VerticalAlignment = VerticalAlignment.Center;void Hint() => hint.Visibility = keyBox.Password.Length == 0 ? Visibility.Visible : Visibility.Collapsed;keyBox.PasswordChanged += (_, _) => Hint();@@ -253,32 +336,7 @@ sealed class Onboarding : WindowDockPanel.SetDock(paste, Dock.Right);paste.Margin = new Thickness(8, 0, 0, 0);row.Children.Add(paste); row.Children.Add(field);- if (app.Ling.HasKey && keyBox.Password.Length == 0 && keyStatus.Content is null) Status(true, AIKey.Masked(app.Key.Read() ?? "") + " · " + L("已连接,可以用了"));- keyStatus.Margin = new Thickness(0, 12, 0, 0);- var second = new StackPanel { Children = { row, keyStatus } };- var card = StepCard(new StackPanel- {- Children =- {- Numbered(Disc(1), L("在 Ling 开放平台创建 key"), L("国内直接注册,不用代理;登录后点“创建令牌”"), open),- Divider(),- Numbered(Disc(2), L("复制 sk- 开头的 key,回来粘贴"), null, below: second),- },- });- FrameworkElement Benefit(string title, string detail) => new StackPanel { Margin = new Thickness(0, 14, 0, 0), Children = { Ui.Text(title, 14, Palette.Ink), Gap(Ui.Text(detail, 12, Palette.Secondary), 2) } };- var side = StepCard(new StackPanel- {- Children =- {- Ui.Text(L("Ling 每月赠送 ¥10 额度"), 16, Palette.Ink, FontWeights.Bold),- Gap(Ui.Text(L("约够 10–50 小时会议"), 13, Palette.Secondary), 4),- new Border { Height = 1, Background = Palette.Line, Margin = new Thickness(0, 14, 0, 0) },- Benefit(L("实时纪要"), L("会中每 45 秒更新")),- Benefit(L("更准的翻译"), L("人名、术语前后一致")),- Benefit(L("自然人声"), L("同传约 2 秒出声")),- },- }, new Thickness(20, 20, 20, 20));- return Page(L("接上 Ling"), L("识别、翻译和纪要都靠它,约 1 分钟。"), Columns(card, side));+ return row;}static FrameworkElement Gap(FrameworkElement e, double top) { e.Margin = new Thickness(0, top, 0, 0); return e; }@@ -303,6 +361,8 @@ sealed class Onboarding : Windowapp.Ling.KeyChanged();var (state, _) = 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)@@ -310,7 +370,9 @@ sealed class Onboarding : Windowif (previous is not null) app.Key.Save(previous); else app.Key.Remove();app.Ling.KeyChanged();}- Status(false, state == KeyState.Invalid ? L("这个 key 不能用,检查是否复制完整,或重新创建一个") : L("连不上 Ling,检查网络"));+ 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));}// MARK: 2 · System audiodiff --git a/windows/src/Cicada/SettingsWindow.cs b/windows/src/Cicada/SettingsWindow.csindex 470d208..89765cf 100644--- a/windows/src/Cicada/SettingsWindow.cs+++ b/windows/src/Cicada/SettingsWindow.cs@@ -17,7 +17,12 @@ sealed class SettingsWindow : Windowreadonly Dictionary<string, FrameworkElement> sections = [];readonly PasswordBox keyBox = new();bool editingKey;- string current = "ling";+ string current = "ai";+ // AI 服务: 自己选模型 unfolded, and a model being typed by hand ("hear", "text", "voice").+ bool modelsOpen;+ string? typing;+ // A custom service's address and models as typed, kept across re-renders until 保存并检查.+ readonly Dictionary<string, TextBox> customFields = [];public SettingsWindow(Controller app){@@ -26,7 +31,7 @@ sealed class SettingsWindow : WindowWidth = 1000; Height = Math.Min(780, SystemParameters.WorkArea.Height - 24); MinWidth = 760; MinHeight = 480;Background = Palette.Page; FontFamily = Palette.Font; Icon = AppIcon.Image;WindowStartupLocation = WindowStartupLocation.CenterScreen;- System.Windows.Automation.AutomationProperties.SetName(keyBox, L("Ling key"));+ System.Windows.Automation.AutomationProperties.SetName(keyBox, L("API key"));var grid = new Grid();grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(200) });grid.ColumnDefinitions.Add(new ColumnDefinition());@@ -45,8 +50,7 @@ sealed class SettingsWindow : Windowvar offset = scroll.VerticalOffset;sections.Clear();var page = new StackPanel { MaxWidth = 640, HorizontalAlignment = HorizontalAlignment.Left };- Section(page, "ling", L("Ling"), KeyCard(), Group(Card(Icons.Notes, L("纪要和翻译用的模型"), L("3.1 更准;3.0 更快、更省。语音识别固定用 Ming。"),- Ui.Choice([("Ling-3.1-flash", "Ling-3.1-flash"), ("Ling-3.0-flash", "Ling-3.0-flash")], app.Settings.Model, v => { app.Settings.Model = v; app.Ling.Model = v; Save(); }))));+ Section(page, "ai", L("AI 服务"), AICards().ToArray());Section(page, "lang", L("语言"), Group(Card(Icons.Globe, L("翻译成"), null, Ui.Choice(Ui.TargetOptions(), app.Settings.Target, app.SetTarget)),Card(null, L("纪要语言"), null, Ui.Choice([("system", L("和字幕一样")), .. Languages.Targets.Select(t => (t.Code, t.Name))], app.Settings.NotesLanguage, v => { app.Settings.NotesLanguage = v; Save(); })),@@ -87,8 +91,15 @@ sealed class SettingsWindow : Windowstatic FrameworkElement Credit() { var t = Ui.Helper(L("说话人识别用 WeSpeaker 的声纹模型(CC BY 4.0)")); t.Margin = new Thickness(6, 0, 0, 0); return t; }- /// Opens one category's page (the debug pipe's `show settings about`).- public void Show(string id) { current = id; Render(); }+ /// Opens one category's page (the debug pipe's `show settings about`; `ai models` unfolds+ /// 自己选模型; the old `ling` is AI 服务).+ public void Show(string id)+ {+ var parts = id.Split(' ');+ current = parts[0] == "ling" ? "ai" : parts[0];+ if (current == "ai") modelsOpen = parts.Contains("models");+ Render();+ }/// An update was found or a check finished: only 关于 shows it.public void UpdatesChanged() { if (current == "about") Render(); }@@ -124,7 +135,7 @@ sealed class SettingsWindow : Windownav.Children.Clear();(string id, string icon, string label)[] items =[- ("ling", Icons.Key, L("Ling")), ("lang", Icons.Globe, L("语言")), ("listen", Icons.Wave, L("听的时候")),+ ("ai", Icons.Key, L("AI 服务")), ("lang", Icons.Globe, L("语言")), ("listen", Icons.Wave, L("听的时候")),("speak", Icons.Mic, L("同声传译")), ("end", Icons.Stop, L("结束会议")), ("privacy", Icons.Shield, L("隐私与启动")), ("about", Icons.Info, L("关于")),];foreach (var (id, icon, label) in items)@@ -168,6 +179,9 @@ sealed class SettingsWindow : Windowif (id != current) return;FrameworkElement h = Ui.Text(title, 28, Palette.Ink, FontWeights.Bold);if (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));h.Margin = new Thickness(0, 0, 0, 20);sections[id] = h;page.Children.Add(h);@@ -232,8 +246,10 @@ sealed class SettingsWindow : Window: cableProgress is { } busy ? Ui.Text(busy, 13, Palette.Secondary, wrap: false): Ui.Button(L("安装"), () => _ = InstallCable(), Ui.Kind.Primary, height: 32);var target = app.Speak.Target;- var voices = VoiceCatalog.Options(target, app.WindowsVoice.Has(target)).Select(v => (v.Id, v.Id == VoiceCatalog.SystemId ? L("Windows 自带") : $"{v.Name} · {string.Join(" · ", v.Tags.Split(" · ").Select(L))}")).ToList();- var chosen = s.SpeakVoices.TryGetValue(VoiceCatalog.Key(target), out var c) ? c : VoiceCatalog.DefaultId(target, app.Ling.HasKey);+ var config = app.Ling.Config;+ var voices = VoiceCatalog.Options(target, config, app.WindowsVoice.Has(target))+ .Select(v => (v.Id, v.Id == VoiceCatalog.SystemId ? L("Windows 自带") : v.Tags.Length == 0 ? v.Name : $"{v.Name} · {string.Join(" · ", v.Tags.Split(" · ").Select(L))}")).ToList();+ var chosen = VoiceCatalog.Chosen(s, target, config, app.Ling.Speaks);var voice = Ui.Row(8,Ui.Choice(voices, chosen, v => { s.SpeakVoices[VoiceCatalog.Key(target)] = v; Save(); }, 280),Ui.Button(L("试听"), () => _ = app.Preview(target), height: 32));@@ -266,44 +282,203 @@ sealed class SettingsWindow : Window});}+ /// AI 服务 (the Mac's AISettings): a custom service's address and models, the key, what works+ /// with this service, its models folded away (the recommended ones are already chosen), and+ /// what is sent where. The service menu is in the page's header.+ IEnumerable<FrameworkElement> AICards()+ {+ var c = app.Ling.Config;+ var p = c.Provider;+ var s = app.Settings;+ if (p.Id == "custom")+ yield return Group(+ Card(null, L("地址"), null, CustomField("base", s.AiCustomBase, "https://api.example.com/v1")),+ Card(null, L("文字模型"), L("纪要和整句翻译"), CustomField("text", s.AiModels.GetValueOrDefault("custom", ""), L("例如 qwen3:14b"))),+ Card(null, L("听的模型"), L("要能输入音频:听对方和“我说”都用它"), CustomField("hear", s.AiHearModels.GetValueOrDefault("custom", ""), L("例如 qwen3-omni"))));+ yield return KeyCard();+ var host = (c.Base ?? "").Split("//")[^1].Split('/')[0];+ if (host.Length == 0) host = L("你填的地址");+ var lockLine = Ui.Helper(p.Id == "ling" ? L("仅保存在本机当前账户下,仅发送至 Ling(ant-ling.com)")+ : p.Id == "custom" ? LF("仅保存在本机当前账户下,仅发送至 %@", host) : LF("仅保存在本机当前账户下,仅发送至 %@(%@)", c.Name, host));+ lockLine.Margin = new Thickness(6, -4, 0, 0);+ yield return lockLine;+ yield return Label(L("现在能用的"));+ yield return Group(UsesRows().ToArray());+ var fold = Ui.LinkText(L("自己选模型") + (modelsOpen ? " ⌄" : " ›"), () => { modelsOpen = !modelsOpen; Render(); });+ fold.Foreground = Palette.Secondary;+ fold.Margin = new Thickness(6, 4, 0, 0);+ yield return fold;+ if (modelsOpen) yield return Group(ModelRows().ToArray());+ var sent = p.Id == "custom" ? host : c.Name;+ var foot = Ui.Helper(p.Id == "ling" ? LF("听的时候,电脑里的声音会发给 %@。", sent) : L("按所选模型计费。") + LF("听的时候,电脑里的声音会发给 %@。", sent));+ foot.Margin = new Thickness(6, 0, 0, 0);+ yield return foot;+ }++ /// 现在能用的 (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.+ IEnumerable<FrameworkElement> UsesRows()+ {+ var ling = app.Ling;+ var c = ling.Config;+ var on = ling.Usable;+ 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),+ "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("这个模型听不了声音,换一个支持音频输入的"))+ : 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 时照常可用"));+ // 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!)+ : on ? Row(L("同传声音"), L("本机"), "local", L("没填声音模型,用 Windows 的声音"))+ : Row(L("同传声音"), L("本机"), "local", L("填好 key 前用 Windows 的声音"));+ }++ /// 自己选模型: what hears, what writes, what speaks for this service.+ IEnumerable<FrameworkElement> ModelRows()+ {+ var c = app.Ling.Config;+ var p = c.Provider;+ if (p.Id == "ling")+ {+ yield return Card(null, L("文字模型"), L("3.1 更准;3.0 更快、更省"), Ui.Choice(p.TextModels.Select(m => (m.Id, m.Id)), c.TextModel, v => app.SetAIModel("text", v), 280));+ yield return Card(null, L("听的模型"), L("Ming 一次识别并翻译"), Ui.Text(c.HearModel, 13, Palette.Tertiary, wrap: false));+ yield break;+ }+ if (p.Id == "custom")+ {+ var s = app.Settings;+ yield return Card(null, L("声音模型"), L("需支持 /audio/speech;不填则同传用 Windows 的声音"), CustomField("voice", s.AiVoiceModels.GetValueOrDefault("custom", ""), L("例如 kokoro")));+ yield return Card(null, L("声音"), null, CustomField("voiceName", s.AiCustomVoice, L("例如 af_heart")));+ yield return Card(null, L("地址"), null, CustomField("voiceBase", s.AiCustomVoiceBase, L("跟上面一样")));+ yield return Card(null, "", null, Ui.Button(L("保存并检查"), () => _ = SaveKey(), Ui.Kind.Primary, height: 32));+ yield break;+ }+ yield return Card(null, L("听的模型"), L("听对方和“我说”都用它"), ModelMenu("hear", c.HearModel, p.HearModels, app.Ling.HearCatalog));+ yield return Card(null, L("文字模型"), L("纪要和整句翻译"), ModelMenu("text", c.TextModel, p.TextModels, app.Ling.TextCatalog));+ if (p.HasVoices) yield return Card(null, L("声音模型"), L("同传念给对方"), ModelMenu("voice", c.VoiceModel ?? "", p.VoiceModels, []));+ }++ /// Recommended models first, with why, then everything the service lists that fits; or a+ /// name typed by hand.+ FrameworkElement ModelMenu(string kind, string current, AIModel[] recommended, IReadOnlyList<string> listed)+ {+ if (typing == kind)+ {+ var box = new TextBox { Text = current };+ var field = Ui.Field(box); field.Width = 240; field.Height = 34;+ void Done() { typing = null; app.SetAIModel(kind, box.Text.Trim()); Render(); }+ box.KeyDown += (_, e) => { if (e.Key == System.Windows.Input.Key.Enter) Done(); };+ Dispatcher.BeginInvoke(() => box.Focus());+ return Ui.Row(8, field, Ui.Button(L("保存"), Done, Ui.Kind.Primary, height: 34), Ui.Button(L("取消"), () => { typing = null; Render(); }, height: 34));+ }+ var options = recommended.Select(m => (m.Id, m.Note.Length > 0 ? $"{m.Id} · {L(m.Note)}" : m.Id)).ToList();+ foreach (var id in listed.Append(current))+ if (id.Length > 0 && !options.Any(o => o.Item1 == id)) options.Add((id, id));+ options.Add(("", L("手动填写…")));+ var menu = Ui.Choice(options, current, v => { if (v.Length == 0) { typing = kind; Render(); } else if (v != current) app.SetAIModel(kind, v); }, 280);+ // The button shows the id alone; the menu says why.+ if (menu.Content is DockPanel d && d.Children.OfType<TextBlock>().FirstOrDefault() is { } label) { label.Text = current; label.TextTrimming = TextTrimming.CharacterEllipsis; }+ return menu;+ }++ /// One of a custom service's fields, with a grey hint while empty.+ FrameworkElement CustomField(string name, string value, string hint)+ {+ if (!customFields.TryGetValue(name, out var box)) customFields[name] = box = new TextBox { Text = value };+ if (box.Parent is Grid old) old.Children.Remove(box);+ var hintText = Ui.Text(hint, 14, Palette.Tertiary, wrap: false);+ hintText.IsHitTestVisible = false; hintText.VerticalAlignment = VerticalAlignment.Center;+ void Hint() => hintText.Visibility = box.Text.Length == 0 ? Visibility.Visible : Visibility.Collapsed;+ box.TextChanged += (_, _) => Hint();+ Hint();+ Ui.StyleField(box);+ var frame = Ui.FieldFrame(new Grid { Children = { box, hintText } }, box);+ frame.Width = 260; frame.Height = 34;+ return frame;+ }+FrameworkElement KeyCard(){- var state = app.Ling.KeyState;- var key = app.Key.Read();- string desc = state switch+ var ling = app.Ling;+ var c = ling.Config;+ var p = c.Provider;+ var state = ling.KeyState;+ 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{- KeyState.None => L("还没填 key"),+ KeyState.None or KeyState.Unchecked => null,KeyState.Checking => L("正在检查…"),- KeyState.Invalid => L("这个 key 不能用,检查是否复制完整,或重新创建一个"),- KeyState.Unreachable => L("连不上 Ling,检查网络"),- _ => $"{AIKey.Masked(key ?? "")} · {L("可以用 · 只加密存在这台电脑上")}",+ KeyState.Invalid => LF("%@ 提示 key 无效,请检查是否复制完整,或重新创建一个", c.Name),+ KeyState.Unreachable => problem ?? LF("连不上 %@,请检查网络或代理", c.Name),+ _ => problem ?? L("已连接") + " · " + LF("%@ · 响应约 %@ 秒", c.TextModel, (ling.Seconds ?? 0).ToString("0.0")),};FrameworkElement control;- if (editingKey)+ if (editingKey || key is null || state == KeyState.Invalid){- if (keyBox.Parent is Panel p) p.Children.Remove(keyBox);- if (keyBox.Parent is Border old) old.Child = null;- var field = Ui.Field(keyBox); field.Width = 300; field.Height = 34;- control = Ui.Row(8, field, Ui.Button(L("保存"), () => _ = SaveKey(), Ui.Kind.Primary, height: 34), Ui.Button(L("取消"), () => { editingKey = false; Render(); }, height: 34));+ 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));+ control = Ui.Row(8, [.. buttons]);}else{- var change = Ui.Button(key is null ? L("填写") : L("更换"), () => { editingKey = true; keyBox.Clear(); Render(); keyBox.Focus(); }, height: 32);- control = key is null ? change : Ui.Row(8, change, Ui.Button(L("删除"), () => { app.Key.Remove(); app.Ling.KeyChanged(); }, height: 32));+ 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 card = Card(Icons.Key, L("Ling key"), desc, control);+ 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;+ // 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);}async Task SaveKey(){+ var s = app.Settings;+ if (s.AiProvider == "custom")+ {+ // The address and models typed so far, kept even before a key.+ string F(string name, string fallback) => customFields.TryGetValue(name, out var b) ? b.Text.Trim() : fallback;+ s.AiCustomBase = F("base", s.AiCustomBase);+ s.AiModels["custom"] = F("text", s.AiModels.GetValueOrDefault("custom", ""));+ s.AiHearModels["custom"] = F("hear", s.AiHearModels.GetValueOrDefault("custom", ""));+ s.AiVoiceModels["custom"] = F("voice", s.AiVoiceModels.GetValueOrDefault("custom", ""));+ s.AiCustomVoice = F("voiceName", s.AiCustomVoice);+ s.AiCustomVoiceBase = F("voiceBase", s.AiCustomVoiceBase);+ s.Save();+ }var text = keyBox.Password.Trim();- if (!text.StartsWith("sk-")) return;- if (!app.Key.Save(text)) 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-")))+ {+ if (!app.Key.Save(text)) return;+ keyBox.Clear();+ }+ else if (text.Length > 0) return;editingKey = false;- app.Ling.KeyChanged();+ app.AIChanged();Render();- await app.Ling.Check();+ await Task.CompletedTask;}static FrameworkElement Keys(string combo)diff --git a/windows/src/Cicada/Strings/en.lproj/Windows.strings b/windows/src/Cicada/Strings/en.lproj/Windows.stringsindex d609c71..c4d573c 100644--- a/windows/src/Cicada/Strings/en.lproj/Windows.strings+++ b/windows/src/Cicada/Strings/en.lproj/Windows.strings@@ -246,3 +246,38 @@"对方听到译文" = "They hear the translation";"会议里对方说的话从电脑扬声器放出来,字幕和纪要都从这里来。Windows 上不用授权。" = "What others say in a meeting comes out of your PC's speakers. Subtitles and notes come from there. No permission needed on Windows.";"点按下载" = "Click to download.";++/* AI 服务: other services than Ling */+"需要 %@ 的 key 才能说" = "Needs a %@ key to speak";+"接上 %@" = "Connect %@";+"API key" = "API key";+"接 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";+"仅保存在本机当前账户下,仅发送至 Ling(ant-ling.com)" = "Saved locally under your account and sent only to Ling (ant-ling.com)";+"仅保存在本机当前账户下,仅发送至 %@(%@)" = "Stored only for this account on this computer, sent only to %1$@ (%2$@)";+"听的时候,电脑里的声音会发给 %@。" = "While listening, your computer's audio is sent to %@.";+"按所选模型计费。" = "Billed by the models you choose. ";+"还不能用" = "Not yet";+"Ming 一次识别并翻译" = "Ming recognizes and translates in one step";+"比 Ling 晚 1–2 秒出字" = "Text appears 1–2 s later than with Ling";+"没填声音模型,用 Windows 的声音" = "No voice model set; using the Windows voice";+"填好 key 前用 Windows 的声音" = "Uses the Windows voice until a key is added";+"需支持 /audio/speech;不填则同传用 Windows 的声音" = "Must support /audio/speech; without one, interpreting uses the Windows voice";+"听对方和“我说”都用它" = "Used for Listen and for Speak";+"手动填写…" = "Enter manually…";+"本机服务,不用 key" = "Local service, no key needed";+"还没接上 %@" = "%@ not connected yet";+"在 设置 › AI 服务 里换一个" = "Change it in Settings › AI Service";+"%@ 太忙,稍后再试" = "%@ is busy. Try again shortly";+"%@ 的 key 无效" = "%@ key is invalid";+"需要 %@ 的 key 才能听" = "Needs a %@ key to listen";+"连不上 %@" = "Can't connect to %@";+"连不上 %@,没有发出去" = "Can't connect to %@. Nothing was sent";+"没人说话时不乱写" = "Writes nothing when no one speaks";+"更快" = "Faster";+"最快,偶尔把杂音写成字" = "Fastest; sometimes turns noise into words";diff --git a/windows/src/Cicada/Strings/ja.lproj/Windows.strings b/windows/src/Cicada/Strings/ja.lproj/Windows.stringsindex cb28fef..d6fb969 100644--- a/windows/src/Cicada/Strings/ja.lproj/Windows.strings+++ b/windows/src/Cicada/Strings/ja.lproj/Windows.strings@@ -246,3 +246,38 @@"对方听到译文" = "相手に翻訳が届く";"会议里对方说的话从电脑扬声器放出来,字幕和纪要都从这里来。Windows 上不用授权。" = "会議で相手が話す声は PC のスピーカーから流れます。字幕とメモはそこから作られます。Windows では許可は不要です。";"点按下载" = "クリックでダウンロード";++/* AI 服务: other services than Ling */+"需要 %@ 的 key 才能说" = "話すには %@ のキーが必要です";+"接上 %@" = "%@ に接続";+"API key" = "API キー";+"接 AI 服务" = "AI サービス";+"仅保存在本机当前账户下,仅发送至 %@" = "このコンピュータのこのアカウントにのみ保存され、%@ にのみ送信されます";+"听、纪要和翻译都能用,模型已经选好。" = "聞き取り・議事メモ・翻訳がすべて使えます。モデルは選択済みです。";+"这个模型听不了声音,换一个支持音频输入的" = "このモデルは音声を聞き取れません。音声入力に対応したモデルに変えてください";+"听的模型" = "聞き取りモデル";+"要能输入音频:听对方和“我说”都用它" = "音声入力に対応している必要があります。相手の聞き取りと「話す」の両方で使います";+"例如 qwen3-omni" = "例:qwen3-omni";+"仅保存在本机当前账户下,仅发送至 Ling(ant-ling.com)" = "このPCの現在のアカウントにのみ保存され、Ling(ant-ling.com)にのみ送信されます";+"仅保存在本机当前账户下,仅发送至 %@(%@)" = "このコンピュータのこのアカウントにのみ保存され、%1$@(%2$@)にのみ送信されます";+"听的时候,电脑里的声音会发给 %@。" = "聞き取り中は、コンピュータの音声が %@ に送信されます。";+"按所选模型计费。" = "選んだモデルに応じて課金されます。";+"还不能用" = "まだ使えません";+"Ming 一次识别并翻译" = "Ming が一度で認識と翻訳を行います";+"比 Ling 晚 1–2 秒出字" = "Ling より文字が 1〜2 秒遅れて出ます";+"没填声音模型,用 Windows 的声音" = "音声モデル未設定のため、Windows の音声を使います";+"填好 key 前用 Windows 的声音" = "キーを入力するまで Windows の音声を使います";+"需支持 /audio/speech;不填则同传用 Windows 的声音" = "/audio/speech 対応が必要。未入力なら通訳は Windows の音声を使います";+"听对方和“我说”都用它" = "相手の聞き取りと「話す」の両方で使います";+"手动填写…" = "手動で入力…";+"本机服务,不用 key" = "ローカルサービスのため key は不要です";+"还没接上 %@" = "%@ にまだ接続していません";+"在 设置 › AI 服务 里换一个" = "設定 › AI サービスで変更してください";+"%@ 太忙,稍后再试" = "%@ が混み合っています。しばらくしてからもう一度お試しください";+"%@ 的 key 无效" = "%@ の key が無効です";+"需要 %@ 的 key 才能听" = "聞き取りには %@ の key が必要です";+"连不上 %@" = "%@ に接続できません";+"连不上 %@,没有发出去" = "%@ に接続できません。送信していません";+"没人说话时不乱写" = "誰も話していないときは何も書かない";+"更快" = "より速い";+"最快,偶尔把杂音写成字" = "最速。雑音を文字にすることがある";diff --git a/windows/src/Cicada/Strings/ko.lproj/Windows.strings b/windows/src/Cicada/Strings/ko.lproj/Windows.stringsindex 9dd5b7a..5c714e8 100644--- a/windows/src/Cicada/Strings/ko.lproj/Windows.strings+++ b/windows/src/Cicada/Strings/ko.lproj/Windows.strings@@ -246,3 +246,38 @@"对方听到译文" = "상대가 번역을 들어요";"会议里对方说的话从电脑扬声器放出来,字幕和纪要都从这里来。Windows 上不用授权。" = "회의에서 상대가 하는 말은 PC 스피커로 나와요. 자막과 회의록은 여기서 만들어져요. Windows에서는 권한이 필요 없어요.";"点按下载" = "클릭하면 다운로드합니다";++/* AI 服务: other services than Ling */+"需要 %@ 的 key 才能说" = "말하려면 %@ 키가 필요합니다";+"接上 %@" = "%@ 연결";+"API key" = "API 키";+"接 AI 服务" = "AI 서비스";+"仅保存在本机当前账户下,仅发送至 %@" = "이 컴퓨터의 현재 계정에만 저장되고 %@에만 전송됩니다";+"听、纪要和翻译都能用,模型已经选好。" = "듣기, 회의록, 번역 모두 사용할 수 있고 모델은 이미 골라 두었습니다.";+"这个模型听不了声音,换一个支持音频输入的" = "이 모델은 오디오를 들을 수 없습니다. 오디오 입력을 지원하는 모델로 바꾸세요";+"听的模型" = "듣기 모델";+"要能输入音频:听对方和“我说”都用它" = "오디오 입력을 지원해야 합니다. 상대방 듣기와 ‘말하기’에 모두 쓰입니다";+"例如 qwen3-omni" = "예: qwen3-omni";+"仅保存在本机当前账户下,仅发送至 Ling(ant-ling.com)" = "이 기기의 현재 계정에만 저장되며 Ling(ant-ling.com)으로만 전송됩니다";+"仅保存在本机当前账户下,仅发送至 %@(%@)" = "이 컴퓨터의 현재 계정에만 저장되고 %1$@(%2$@)에만 전송됩니다";+"听的时候,电脑里的声音会发给 %@。" = "듣는 동안 컴퓨터의 소리가 %@(으)로 전송됩니다.";+"按所选模型计费。" = "선택한 모델에 따라 요금이 부과됩니다. ";+"还不能用" = "아직 안 됨";+"Ming 一次识别并翻译" = "Ming이 한 번에 인식하고 번역합니다";+"比 Ling 晚 1–2 秒出字" = "Ling보다 글자가 1~2초 늦게 나옵니다";+"没填声音模型,用 Windows 的声音" = "음성 모델이 없어 Windows 음성을 사용합니다";+"填好 key 前用 Windows 的声音" = "키를 입력하기 전까지 Windows 음성을 사용합니다";+"需支持 /audio/speech;不填则同传用 Windows 的声音" = "/audio/speech 지원 필요. 비워 두면 통역에 Windows 음성을 사용합니다";+"听对方和“我说”都用它" = "상대방 듣기와 ‘말하기’에 모두 쓰입니다";+"手动填写…" = "직접 입력…";+"本机服务,不用 key" = "로컬 서비스라 key가 필요 없습니다";+"还没接上 %@" = "아직 %@에 연결되지 않음";+"在 设置 › AI 服务 里换一个" = "설정 › AI 서비스에서 바꾸세요";+"%@ 太忙,稍后再试" = "%@이(가) 바쁩니다. 잠시 후 다시 시도하세요";+"%@ 的 key 无效" = "%@ key가 유효하지 않습니다";+"需要 %@ 的 key 才能听" = "들으려면 %@ key가 필요합니다";+"连不上 %@" = "%@에 연결할 수 없음";+"连不上 %@,没有发出去" = "%@에 연결할 수 없어 보내지 않았습니다";+"没人说话时不乱写" = "아무도 말하지 않을 때 아무것도 쓰지 않음";+"更快" = "더 빠름";+"最快,偶尔把杂音写成字" = "가장 빠름, 가끔 잡음을 글자로 씀";diff --git a/windows/src/Cicada/TrayFlyout.cs b/windows/src/Cicada/TrayFlyout.csindex 59785b0..3f22943 100644--- a/windows/src/Cicada/TrayFlyout.cs+++ b/windows/src/Cicada/TrayFlyout.cs@@ -71,7 +71,7 @@ sealed class TrayFlyout : Window? Ui.Row(6, Ui.Dot(Palette.Tertiary, 6), Ui.Text(L("会议已自动结束"), 13, Palette.Secondary, wrap: false)): app.Ling.HasKey? Ui.Row(6, Ui.Dot(Palette.Toggle, 6), Ui.Text(L("没在听"), 13, Palette.Secondary, wrap: false))- : Ui.Row(6, Ui.Dot(Palette.Tertiary, 6), Ui.Text(L("还没接上 Ling"), 13, Palette.Secondary, wrap: false));+ : Ui.Row(6, Ui.Dot(Palette.Tertiary, 6), Ui.Text(app.Ling.Config.IsLing ? L("还没接上 Ling") : LF("还没接上 %@", app.Ling.Config.Name), 13, Palette.Secondary, wrap: false));var title = Ui.Row(12, AppIcon.Small(40), Ui.Stack(1, Ui.Text(L("知了"), 17, Palette.Ink, Palette.Strong, wrap: false), status));var head = Ui.Spread(title, Ui.IconButton(Icons.Gear, L("打开设置"), () => Do(app.ShowSettings), Palette.Body, 36, 18));stack.Children.Add(head);diff --git a/windows/tests/Cicada.Tests/Program.cs b/windows/tests/Cicada.Tests/Program.csindex 2485460..fb4ee92 100644--- a/windows/tests/Cicada.Tests/Program.cs+++ b/windows/tests/Cicada.Tests/Program.cs@@ -1002,4 +1002,305 @@ static class Tests}finally { File.Delete(file); }}++ // MARK: AI 服务 (other services than Ling: linux/tests/test_providers.py, case for case)++ /// Answers every request with `respond(url, body)` and records where each went.+ sealed class Service(Func<string, string, HttpResponseMessage> respond) : HttpMessageHandler+ {+ public readonly List<(string url, string body)> Sent = [];+ 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));+ return respond(url, body);+ }+ }++ static (LingClient ling, AppSettings settings) Using(Service fake, string provider = "zenmux", string? key = "sk-test-0000000000", AppSettings? s = null)+ {+ s ??= new AppSettings();+ s.AiProvider = provider;+ var k = new AIKey(new PlainProtector(), service: () => s.AiProvider);+ k.Remove();+ if (key is not null) k.Save(key);+ return (new LingClient(k, fake, s.AIConfig), s);+ }++ static HttpResponseMessage Status(int code, string body = "{}") => new((HttpStatusCode)code) { Content = new StringContent(body) };++ public static void ServicesDefaultToTheirRecommendedModels()+ {+ var c = new AppSettings { AiProvider = "zenmux" }.AIConfig();+ Equal("https://zenmux.ai/api/v1/", c.Base, "base");+ Equal("qwen/qwen3.8-omni-flash", c.HearModel, "hear");+ Equal("inclusionai/ling-3.0-flash", c.TextModel, "text");+ Equal("google/gemini-3.8-flash-tts", c.VoiceModel, "voice");+ var ling = new AppSettings().AIConfig();+ Equal(("Ming-3.0-audio-flash", "Ling-3.1-flash"), (ling.HearModel, ling.TextModel), "Ling");+ Equal("Ling-3.0-flash", new AppSettings { Model = "Ling-3.0-flash" }.AIConfig().TextModel, "Ling keeps its own key");+ Equal("ling", AIProvider.Named("openai").Id, "OpenAI isn't offered: Ling");+ Equal(0.6, AIProvider.Ling.Spacing, "Ling's gate");+ Equal(0.1, AIProvider.ZenMux.Spacing, "the aggregators'");+ }++ public static void ChosenModelsAndACustomService()+ {+ var s = new AppSettings { AiProvider = "openrouter", AiHearModels = { ["openrouter"] = "google/gemini-3.1-flash-lite" } };+ Equal("google/gemini-3.1-flash-lite", s.AIConfig().HearModel, "chosen hear model");+ s = new AppSettings { AiProvider = "custom", AiCustomBase = "localhost:11434/v1", AiModels = { ["custom"] = "qwen3:14b" } };+ var c = s.AIConfig();+ Equal("http://localhost:11434/v1/", c.Base, "local address");+ Equal("", c.HearModel, "no hear model yet");+ Check(!c.HasVoices, "no voices without a speech model");+ s.AiVoiceModels["custom"] = "kokoro"; s.AiCustomVoice = "af_heart";+ Equal(("kokoro", "http://localhost:11434/v1/"), (s.AIConfig().VoiceModel, s.AIConfig().VoiceBase), "speech model on the same address");+ Equal("af_heart", s.AIConfig().Voices.Single().Id, "the one voice named");+ }++ public static void CustomAddress()+ {+ Equal("https://api.example.com/v1/", AIProvider.CustomBase("api.example.com/v1"), "https by default");+ Equal("http://127.0.0.1:1234/v1/", AIProvider.CustomBase("127.0.0.1:1234/v1"), "http on this computer");+ Equal(null, AIProvider.CustomBase("http://api.example.com/v1"), "http only on this computer");+ Equal(null, AIProvider.CustomBase(" "), "nothing");+ }++ public static void SettingsKeepTheServiceAcrossARestart()+ {+ new AppSettings { AiProvider = "zenmux", AiHearModels = { ["zenmux"] = "bytedance/doubao-seed-2.0-mini" } }.Save();+ var back = AppSettings.Load();+ Equal("zenmux", back.AiProvider, "service");+ Equal("bytedance/doubao-seed-2.0-mini", back.AIConfig().HearModel, "hear model");+ var json = File.ReadAllText(Paths.Settings);+ Check(json.Contains("\"aiProvider\"") && json.Contains("\"aiHearModels\""), "the Mac's key names");+ File.Delete(Paths.Settings);+ }++ public static void EachServiceTurnsThinkingOffItsOwnWay()+ {+ foreach (var (id, key, value) in new[] { ("ling", "thinking", "{\"type\":\"disabled\"}"), ("zenmux", "reasoning", "{\"enabled\":false}"), ("openrouter", "reasoning", "{\"enabled\":false}") })+ {+ var body = new JsonObject();+ new AppSettings { AiProvider = id }.AIConfig().Shape(body, 100);+ Equal(value, body[key]!.ToJsonString(), id);+ Equal(100, body["max_tokens"]!.GetValue<int>(), "max_tokens");+ }+ var custom = new JsonObject();+ new AppSettings { AiProvider = "custom", AiCustomBase = "https://x.example/v1" }.AIConfig().Shape(custom, 5);+ Check(custom["reasoning"] is null && custom["thinking"] is null && custom["temperature"]!.GetValue<double>() == 0.2, "custom: neither");+ }++ public static void AudioGoesInTheFormEachModelTakes()+ {+ byte[] wav = [1, 2, 3];+ Equal("{\"type\":\"audio_url\",\"audio_url\":{\"url\":\"data:audio/wav;base64,AQID\"}}", new AppSettings().AIConfig().AudioPart(wav, "Ming-3.0-audio-flash").ToJsonString(), "Ming");+ var zen = new AppSettings { AiProvider = "zenmux" }.AIConfig();+ Equal("{\"type\":\"input_audio\",\"input_audio\":{\"data\":\"AQID\",\"format\":\"wav\"}}", zen.AudioPart(wav, "google/gemini-3.1-flash-lite").ToJsonString(), "input_audio");+ Equal("data:audio/wav;base64,AQID", zen.AudioPart(wav, "qwen/qwen3.8-omni-flash")["input_audio"]!["data"]!.GetValue<string>(), "Qwen wants a data URL");+ }++ public static void CatalogListsChatModelsAndThoseThatHear()+ {+ const string data = """+ {"data": [+ {"id": "qwen/qwen3.8-omni-flash", "input_modalities": ["text", "image", "audio", "video"], "output_modalities": ["text"]},+ {"id": "x/asr-only", "input_modalities": ["audio"], "output_modalities": ["text"]},+ {"id": "x/text-model", "architecture": {"input_modalities": ["text"], "output_modalities": ["text"]}},+ {"id": "x/tts", "input_modalities": ["text"], "output_modalities": ["audio"]},+ {"id": "x/embed-1"},+ {"id": "google/gemini-3.1-flash-lite:batch", "input_modalities": ["audio", "text"], "output_modalities": ["text"]}+ ]}+ """;+ Equal("rec/one,qwen/qwen3.8-omni-flash", string.Join(",", AIProvider.Catalog(data, ["rec/one"], hears: true)), "hear");+ Equal("qwen/qwen3.8-omni-flash,x/text-model", string.Join(",", AIProvider.Catalog(data, [], hears: false)), "text");+ Equal(0, AIProvider.Catalog("not json", [], hears: false).Count, "no /models");+ }++ public static void OneKeyFilePerService()+ {+ var s = new AppSettings();+ var k = new AIKey(new PlainProtector(), service: () => s.AiProvider);+ k.Save("sk-ling-000000000");+ s.AiProvider = "zenmux";+ Equal(null, k.Read(), "ZenMux has none yet");+ k.Save("sk-zen-0000000000");+ Check(k.File_.EndsWith("ai-key-zenmux"), "named as on the Mac");+ if (!OperatingSystem.IsWindows()) Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(k.File_), "0600");+ s.AiProvider = "ling";+ Equal("sk-ling-000000000", k.Read(), "switching back keeps Ling's");+ s.Save();+ Check(!File.ReadAllText(Paths.Settings).Contains("sk-"), "never in settings");+ k.Remove(); s.AiProvider = "zenmux"; k.Remove(); File.Delete(Paths.Settings);+ }++ public static void ALocalCustomServiceNeedsNoKey()+ {+ var (ling, s) = Using(new Service((_, _) => Reply("ok")), "custom", key: null,+ new AppSettings { AiCustomBase = "localhost:11434/v1", AiModels = { ["custom"] = "qwen3:14b" } });+ Equal("", ling.CurrentKey(), "no key needed");+ Check(ling.HasKey, "has one, in effect");+ s.AiCustomBase = "https://api.example.com/v1";+ Check(!ling.HasKey, "a remote one needs a key");+ }++ public static async Task RequestsGoToTheServiceInItsShape()+ {+ var old = LingClient.Spacing; LingClient.Spacing = 0;+ try+ {+ var fake = new Service((_, _) => Reply("LANG: en\nORIGINAL: Hi.\nTRANSLATION: 嗨。", finish: null));+ var (ling, _) = Using(fake);+ // No finish reason: Ling's search essays come without one, other services may just omit it.+ var r = await ling.Chat("c", "i", Priority.Translate, model: "qwen/qwen3.8-omni-flash", audio: [1]);+ Check(r.Contains("ORIGINAL: Hi."), "kept without a finish reason");+ Equal("https://zenmux.ai/api/v1/chat/completions", fake.Sent[0].url, "the service's address");+ var b = JsonNode.Parse(fake.Sent[0].body)!;+ Equal(false, b["reasoning"]!["enabled"]!.GetValue<bool>(), "reasoning off");+ Check(b["thinking"] is null, "no Ling-only fields");+ Equal("input_audio", b["messages"]![1]!["content"]![0]!["type"]!.GetValue<string>(), "input_audio");+ await ling.Chat("c", "i", Priority.Translate);+ Equal("inclusionai/ling-3.0-flash", JsonNode.Parse(fake.Sent[1].body)!["model"]!.GetValue<string>(), "text calls use the text model");+ }+ finally { LingClient.Spacing = old; }+ }++ public static async Task CheckFindsAHearModelThatRefusesAudio()+ {+ var old = LingClient.Spacing; LingClient.Spacing = 0;+ try+ {+ var (ling, s) = Using(new Service((url, body) =>+ url.EndsWith("models") ? Status(200, "{\"data\":[{\"id\":\"a/b\",\"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");+ Check(!ling.CanHear && ling.Usable, "notes and translation still work");+ Check(ling.TextCatalog.Contains("a/b"), "catalog fetched after a good check");+ s.AiHearModels.Clear();+ ling.KeyChanged();+ Equal(null, ling.Hears, "a new model is asked again");+ }+ finally { LingClient.Spacing = old; }+ }++ public static async Task CheckSaysWhy()+ {+ var old = LingClient.Spacing; LingClient.Spacing = 0;+ try+ {+ var (ling, _) = Using(new Service((_, _) => Status(401)));+ Equal(KeyState.Invalid, (await ling.Check()).state, "401");+ (ling, _) = Using(new Service((_, _) => 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");+ (ling, _) = Using(new Service((_, _) => Reply("ok")), "openrouter", key: null);+ Equal(KeyState.None, ling.KeyState, "no key");+ }+ finally { LingClient.Spacing = old; }+ }++ static async Task<string> Joined(IAsyncEnumerable<byte[]> chunks)+ {+ var all = new List<byte>();+ await foreach (var c in chunks) all.AddRange(c);+ return string.Join(",", all);+ }++ public static async Task SpeechFromEachService()+ {+ var old = LingClient.Spacing; LingClient.Spacing = 0;+ try+ {+ // ZenMux: server-sent base64, with `stream`.+ var sse = new Service((_, _) => new HttpResponseMessage(HttpStatusCode.OK)+ {+ Content = new StringContent("data: {\"audio\":\"AQACAA==\"}\n\ndata: {\"type\":\"speech.audio.done\"}\n\n", System.Text.Encoding.UTF8, "text/event-stream"),+ });+ var (ling, _) = Using(sse);+ Equal("1,0,2,0", await Joined(ling.Speech("Hello", "Puck", "ja")), "SSE chunks");+ var b = JsonNode.Parse(sse.Sent[0].body)!;+ Equal("https://zenmux.ai/api/v1/audio/speech", sse.Sent[0].url, "speech address");+ Equal(("google/gemini-3.8-flash-tts", "Puck", true), (b["model"]!.GetValue<string>(), b["voice"]!.GetValue<string>(), b["stream"]!.GetValue<bool>()), "body");+ Check(b["language_id"] is null, "language_id is Ming's only");+ // A voice that isn't this service's (a Ming name left in settings) becomes its first one.+ await Joined(ling.Speech("Hello", "US_Emma"));+ Equal("Kore", JsonNode.Parse(sse.Sent[1].body)!["voice"]!.GetValue<string>(), "first voice");+ // OpenRouter streams the PCM bytes themselves, without `stream`.+ var raw = new Service((_, _) => new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent([5, 0, 6, 0]) { Headers = { ContentType = new("audio/pcm") } } });+ (ling, _) = Using(raw, "openrouter");+ Equal("5,0,6,0", await Joined(ling.Speech("Hi", null)), "raw PCM");+ Check(JsonNode.Parse(raw.Sent[0].body)!["stream"] is null, "no stream for OpenRouter");+ // One JSON with a WAV in it.+ var wav = Wav.Bytes([7, 8], 24000);+ var one = new Service((_, _) => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent($"{{\"audio\":\"{Convert.ToBase64String(wav)}\"}}", System.Text.Encoding.UTF8, "application/json") });+ (ling, _) = Using(one, "custom", s: new AppSettings { AiCustomBase = "https://x.example/v1", AiModels = { ["custom"] = "m" }, AiVoiceModels = { ["custom"] = "kokoro" }, AiCustomVoice = "af_heart" });+ Equal("7,0,8,0", await Joined(ling.Speech("Hi", "af_heart")), "JSON WAV");+ Equal("7,0,8,0", string.Join(",", LingClient.PcmFromWav(wav)), "the data chunk");+ }+ finally { LingClient.Spacing = old; }+ }++ public static async Task NoVoiceModelMeansWindowsSpeaks()+ {+ var old = LingClient.Spacing; LingClient.Spacing = 0;+ try+ {+ var settings = new AppSettings { AiCustomBase = "https://x.example/v1", AiModels = { ["custom"] = "m" }, SpeakVoices = { ["en"] = "ming:US_Emma" } };+ var fake = new Service((_, _) => Reply("ok"));+ var (ling, _) = Using(fake, "custom", s: settings);+ Check(!ling.Speaks, "no speech model, no service voice");+ var voice = new NoVoice();+ var engine = new SpeakEngine(ling, new Translator(ling), new SessionStore(), settings, () => "en", () => null, voice);+ Check(await engine.Voice("Hello", "en", new Sink()), "something was said");+ Equal("system", engine.LastVoice, "by Windows");+ Check(fake.Sent.Count == 0, "the old Ming voice went nowhere");+ Equal(VoiceCatalog.SystemId, VoiceCatalog.Options("en", ling.Config).Single().Id, "Windows is the only choice");+ }+ finally { LingClient.Spacing = old; }+ }++ public static void VoicesFollowTheService()+ {+ var zen = new AppSettings { AiProvider = "zenmux" }.AIConfig();+ Equal("cloud:Kore,cloud:Aoede,cloud:Charon,cloud:Puck,system", string.Join(",", VoiceCatalog.Options("ja", zen).Select(v => v.Id)), "Gemini's voices in every language, then Windows'");+ Equal("cloud:Kore", VoiceCatalog.DefaultId("en", zen, speaks: true), "the service's first");+ Equal("system", VoiceCatalog.DefaultId("en", zen, speaks: false), "Windows' until it can speak");+ var settings = new AppSettings { SpeakVoices = { ["en"] = "ming:US_Emma" } };+ Equal("cloud:Kore", VoiceCatalog.Chosen(settings, "en", zen, true), "a Ming voice isn't sent to ZenMux");+ Equal("ming:US_Emma", VoiceCatalog.Chosen(settings, "en", new AppSettings().AIConfig(), true), "and is used again on Ling");+ }++ public static async Task HearingGoesToTheChosenHearModel()+ {+ Equal(12.0, Translator.HearTimeout(new AppSettings().AIConfig()), "Ming's timeout");+ Equal(20.0, Translator.HearTimeout(new AppSettings { AiProvider = "zenmux" }.AIConfig()), "the others'");+ var old = LingClient.Spacing; LingClient.Spacing = 0;+ try+ {+ var fake = new Service((_, _) => Reply("LANG: en\nORIGINAL: We ship on Friday.\nTRANSLATION: 我们周五发布。"));+ var (ling, _) = Using(fake, s: new AppSettings { AiHearModels = { ["zenmux"] = "bytedance/doubao-seed-2.0-mini" } });+ var heard = await new Translator(ling).Hear(Wav.Bytes(Tone(1)), "zh-CN", null);+ Equal("我们周五发布。", heard?.Translation, "heard");+ Equal("bytedance/doubao-seed-2.0-mini", JsonNode.Parse(fake.Sent[0].body)!["model"]!.GetValue<string>(), "model");+ }+ finally { LingClient.Spacing = old; }+ }++ public static void ProblemsNameTheService()+ {+ Check(ListenEngine.Words(LingException.Kind.Http, 400, "ZenMux").Settings, "a hear model that refuses audio is fixed in settings");+ Check(ListenEngine.Words(LingException.Kind.Network, 0, "ZenMux").Title!.Contains("ZenMux"), "named");+ Equal("连不上 Ling", ListenEngine.Words(LingException.Kind.Timeout, 0, "Ling").Title, "Ling keeps its words");+ Check(!ListenEngine.Words(LingException.Kind.Http, 400, "Ling").Settings, "Ling's 400 is the network bar");+ }++ public static void AClockIsNotSpeech()+ {+ foreach (var madeUp in new[] { "00:00", "00:00.", "1:02:03" }) Check(Translator.IsNoise(madeUp, 1.2), madeUp);+ foreach (var said in new[] { "Hello.", "3 点", "15%", "好的" }) Check(!Translator.IsNoise(said, 1.2), said);+ }}