知了 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
refactor(windows): remove code comments
wquguru67c7163433b5
diff --git a/windows/scripts/build.sh b/windows/scripts/build.shindex c79535c..952a988 100755--- a/windows/scripts/build.sh+++ b/windows/scripts/build.sh@@ -1,14 +1,9 @@#!/bin/bash-# Builds the Windows app on the Mac: build/Cicada-win-x64/ and build/Cicada-win-arm64/, each a-# self-contained Cicada.exe with everything inside it. RELEASE=1 for a release build, which also-# writes build/Cicada-<v>-Windows-x64.exe and -ARM64.exe (the same exe, for people to download);-# else a dev build, which keeps its records under "Cicada Dev" and opens the debug pipe.set -euo pipefailcd "$(dirname "$0")/.."root=..mkdir -p build/icon src/Cicada/Assets-# The icon (committed, regenerated here): the Mac app's 256 px icon at the sizes Windows asks for, PNGs inside one .ico.for s in 16 24 32 48 64 256; do sips -z $s $s "$root/docs/icon.png" --out "build/icon/$s.png" >/dev/null; donepython3 - build/icon <<'PY'import struct, sys, os@@ -20,9 +15,6 @@ for s, p in zip(sizes, pngs):open(os.path.join(d, "..", "..", "src", "Cicada", "Assets", "cicada.ico"), "wb").write(out + b"".join(pngs))PY-# The onboarding sample as 16 kHz WAV: SoundPlayer and the file source both read WAV only.-# afconvert writes WAVE_FORMAT_EXTENSIBLE plus a FLLR chunk, which SoundPlayer refuses-# (InvalidOperationException), so rewrite it as a plain PCM WAV.afconvert -f WAVE -d LEI16@16000 -c 1 "$root/Resources/sample/sample.m4a" build/icon/sample.wavpython3 - build/icon/sample.wav src/Cicada/Assets/sample.wav <<'PY'import struct, sys@@ -41,7 +33,6 @@ for rid in win-x64 win-arm64; dorm -rf "$out"scripts/dotnet.sh publish src/Cicada -c "$config" -r "$rid" -o "$out" -p:DebugType=embedded -v quiet -nologo 2>&1 | grep -E ' error |warning CS' | sort -u || true[ -f "$out/Cicada.exe" ] || { echo "build failed for $rid" >&2; exit 1; }- # The exe is the whole app (the UI text and the sample are inside it): the installer is a copy.[ "$(ls "$out" | grep -v '^Cicada.exe$' | grep -v '^test$' | grep -v '^Cicada Dev.cmd$' || true)" = "" ] || { echo "unexpected files beside Cicada.exe in $out: $(ls "$out")" >&2; exit 1; }if [ "$config" = Release ]; thenarch=x64; [ "$rid" = win-arm64 ] && arch=ARM64@@ -50,7 +41,6 @@ for rid in win-x64 win-arm64; dofiif [ "$config" = Debug ]; thenprintf '@echo off\r\nstart "" "%%~dp0Cicada.exe" --dev\r\n' > "$out/Cicada Dev.cmd"- # Everything the VM test needs in the one folder: the capture probe, the control script and the clips.mkdir -p "$out/test"scripts/dotnet.sh publish spike/LoopbackProbe -c Release -r "$rid" -o "$out/test" -p:DebugType=none -v quiet -nologo >/dev/nullcp scripts/cicadactl.ps1 "$out/test/"diff --git a/windows/scripts/cicadactl.ps1 b/windows/scripts/cicadactl.ps1index ee9b799..b5d17f6 100644--- a/windows/scripts/cicadactl.ps1+++ b/windows/scripts/cicadactl.ps1@@ -1,13 +1,3 @@-# Sends one debug command to a running dev build (Cicada.exe --dev) and prints its JSON state.-# .\cicadactl.ps1 state | start | stop | end | notesproblem failed | sample | feed C:\clip.wav | view subtitles | capture on | show records | hide notes | quit-# AI 服务: provider ling|openrouter|zenmux|custom | switchtoling (a status line's 改用 Ling) | ai-model hear|text|voice|notes <id> | ai-notes same|own [address] | ai-custom-only on|off | show settings ai models-# AI 服务检查: ai-check | ai-check-sim <unreachable|invalidKey|noCredit|mgmtKey|noModel|noJSON|deaf|busy|serverError|lowBalance|off> (state › ai.check: every step)-# 结束会议: calls zoom.exe=Zoom|none|real | realcalls | endtimes <silence> <countdown> <grace>|off | endkeep-# 改正听错的词: silentlisten zh-CN | heard <text> | fixstate | fixanswer yes|no | fixlater | fixrevert <line> | fixedit <line>=<text>[|one][|keep0] | fixundo | vocabadd Morpho=莫拉 | vocabstate (… @<id> for another meeting)-# 分享…: share "<id>[,full][,pw]" | unshare <id> | sharesheet "<id>[,full][,pw][,names][,30|365][,go]" | sharesheet leaveout | sharesheet | shareinfo <id>-# (quote anything with a comma: PowerShell would make it a list)-# 存到文件夹: export [state] | export on | off | folder C:\Notes\Cicada | choose (the 存到哪里 dialog) | all (也存一份) | retry (state › export too); rename <id> <title>-# 会议记录搜索 (Ctrl+F): search <text> | searchstep 1|-1 (meetings found, lines found in the shown one, the line it is on)param([Parameter(ValueFromRemainingArguments = $true)][string[]]$Command)$pipe = New-Object System.IO.Pipes.NamedPipeClientStream(".", "cicada-dev", [System.IO.Pipes.PipeDirection]::InOut)$pipe.Connect(3000)diff --git a/windows/scripts/compress-voiceprint.py b/windows/scripts/compress-voiceprint.pyindex cb4d25f..767b498 100644--- a/windows/scripts/compress-voiceprint.py+++ b/windows/scripts/compress-voiceprint.py@@ -1,23 +1,13 @@# Shrinks the WeSpeaker ResNet34-LM voiceprint model (VoxCeleb, CC BY 4.0) for the Windows app:-# every conv and dense weight becomes int8 with one scale per output channel, turned back into float by a-# Cast and a Mul when the model loads. Only opset-12 ops, so Windows' built-in Windows ML on-# Windows 10 2004 runs it; inference stays float32. 26.5 MB → 6.7 MB.-# Developer-only, run once; the app needs no Python. Needs: onnx numpy (onnxruntime to check).-# The source is the file the Mac's scripts/convert-voiceprint.py starts from-# (sha256 7bb2f06e9df17cdf1ef14ee8a15ab08ed28e8d0ef5054ee135741560df2ec068).-# usage: python3 scripts/compress-voiceprint.py voxceleb_resnet34_LM.onnx src/Cicada/Assets/voiceprint.onnximport sys, hashlib, numpy as np, onnxfrom onnx import helper, numpy_helper as nh, TensorProtosrc, out = sys.argv[1], sys.argv[2]-# --bits 4 packs two weights per byte (unpacked with Floor/Mul/Sub/Concat, still opset 12).bits = int(sys.argv[sys.argv.index("--bits") + 1]) if "--bits" in sys.argv else 8levels = 127 if bits == 8 else 7assert hashlib.sha256(open(src, "rb").read()).hexdigest() == "7bb2f06e9df17cdf1ef14ee8a15ab08ed28e8d0ef5054ee135741560df2ec068", "not the pinned WeSpeaker model"m = onnx.load(src)g = m.graph-# Conv weights (out, in, kh, kw) and the embedding layer's Gemm weight (out, in; transB=1): both-# have output channels first, so one scale per row.gemm_ok = all(any(a.name == "transB" and a.i == 1 for a in n.attribute) for n in g.node if n.op_type == "Gemm")assert gemm_ok, "expected Gemm with transB=1"conv_weights = {n.input[1] for n in g.node if n.op_type in ("Conv", "Gemm")}@@ -33,7 +23,6 @@ for name in conv_weights:row = int(np.prod(w.shape[1:]))group = 32if bits == 4 and row % group == 0:- # 4-bit, one scale per 32 weights of a row (fp16 scales): fine enough to keep the voice.G = w.reshape(w.shape[0], row // group, group)gs = np.abs(G).max(axis=2, keepdims=True); gs = np.where(gs > 0, gs / 7, 1).astype(np.float16)q4 = np.clip(np.round(G / gs.astype(np.float32)), -7, 7).astype(np.int16) + 8@@ -60,14 +49,14 @@ for name in conv_weights:]continueif bits == 8 or row % group != 0:- if bits == 4: # rows that don't split into groups (the first conv): 8-bit+ if bits == 4:scale = np.where(flat > 0, flat / 127, 1.0).astype(np.float32); shaped = scale.reshape(-1, *([1] * (w.ndim - 1)))q = np.clip(np.round(w / shaped), -127, 127).astype(np.int8)new_inits += [nh.from_array(q, name + "_q"), nh.from_array(shaped, name + "_s")]new_nodes += [helper.make_node("Cast", [name + "_q"], [name + "_f"], to=TensorProto.FLOAT),helper.make_node("Mul", [name + "_f", name + "_s"], [name])]else:- u = (q.reshape(-1).astype(np.int16) + 8).astype(np.uint8) # 1…15+ u = (q.reshape(-1).astype(np.int16) + 8).astype(np.uint8)if u.size % 2: u = np.append(u, np.uint8(8))packed = (u[0::2] << 4 | u[1::2]).astype(np.uint8)n = name@@ -94,7 +83,6 @@ g.initializer.extend(new_inits)nodes = list(g.node)del g.node[:]g.node.extend(new_nodes + nodes)-# Unsqueeze took its axes as an attribute before opset 13: move them back from the input.consts = {n.output[0]: nh.to_array(n.attribute[0].t) for n in g.node if n.op_type == "Constant"}consts.update({i.name: nh.to_array(i) for i in g.initializer})for n in g.node:@@ -102,7 +90,6 @@ for n in g.node:axes = [int(x) for x in np.atleast_1d(consts[n.input[1]])]del n.input[1]n.attribute.append(helper.make_attribute("axes", axes))-# Every other op here is unchanged since opset 12 (ReduceMean keeps its axes attribute until 18).del m.opset_import[:]m.opset_import.extend([helper.make_opsetid("", 12)])m.ir_version = 7diff --git a/windows/scripts/dotnet.sh b/windows/scripts/dotnet.shindex 39c481f..ab650ba 100755--- a/windows/scripts/dotnet.sh+++ b/windows/scripts/dotnet.sh@@ -1,7 +1,4 @@#!/bin/bash-# Runs the .NET SDK the Windows build uses: ~/.dotnet (installed by dotnet-install.sh, no sudo)-# or one on PATH. Downloads skip the proxy: NuGet and Microsoft's CDN are fast direct and very-# slow through it.export DOTNET_ROOT="${DOTNET_ROOT:-$HOME/.dotnet}" DOTNET_CLI_TELEMETRY_OPTOUT=1 DOTNET_NOLOGO=1dotnet="$DOTNET_ROOT/dotnet"; [ -x "$dotnet" ] || dotnet=$(command -v dotnet) || { echo "no .NET SDK: run scripts/install-dotnet.sh" >&2; exit 2; }exec env -u http_proxy -u https_proxy -u all_proxy -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY "$dotnet" "$@"diff --git a/windows/scripts/install-dotnet.sh b/windows/scripts/install-dotnet.shindex f1042bd..7ca2524 100755--- a/windows/scripts/install-dotnet.sh+++ b/windows/scripts/install-dotnet.sh@@ -1,5 +1,4 @@#!/bin/bash-# Installs the .NET 10 SDK into ~/.dotnet with Microsoft's script (no sudo, nothing system-wide).set -euo pipefailT=$(mktemp -d); trap 'rm -rf "$T"' EXITcurl -fsSL https://dot.net/v1/dotnet-install.sh -o "$T/dotnet-install.sh"diff --git a/windows/scripts/strings.py b/windows/scripts/strings.pyindex 03fc22e..0195850 100755--- a/windows/scripts/strings.py+++ b/windows/scripts/strings.py@@ -1,9 +1,5 @@#!/usr/bin/env python3-"""Lists Windows UI text with no translation: every L("…") / LF("…") key in windows/src that is in-neither the Mac's Resources/<lang>.lproj/Localizable.strings nor windows/src/Cicada/Strings/<lang>.lproj/Windows.strings.---write appends the missing keys to Windows.strings as TODO lines (value = the Chinese)."""import re, sys, pathlib-# The Windows console is cp1252: Chinese keys would crash the report itself.sys.stdout.reconfigure(encoding="utf-8")win = pathlib.Path(__file__).resolve().parent.parentroot = win.parentdiff --git a/windows/scripts/test.sh b/windows/scripts/test.shindex dc27646..0675bf8 100755--- a/windows/scripts/test.sh+++ b/windows/scripts/test.sh@@ -1,8 +1,6 @@#!/bin/bash-# Unit tests for the Windows engines; runs on the Mac and in CI (no network, no Windows needed).set -euo pipefailcd "$(dirname "$0")/.."-# A failed build must fail here, or the last good binary's results would be reported.if ! out=$(scripts/dotnet.sh build tests/Cicada.Tests -o build/tests -v quiet -nologo 2>&1); thenecho "$out" | grep -E ' error ' | sort -u >&2exit 1diff --git a/windows/spike/LoopbackProbe/Program.cs b/windows/spike/LoopbackProbe/Program.csindex 57436d5..d37504d 100644--- a/windows/spike/LoopbackProbe/Program.cs+++ b/windows/spike/LoopbackProbe/Program.cs@@ -1,12 +1,3 @@-// M0 spike: can Windows give us "everything the PC plays, except Cicada itself", the way the-// Core Audio process tap does on the Mac? Captures with WASAPI process loopback while this process-// plays a 1 kHz tone of its own, then checks the tone is absent from the capture (and, with-// --include-self, present: proof the check works). Writes 16 kHz mono Int16 WAV, the format the-// Windows AudioRouter will hand to Ming.-//-// LoopbackProbe.exe [seconds] [--include-self] [--no-tone] [--out capture.wav]-//-// Needs Windows 10 2004 (build 19041) or later.using System.Runtime.InteropServices;static class Program@@ -52,8 +43,6 @@ static class Program}}-/// WASAPI process loopback: ActivateAudioInterfaceAsync on the virtual loopback device, with-/// this process's tree excluded (or, for the control run, the only one included).static class Loopback{const string LoopbackDevice = "VAD\\Process_Loopback";@@ -65,8 +54,6 @@ static class Loopbackpublic static short[] Capture(int seconds, bool includeSelf){var client = Activate((uint)Environment.ProcessId, includeSelf ? 0 : 1);- // Process loopback has no mix format (GetMixFormat is E_NOTIMPL): ask for what Ming wants- // and let Windows convert; fall back to 48 kHz stereo and convert ourselves.(int rate, int channels)[] tries = [(16000, 1), (48000, 2), (44100, 2)];int rate = 0, channels = 0, hr = -1;foreach (var (r, c) in tries)@@ -79,7 +66,7 @@ static class LoopbackMarshal.FreeHGlobal(p);Console.WriteLine($" Initialize {r} Hz x{c}: 0x{hr:X8}");if (hr == 0) { rate = r; channels = c; break; }- client = Activate((uint)Environment.ProcessId, includeSelf ? 0 : 1); // a failed Initialize spoils the client+ client = Activate((uint)Environment.ProcessId, includeSelf ? 0 : 1);}Marshal.ThrowExceptionForHR(hr);@@ -95,7 +82,7 @@ static class Loopbacklong frames = 0;while (DateTime.UtcNow < end){- ready.WaitOne(100); // no events while nothing plays; keep the clock running+ ready.WaitOne(100);while (capture.GetNextPacketSize(out var packet) == 0 && packet > 0){Marshal.ThrowExceptionForHR(capture.GetBuffer(out var data, out var n, out var flags, out _, out _));@@ -108,8 +95,6 @@ static class Loopback}client.Stop();Console.WriteLine($" captured {frames} frames at {rate} Hz x{channels}");- // Loopback only delivers packets while something plays, so pad to wall-clock length is- // not attempted: the WAV holds what was heard, back to back.return Resample.ToMono16k(raw.ToArray(), rate, channels);}@@ -119,7 +104,7 @@ static class Loopbackint size = Marshal.SizeOf<ActivationParams>();var blob = Marshal.AllocHGlobal(size);Marshal.StructureToPtr(p, blob, false);- var variant = new PropVariantBlob { vt = 65 /* VT_BLOB */, cbSize = (uint)size, pBlobData = blob };+ var variant = new PropVariantBlob { vt = 65, cbSize = (uint)size, pBlobData = blob };var handler = new Completion();var iid = typeof(IAudioClient).GUID;try@@ -137,7 +122,6 @@ static class Loopbackstatic extern int ActivateAudioInterfaceAsync(string path, ref Guid riid, ref PropVariantBlob activationParams,IActivateAudioInterfaceCompletionHandler handler, out IActivateAudioInterfaceAsyncOperation op);- // The handler must be agile or activation fails with E_ILLEGAL_METHOD_CALL.[ComVisible(true)]sealed class Completion : IActivateAudioInterfaceCompletionHandler, IAgileObject{@@ -209,7 +193,6 @@ interface IActivateAudioInterfaceCompletionHandler[ComImport, Guid("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]interface IAgileObject { }-/// A looping tone played by this process through winmm, so the excluded tree makes a sound.static class Tone{const uint SndAsync = 0x1, SndMemory = 0x4, SndLoop = 0x8;@@ -217,10 +200,10 @@ static class Tonepublic static GCHandle Start(){const int rate = 16000;- var samples = new short[rate]; // 1 s, a whole number of cycles so the loop has no click+ var samples = new short[rate];for (int i = 0; i < samples.Length; i++)samples[i] = (short)(Math.Sin(2 * Math.PI * 1000 * i / rate) * 0.3 * short.MaxValue);- var handle = GCHandle.Alloc(Wav.Bytes(samples, rate), GCHandleType.Pinned); // must outlive async playback+ var handle = GCHandle.Alloc(Wav.Bytes(samples, rate), GCHandleType.Pinned);PlaySound(handle.AddrOfPinnedObject(), IntPtr.Zero, SndAsync | SndMemory | SndLoop);Thread.Sleep(300);return handle;@@ -244,7 +227,6 @@ static class Resamplemono[f] = sum / channels;}if (rate == 16000) return mono.Select(x => (short)x).ToArray();- // Spike-grade resampling: box-average then linear interpolation; the app will use Media Foundation.int window = Math.Max(1, rate / 16000);int outCount = (int)((long)frames * 16000 / rate);var output = new short[outCount];@@ -261,8 +243,6 @@ static class Resamplestatic class Analysis{- /// Overall RMS (0–1) and the 1 kHz tone's amplitude relative to what was played, from- /// Goertzel over 100 ms blocks, taking the loudest-tone block's median to ignore gaps.public static (double rms, double toneLevel) Run(short[] pcm, int rate, double hz, double playedAmp){if (pcm.Length == 0) return (0, 0);diff --git a/windows/spike/WinMLProbe/Program.cs b/windows/spike/WinMLProbe/Program.csindex 956b10a..7efe35f 100644--- a/windows/spike/WinMLProbe/Program.cs+++ b/windows/spike/WinMLProbe/Program.cs@@ -1,6 +1,3 @@-// usage: WinMLProbe <model.onnx> <ref.json> <feats dir>-// Loads the model with Windows.AI.MachineLearning, embeds each fixture's features, and prints the-// cosine to the Mac's onnxruntime embedding and the time per clip.using System.Diagnostics;using System.Text.Json;using Windows.AI.MachineLearning;diff --git a/windows/spike/make-clips.sh b/windows/spike/make-clips.shindex aa3560a..b5b5a3b 100755--- a/windows/spike/make-clips.sh+++ b/windows/spike/make-clips.sh@@ -1,6 +1,4 @@#!/bin/bash-# Regenerates windows/spike/clips/{en,zh,ja}.wav from the .txt beside them: one `say` call per-# sentence, 0.8 s of silence between sentences so the pauses look like a meeting. macOS only.set -euo pipefailcd "$(dirname "$0")/clips"T=$(mktemp -d); trap 'rm -rf "$T"' EXITdiff --git a/windows/spike/ming_asr.py b/windows/spike/ming_asr.pyindex d679be7..4cc1a1f 100644--- a/windows/spike/ming_asr.py+++ b/windows/spike/ming_asr.py@@ -1,29 +1,17 @@#!/usr/bin/env python3-"""M0 spike: can Ming's audio model stand in for on-device recognition on Windows?--Cuts a recording the way the Windows AudioRouter would (loudness only: a pause of 0.6 s or 8 s-of audio ends a segment), sends each segment to Ming-3.0-audio-flash in one call that returns the-language, the original and the translation, and reports latency, tokens and the character error-rate against a reference text.-- python3 ming_asr.py clips/en.wav --ref clips/en.txt --target zh-CN--macOS only (afconvert); stdlib only. The key is read from the app's key file and never printed.-"""import argparse, base64, io, json, os, re, statistics, subprocess, sys, tempfile, time, unicodedata, urllib.request, waveRATE = 16000-FRAME = 480 # 30 ms-THRESHOLD = 0.01 # same loudness gate as AudioRouter.swift (about -40 dBFS)+FRAME = 480+THRESHOLD = 0.01PAUSE, MAX_SEG, MIN_SEG = 0.6, 8.0, 0.25-GAP = 0.6 # LingClient spaces request starts at least 0.6 s apart+GAP = 0.6NAMES = {"en": "English", "zh-CN": "Simplified Chinese", "ja": "Japanese", "ko": "Korean"}KEY_FILES = ["~/Library/Application Support/LiveSubs Dev/ling-api-key","~/Library/Application Support/LiveSubs/ling-api-key"]def load_pcm(path):- """16 kHz mono Int16 samples of any file afconvert reads."""with tempfile.TemporaryDirectory() as tmp:out = os.path.join(tmp, "a.wav")subprocess.run(["afconvert", "-f", "WAVE", "-d", f"LEI16@{RATE}", "-c", "1", path, out], check=True)@@ -32,7 +20,6 @@ def load_pcm(path):def segments(pcm):- """(start, end) sample ranges, cut on pauses or length, like the Windows router will."""import arraya = array.array("h", pcm)loud = []@@ -90,7 +77,6 @@ def ask(key, wav, target):def norm(s):- """Letters and digits only, lower case: punctuation and spacing don't count as errors."""return [c for c in unicodedata.normalize("NFKC", s).lower() if c.isalnum()]diff --git a/windows/src/Cicada.Cli/Program.cs b/windows/src/Cicada.Cli/Program.csindex b219dca..d801c3c 100644--- a/windows/src/Cicada.Cli/Program.cs+++ b/windows/src/Cicada.Cli/Program.cs@@ -1,21 +1,3 @@-// cicada-cli: the Windows engines without Windows.-//-// cicada-cli listen <file.wav> [--target zh-CN] [--speed 1|0] [--notes]-// 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. --room <mic.wav> hears that file as the room mic too-// (电脑和会议室: two engines, the echo gate and EchoMatch); --room-only hears it alone (会议室).-// 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; --voice <id>,-// --lang <code> (Ming's language_id), --clone <reference.wav> [--clone-text <what it says>]-// [--from <my language>] for the user's own voice (Ling only), kept as the app keeps it-// (quiet ends trimmed) unless --raw sends the file as it is-// 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-//-// --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;@@ -76,9 +58,6 @@ switch (args_[0]){var ling = Client();var pcm = new List<byte>();- // --clone <reference.wav>: the user's own voice, as 我自己的声音 does. The clip is checked- // as the app checks a recording (length, heard by the hear model, pace) unless --clone-text- // gives what it says.(string Audio, string Text)? reference = null;if (Opt("--clone", "") is { Length: > 0 } refFile){@@ -97,7 +76,6 @@ switch (args_[0])if (args_.Contains("--raw")) reference = ("data:audio/wav;base64," + Convert.ToBase64String(refWav), text);else{- // Kept and read back as the app keeps it (VoiceReference.Save trims the quiet ends).var kept = new VoiceReference(new PlainProtector(), Path.Combine(Path.GetTempPath(), $"cicada-cli-voice-{Environment.ProcessId}"));kept.Save(refWav, text);reference = kept.Reference();@@ -117,7 +95,6 @@ switch (args_[0])}case "hear":{- // 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,diff --git a/windows/src/Cicada.Core/AICheck.cs b/windows/src/Cicada.Core/AICheck.csindex 122238b..433403d 100644--- a/windows/src/Cicada.Core/AICheck.cs+++ b/windows/src/Cicada.Core/AICheck.cs@@ -3,28 +3,14 @@ using System.Text.Json.Nodes;namespace Cicada;-/// What the last look at the AI service found, step by step (the Mac's AICheck.swift): can this-/// computer reach it, does it take the key, does the text model answer, and, on the ports, does the-/// hear model take audio. A failed step stops the ones after it, so the settings can say exactly-/// where it broke and offer the one thing that fixes it.-///-/// Most of the time the answer comes from real requests (hearing, notes, translation): every call-/// reports back, so a meeting keeps the steps current without any extra request. An explicit check-/// runs only when the service, model or key changes, at launch, on 重新检查, before 开始听 when the-/// service was unreachable, and when the network changes after it was unreachable.-///-/// A value: LingClient changes a copy and swaps it in, since requests report from worker threads.public sealed class AICheck{- /// In order. Hear is the ports' own: they hear through the service (the Mac recognizes on the device).public enum StepId { Reach, Key, Text, Hear }public enum Reason { Unreachable, BadAddress, InvalidKey, MgmtKey, NoCredit, NoModel, NoJSON, Deaf, Busy, ServerError }public enum Kind { Running, Ok, Busy, Fail, Skipped, Untested }- /// One step's state. `Seconds`: the request that proved it (null when it came with another- /// step's request). Busy (429): the service is busy but the key works; it counts as passed.public readonly record struct State(Kind Kind, double? Seconds = null, Reason? Why = null, int? Code = null){public static State Ok(double? seconds = null) => new(Kind.Ok, seconds);@@ -37,9 +23,6 @@ public sealed class AICheckpublic enum ProxyKind { SystemOn, AppRunning, None }- /// Where the proxy stands when the service can't be reached: only read, to word the hint.- /// SystemOn: a system proxy is on and it still can't connect; AppRunning: nothing in the system- /// settings, but a proxy app listens on `Port`.public readonly record struct ProxyHint(ProxyKind Kind, int Port = 0){public override string ToString() => Kind == ProxyKind.AppRunning ? $"appRunning({Port})" : Kind == ProxyKind.SystemOn ? "systemOn" : "none";@@ -48,32 +31,20 @@ public sealed class AICheckpublic static readonly StepId[] Order = [StepId.Reach, StepId.Key, StepId.Text, StepId.Hear];readonly State[] steps = [State.Untested, State.Untested, State.Untested, State.Untested];- /// When the newest result came in.public DateTimeOffset? At { get; set; }- /// The newest result came from a real request in a meeting, not from a check.public bool Passive { get; set; }public ProxyHint? Proxy { get; set; }- /// OpenRouter only: dollars left (the smaller of the key's limit and the account's credits).public double? Balance { get; set; }- /// A custom service: how long one real sentence took, and whether the model thought first.public Speed? Translate { get; set; }- /// A custom service whose notes go to another model or server: how that one answered (Running,- /// Ok with seconds, or Fail with why). Null while notes use the translation model (then the- /// steps say it all). A notes failure doesn't stop translation: Failure and Passed stay about- /// translation.public State? Notes { get; set; }- /// Translation works but the notes' own model or server doesn't (a busy one fixes itself).public bool NotesFailed => Notes is { Kind: Kind.Fail, Why: not Reason.Busy };- /// A sentence that takes `SlowAfter` seconds often misses the 6 s a translation is given- /// (Translator) and falls back to Google; a model that thinks first does every time.public readonly record struct Speed(double Seconds, bool Thinks){public const double SlowAfter = 3;public bool Slow => Thinks || Seconds >= SlowAfter;}- /// Text works but every sentence is slow (a thinking model): translations will fall back.public bool Slow => Failure is null && Translate?.Slow == true;public const double LowBalance = 0.5;@@ -93,10 +64,8 @@ public sealed class AICheckreturn c;}- /// The same states and reasons; how many seconds a request took doesn't count.public bool SameSteps(AICheck other) => steps.Zip(other.steps).All(p => p.First with { Seconds = null } == p.Second with { Seconds = null });- /// The first step that failed, and why.public (StepId Step, Reason Why, int? Code)? Failure{get@@ -108,28 +77,18 @@ public sealed class AICheckpublic bool IsRunning => steps.Any(s => s.Kind == Kind.Running) || Notes?.Kind == Kind.Running;public bool IsBusy => steps.Any(s => s.Kind == Kind.Busy);- /// Every step passed (busy counts; a step nothing has tested yet does not block).public bool Passed => At is not null && Failure is null && !IsRunning;public bool IsLowBalance => (Balance ?? double.PositiveInfinity) < LowBalance;- /// Something only the user can fix (a busy service or a server error fixes itself).public bool NeedsUser => Failure is { } f ? f.Why is not (Reason.Busy or Reason.ServerError) : IsLowBalance;- /// What stops listening or the notes until the user changes something (the Mac's- /// AIServiceStrip.blocking): the tray's dot and the one notification a meeting, beyond the panel.- /// Not the network, a busy service or a server error (they pass by themselves), nor a low balance- /// (it still works). Deaf is the ports' own: the hear model is the user's choice to change.public static bool Blocks(Reason why) => why is Reason.InvalidKey or Reason.MgmtKey or Reason.NoCreditor Reason.NoModel or Reason.BadAddress or Reason.NoJSON or Reason.Deaf;public bool Blocking => Failure is { } f && Blocks(f.Why);- /// Whether a request to `later` must have got past `step`: the hear model's request proves the- /// address and the key, not the text model, and the text model's says nothing about hearing.static bool Needs(StepId later, StepId step) => later == StepId.Hear ? step is StepId.Reach or StepId.Key : step < later;- /// `step` failed and the steps that need it were never reached. `reached`: a reply came back,- /// so the steps it needs passed (false when nothing was sent, like a management key).public void Fail(StepId step, Reason why, int? code = null, bool reached = true){foreach (var id in Order)@@ -141,8 +100,6 @@ public sealed class AICheckif (why != Reason.Unreachable) Proxy = null;}- /// One request proved `step` and the steps it needs (a chat proves the address, the key and- /// the text model). Clears what failed before; steps that need it and were skipped are open again.public void Pass(StepId step, double? seconds){foreach (var id in Order)@@ -150,23 +107,17 @@ public sealed class AICheckif (id == step) steps[(int)id] = State.Ok(seconds);else if (Needs(step, id) && steps[(int)id].Kind != Kind.Ok) steps[(int)id] = State.Ok();}- // Skipped because a step it needs failed; now nothing it needs has failed.foreach (var id in Order)if (steps[(int)id].Kind == Kind.Skipped && !Order.Any(n => Needs(id, n) && steps[(int)n].Kind == Kind.Fail)) steps[(int)id] = State.Untested;Proxy = null;}- /// A 429 on `step`: the steps it needs passed, and it is busy (not a failure).public void Busy(StepId step){Pass(step, null);steps[(int)step] = State.Busy;}- /// Which step a failed request stops at, and why. `step` is the step the request was proving- /// (the text model for a chat, the hear model for audio). Null: says nothing about the service.- /// `hearElsewhere`: the hear model has an address of its own, so not reaching it says nothing- /// about the service's address.public static (StepId Step, Reason Why, int? Code)? Classify(LingException.Kind kind, int status, StepId step, bool hearElsewhere = false) => kind switch{LingException.Kind.Network or LingException.Kind.Timeout when hearElsewhere && step == StepId.Hear => (StepId.Hear, Reason.Unreachable, null),@@ -174,15 +125,12 @@ public sealed class AICheckLingException.Kind.InvalidKey => (StepId.Key, Reason.InvalidKey, null),LingException.Kind.RateLimited => (step, Reason.Busy, null),LingException.Kind.Http when status == 402 => (StepId.Key, Reason.NoCredit, 402),- // A hear model that refuses audio answers 400, 404, 415 or 422 (HearsAudio).LingException.Kind.Http when step == StepId.Hear && status is 400 or 404 or 415 or 422 => (StepId.Hear, Reason.Deaf, status),LingException.Kind.Http when step == StepId.Text && status is 400 or 404 => (StepId.Text, Reason.NoModel, status),LingException.Kind.Http => (step, Reason.ServerError, status),_ => null,};- /// The prefix of a key says whose it is: `sk-or-` OpenRouter, `sk-payg` ZenMux, `sk-mgmt` ZenMux's- /// management key (it can't call models). Null: nothing to tell.public static (string Service, bool Management)? Owner(string key){var k = key.Trim();@@ -192,7 +140,6 @@ public sealed class AICheckreturn null;}- /// Model ids in a `/models` reply, as listed (null when the reply can't be read or lists none).public static HashSet<string>? ListedModels(string json){JsonNode? root;@@ -202,8 +149,6 @@ public sealed class AICheckreturn ids.Count == 0 ? null : ids;}- /// The models in a `/models` reply that say they take audio in. Null when none says anything- /// about its input (a custom service): then the list proves nothing about hearing.public static HashSet<string>? ListedHearing(string json){JsonNode? root;@@ -221,8 +166,6 @@ public sealed class AICheckreturn told ? ids : null;}- /// OpenRouter: dollars left from `/key` (`limit_remaining`, null without a key limit) and- /// `/credits` (bought minus used); the smaller one is what the next meeting can spend.public static double? BalanceFrom(string? key, string? credits){static JsonObject? Data(string? json)@@ -247,7 +190,6 @@ public sealed class AICheck_ => Strings.L("听对方"),};- /// Why the failed step failed, in one sentence. `model`: the text model, `hear`: the hear model.public string? Message(string service, string host, string model, string hear){if (Failure is not { } f) return IsBusy ? Strings.LF("%@ 现在很忙,key 没问题。开会时会自动重试。", service) : null;@@ -266,13 +208,10 @@ public sealed class AICheck};}- /// Why translations are slow, and what to do (a custom service). The Mac's words: the- /// translation timeout is the same 6 s here.public string? SlowLine(bool googleOff = false){if (!Slow || Translate is not { } t) return null;var secs = t.Seconds.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture);- // 语音和文字只发给你的服务: a sentence that takes too long isn't handed to Google.if (googleOff)return t.Thinks ? Strings.LF("这个模型先思考再回答,翻一句要 %@ 秒,超过 6 秒这句就不等它了。在服务端关掉思考,或换一个不思考的模型。", secs): Strings.LF("翻一句要 %@ 秒,超过 6 秒这句就不等它了。换一个更小的模型会快一些。", secs);@@ -280,8 +219,6 @@ public sealed class AICheck: Strings.LF("翻一句要 %@ 秒,超过 6 秒会改用 Google。换一个更小的模型会快一些。", secs);}- /// The notes' own model or server's problem, in one sentence. `sharedKey`: notes use the- /// translation key, so a refused key wants one of their own.public string? NotesLine(string host, string model, bool sharedKey){if (Notes is not { Kind: Kind.Fail, Why: { } why } n) return null;@@ -298,25 +235,20 @@ public sealed class AICheck};}- /// The proxy line under "can't reach": what this computer's proxy looks like, and what to do.public string? ProxyLine(string service, string host){- // A server on this PC or the local network: a proxy has nothing to do with it.if (Failure?.Why != Reason.Unreachable || Proxy is not { } p || AIProvider.IsNearby(host)) return null;return p.Kind switch{ProxyKind.SystemOn => Strings.LF("开了代理也连不上:换一个节点,或检查代理软件是否放过 %@。", host),- // As text: a number would be grouped ("7,890").ProxyKind.AppRunning => Strings.LF("代理软件在运行(端口 %@),但没开系统代理。在代理软件里打开“系统代理”。", p.Port.ToString(System.Globalization.CultureInfo.InvariantCulture)),_ => Strings.LF("这台电脑没开代理。在国内通常要开代理才能用 %@。", service),};}- /// "OpenRouter 余额快用完了(还剩 $0.40)" when it is.public string? BalanceLine(string service) =>IsLowBalance && Balance is { } b ? Strings.LF("%@ 余额快用完了(还剩 $%@)", service, Math.Max(0, b).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)) : null;- /// Debug and logs: "reach=ok key=fail(invalidKey) text=skipped hear=skipped".public string Summary{get@@ -336,10 +268,8 @@ public sealed class AICheck}}- /// The website's proxy help, in the UI language.public static string HelpUrl => "https://cicada.indaloop.app" + (Strings.Language is "en" or "ja" or "ko" ? "/" + Strings.Language : "") + "/start/#proxy";- /// "12 分钟前": when the newest evidence came in, for "%@ 开会时用过".public static string Ago(DateTimeOffset at, DateTimeOffset now){var minutes = (int)Math.Floor((now - at).TotalMinutes);@@ -351,30 +281,21 @@ public sealed class AICheck}}-/// Words the "can't reach the AI service" hint. Read-only on purpose: the app never sets or uses a-/// proxy of its own (HttpClient already goes through the system proxy); it only tells the user which-/// of three situations they are in. The system settings come from the app (the registry on Windows).-/// When to look at the AI service again after the system proxy changed (the app polls the-/// settings while this says so). It watches from the first unreachable result until a check-/// finishes reachable, and keeps watching while a check runs: a change made during that check-/// counts once it is over (the check may have gone out on the old settings).public sealed class ProxyWatch{string? seen;- /// After every change to the check. True while the settings should be polled.public bool Update(bool unreachable, bool running, Func<string> settings){if (!unreachable && !running) { seen = null; return false; }if (seen is null){- if (!unreachable) return false; // a check from a good state: nothing to watch yet+ if (!unreachable) return false;seen = settings();}return true;}- /// A poll: true when the settings differ from the last ones seen and no check is running.public bool Changed(string now, bool running){if (seen is null || running || now == seen) return false;@@ -385,7 +306,6 @@ public sealed class ProxyWatchpublic static class ProxyProbe{- /// Ports common proxy apps listen on (Clash 7890, Clash Verge 7897, SOCKS 1080).public static readonly int[] Ports = [7890, 7897, 1080];public static async Task<AICheck.ProxyHint> Hint(Func<bool> systemOn)@@ -395,10 +315,8 @@ public static class ProxyProbereturn new(AICheck.ProxyKind.None);}- /// An HTTPS proxy set for programs started from here (HttpClient reads it too).static bool EnvProxy() => new[] { "HTTPS_PROXY", "https_proxy" }.Any(n => Environment.GetEnvironmentVariable(n) is { Length: > 0 });- /// Something accepts a TCP connection on 127.0.0.1:`port` within 0.3 s. Nothing is sent.public static async Task<bool> Listening(int port){using var tcp = new TcpClient();diff --git a/windows/src/Cicada.Core/AIProviders.cs b/windows/src/Cicada.Core/AIProviders.csindex b0e90da..ef84b44 100644--- a/windows/src/Cicada.Core/AIProviders.cs+++ b/windows/src/Cicada.Core/AIProviders.cs@@ -3,22 +3,10 @@ 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){@@ -26,7 +14,6 @@ public sealed record AIProvider(string Id, string Name, string? Base, string? Sistatic 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);@@ -41,28 +28,19 @@ public sealed record AIProvider(string Id, string Name, string? Base, string? Si[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;- /// This computer: a key isn't needed.public static bool IsLocal(string hostOrUrl) => Host(hostOrUrl) is "localhost" or "127.0.0.1" or "::1";- /// This computer or the local network (Ollama, LM Studio, a GPU box at home or work, a Tailscale- /// address): plain http is allowed and a key isn't needed. Private IPv4 (10/8, 172.16/12,- /// 192.168/16), link-local, Tailscale's 100.64/10, IPv6 unique and link-local addresses, and- /// `.local` names.public static bool IsNearby(string hostOrUrl){var h = Host(hostOrUrl).ToLowerInvariant();if (IsLocal(h) || h.EndsWith(".local")) return true;var parts = h.Split('.');- // Exactly four numbers: "10.0.0.5.evil.com" is a name, not a private address.if (parts.Length == 4 && parts.All(x => x.Length is > 0 and <= 3 && x.All(char.IsAsciiDigit) && int.Parse(x) <= 255)){int a = int.Parse(parts[0]), b = int.Parse(parts[1]);@@ -79,8 +57,6 @@ public sealed record AIProvider(string Id, string Name, string? Base, string? Sireturn (Uri.TryCreate(u, UriKind.Absolute, out var uri) ? uri.Host : s).Trim('[', ']');}- /// The address as typed, normalized: https, or http only on this computer or the local- /// network; ends in "/".public static string? CustomBase(string? raw){var s = (raw ?? "").Trim();@@ -94,9 +70,6 @@ public sealed record AIProvider(string Id, string Name, string? Base, string? Sistatic readonly Regex NotChat = new(@"(embed|whisper|tts|asr|transcribe|dall-e|image|moderation|realtime|sora|search|video|seedance|wan\d)");- /// Model ids from a `/models` reply, recommended ones first: those that answer in text, and for- /// `hears` only those that take audio in. ZenMux lists modalities at the top level, OpenRouter- /// 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;@@ -110,7 +83,7 @@ public sealed record AIProvider(string Id, string Name, string? Base, string? Sivar 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 (ins is ["audio"]) continue;if (hears && !ins.Contains("audio")) continue;if (outs.Count == 0 && NotChat.IsMatch(id)) continue;ids.Add(id);@@ -123,41 +96,25 @@ public sealed record AIProvider(string Id, string Name, string? Base, string? Sistatic 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. `HearBase` is where the hear model is-/// asked: the service's address, or a custom service's own one for it (null: not a valid address).-///-/// A custom service's notes (实时纪要, 说话人): `NotesModel` another model, and with 另一个服务-/// (`NotesOwnService`) `NotesBase` another server with its own key; null: the same as translation.-/// `NotesBadAddress`: 另一个服务 with an address that can't be used (http to the internet).public sealed record AIConfig(AIProvider Provider, string? Base, string TextModel, string HearModel,string? VoiceModel = null, string? VoiceBase = null, string? CustomVoice = null, string? HearBase = null,string? NotesModel = null, string? NotesBase = null, bool NotesOwnService = false, bool NotesBadAddress = false){- /// Notes go somewhere translation doesn't: they get their own check, result, key and start gate.public bool NotesApart => Provider.Id == "custom" && (NotesModel is not null || NotesBase is not null || NotesOwnService);- /// What a notes call is sent with: notes' model at notes' address, the rest as translation.public AIConfig ForNotes => !NotesApart ? this : this with { TextModel = NotesModel ?? TextModel, Base = NotesBase ?? Base };public bool IsLing => Provider.Id == "ling";public bool HasVoices => VoiceModel is not null && VoiceBase is not null;- /// What the UI and errors call it ("其他(兼容 OpenAI)" is a UI key, localized by the caller).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());- /// The hear model has an address of its own (a custom service's speech server).public bool HearElsewhere => HearBase != Base;- /// Each service turns thinking off its own way (AIConfig.shape on the Mac). A custom service- /// gets `chat_template_kwargs` (vLLM, SGLang and llama.cpp pass it to the chat template, which- /// is how Qwen3 turns thinking off); `templateKwargs` false leaves it out for a server that refused it.public void Shape(JsonObject body, int maxTokens, bool templateKwargs = true){body["max_tokens"] = maxTokens;@@ -167,9 +124,6 @@ public sealed record AIConfig(AIProvider Provider, string? Base, string TextModeelse if (Provider.Id == "custom" && templateKwargs) body["chat_template_kwargs"] = new JsonObject { ["enable_thinking"] = false };}- /// The model thought before answering, which makes every translation slow: a `reasoning_content`- /// (or `reasoning`) field, reasoning tokens in the usage, or a `<think>` block in the answer.- /// A server's reasoning parser may put the whole answer in `reasoning_content`, content empty.public static bool Thought(JsonNode? root){var message = root?["choices"]?[0]?["message"];@@ -179,8 +133,6 @@ public sealed record AIConfig(AIProvider Provider, string? Base, string TextModereturn message?["content"] is JsonValue c && c.TryGetValue<string>(out var content) && content.Contains("<think>");}- /// One WAV in a user message: Ming takes a data URL; the others the standard `input_audio`,- /// 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);@@ -189,7 +141,6 @@ public sealed record AIConfig(AIProvider Provider, string? Base, string TextModereturn 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);@@ -205,7 +156,6 @@ public sealed record AIConfig(AIProvider Provider, string? Base, string TextModevar voice = Pick(s.AiVoiceModels);var voiceBase = s.AiCustomVoiceBase.Trim().Length > 0 ? AIProvider.CustomBase(s.AiCustomVoiceBase) : b;var name = s.AiCustomVoice.Trim();- // The hear model may run as its own server; empty is the text model's address.var hearBase = s.AiCustomHearBase.Trim().Length > 0 ? AIProvider.CustomBase(s.AiCustomHearBase) : b;var textModel = Pick(s.AiModels);var notesModel = s.AiModels.TryGetValue("custom.notes", out var nm) ? nm.Trim() : "";diff --git a/windows/src/Cicada.Core/Adts.cs b/windows/src/Cicada.Core/Adts.csindex db4db88..5d99374 100644--- a/windows/src/Cicada.Core/Adts.cs+++ b/windows/src/Cicada.Core/Adts.cs@@ -1,14 +1,9 @@namespace Cicada;-/// The frames of an ADTS file (`system.aac`), for rewrapping into an .m4a without re-encoding.-/// Windows' own ADTS reader hands out byte chunks of several frames each, which the MP4 sink can't-/// time, so the file is split here. A frame cut off by a crash ends the list.public static class Adts{public readonly record struct Frame(int Offset, int Length);- /// What the frames hold: AAC object type, sample rate and channels, and the AudioSpecificConfig- /// an MP4 track needs.public sealed record Config(int ObjectType, int Rate, int Channels, byte[] SpecificConfig);static readonly int[] Rates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];@@ -24,7 +19,6 @@ public static class Adtsreturn new Config(obj, Rates[index], channels, asc);}- /// Each frame's payload (the header left out), in order.public static List<Frame> Frames(ReadOnlySpan<byte> file){var frames = new List<Frame>();@@ -35,10 +29,9 @@ public static class Adtsint length = ((h[3] & 3) << 11) | (h[4] << 3) | (h[5] >> 5);int header = (h[1] & 1) == 1 ? 7 : 9;if (length <= header) { at = Sync(file, at + 1); continue; }- if (at + length > file.Length) break; // cut off mid-frame+ if (at + length > file.Length) break;frames.Add(new Frame(at + header, length - header));at += length;- // Something not a frame (a torn write): skip to the next sync word.if (at < file.Length && !IsSync(file, at)) at = Sync(file, at);}return frames;diff --git a/windows/src/Cicada.Core/Audio.cs b/windows/src/Cicada.Core/Audio.csindex 94e8e18..6bd7ea6 100644--- a/windows/src/Cicada.Core/Audio.cs+++ b/windows/src/Cicada.Core/Audio.cs@@ -1,20 +1,16 @@namespace Cicada;-/// Where listening gets its sound: 16 kHz mono Int16, pushed from any thread. On Windows the-/// process loopback tap (everything the PC plays except Cicada); in tests and the CLI, a file.public interface IAudioSource{event Action<short[]>? Samples;- /// Fires once when the source can't go on (device gone, file finished).event Action<string?>? Ended;void Start();void Stop();}-/// Debug (`silentlisten`): a meeting with no audio at all, its lines given by `heard`.public sealed class SilentSource : IAudioSource{-#pragma warning disable CS0067 // never raised: there is nothing to hear+#pragma warning disable CS0067public event Action<short[]>? Samples;public event Action<string?>? Ended;#pragma warning restore CS0067@@ -22,7 +18,6 @@ public sealed class SilentSource : IAudioSourcepublic void Stop() { }}-/// Plays a WAV into listening, in real time or as fast as it can (`speed` 0).public sealed class FileAudioSource(string path, double speed = 1) : IAudioSource{CancellationTokenSource? cts;@@ -36,7 +31,7 @@ public sealed class FileAudioSource(string path, double speed = 1) : IAudioSourcvar pcm = Wav.Read(path);Task.Run(async () =>{- const int chunk = Segmenter.Rate / 10; // 100 ms, like a capture callback+ const int chunk = Segmenter.Rate / 10;var started = DateTime.UtcNow;for (int i = 0; i < pcm.Length && !token.IsCancellationRequested; i += chunk){@@ -48,7 +43,6 @@ public sealed class FileAudioSource(string path, double speed = 1) : IAudioSourcif (wait > TimeSpan.Zero) await Task.Delay(wait, CancellationToken.None);}}- // A second of silence so the last sentence's pause is heard.Samples?.Invoke(new short[Segmenter.Rate]);Ended?.Invoke(null);});@@ -57,20 +51,10 @@ public sealed class FileAudioSource(string path, double speed = 1) : IAudioSourcpublic void Stop() => cts?.Cancel();}-/// Loopback capture sends nothing while nothing plays, so SystemAudioTap feeds silence itself to end-/// segments and keep the clock going. But a packet that is merely late (a busy PC, a VM) arrives-/// after that silence: a gap that wasn't there goes into the middle of the sentence, and with the-/// pause between two words it reaches the segmenter's 0.6 s and the line splits in two ("…keep-/// the twenty." / "First is the release date…"). Waiting 300 ms, as the tap did, let any stall from-/// 300 ms up do that; it now waits a whole second, so only a stall over a second can. Silence that-/// is real costs nothing until the pause would end a segment anyway, then 0.4 s at most, once,-/// when the playback stops altogether (a meeting app or player keeps sending silent packets).public static class LoopbackGap{public const double Late = 1.0;- /// Samples of silence to feed now: none until `sinceLastPacket` reaches Late, then all of- /// `sinceFed` (the time since audio, or silence, was last handed on).public static int Silence(double sinceLastPacket, double sinceFed) =>sinceLastPacket >= Late ? (int)(Math.Max(0, sinceFed) * Segmenter.Rate) : 0;}@@ -89,7 +73,6 @@ public static class Wavreturn ms.ToArray();}- /// A PCM16 WAV of any rate and channel count, as 16 kHz mono.public static short[] Read(string path){using var r = new BinaryReader(File.OpenRead(path));@@ -125,7 +108,6 @@ public static class Wavthrow new InvalidDataException("no data chunk");}- /// Linear interpolation after a box average: plenty for speech going to a recognizer.public static short[] Resample(double[] mono, int rate){if (rate == Segmenter.Rate) return mono.Select(x => (short)Math.Clamp(x, short.MinValue, short.MaxValue)).ToArray();diff --git a/windows/src/Cicada.Core/Correction.cs b/windows/src/Cicada.Core/Correction.csindex db7fed1..934f14e 100644--- a/windows/src/Cicada.Core/Correction.cs+++ b/windows/src/Cicada.Core/Correction.cs@@ -3,11 +3,6 @@ using System.Text.Json.Nodes;namespace Cicada;-/// 改正听错的词: deciding which of the AI service's proposed fixes to take, without asking it again,-/// and the line as shown once they are in. The Mac's Correction.swift, rule for rule. The service's-/// own confidence isn't enough (in a 21-minute test it rated "快销 → 区块" and "苍蝇 → 方向" above-/// 0.85), so a Chinese word may only be swapped for one that sounds alike (pinyin), a Latin word-/// only for a near spelling, and a new name only once the user says so.public static class Correction{public sealed record Edit(string From, string To, double Confidence);@@ -16,7 +11,6 @@ public static class Correctionpublic const double ApplyAt = 0.6, SpellingAt = 0.8, AskAt = 0.8;- /// Characters as the Mac counts them (grapheme clusters, Swift's Character).static string[] Chars(string s){var e = StringInfo.GetTextElementEnumerator(s);@@ -29,17 +23,12 @@ public static class Correctionstatic bool Word(string c) => c.Length == 1 && char.IsAsciiLetterOrDigit(c[0]);- /// A fix as the UI names it (听成 X → Y, 已改回 X): the changed words, or the whole fix when- /// it only adds or drops words ("in" → "in now", whose changed part alone would be "" → " now").public static (string From, string To) Label(LineFix f){var c = Core(f.From, f.To);return c.From.Length == 0 || c.To.Length == 0 ? (f.From, f.To) : c;}- /// The part an edit changes, as a word: "解除质压" → "解除质押" is "质压" → "质押" (at least two- /// characters, so one refusal doesn't block every 压 → 押), and a Latin word stays whole- /// ("Un450P三" → "Uniswap V3", not "450P三" → "iswap V3").public static (string From, string To) Core(string from, string to){var a = Chars(from); var b = Chars(to);@@ -48,12 +37,10 @@ public static class Correctionwhile (i < min && a[i] == b[i]) i++;int j = 0;while (j < min - i && a[a.Length - 1 - j] == b[b.Length - 1 - j]) j++;- // Only a change that starts or ends inside a Latin word takes the rest of the word.bool FromEdge(int k) => (k < a.Length && Word(a[k])) || (k < b.Length && Word(b[k]));if (FromEdge(i)) while (i > 0 && Word(a[i - 1])) i--;if ((a.Length - j - 1 >= 0 && Word(a[a.Length - j - 1])) || (b.Length - j - 1 >= 0 && Word(b[b.Length - j - 1])))while (j > 0 && Word(a[a.Length - j])) j--;- // Two characters at least, taken from the Chinese side: "FFT制押" → "FFT质押" is "制押" → "质押".while (a.Length - j - i < 2 || b.Length - j - i < 2){if (j > 0 && !Word(a[a.Length - j])) j--;@@ -63,8 +50,6 @@ public static class Correctionreturn (string.Concat(a[i..(a.Length - j)]), string.Concat(b[i..(b.Length - j)]));}- /// `known`: the user confirmed this heard form for this word (the word list). `rejected`: they- /// said no to it in this meeting.public static Verdict Decide(Edit e, Func<string, string, bool> known, Func<string, string, bool> rejected){var c = Core(e.From, e.To);@@ -76,25 +61,15 @@ public static class Correctionif (!latinFrom && !latinTo && Han(c.From) && Han(c.To) && SoundsAlike(c.From, c.To)) return Verdict.Apply;if (latinFrom && latinTo && c.From.All(char.IsAscii) && c.To.All(char.IsAscii) && e.Confidence >= SpellingAt&& Distance(c.From.ToLowerInvariant(), c.To.ToLowerInvariant()) <= 2) return Verdict.Apply;- // A new name (Chinese heard as a Latin name, or a respelled one): sound can't check it. A- // name has a capital or a digit; "X平台 → X platform" is a translation, and one 对 to it- // taught the word list 平台 → platform, which then rewrote every 平台 in the meeting.if (latinTo && e.Confidence >= AskAt && NameShaped(c.To)) return Verdict.Ask;return Verdict.Drop;}- /// Latin text that could be a name: a capital or a digit in it (Morpho, GPT4o), not "platform".public static bool NameShaped(string s) => s.Any(c => char.IsAsciiLetterUpper(c) || char.IsAsciiDigit(c));- /// A Chinese word "fixed" into a plain English one (平台 → platform): a translation, not a- /// misheard name.public static bool Translation(string heard, string word) =>Han(heard) && word.Any(char.IsAsciiLetter) && word.All(char.IsAscii) && !NameShaped(word);- // Toneless pinyin for every CJK Unified Ideograph (U+4E00–U+9FFF) that has a reading: Windows- // has no Mandarin transform of its own, so this table was generated once from Apple's ICU/CLDR- // Han-Latin transform (the one the Mac uses, kCFStringTransformMandarinLatin with diacritics- // stripped). Data, not a dependency: one "<char>\t<syllable>" per line.static readonly Lazy<Dictionary<char, string>> Table = new(() =>{var d = new Dictionary<char, string>();@@ -106,7 +81,6 @@ public static class Correctionreturn d;});- /// Toneless pinyin, one syllable per character; a character the table doesn't read stays itself.public static string[] Pinyin(string s) =>Chars(s).Select(ch => ch.Length == 1 && Table.Value.TryGetValue(ch[0], out var p) ? p : ch.ToLowerInvariant().Trim()).ToArray();@@ -119,8 +93,6 @@ public static class Correctionreturn ("", syllable);}- /// Same number of syllables, and on average three quarters alike: a syllable counts whole when- /// equal, half when its initial or its final matches (质/追, 销/照). 苍蝇/方向 is a quarter.public static bool SoundsAlike(string a, string b){var x = Pinyin(a); var y = Pinyin(b);@@ -135,7 +107,6 @@ public static class Correctionreturn score / x.Length >= 0.75;}- /// Every character an ideograph (Swift's isIdeographic).public static bool Han(string s) => s.EnumerateRunes().All(r => r.Value is >= 0x3400 and <= 0x4DBF or >= 0x4E00 and <= 0x9FFFor >= 0xF900 and <= 0xFAFF or >= 0x20000 and <= 0x3134F or 0x3006 or 0x3007 or >= 0x3021 and <= 0x3029);@@ -156,9 +127,6 @@ public static class Correctionreturn row[b.Length];}- /// Where `s` stands as words of its own in `text` (its offset, or -1): a Latin edge of it never- /// runs on into a Latin word around it. `Core` pads a fix to two characters, so the word list- /// learned "S平 → X平", which matched inside "iOS平台" and made it "iOX平台".public static int WordIn(string s, string text){if (s.Length == 0) return -1;@@ -174,13 +142,10 @@ public static class Correctionreturn -1;}- /// The line as shown: each applied fix replaces its words where they still are. The marks are- /// the replaced words (start, length in the shown text), for the dotted underline.public static (string Text, List<(int Start, int Length)> Marks) Apply(IReadOnlyList<LineFix> fixes, string src){var text = src;var spans = new List<(string Word, int At)>();- // The user's own last: written against the line as it was shown, other fixes in.foreach (var f in fixes.Where(f => f.User != true).Concat(fixes.Where(f => f.User == true))){if (!f.Applied || f.From.Length == 0) continue;@@ -196,13 +161,8 @@ public static class Correctionreturn (text, marks);}- /// The service's reply to a sentence sent with fixes asked for:- /// {"translation": "…", "fixes": [{"from", "to", "confidence"}]}. Null when it isn't that shape,- /// and the caller treats the reply as a failed one. Fixes whose words aren't in the subtitle are- /// dropped: the service sometimes quotes them rephrased.public static (string Translation, List<Edit> Edits)? Parse(string reply, string subtitle){- // Asked for JSON in the prompt only: take the outermost {…}, fenced or not.int open = reply.IndexOf('{'), close = reply.LastIndexOf('}');if (open < 0 || close <= open) return null;JsonObject? o;@@ -220,9 +180,6 @@ public static class Correctionreturn (translation.Trim(), edits);}- /// What a line's fixes become after the service answered for it again (a joined line): the- /// user's decisions stay (said no, said yes, wrote it), and of the rest only what is proposed- /// again. So a pass that no longer proposes a fix takes it back.public static List<LineFix> Merge(IReadOnlyList<LineFix> old, IReadOnlyList<LineFix> fresh){var kept = old.Where(f => f.Off == true || f.User == true).ToList();@@ -234,19 +191,10 @@ public static class Correctionreturn [.. kept, .. added];}- /// 改这句…: the user rewrote the line as shown. What changed, as a fix on top of the others: the- /// changed span grown to whole tokens (a Latin word, or one CJK character), and further, a token- /// at a time, until it holds a letter and is the only such span in the line. An added word- /// ("lock that in." → "lock that in now.") is then "in" → "in now" on this line, never "." on- /// every line. `Swap` is whether words were replaced (not only added or dropped): only a swap- /// may go to the rest of the meeting and teach the word list. `Heard` is the words in `src`- /// when they are there, else the heard words of the fix the user corrected again ("莫纳" →- /// "Morpho" → "Monad").public static (LineFix Fix, string Heard, bool Swap)? UserEdit(string shown, string edited, string src, IReadOnlyList<LineFix> fixes){var now = edited.Trim();if (now.Length == 0 || now == shown) return null;- // Characters as the Mac counts them (grapheme clusters), so the spans match Swift's.static string[] Chars(string x){var e = StringInfo.GetTextElementEnumerator(x);@@ -260,7 +208,6 @@ public static class Correctionint q = 0;while (q < Math.Min(a.Length, b.Length) - p && a[a.Length - 1 - q] == b[b.Length - 1 - q]) q++;bool swap = a.Length - p - q > 0 && b.Length - p - q > 0;- // Tokens of the shown line: a run of ASCII letters and digits, else one character.static bool Latin(string c) => c.Length == 1 && c[0] < 128 && char.IsLetterOrDigit(c[0]);var tokens = new List<(int Lo, int Hi)>();for (int k = 0; k < a.Length;)@@ -282,7 +229,6 @@ public static class Correctionreturn n;}string Replacement() => string.Concat(b[start..(b.Length - (a.Length - end))]);- // A dropped word ("in now." → "in.") grows too, so neither side of the fix is empty.while (!Span().Any(char.IsLetterOrDigit) || Count(Span()) != 1 || Replacement().Length == 0){int before = tokens.FindLastIndex(t => t.Hi <= start), after = tokens.FindIndex(t => t.Lo >= end);diff --git a/windows/src/Cicada.Core/Ed25519.cs b/windows/src/Cicada.Core/Ed25519.csindex ee36341..838edc7 100644--- a/windows/src/Cicada.Core/Ed25519.cs+++ b/windows/src/Cicada.Core/Ed25519.cs@@ -3,11 +3,6 @@ using System.Security.Cryptography;namespace Cicada;-/// Ed25519 signatures (RFC 8032 §5.1), for the share service's device key. .NET 10 has no Ed25519-/// of its own (only inside composite ML-DSA) and Windows CNG can't sign with it, so this is the-/// RFC's reference algorithm over BigInteger with the built-in SHA-512, checked against the RFC's-/// test vectors. Not constant-time: the key only names this install to the share service (rate-/// limits, owning its shares), and anyone can make a new one, so a local timing attack gains nothing.public static class Ed25519{static readonly BigInteger P = BigInteger.Pow(2, 255) - 19;@@ -111,7 +106,6 @@ public static class Ed25519return Number(sha.GetHashAndReset()) % L;}- /// A new private key (the 32-byte seed RFC 8032 calls the secret key).public static byte[] NewKey() => RandomNumberGenerator.GetBytes(32);public static byte[] PublicKey(ReadOnlySpan<byte> seed) => Compress(Multiply(Expand(seed).a, G));diff --git a/windows/src/Cicada.Core/FolderExport.cs b/windows/src/Cicada.Core/FolderExport.csindex 32b4d14..4e2d596 100644--- a/windows/src/Cicada.Core/FolderExport.cs+++ b/windows/src/Cicada.Core/FolderExport.cs@@ -5,13 +5,8 @@ using System.Text.Json.Serialization;namespace Cicada;-/// 存到文件夹: the file a settled meeting becomes (docs/folder-export.md, the Mac's FolderExport.swift).-/// The name and frontmatter are a contract with the Mac and the other ports-/// (Tests/fixtures/folder-export); the body is 导出 Markdown's.public static class FolderExportFormat{- /// The record's own name: what the user called it, else the notes' title, else the imported- /// file's name. Never DisplayTitle, which is localized and carries a date.public static string Name(Session s){if (s.Renamed ?? !s.Title.StartsWith("会议 ", StringComparison.Ordinal)) return s.Title;@@ -20,14 +15,11 @@ public static class FolderExportFormatreturn "";}- /// A name every system accepts and a vault can link to: no path, wildcard or link characters,- /// at most 120 UTF-8 bytes (vaults sync between systems, so the union of their rules).public static string SafeName(string name){var spaced = new StringBuilder();foreach (var r in name.EnumerateRunes())spaced.Append(r.Value < 0x20 || (r.IsAscii && "/\\:*?\"<>|#^[]".Contains((char)r.Value)) ? " " : r.ToString());- // Runs of whitespace (any Unicode space, as Swift's isWhitespace) become one space.var joined = new StringBuilder();bool space = false;foreach (var r in spaced.ToString().EnumerateRunes())@@ -62,7 +54,6 @@ public static class FolderExportFormatreturn safe.Length == 0 ? date : $"{date} {safe}";}- /// `stem.md`, or `stem 2.md`, `stem 3.md`… when a name is taken.public static string FileName(string stem, Func<string, bool> taken){for (int n = 1; ; n++)@@ -72,7 +63,6 @@ public static class FolderExportFormat}}- /// A JSON-style double-quoted string, which YAML reads as is.public static string Quote(string s){var b = new StringBuilder("\"");@@ -92,11 +82,9 @@ public static class FolderExportFormatreturn b.Append('"').ToString();}- /// Joined with "\n" whatever the system: the bytes are the contract.public static string Frontmatter(Session s, TimeZoneInfo? zone = null){var ended = s.EndedAt ?? s.StartedAt;- // Language codes are ASCII, where ordinal order is code point order.var languages = s.Lines.Select(l => l.SrcLang).Distinct().OrderBy(x => x, StringComparer.Ordinal);var notes = s.Notes is not { IsEmpty: false } n ? "none" : n.Final ? "final" : "draft";string[] lines =@@ -121,14 +109,12 @@ public static class FolderExportFormatstatic DateTimeOffset Local(DateTimeOffset at, TimeZoneInfo? zone) => TimeZoneInfo.ConvertTime(at, zone ?? TimeZoneInfo.Local);- /// Local time with its offset ("+08:00", "+00:00" for UTC, never "Z"), whole seconds.static string Time(DateTimeOffset at, TimeZoneInfo? zone) => Local(at, zone).ToString("yyyy-MM-dd'T'HH:mm:sszzz", CultureInfo.InvariantCulture);// MARK: Paths (split on both separators: the tests run on the Mac, the app on Windows)static readonly char[] Separators = ['\\', '/'];- /// The same folder or one inside it, ignoring case as Windows does.public static bool Under(string path, string root){var p = path.TrimEnd(Separators);@@ -138,7 +124,6 @@ public static class FolderExportFormatreturn p.Length > r.Length && p.StartsWith(r, StringComparison.OrdinalIgnoreCase) && Separators.Contains(p[r.Length]);}- /// The folder a path is in ("D:" for a drive's top folder), or null at the top.public static string? Parent(string path){var p = path.TrimEnd(Separators);@@ -155,7 +140,6 @@ public static class FolderExportFormatreturn i < 0 ? p : p[(i + 1)..];}- /// "工作笔记 › Cicada": the folder and the one it is in, by `name` (Explorer's names in the app).public static string ShortPath(string folder, Func<string, string?>? name = null){string Named(string p) => name?.Invoke(p) is { Length: > 0 } n ? n : LastName(p) is { Length: > 0 } l ? l : p;@@ -164,7 +148,6 @@ public static class FolderExportFormat// MARK: Obsidian- /// Obsidian's vaults (its `obsidian.json`), the most recently opened first; only ones that exist.public static List<string> ObsidianVaults(string json, Func<string, bool>? exists = null){exists ??= Directory.Exists;@@ -182,7 +165,6 @@ public static class FolderExportFormatcatch (Exception) { return []; }}- /// %APPDATA%\obsidian\obsidian.json.public static List<string> ObsidianVaults(){var file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "obsidian", "obsidian.json");@@ -192,15 +174,12 @@ public static class FolderExportFormatpublic static string? Vault(string folder, IEnumerable<string>? vaults = null) => (vaults ?? ObsidianVaults()).FirstOrDefault(v => Under(folder, v));- /// Documents\Cicada (Documents may be OneDrive's; that syncs, which is the point).public static string DocumentsFolder => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Cicada");- /// The suggestion: a Cicada folder in the most recently opened vault, else Documents\Cicada.public static string DefaultFolder() => ObsidianVaults().FirstOrDefault() is { } v ? Path.Combine(v, "Cicada") : DocumentsFolder;// MARK: Controlled folder access- /// The folders Defender's 受控文件夹访问 protects by default (when it is on).public static List<string> ProtectedRoots(){Environment.SpecialFolder[] known =@@ -213,29 +192,19 @@ public static class FolderExportFormatreturn known.Select(Environment.GetFolderPath).Where(p => p.Length > 0).Distinct().ToList();}- /// Inside a folder controlled folder access protects: an access-denied error there is most likely- /// it, which Windows announces itself and Windows 安全中心 can allow. Elsewhere it is plain- /// file permissions. (The error is the same either way; this is the best guess there is.)public static bool Protected(string folder, IEnumerable<string>? roots = null) => (roots ?? ProtectedRoots()).Any(r => Under(folder, r));}-/// Writes settled meetings into the chosen folder and keeps the index of what it wrote. State-/// belongs to the UI thread (`Post`, as the Mac's main actor): the records are rendered there, and-/// the files are written one at a time, in order, on one background worker.public sealed class FolderExporter{public enum Kind { Denied, Missing, Failed }- /// Denied: no permission (controlled folder access, or the folder's own permissions).- /// Missing: the folder, or the drive it was on, is gone.public sealed record Problem(Kind Kind, string? Message = null);public sealed class Index{[JsonPropertyName("folder")] public string Folder { get; set; } = "";- /// Record id → the file name Cicada wrote.[JsonPropertyName("files")] public Dictionary<string, string> Files { get; set; } = [];- /// Records waiting to be written.[JsonPropertyName("pending")] public List<string> Pending { get; set; } = [];[JsonPropertyName("lastFile")] public string? LastFile { get; set; }[JsonPropertyName("lastAt")] public DateTimeOffset? LastAt { get; set; }@@ -246,30 +215,19 @@ public sealed class FolderExporterreadonly string indexPath;readonly Timer timer;bool scheduledFromMeeting;- /// The one worker: each job starts when the one before it ends.Task worker = Task.CompletedTask;readonly object workerGate = new();- /// A flush is out on the worker: another waits for it (`again`), or a record still pending- /// would be rendered twice and its second copy find the first's file "taken".bool writing, again, againFromMeeting;- /// Told about this problem already (cleared once a write works).bool notified;public Index State { get; private set; } = new();public Problem? Trouble { get; private set; }- /// Checking a newly chosen folder.public bool Checking { get; private set; }- /// Runs on the UI thread (the app's dispatcher; inline in tests).public Action<Action> Post { get; set; } = a => a();- /// The meeting being listened to: never written while it runs.public Func<string?> LiveId { get; set; } = () => null;- /// The meeting's final notes pass is running or waiting.public Func<string, bool> Settling { get; set; } = _ => false;- /// Denied after a meeting, outside the folders controlled folder access protects (inside them- /// Windows shows its own notification): the app's one notification.public Action? NotifyDenied { get; set; }- /// How long a change waits for the next before writing (2 s; tests shorten it).public TimeSpan Delay { get; set; } = TimeSpan.FromSeconds(2);public event Action? Changed;@@ -291,15 +249,12 @@ public sealed class FolderExporterpublic bool IsPending(string id) => On && State.Pending.Contains(id);- /// Ended, not being imported, with something said.public bool Ready(Session s) => s.EndedAt is not null && s.Importing != true && s.Lines.Count > 0 && s.Id != LiveId();- /// Settled records not written to this folder yet.public List<Session> Unwritten => store.All().Where(s => Ready(s) && !State.Files.ContainsKey(s.Id) && !State.Pending.Contains(s.Id)).ToList();// MARK: Triggers- /// A meeting ended: write it once it is settled.public void Ended(string id){if (!On) return;@@ -308,7 +263,6 @@ public sealed class FolderExporterSchedule();}- /// A record was saved: rewrite it if it was written, or write it if it is waiting.public void Saved(string id){if (!On || !(State.Files.ContainsKey(id) || State.Pending.Contains(id))) return;@@ -316,10 +270,8 @@ public sealed class FolderExporterSchedule();}- /// The final notes pass for a meeting is over (written, failed, no key, nothing to do).public void Settled(string id) { if (On && State.Pending.Contains(id)) Schedule(); }- /// 也存一份: every settled record not written yet. Never notifies.public void WriteAll(){if (!On) return;@@ -328,14 +280,12 @@ public sealed class FolderExporterFlush(fromMeeting: false);}- /// At launch and when the app comes forward: try what is still waiting.public void Retry(){if (!On || State.Pending.Count == 0) return;Schedule(TimeSpan.FromMilliseconds(500), fromMeeting: false);}- /// The record was deleted in Cicada; its file stays.public void Deleted(string id){State.Files.Remove(id);@@ -346,8 +296,6 @@ public sealed class FolderExporter// MARK: Choosing the folder- /// A new folder (or the same one again after a fix): start its index, and write a file there at- /// once so a problem shows while settings is open, not when a meeting ends.public void Choose(string folder){settings.ExportFolder = folder;@@ -393,7 +341,6 @@ public sealed class FolderExporterlock (workerGate) worker = worker.ContinueWith(_ => work(), TaskScheduler.Default);}- /// Tests: until nothing is waiting on the worker.public async Task Idle(){while (true)@@ -414,7 +361,6 @@ public sealed class FolderExporterpublic sealed record Stopped(Problem Problem) : Outcome;}- /// Renders what is settled here, on the UI thread; writes it on the worker.void Flush(bool fromMeeting){if (!On || Folder is not { } folder) return;@@ -462,8 +408,6 @@ public sealed class FolderExporterTrouble = stopped;Log.Debug($"folder export: {outcomes.Count(o => o is Outcome.Wrote)} written, {outcomes.Count(o => o is Outcome.Unchanged)} unchanged{(stopped is null ? "" : $", stopped: {stopped.Kind}")}");if (stopped is null) notified = false;- // Told once the meeting has settled (its Settled flush comes back here): the tray shows one- // notification at a time, and 纪要整理好了 a second later would replace this one.if (stopped?.Kind == Kind.Denied && fromMeeting && !notified && !State.Pending.Any(Settling)){notified = true;@@ -482,14 +426,12 @@ public sealed class FolderExporterstatic bool Same(string? a, string? b) => a is not null && b is not null && string.Equals(a, b, StringComparison.OrdinalIgnoreCase);- /// On the worker. Stops at the first problem: the rest would fail the same way.static List<Outcome> Write(List<Job> jobs, string folder, Dictionary<string, string> ours){if (Ensure(folder) is { } p) return [new Outcome.Stopped(p)];var output = new List<Outcome>();foreach (var job in jobs){- // Windows names ignore case: "周会.md" and "周会.MD" are one file.var mine = new HashSet<string>(ours.Where(o => o.Key != job.Id).Select(o => o.Value), StringComparer.OrdinalIgnoreCase);var name = FolderExportFormat.FileName(job.Stem, candidate =>{@@ -501,7 +443,7 @@ public sealed class FolderExporterif (Same(name, job.Old)){try { if (File.Exists(path) && File.ReadAllText(path) == job.Text) { output.Add(new Outcome.Unchanged(job.Id)); continue; } }- catch (Exception) { } // unreadable: written again below, which says what is wrong+ catch (Exception) { }}try { WriteAtomically(path, job.Text); }catch (Exception e)@@ -509,7 +451,6 @@ public sealed class FolderExporteroutput.Add(new Outcome.Stopped(Classify(e, folder)));return output;}- // Renamed: the old file goes, only if it is the one Cicada wrote.if (job.Old is { } old && !Same(old, name)) try { File.Delete(Path.Combine(folder, old)); } catch (Exception) { }ours[job.Id] = name;output.Add(new Outcome.Wrote(job.Id, name));@@ -517,8 +458,6 @@ public sealed class FolderExporterreturn output;}- /// A hidden temporary file in the same folder, then moved over the old one: a vault or a sync- /// client never sees half a file.static void WriteAtomically(string path, string text){var tmp = Path.Combine(Path.GetDirectoryName(path)!, $".cicada-{Guid.NewGuid():N}.tmp");@@ -534,7 +473,6 @@ public sealed class FolderExporter}}- /// The folder exists, or is made when only it is missing (never on a drive that isn't there).static Problem? Ensure(string folder){if (Directory.Exists(folder)) return null;@@ -543,7 +481,6 @@ public sealed class FolderExportercatch (Exception e) { return Classify(e, folder); }}- /// Writes and removes a hidden file: the check after choosing a folder.public static Problem? Probe(string folder){if (Ensure(folder) is { } p) return p;@@ -557,8 +494,6 @@ public sealed class FolderExportercatch (Exception e) { return Classify(e, folder); }}- /// Access denied is the same error whether controlled folder access or the folder's permissions- /// said no. A file held open by a sync client is an IOException: just "not saved", tried again.static Problem Classify(Exception e, string folder){if (e is UnauthorizedAccessException) return new Problem(Kind.Denied);diff --git a/windows/src/Cicada.Core/Hybrid.cs b/windows/src/Cicada.Core/Hybrid.csindex d9c9dc1..9064500 100644--- a/windows/src/Cicada.Core/Hybrid.cs+++ b/windows/src/Cicada.Core/Hybrid.cs@@ -1,52 +1,28 @@namespace Cicada;-// 电脑和会议室: the room side's echo handling, and how its lines are shown (RoomMic.swift,-// EchoMatch.swift, RecordList.swift).--/// 打开麦克风 while the computer plays a meeting: the room mic hears the remote voices again from-/// the speakers (EchoGate in RoomMic.swift, same rules). The room mic hears silence while the-/// computer plays speech, until `Hang` after it, but only when that is needed and only for speech:-///-/// - Echo is measured: the room mic's loud end while the computer is loud over its floor while the-/// computer is quiet. Headphones or a meeting mic leave it where it was, and then nothing is-/// silenced, so people at the table are heard over a remote speaker too. Until there is enough-/// to tell (and whenever it is unclear) the speakers are taken to echo.-/// - Music isn't speech: a loud stretch the computer's side has recognized no words in for `Music`-/// seconds stops closing the gate. Words close it again. Longer than the Mac's 4 s: here words-/// only come back after a whole segment has gone to the service.public sealed class EchoGate(Func<double>? clock = null){public const double Hang = 0.4;- /// Seconds of loud audio without words before it counts as music.public const double Music = 20;- /// A pause this long ends a loud stretch.public const double StretchGap = 1.5;- /// Computer audio this recent makes a room block "during"; this long ago, "the computer is quiet".public const double During = 0.15, QuietAfter = 1.0;- /// The ratio at or over which there is echo, and under which there is none.public const double EchoRatio = 3, ClearRatio = 2;- /// Seconds of each that a decision needs, and how much is kept.public const double Enough = 3, Window = 20;- /// Seconds; a monotonic clock shared with EchoMatch's times.public readonly Func<double> Clock = clock ?? (() => Environment.TickCount64 / 1000.0);readonly object gate = new();double until = double.NegativeInfinity, lastLoud = double.NegativeInfinity, stretchStart = double.NegativeInfinity, lastWords = double.NegativeInfinity;readonly List<(double t, double rms, double s)> during = [], quiet = [];bool echo = true;- /// Debug (`roomEchoSim`): pretend the measurement says this.public bool? Forced { get; set; }- /// When the computer last played something loud.public double LastLoud { get { lock (gate) return lastLoud; } }- /// Whether the speakers reach the room mic, as last measured.public bool Echo { get { lock (gate) return Forced ?? echo; } }public bool PlayingMusic { get { var now = Clock(); lock (gate) return MusicLocked(now); } }public bool Closed { get { var now = Clock(); lock (gate) return now < until; } }bool MusicLocked(double now) => now - lastLoud <= StretchGap && now - stretchStart >= Music && lastWords < now - Music;- /// A loud buffer of the computer's audio.public void Hold(){var now = Clock();@@ -59,10 +35,8 @@ public sealed class EchoGate(Func<double>? clock = null)}}- /// The computer's side recognized words.public void HeardWords() { var now = Clock(); lock (gate) lastWords = now; }- /// A buffer of what the room mic heard, before any silencing.public void RoomLevel(double rms, double seconds){var now = Clock();@@ -81,9 +55,6 @@ public sealed class EchoGate(Func<double>? clock = null)}}- /// The room mic's loud end (a fifth of it louder) while the computer is loud over its floor (the- /// quietest fifth) while it is quiet, or null without `Enough` of both. People at the table- /// talking over the computer raise it too: that errs on the side of echo.public static double? Ratio(IEnumerable<(double rms, double s)> during, IEnumerable<(double rms, double s)> quiet){var d = during.ToList(); var q = quiet.ToList();@@ -93,19 +64,12 @@ public sealed class EchoGate(Func<double>? clock = null)}}-/// 电脑和会议室's last line of defence against hearing a remote sentence twice: once from the-/// computer's audio, once more from the speakers into the room mic. A room line made mostly of-/// what the computer played around the same time is dropped (EchoMatch.swift, same numbers).public static class EchoMatch{- /// Times in seconds on EchoGate's clock.public sealed record Heard(string Text, double Start, double End);- /// Seconds around the room line where the computer's lines count.public const double Window = 3.0;- /// How long a room line waits for the computer's line it may echo.public const double Hold = 2.5;- /// Share of the room line found in the computer's lines that makes it an echo.public const double Contained = 0.6;public static bool IsEcho(Heard room, IEnumerable<Heard> online)@@ -115,14 +79,12 @@ public static class EchoMatchvar r = Units(room.Text);if (r.Count == 0) return false;var o = near.Select(n => Units(n.Text)).ToList();- // A word or two ("OK", "对"): the very same words near it.if (r.Count <= 2) return o.Any(x => x.SequenceEqual(r));var mine = Pairs(r).ToHashSet();var theirs = o.SelectMany(Pairs).ToHashSet();return (double)mine.Count(theirs.Contains) / mine.Count >= Contained;}- /// Lower-case words, each CJK character on its own; punctuation and spacing don't count.public static List<string> Units(string text){var output = new List<string>();@@ -146,7 +108,6 @@ public static class EchoMatchstatic bool Cjk(int v) => v is >= 0x3040 and <= 0x30FF or >= 0x3400 and <= 0x4DBF or >= 0x4E00 and <= 0x9FFF or >= 0xAC00 and <= 0xD7AF or >= 0xF900 and <= 0xFAFF;}-/// The computer's recent lines, for the room side to check its own against.public sealed class EchoFilter(EchoGate gate){public readonly EchoGate Gate = gate;@@ -163,14 +124,11 @@ public sealed class EchoFilter(EchoGate gate)public bool IsEcho(EchoMatch.Heard room) { lock (online) return EchoMatch.IsEcho(room, online); }- /// The computer played nothing loud around this room line: there is nothing for it to echo.public bool Quiet(EchoMatch.Heard room) => Gate.LastLoud < room.Start - EchoMatch.Window;}-/// A meeting that heard both: each of the other side's lines says where (RecordList.swift).public static class Places{- /// The room mic and the computer's audio both brought in the other side's lines.public static bool HeardBoth(IEnumerable<TranscriptLine> lines){bool room = false, computer = false;@@ -183,7 +141,6 @@ public static class Placesreturn false;}- /// The other side's lines where the place changes from the line before: their label shows again.public static HashSet<string> Starts(IEnumerable<TranscriptLine> lines){var output = new HashSet<string>();diff --git a/windows/src/Cicada.Core/Json.cs b/windows/src/Cicada.Core/Json.csindex 0637e7f..09593b8 100644--- a/windows/src/Cicada.Core/Json.cs+++ b/windows/src/Cicada.Core/Json.cs@@ -5,9 +5,6 @@ using System.Text.Json.Serialization;namespace Cicada;-/// How records are written: what Swift's JSONEncoder (pretty, sorted keys, ISO-8601) produces, as-/// far as the Mac app's decoder cares. Whitespace differs ("key": vs "key" :); the values and keys-/// don't, and Chinese stays readable rather than \u-escaped.public static class Json{public static readonly JsonSerializerOptions Options = Make(indented: true);@@ -30,7 +27,6 @@ public static class Jsonpublic static string Write<T>(T value) => JsonSerializer.Serialize(value, Options);public static T? Read<T>(string text) => JsonSerializer.Deserialize<T>(text, Options);- /// Whole seconds, UTC, "Z": what `.iso8601` writes (and expects back).sealed class Iso8601 : JsonConverter<DateTimeOffset>{public override DateTimeOffset Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options) =>diff --git a/windows/src/Cicada.Core/Ling.cs b/windows/src/Cicada.Core/Ling.csindex 6659ce7..2fc5428 100644--- a/windows/src/Cicada.Core/Ling.cs+++ b/windows/src/Cicada.Core/Ling.cs@@ -6,8 +6,6 @@ using System.Text.Json.Nodes;namespace Cicada;-/// Turns the key into bytes on disk and back. Windows uses DPAPI (the current user only); the-/// plain one is for the Mac-side CLI and tests.public interface IKeyProtector{string Tag { get; }@@ -22,11 +20,6 @@ public sealed class PlainProtector : IKeyProtectorpublic byte[] Unprotect(byte[] data) => data;}-/// 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){readonly Func<string> service = service ?? (() => "ling");@@ -37,7 +30,6 @@ public sealed class AIKey(IKeyProtector protector, string? file = null, Func<strpublic string? Read() => ReadAt(File_);- /// Another service's saved key, without switching to it (改用 Ling asks whether Ling has one).public string? Read(string service) => file is null ? ReadAt(Paths.KeyFile(service)) : null;string? ReadAt(string path)@@ -63,7 +55,6 @@ public sealed class AIKey(IKeyProtector protector, string? file = null, Func<strpublic bool Save(string key) => SaveAt(File_, key);- /// Another key file of this user's (a custom service's notes server, `custom-notes`).public bool Save(string key, string service) => file is null && SaveAt(Paths.KeyFile(service), key);bool SaveAt(string path, string key)@@ -89,7 +80,6 @@ public sealed class AIKey(IKeyProtector protector, string? file = null, Func<str}}- /// Removes the key of the service in use only.public void Remove() => RemoveAt(File_);public void Remove(string service) { if (file is null) RemoveAt(Paths.KeyFile(service)); }@@ -103,10 +93,8 @@ public sealed class AIKey(IKeyProtector protector, string? file = null, Func<str}}- /// 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..];}@@ -118,70 +106,47 @@ public sealed class LingException(LingException.Kind kind, int status = 0, doubl{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;- /// Seconds the service asked us to wait (a 429's Retry-After), when it said.public double? RetryAfter { get; } = retryAfter;}-/// Time for LingClient's start gate; tests hand in one that moves on by itself.public class GateClock{public virtual DateTime UtcNow => DateTime.UtcNow;public virtual Task Delay(TimeSpan wait) => Task.Delay(wait);}-/// 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(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;readonly Func<AIConfig> config;- /// The short form older callers read (Usable, the early stop of every request): derived from Health.public KeyState KeyState { get; private set; }public DateTimeOffset? RateLimitedAt { get; private set; }- /// Step by step, where the service stands (AICheck). Swapped whole: requests report from worker threads.public AICheck Health { get { lock (healthGate) return health; } }AICheck health = new();readonly object healthGate = new();int checking;- /// Which check is the newest: a check that started before a change (a model switched while- /// one ran) finishes into nothing, so an old answer never lands over the new setting.int generation;- /// How long the text model took in the last check that reached it.public double? Seconds => Health[AICheck.StepId.Text].Seconds;- /// Whether the hear model takes audio: null until a check or a meeting found out.public bool? Hears => Health[AICheck.StepId.Hear] switch{{ Kind: AICheck.Kind.Ok or AICheck.Kind.Busy } => true,{ Kind: AICheck.Kind.Fail, Why: AICheck.Reason.Deaf } => false,_ => null,};- /// The last time the room voice spoke (or failed to) through this service.public (bool Ok, DateTimeOffset At)? LastVoice { get; private set; }- /// The service's models from `/models`, recommended first: all that chat, and those that hear.public IReadOnlyList<string> TextCatalog { get; private set; } = [];public IReadOnlyList<string> HearCatalog { get; private set; } = [];- /// Every model id the service lists, and those it says take audio: whether the chosen ones still exist.HashSet<string>? listed, listedHearing;- /// Reads this computer's proxy settings to word the "can't reach" hint (never used to connect).public Func<Task<AICheck.ProxyHint>>? ProxyHint { get; set; }- /// Debug pipe only: the next checks end this way (screenshots of every state).public AICheck.Reason? SimulateCheck { get; set; }- /// Debug pipe only: report this OpenRouter balance instead of the real one.public double? SimulateBalance { get; set; }public event Action? Changed;@@ -191,7 +156,7 @@ public sealed class LingClientthis.clock = clock ?? new GateClock();this.config = config ?? (() => AIConfig.Default);http = handler is null ? new HttpClient() : new HttpClient(handler);- http.Timeout = Timeout.InfiniteTimeSpan; // per request below+ http.Timeout = Timeout.InfiniteTimeSpan;http.DefaultRequestHeaders.UserAgent.ParseAdd("Cicada-Windows/0.1");KeyState = CurrentKey() is null ? KeyState.None : KeyState.Unchecked;}@@ -199,7 +164,6 @@ public sealed class LingClientpublic AIConfig Config => config();public AIProvider Provider => Config.Provider;- /// The key for the service in use. A custom service on this computer or the local network may need none: "".public string? CurrentKey(){var c = Config;@@ -210,36 +174,23 @@ public sealed class LingClientpublic bool HasKey => CurrentKey() is not null;- /// The key file of a custom service's notes server (另一个服务), as on the Mac.public const string NotesKeyName = "custom-notes";- /// The key notes are sent with: with 另一个服务, their own key file if there is one, else the- /// translation key ("不填就用上面的 key").public string? NotesKey() => Config.NotesOwnService && key.Read(NotesKeyName) is { } own ? own : CurrentKey();- /// Notes have a key file of their own (另一个服务 only).public bool NotesHasOwnKey => Config.NotesOwnService && key.Read(NotesKeyName) is not null;- /// Notes' own key (另一个服务); the caller checks again (Controller.AIChanged).public bool SaveNotesKey(string raw) => raw.Trim().Length > 0 && key.Save(raw.Trim(), NotesKeyName);- /// Notes go back to the translation key.public void RemoveNotesKey() => key.Remove(NotesKeyName);- /// Notes' own server's text models from its `/models` (empty while notes share translation's address).public IReadOnlyList<string> NotesCatalog { get; private set; } = [];public bool Usable => HasKey && KeyState != KeyState.Invalid;- /// Voices in the room from this service (else Windows' own voice speaks).public bool Speaks => Usable && Config.HasVoices;- /// The user's own voice: only Ling clones.public bool Clones => Speaks && Config.Provider.Clones;- /// Listening and 同声传译 can work: the hear model wasn't found to refuse audio.public bool CanHear => Usable && Hears != false && Config.HearModel.Length > 0;- /// The addresses that refused `chat_template_kwargs` once (a custom service's text and hear- /// models may be separate servers): left out there until settings change.readonly System.Collections.Concurrent.ConcurrentDictionary<string, bool> noTemplateKwargs = new();- /// The key, the service or its models changed: forget what the last check found.public void KeyChanged(){key.Reload();@@ -253,28 +204,17 @@ public sealed class LingClientChanged?.Invoke();}- /// What messages call the service ("这个服务" for a custom address) and its host.public string ServiceName => Config.Provider.Id == "custom" ? Strings.L("这个服务") : Config.Name;public string ServiceHost => Host(Config.Base);- /// Who a status line names: a custom service by its address, which says more than 这个服务- /// and reads right in "The … key doesn't work".public string ServiceLabel => Config.Provider.Id == "custom" && ServiceHost.Length > 0 ? ServiceHost : ServiceName;- /// Where the hear model is asked (a custom service's own address for it, else the service's).public string HearHost => Host(Config.HearBase ?? Config.Base);static string Host(string? b) => b is not null && Uri.TryCreate(b, UriKind.Absolute, out var u) ? u.Host : "";- /// The hear model in messages; the service when none is named (a custom one not filled in).public string HearName => Config.HearModel.Length > 0 ? Config.HearModel : ServiceName;- /// The cheapest requests that prove each step: Ling's tiny model, else one token from the text- /// model; the others' hear model must take audio (half a second of silence), a custom service- /// must return JSON (the notes need it), and the model list must still have both models.- /// OpenRouter also tells the balance. Ling's Ming isn't asked: a meeting records how it hears.public async Task<(KeyState state, double seconds)> Check(){var started = DateTime.UtcNow;var c = Config;- // Counted before anything else: a slower check still running (a custom service that thinks- // for seconds) must not land on top of what this one finds, even "no key".var gen = Interlocked.Increment(ref generation);if (CurrentKey() is not { } k){@@ -317,22 +257,18 @@ public sealed class LingClientelse if (c.Provider.Id != "custom") await Chat("Reply with OK.", "Reply.", Priority.Speak, maxTokens: 5, timeout: 20);else{- // A real sentence, the way a meeting translates: one token says nothing about a- // model that thinks for six seconds before every answer.JsonNode? root = null;try{await Chat("Translate the text into Simplified Chinese. Reply with the translation only.\n\nWe will ship the new version on Friday after the design review.","Translate.", Priority.Speak, maxTokens: 120, timeout: 30, reply: n => root = n);}- // A reasoning parser that put the whole answer in reasoning_content: it answered, by thinking.catch (LingException e) when (e.Failure == LingException.Kind.Parse && AIConfig.Thought(root)) { }r.Translate = new AICheck.Speed(Since(t), AIConfig.Thought(root));}r.Pass(AICheck.StepId.Text, Since(t));if (c.NotesApart){- // Notes at their own model or server: their failure is theirs, translation goes on.r.Notes = AICheck.State.Running;lock (healthGate) { if (gen == generation) health = r.Clone(); }Changed?.Invoke();@@ -344,8 +280,6 @@ public sealed class LingClienttry { await Chat(ask, "Reply.", Priority.Speak, json: true, maxTokens: 20, timeout: 30, jsonFallback: false); }catch (LingException e) when (e.Failure == LingException.Kind.Http){- // JSON mode refused (some hosts of a model do): meetings then ask without it, so- // what counts is whether the model still answers with a JSON object.string? said = null;try { said = await Chat(ask, "Reply.", Priority.Speak, maxTokens: 20, timeout: 30); } catch (LingException) { }if (!AnswersJSON(said)) r.Fail(AICheck.StepId.Text, AICheck.Reason.NoJSON, e.Status);@@ -354,7 +288,6 @@ public sealed class LingClient}catch (LingException e) { Failed(e, AICheck.StepId.Text); }catch (Exception) { r.Fail(AICheck.StepId.Reach, AICheck.Reason.Unreachable); }- // The address and the key work: hearing is its own question (the text model may be the one gone).if (c.IsLing || r.Failure is { Step: AICheck.StepId.Reach or AICheck.StepId.Key }) return;if (c.HearModel.Length == 0) r.Fail(AICheck.StepId.Hear, AICheck.Reason.Deaf);else if (c.HearBase is null) r.Fail(AICheck.StepId.Hear, AICheck.Reason.BadAddress);@@ -367,19 +300,14 @@ public sealed class LingClientmodel: c.HearModel, audio: Wav.Bytes(new short[8000]));r.Pass(AICheck.StepId.Hear, Since(t));}- // A made-up answer to silence still came from a model that took the audio.catch (LingException e) when (e.Failure == LingException.Kind.Hijacked) { r.Pass(AICheck.StepId.Hear, Since(t)); }catch (LingException e) { Failed(e, AICheck.StepId.Hear); }catch (Exception) { }}await FetchCatalog();- // A model the service no longer lists fails here, before a meeting finds out. On a custom- // service, one a real sentence just went through exists whatever the list says (an alias,- // a name typed by hand).var proven = c.Provider.Id == "custom" && r.Translate is not null;if (listed is { } ids && c.TextModel.Length > 0 && !proven && r[AICheck.StepId.Text].Kind != AICheck.Kind.Fail && !ids.Contains(c.TextModel))r.Fail(AICheck.StepId.Text, AICheck.Reason.NoModel);- // The list is the text address's: it says nothing about a hear model served elsewhere.if (listedHearing is { } hearing && !c.HearElsewhere && c.HearModel.Length > 0 && r[AICheck.StepId.Hear].Kind != AICheck.Kind.Fail && !hearing.Contains(c.HearModel))r.Fail(AICheck.StepId.Hear, AICheck.Reason.Deaf);if (c.Provider.Id == "openrouter") r.Balance = AICheck.BalanceFrom(await GetText("key", k), await GetText("credits", k));@@ -397,7 +325,6 @@ public sealed class LingClientChanged?.Invoke();}- /// A made-up result for `reason` (debug screenshots of every state).static AICheck Simulated(AICheck.Reason reason){var r = new AICheck();@@ -415,8 +342,6 @@ public sealed class LingClientreturn r;}- /// The short form older callers read: a refused key stops every request; a hear model that- /// can't hear leaves the key good (notes and translation work).void SyncKeyState(){var h = Health;@@ -428,15 +353,11 @@ public sealed class LingClient: KeyState.Ok;}- /// A real request (hearing, notes, translation) came back: keep the steps current without a- /// check. One server error in a meeting isn't worth repainting the settings for, nor is the- /// same good result again.void Observe(LingException? failure, double seconds, bool audio, bool notes = false){if (!HasKey || Volatile.Read(ref checking) > 0 || SimulateCheck is not null) return;if (notes){- // Notes at their own model or server: theirs alone, translation's steps (and KeyState) are untouched.AICheck.State now;if (failure is not null){@@ -487,7 +408,6 @@ public sealed class LingClient});}- /// The network changed while the service was unreachable: look again (never on a timer).public void NetworkChanged(){var h = Health;@@ -496,8 +416,6 @@ public sealed class LingClient_ = Check();}- /// One click on 换成推荐的: the model that was wrong is the service's first recommended one now.- /// Null when there is none (a custom service), or the chosen one is it already.public string? Recommended(AICheck.StepId step){var c = Config;@@ -505,7 +423,6 @@ public sealed class LingClientreturn models.FirstOrDefault()?.Id is { } id && id != current ? id : null;}- /// One GET on the service's API (OpenRouter's key info and credits); null when it fails.async Task<string?> GetText(string path, string k, string? at = null){if ((at ?? Config.Base) is not { } b) return null;@@ -520,8 +437,6 @@ public sealed class LingClientcatch (Exception e) when (e is HttpRequestException or OperationCanceledException) { return null; }}- /// The service's models, for the model menus. Quietly just the recommended ones when the- /// service has no `/models`.public async Task FetchCatalog(){var c = Config;@@ -535,9 +450,6 @@ public sealed class LingClientChanged?.Invoke();}- /// Notes' own model or server (AIConfig.NotesApart): one JSON request the way a meeting's notes- /// ask, sent straight (no gate, no retries: a check), then, at another address, its model list- /// for the menu.async Task<AICheck.State> CheckNotes(AIConfig config){if (config.NotesBadAddress) return AICheck.State.Fail(AICheck.Reason.BadAddress);@@ -563,8 +475,6 @@ public sealed class LingClient}catch (LingException e) when (e.Failure == LingException.Kind.Http && e.Status is 400 or 422){- // JSON mode refused (some hosts of a model do): meetings then ask without it, so what- // counts is whether the model still answers with a JSON object.body.Remove("response_format");string? said = null;try { said = Str((await PostChat(url, body, b, k, 60, default))["choices"]?[0]?["message"]?["content"]); } catch (LingException) { }@@ -580,7 +490,6 @@ public sealed class LingClientreturn result;}- /// Notes' own address's text models, for its menu. Quietly empty when it has no `/models`.public async Task FetchNotesCatalog(){var c = Config;@@ -592,29 +501,15 @@ public sealed class LingClientChanged?.Invoke();}- /// One chat completion. `content` goes in the system message, `instruction` is the fixed user- /// message, `audio` (a WAV) goes before it for the hear model. Notes and heard audio retry 429s- /// with backoff (RetryWaits); the rest fail fast so the caller can fall back. `model` defaults to- /// the service's text model. `patient` (the final notes) keeps retrying for about a minute. A 429- /// holds every request start for a while (RateLimited), and a retry keeps its place in the- /// queue, so lines stay in order. Audio goes to the hear model's address (a custom service's own- /// one for it). `reply` sees the whole reply before its text is read (the check's thinking test).- /// A JSON request refused with 400 is asked again without JSON mode unless `jsonFallback` is- /// off (the check asks again itself). Notes (`notes`, by default the Notes priority) go to a- /// custom service's notes model, address and key when they have their own (AIConfig.ForNotes);- /// a live line's corrections ride at Notes priority but are translation's, as on the Mac.public async Task<string> Chat(string content, string instruction, Priority priority, bool json = false,int maxTokens = 1024, double timeout = 30, string? model = null, byte[]? audio = null, bool patient = false,CancellationToken cancel = default, Action<JsonNode>? reply = null, bool jsonFallback = true, bool? notes = null){var all = Config;var notesSide = (notes ?? priority == Priority.Notes) && audio is null && all.NotesApart;- // 另一个服务 at an address that can't be used: never fall back to translation's server with- // the notes' key (the Mac does; the check already says the address is wrong).if (notesSide && all.NotesBadAddress) throw new LingException(LingException.Kind.NoKey);var c = notesSide ? all.ForNotes : all;var k = (notesSide ? NotesKey() : CurrentKey()) ?? throw new LingException(LingException.Kind.NoKey);- // A refused notes key stops notes only; a refused translation key stops everything else.if (notesSide ? Health.Notes?.Why is AICheck.Reason.InvalidKey or AICheck.Reason.MgmtKey : KeyState == KeyState.Invalid)throw new LingException(LingException.Kind.InvalidKey);var b = audio is null ? c.Base : c.Provider.Id == "custom" ? c.HearBase : c.HearBase ?? c.Base;@@ -639,7 +534,6 @@ public sealed class LingClientfor (int attempt = 1; ; attempt++){var queued = DateTime.UtcNow;- // One that wouldn't retry fails at once while the service is cooling down: its caller falls back.ticket = await Acquire(g, priority, c.Provider.Spacing, cancel, ticket, failIfPaused: waits.Length == 0);var started = DateTime.UtcNow;if ((started - queued).TotalSeconds > 1) Log.Debug($"ling: {priority} waited {(started - queued).TotalMilliseconds:F0} ms at the gate");@@ -649,8 +543,6 @@ public sealed class LingClienttry { root = await PostChat(url, body, b, k, timeout, cancel); }catch (LingException e) when (jsonFallback && e.Failure == LingException.Kind.Http && e.Status == 400 && body.ContainsKey("response_format")){- // Some hosts of a model refuse JSON mode (on OpenRouter, Novita for Ling 3.1 Flash)- // while the model answers JSON anyway: the prompt asks for it, the parsers find it.Log.Debug($"ling: {priority} JSON mode refused (400), asking again without it");body.Remove("response_format");root = await PostChat(url, body, b, k, timeout, cancel);@@ -660,7 +552,6 @@ public sealed class LingClientvar text = Str(choice?["message"]?["content"]) ?? throw new LingException(LingException.Kind.Parse);var finish = Str(choice?["finish_reason"]);var trimmed = text.Trim();- // 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");@@ -683,25 +574,12 @@ public sealed class LingClient}}- /// Seconds before each retry of a 429 (Ling.swift › retryWaits). Notes can wait; the rest fail- /// fast, except heard audio. A meeting's: on Windows a lost reply loses the words (on the Mac- /// recognition is local and only the translation is lost), and Ling's 429s came in runs of up to- /// ~10 s (two in a row lost about 2 lines a minute with one retry, 2026-11), so it keeps at it for- /// about 15 s. What the user says (Speak) retries once: late into the room is worse than "try again".- /// `patient` (the final notes) keeps at it for about a minute: a model limited upstream- /// (OpenRouter's Ling 3.1 by DeepInfra, 2026-11) came back after ~15 s, and a meeting left- /// without its notes is worse than notes a little late.public static double[] RetryWaits(Priority priority, bool audio = false, bool patient = false) =>priority == Priority.Notes ? (patient ? [1, 2, 4, 8, 16, 30] : [1, 2, 4]): audio ? (priority == Priority.Translate ? [1, 2, 4, 8] : [1]) : [];- /// Longest Retry-After worth waiting for; longer is an outage, not a busy moment.public const double MaxPause = 30;- /// After a 429: no request starts for `backoff` seconds, or as long as the service asked- /// (Retry-After; Ling sends none), plus a little jitter. The queue waits at the gate instead of- /// each request spending its retries on the same limit. Null when that is over MaxPause (the- /// gate still holds for MaxPause).double? RateLimited(StartGate g, double backoff, double? retryAfter){var wait = Math.Max(backoff, retryAfter ?? 0) + Random.Shared.NextDouble() * 0.5;@@ -713,19 +591,11 @@ public sealed class LingClientreturn wait <= MaxPause ? wait : null;}- /// A Retry-After header in seconds: a delay or a date. Null when there is none.public static double? RetryAfterSeconds(System.Net.Http.Headers.RetryConditionHeaderValue? value, DateTimeOffset now) =>value?.Delta is { } d ? Math.Max(0, d.TotalSeconds): value?.Date is { } at ? Math.Max(0, (at - now).TotalSeconds): 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>}`.- /// `reference` (Ling only): a voice cloned from the user's recording (a WAV data URI and what it- /// says) instead of `voice`; the whole clip goes with every sentence, so it waits longer.public async IAsyncEnumerable<byte[]> Speech(string text, string? voice, string? languageId = null,(string Audio, string Text)? reference = null,[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancel = default)@@ -791,9 +661,6 @@ public sealed class LingClient}else{- // Raw PCM: handed on in 0.1 s pieces at 24 kHz, so playback starts early. A read can- // end mid-sample (OpenRouter's does): the odd byte waits for the next read, or every- // sample after it would be split across two pieces.var buffer = new byte[4800];int held = 0;while (true)@@ -815,8 +682,6 @@ public sealed class LingClient}}- /// The `/audio/speech` request (Ling.swift › speech): Ming's voice, or a clone of `reference`, on- /// Ling; elsewhere the configured speech model with one of its voices.public static JsonObject SpeechBody(AIConfig c, string text, string? voice, string? languageId, (string Audio, string Text)? reference = null){var body = new JsonObject { ["model"] = c.VoiceModel, ["input"] = text, ["response_format"] = "pcm" };@@ -829,7 +694,6 @@ public sealed class LingClient}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";@@ -837,14 +701,12 @@ public sealed class LingClientreturn body;}- /// The room voice spoke through this service, or failed and Windows spoke instead (现在能用的 says which).public void VoiceSpoke(bool ok){LastVoice = (ok, DateTimeOffset.Now);Changed?.Invoke();}- /// One SSE line of a voice stream: the PCM it carries, or `done` at the end.public static byte[]? SpeechChunk(string line, out bool done){done = false;@@ -859,7 +721,6 @@ public sealed class LingClientstatic 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;@@ -873,10 +734,6 @@ public sealed class LingClientreturn [];}- /// A chat completion. A strict gateway answers 400 or 422 to a field it doesn't know: asked- /// again without `chat_template_kwargs`, and not sent it again (to `b`) until settings change,- /// but only when that request goes through (Ling.swift › postChat): a 400 for something else- /// (no JSON mode) must not turn thinking back on for every translation.async Task<JsonNode> PostChat(Uri url, JsonObject body, string b, string k, double timeout, CancellationToken cancel){try { return await Post(url, body.ToJsonString(), k, timeout, cancel); }@@ -893,7 +750,6 @@ public sealed class LingClient}}- /// A chat reply's text holds a JSON object (a fence or a sentence around it is fine).public static bool AnswersJSON(string? text){if (text is null) return false;@@ -924,7 +780,6 @@ public sealed class LingClientswitch (res.StatusCode){case HttpStatusCode.OK: break;- // Chat reports it to the check (Observe), which stops every request after it.case HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden: throw new LingException(LingException.Kind.InvalidKey);case HttpStatusCode.TooManyRequests:throw new LingException(LingException.Kind.RateLimited, 429, RetryAfterSeconds(res.Headers.RetryAfter, DateTimeOffset.UtcNow));@@ -942,14 +797,8 @@ public sealed class LingClient}}- // Start gate: request starts ≥ the service's spacing apart, the most urgent waiting one first,- // none while the server is cooling down after a 429. One per server (by host): notes or a hear- // model on another server don't wait behind translation, and a 429 there doesn't hold it back.-- /// Tests only: overrides the service's spacing.public static double? Spacing { get; set; }readonly GateClock clock;- /// Guards every StartGate and the shared ticket counter.readonly object gate = new();readonly Dictionary<string, StartGate> gates = [];long seq;@@ -963,7 +812,6 @@ public sealed class LingClientpublic double Spacing = 0.6;}- /// The gate of the server at `address` (its host; the service's when there is none).StartGate GateFor(string? address){var host = Host(address ?? Config.Base);@@ -974,8 +822,6 @@ public sealed class LingClient}}- /// Waits for this request's turn to start. `ticket` is a retry's first one, which keeps its- /// place ahead of requests queued after it. Returns the ticket.Task<long> Acquire(StartGate g, Priority priority, double serviceSpacing, CancellationToken cancel, long? ticket = null, bool failIfPaused = false){lock (gate)@@ -996,10 +842,8 @@ public sealed class LingClient}}- /// Close enough to go: a wait comes back a tick short (TimeSpan rounding).const double Slack = 0.001;- /// Seconds until the next start may go (gate held).static double Wait(StartGate g, DateTime now) => Math.Max(g.Spacing - (now - g.LastStart).TotalSeconds, (g.PausedUntil - now).TotalSeconds);async Task Pump(StartGate g)diff --git a/windows/src/Cicada.Core/ListenEngine.cs b/windows/src/Cicada.Core/ListenEngine.csindex 7c4890c..8b2ded1 100644--- a/windows/src/Cicada.Core/ListenEngine.cs+++ b/windows/src/Cicada.Core/ListenEngine.cs@@ -2,12 +2,6 @@ using System.Threading.Channels;namespace Cicada;-/// 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-/// still go through LingClient's gate, and lines are delivered in segment order.public sealed class ListenEngine{readonly LingClient ling;@@ -19,23 +13,16 @@ public sealed class ListenEngineIAudioSource? source;Channel<(short[] buf, double at)>? audio;- /// When this side began (Stopwatch ticks): with `offset`, the meeting's clock.long began;- /// 保存会议录音: the main side writes what it hears to the meeting's system.aac.IAudioWriter? recorder;- /// The main side's recording, which 电脑和会议室's room side adds itself into (`Join`).public RoomMix? Mix => recorder as RoomMix;- /// The room side: the main side's recording, where what the room mic hears goes too.RoomMix? roomMix;Task? worker;Segmenter? segmenter;readonly Dictionary<int, Heard?> done = [];readonly Dictionary<int, Segment> segments = [];- // 说话人识别: voiceprints are made alongside Ming's reply (order doesn't matter there), and- // grouped in line order when the line is recorded (it does there).readonly Dictionary<int, Task<float[]?>> prints = [];VoiceClusterer clusterer = new();- /// Set by the app: the voiceprint model, or null where there is none (the Mac CLI, tests).public IVoiceprint? Voiceprint { get; set; }readonly List<Task> inFlight = [];int nextToDeliver = 1, lineCount;@@ -46,26 +33,14 @@ public sealed class ListenEnginepublic bool Listening { get; private set; }public string? SessionId { get; private set; }- /// The meeting's language so far (null until Ming has heard something).public string? Spoken => hint;- /// 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 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; }- /// Stretches in a row the service answered with a 5xx; said from the third (ListenEngine.swift's- /// cloudFailures): one isn't worth a bar, but a meeting with no subtitles and no reason is worse.int serverErrors;public const int ServerErrorsShown = 3;public static bool IsServerError(LingException.Kind kind, int status) => kind == LingException.Kind.Http && status >= 500;- /// 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,- /// 415, 422: AICheck's deaf) is a settings problem, not the network; `hear` names it. A lost- /// connection needs nothing from the user: segments keep going out and pick up by themselves.public static (string? Title, string Body, bool Settings) Words(LingException.Kind kind, int status, string service, string? hear = null){var ling = service == "Ling";@@ -73,20 +48,16 @@ public sealed class ListenEnginereturn (Strings.LF("%@ 听不了声音。", hear ?? service), Strings.L("在 设置 › AI 服务 里换一个"), true);return kind switch{- // It answered, with an error (a gateway's 502): like busy, it passes by itself; not the network.LingException.Kind.Http when status >= 500 => (null, Strings.LF("%@ 暂时出错(HTTP %lld),稍后再试。", service, status), false),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),- // The service hears the meeting here, so the subtitles wait with the notes._ => (null, Strings.LF("字幕和纪要等 %@ 恢复 · 连上后自动继续", service), 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){var parts = kind.Split(' ');@@ -105,32 +76,20 @@ public sealed class ListenEnginepublic string Target => settings.TargetCode;- /// 会议室: what listening hears is a microphone (its speech line follows the room's noise).public bool Room { get; private set; }- /// 电脑和会议室's room side (the Mac's `.room` role): it adds to the main engine's meeting rather- /// than keeping one, with its own language and pauses; its lines say `via: "room"` and their ids- /// start at RoomIDs, so the two never share one.public bool RoomSide { get; }public const int RoomIDs = 1_000_000;- /// 电脑和会议室: the main side holds the gate on loud audio and lists what it heard; the room- /// side checks its lines against that before recording them.public EchoFilter? Echo { get; set; }- /// When the computer's audio was loud (the talk key's echo check), fed while listening to it.public LoudnessLog? Loudness { get; set; }- /// Seconds from the meeting's start to this side's first sample (the room side joins later).double offset;Channel<(Segment seg, Heard heard, double at, double queued)>? held;Task? holding;CancellationTokenSource? flush;readonly Dictionary<int, double> emitted = [];- /// 改正听错的词 (set by the app): null leaves lines as heard.public LiveFixes? Fixes { get; set; }- /// Debug (`heard <text>` after `silentlisten`): a finished sentence as if Ming heard it in- /// `lang` with no translation, so the record, its translation and fixes and the windows all- /// follow without any audio. Each comes as its own line (a pause before it).public void DebugHeard(string text, string lang){if (!Listening || SessionId is null) return;@@ -149,12 +108,10 @@ public sealed class ListenEngine{if (Listening || RoomSide) return;var session = store.Begin();- // The clock starts with the record, not after the encoder has opened.var since = System.Diagnostics.Stopwatch.GetTimestamp();SessionId = session.Id;Room = room;if (room) store.MarkRoom(session.Id);- // A silent debug meeting has nothing to record: an empty recording would be retried every launch.if (settings.RecordAudio && store.Audio is { } files && from is not SilentSource){var path = Recording.Partial(Recording.SystemAudio(session.Id));@@ -174,8 +131,6 @@ public sealed class ListenEngineChanged?.Invoke();}- /// The room side joins the meeting `sessionId`, which began at `startedAt`; what it hears goes- /// into the meeting's recording `mix` (the main side's `Mix`) too.public void Join(IAudioSource mic, string sessionId, DateTimeOffset startedAt, RoomMix? mix = null){if (Listening || !RoomSide) return;@@ -209,13 +164,10 @@ public sealed class ListenEnginevar reader = audio.Reader;began = since ?? System.Diagnostics.Stopwatch.GetTimestamp();long fed = 0;- // One reader thread owns the segmenter (and the recording): audio callbacks only queue buffers.worker = Task.Run(async () =>{await foreach (var (buf, at) in reader.ReadAllAsync()){- // Keep the meeting's clock: a gap the source left (the PC silent, a source switch)- // goes in as silence, so a line's t and the recording both stay on the wall clock.if (Recording.Behind(at, fed, buf.Length) is > 0 and var gap){var silence = new short[gap];@@ -226,7 +178,6 @@ public sealed class ListenEngineRecord(buf, fed);fed += buf.Length;Level = Rms(buf);- // The computer is playing speech: the room mic would hear it from the speakers.if (!RoomSide && Echo is { } echo && Level >= Segmenter.Threshold) echo.Gate.Hold();if (!RoomSide) Loudness?.Add(Level >= Segmenter.Threshold);segmenter.Feed(buf);@@ -239,9 +190,6 @@ public sealed class ListenEngineListening = true;}- /// The room side's lines wait a moment for the computer's line they may echo (EchoMatch.Hold),- /// in order; one around which the computer played nothing goes straight in. Stopping records- /// what still waits without the wait: it was said.async Task Hold(ChannelReader<(Segment seg, Heard heard, double at, double queued)> reader, EchoFilter echo, CancellationToken stopping){await foreach (var (seg, heard, at, queued) in reader.ReadAllAsync())@@ -260,7 +208,6 @@ public sealed class ListenEnginevoid OnSamples(short[] buf) => audio?.Writer.TryWrite((buf, System.Diagnostics.Stopwatch.GetElapsedTime(began).TotalSeconds));- /// `fed`: samples this side gave before these, so the room's land at their place in the meeting.void Record(short[] pcm, long fed){if (RoomSide)@@ -284,8 +231,6 @@ public sealed class ListenEnginetry { r?.Close(); } catch (Exception e) { Log.Debug($"listen: recording close failed {e.GetType().Name}"); }}- /// 听哪里 changed mid-meeting between the computer and the room: the same meeting goes on from the- /// other source, its clock running on.public void SwitchSource(IAudioSource to, bool room){if (!Listening || SessionId is not { } id) return;@@ -308,9 +253,6 @@ public sealed class ListenEnginereturn Math.Sqrt(sum / buf.Length) / 32768;}- /// Stops listening, waits (briefly) for segments still at Ming, ends the record (at `endedAt` for- /// a meeting that ended by itself) and writes the final notes. The task ends when the record is- /// saved; the notes' final pass may run on.public async Task Stop(DateTimeOffset? endedAt = null){if (!Listening) return;@@ -326,7 +268,6 @@ public sealed class ListenEnginevar id = SessionId!;if (RoomSide){- // The meeting is the main side's to end; lines still waiting for their echo check go in.held?.Writer.TryComplete();flush?.Cancel();if (holding is not null) await holding;@@ -380,7 +321,6 @@ public sealed class ListenEnginelock (gate) { inFlight.Add(task); inFlight.RemoveAll(t => t.IsCompleted); }}- /// Hands finished segments on in order: one slow reply holds back those after it.void Deliver(){var ready = new List<(Segment seg, Heard? heard)>();@@ -396,7 +336,6 @@ public sealed class ListenEngineforeach (var (seg, heard) in ready){if (heard is null) continue;- // Words in the computer's audio: speech, which the room mic is silenced for (EchoGate).if (!RoomSide && Echo is { } words && !string.IsNullOrWhiteSpace(heard.Original)) words.Gate.HeardWords();if (RoomSide && held is { } h && Echo is { } echo) h.Writer.TryWrite((seg, heard, EmittedAt(seg), echo.Gate.Clock()));else Record(seg, heard);@@ -404,7 +343,6 @@ public sealed class ListenEngineif (ready.Count > 0) Changed?.Invoke();}- /// When the segmenter let go of `seg` (just after its last word), on EchoGate's clock.double EmittedAt(Segment seg){lock (gate) return emitted.Remove(seg.Index, out var at) ? at : Echo?.Gate.Clock() ?? 0;@@ -414,14 +352,11 @@ public sealed class ListenEngine{var id = SessionId!;var target = Target;- // 电脑和会议室: what the computer said, for the room side to tell its copy of it.if (!RoomSide && Echo is { } echo){var at = EmittedAt(seg);echo.Online(new EchoMatch.Heard(heard.Original, at - seg.Seconds, at));}- // The meeting's language moves only after two segments agree, so one misheard stretch- // doesn't flip the hint (the Mac waits for confidence the same way).lock (gate){if (hint is null) hint = heard.Lang;@@ -433,7 +368,6 @@ public sealed class ListenEngineelse { candidate = null; candidateVotes = 0; }}- // Whose voice: a line with hardly a letter ("." from a breath) gets none.int? voice = null;Task<float[]?>? print;lock (gate) { prints.Remove(seg.Index, out print); }@@ -447,7 +381,6 @@ public sealed class ListenEnginebool joined = false;lock (gate){- // Two voices never share a line, however the sentence was cut.if (last is not null && Continues(last, seg.Start - lastEnd, heard) && (voice is null || last.Voice is null || voice == last.Voice)){last.Src = Join(last.Src, heard.Original, heard.Lang);@@ -461,8 +394,6 @@ public sealed class ListenEngine{Id = $"h{++lineCount}-{(RoomSide ? RoomIDs : 0) + seg.Index}", T = Math.Round(offset + seg.Start, 3), Speaker = "them",Src = heard.Original, Dst = heard.Translation, SrcLang = heard.Lang, DstLang = target, Voice = voice,- // 会议室 alone too: a meeting switched to it from 电脑和会议室 would otherwise- // mark its later room lines 线上 (as on the Mac).Via = RoomSide || settings.ListensToRoom ? "room" : null,};last = line;@@ -470,16 +401,8 @@ public sealed class ListenEnginelastEnd = seg.Start + seg.Seconds;}if (joined) store.Replace(id, line.Copy()); else store.Append(id, line.Copy());- // 改正听错的词: the word list's confirmed heard forms, without asking anyone.Fixes?.ApplyKnown(id, line.Id);- // A joined sentence is translated again as a whole; a line Ming didn't translate gets text- // translation. With 改正听错的词 every finished line is translated again by the AI service,- // which also points out misheard words in the same request (the Mac's viaLingFixing): Ming- // gives the translation with the audio, so there is no text request of its own to ride on.- // The new translation (of the sentence as fixed) replaces Ming's; a joined line's second- // pass may take back a fix it no longer proposes. Lines Ming already translated go at the- // notes' priority, so the subtitles' hearing requests keep going first.var retranslate = (joined || line.Dst is null) && line.SrcLang != target;var context = line.SrcLang != target && ling.Usable ? Fixes?.Context(id, line.Id) : null;if (retranslate || context is not null)@@ -511,8 +434,6 @@ public sealed class ListenEngine}}- /// A segment continues the last line when the cut came mid-sentence: no sentence end on the- /// last line, a short gap, the same language, and the joined line not too long to read.public static bool Continues(TranscriptLine last, double gap, Heard next){if (gap > 0.8 || last.SrcLang != next.Lang) return false;diff --git a/windows/src/Cicada.Core/LiveFixes.cs b/windows/src/Cicada.Core/LiveFixes.csindex 777ca4a..6d02440 100644--- a/windows/src/Cicada.Core/LiveFixes.cs+++ b/windows/src/Cicada.Core/LiveFixes.cs@@ -1,10 +1,5 @@namespace Cicada;-/// 改正听错的词, between the translation and the records (the Mac's LiveFixes.swift): which fixes a-/// line takes, which wait for the user (待确认), and what the user's answers and edits teach the-/// word list. Who wins: the user's own decisions, then the word list, then a later pass, then the-/// first live guess. UI-free and thread-safe (replies arrive on worker threads); `Changed` fires on-/// whichever thread made the change, and the app shows `Pending`, `Asking` and `Toast`.public sealed class LiveFixes{readonly SessionStore store;@@ -13,23 +8,17 @@ public sealed class LiveFixesreadonly object gate = new();public event Action? Changed;- /// The last thing the user did, said back with 撤销 for a few seconds.public sealed record Note(int Id, string Text);public Note? Toast { get; private set; }int toastIds;Timer? toastTimer;- /// Fixes said no to in this meeting ("from→to"), and how often each heard form was turned down- /// overall this run: twice and it leaves the word list.HashSet<string> refused = [];readonly Dictionary<string, int> refusals = [];- /// 稍后再看 on the card: still waiting, but asked again only after the meeting.HashSet<string> deferred = [];- /// What 撤销 puts back: the lines' fixes and the word list as they were.sealed record Step(string Session, Dictionary<string, List<LineFix>> Lines, List<Vocabulary.Term> Words, HashSet<string> Refused, HashSet<string> Deferred);readonly List<Step> undo = [];- /// The card asks about at most this many names in a row; the rest wait for after the meeting.public const int AskAtOnce = 3;public LiveFixes(SessionStore store, Vocabulary vocabulary, AppSettings settings)@@ -46,8 +35,6 @@ public sealed class LiveFixes// MARK: The service's proposals- /// What a finished sentence's request carries; null while fixing is off. On a second pass (a- /// joined line) the lines after it and the notes' summary are there too.public Translator.FixContext? Context(string id, string lineId){if (!settings.FixMisheard || store.Get(id) is not { } s) return null;@@ -59,8 +46,6 @@ public sealed class LiveFixesreturn new Translator.FixContext(topic, Vocabulary.PromptLines(), recent, following, s.Notes?.Summary is { Length: > 0 } sum ? sum : null);}- /// The service's proposals for a line (none at all is an answer too: a later pass takes back- /// what isn't proposed again).public void Received(string id, string lineId, IReadOnlyList<Correction.Edit> edits){if (!settings.FixMisheard) return;@@ -75,7 +60,6 @@ public sealed class LiveFixesif (verdict == Correction.Verdict.Apply){fresh.Add(new LineFix(e.From, e.To));- // A listed word counts as used whichever way the fix was found (a sound-alike too).Vocabulary.Use(Correction.Core(e.From, e.To).To);}else if (verdict == Correction.Verdict.Ask && settings.AskNames) fresh.Add(new LineFix(e.From, e.To, ask: true));@@ -89,8 +73,6 @@ public sealed class LiveFixesChanged?.Invoke();}- /// The word list's confirmed heard forms, fixed without asking anyone: also with no AI service.- /// Two characters at least, so a single 压 never turns into 押 everywhere.public void ApplyKnown(string id, string lineId){if (!settings.FixMisheard) return;@@ -108,8 +90,6 @@ public sealed class LiveFixesforeach (var t in Vocabulary.Terms)foreach (var h in t.Heard){- // A heard form two words claim (两个都留) is never fixed silently. A translation a yes taught- // before that was refused (平台 → platform) isn't either; one the user typed is.if (Correction.Length(h) < 2 || Correction.WordIn(h, src) < 0 || refused.Contains(Pair(h, t.Word))|| (t.Source != "user" && Correction.Translation(h, t.Word))|| Vocabulary.Owners(h, t.Word).Count > 0) continue;@@ -127,7 +107,6 @@ public sealed class LiveFixes// MARK: 待确认- /// 待确认 in a meeting: each (from → to) once, oldest first.public List<(TranscriptLine Line, LineFix Fix)> Pending(string id){var seen = new HashSet<string>();@@ -138,8 +117,6 @@ public sealed class LiveFixesreturn out_;}- /// What the notes window's card asks now: not what was put off (稍后再看), and only the first- /// few, so a burst of names doesn't keep the card up all meeting.public (TranscriptLine Line, LineFix Fix, int Position, int Of)? Asking(string id){HashSet<string> later;@@ -149,7 +126,6 @@ public sealed class LiveFixesreturn (open[0].Line, open[0].Fix, 1, Math.Min(open.Count, AskAtOnce));}- /// The card's ×: asked again only after the meeting.public void Later(LineFix fix, string id){lock (gate)@@ -160,8 +136,6 @@ public sealed class LiveFixesSay(Strings.L("已收进人名和术语,稍后再看"));}- /// 对 / 不对 on a waiting fix: every line in the meeting waiting on the same change follows,- /// and a yes goes into the word list so the next meeting fixes it without asking.public void Answer(LineFix fix, bool yes, string id){var c = Correction.Core(fix.From, fix.To);@@ -177,7 +151,6 @@ public sealed class LiveFixesif (yes){Vocabulary.Confirm(c.From, c.To);- // The rest of the meeting heard the same way follows now, not with the next line.if (settings.FixMisheard)foreach (var l in others)if (Line(id, l.Id) is { } now) Set(Known(now.Src, now.Fixes ?? []), l.Id, id);@@ -188,14 +161,12 @@ public sealed class LiveFixesSay(yes ? Strings.LF("已改 %@ → %@,记进词表", c.From, c.To) : Strings.LF("这场不再问 %@", c.From));}- /// 改回: this line goes back to what was heard, and the meeting stops making this change.public void Revert(LineFix fix, string lineId, string id){var c = Correction.Core(fix.From, fix.To);lock (gate){if (Line(id, lineId) is not { Fixes: { } fixes }) return;- // The one still on: an earlier, already undone copy of the same change may sit before it.int k = fixes.FindIndex(f => f.From == fix.From && f.To == fix.To && f.Applied);if (k < 0) k = fixes.FindIndex(f => f.From == fix.From && f.To == fix.To);if (k < 0) return;@@ -215,8 +186,6 @@ public sealed class LiveFixes// MARK: 改这句…- /// How many lines of the meeting the same edit would change ("整场听成 木娜 的 2 处都改").- /// An edit that only adds or drops words stays on its line (count 1, nothing to learn).public (string Heard, int Count, bool Swap)? SameHeard(string lineId, string id, string edited){if (store.Get(id) is not { } s || s.Lines.FirstOrDefault(l => l.Id == lineId) is not { } l@@ -225,8 +194,6 @@ public sealed class LiveFixesreturn (e.Heard, Math.Max(1, n), e.Swap);}- /// The user rewrote a line (改这句…): what changed becomes their own fix, on this line or on- /// every line showing the same words, and with `remember` the heard form joins the word list.public int Edit(string lineId, string id, string edited, bool everywhere, bool remember){int count;@@ -241,8 +208,6 @@ public sealed class LiveFixesRemember(id, targets.Select(t => t.Id));foreach (var t in targets){- // A guess still waiting on the same words is answered by the edit: not that.- // The same change made again replaces any earlier copy (say, one undone with 改回).var fixes = (t.Fixes ?? []).Where(f => !(f.From == e.Fix.From && f.To == e.Fix.To)).Select(f => f.Ask == true && (f.From.Contains(e.Heard, StringComparison.Ordinal) || e.Heard.Contains(f.From, StringComparison.Ordinal))? f with { Ask = null, Off = true } : f).ToList();Set([.. fixes, e.Fix], t.Id, id);@@ -250,12 +215,8 @@ public sealed class LiveFixescount = targets.Count;heard = e.Heard;to = Correction.Core(e.Fix.From, e.Fix.To).To.Trim();- // Only a change made everywhere teaches the word list (a one-off must not), and only a- // word for a word (`Vocabulary.Learnable`).learned = remember && everywhere && Vocabulary.Learnable(heard, to) is not null;if (learned) Vocabulary.Confirm(heard, to, "user");- // A swap reads as the words swapped; an added or dropped word as the span it changed- // ("in → in now", not "in → now").if (!e.Swap) (heard, to) = (e.Fix.From, e.Fix.To);}Log.Debug($"fix edited lines={count} learned={learned}");diff --git a/windows/src/Cicada.Core/MeetingEnd.cs b/windows/src/Cicada.Core/MeetingEnd.csindex 65812bd..7856820 100644--- a/windows/src/Cicada.Core/MeetingEnd.cs+++ b/windows/src/Cicada.Core/MeetingEnd.cs@@ -1,14 +1,5 @@namespace Cicada;-/// When a meeting is over (MeetingEnd.swift), so one nobody ended doesn't run on for hours and pull-/// the next video or meeting into its notes.-///-/// Two signals, as on the Mac. The main one: a meeting app (Zoom, 腾讯会议…) that was reading a-/// microphone during this meeting lets go of it, which is what hanging up looks like from outside; a-/// short grace covers switching devices. The fallback, for meetings in a browser or in the room:-/// nothing was recognised for a while ("nothing recognised" counts words, not sound, so background-/// music doesn't keep a meeting alive). While a meeting app is still in a call, silence doesn't-/// count. Pure: the controller ticks it with the clock and `MicUse.Calls`.public sealed class MeetingEndWatch{public enum Silence { Prompt, End, Off }@@ -16,8 +7,6 @@ public sealed class MeetingEndWatchpublic sealed record Config(bool FollowApps = true, Silence Silence = Silence.Prompt, double SilenceAfter = 600,double Countdown = 60, double AppGrace = 30);- /// Why the meeting ends: an app hung up (its name), silence, or nobody spoke at all (nothing to- /// keep, so it just stops, without a countdown).public sealed record Reason(string Kind, string Name = ""){public static readonly Reason SilenceEnd = new("silence");@@ -31,7 +20,6 @@ public sealed class MeetingEndWatchpublic Config Settings;public Pending? Waiting { get; private set; }public DateTimeOffset LastSpeech { get; private set; }- /// Meeting apps seen in a call during this meeting (id → name).public Dictionary<string, string> InCall { get; private set; } = [];public MeetingEndWatch(Config config, DateTimeOffset start)@@ -40,15 +28,12 @@ public sealed class MeetingEndWatchLastSpeech = start;}- /// Words were recognised (theirs or mine): a silence countdown stops. A hang-up doesn't: the- /// next video would talk over it.public void Heard(DateTimeOffset now){LastSpeech = now;if (Waiting?.Reason.Kind == "silence") Waiting = null;}- /// 继续记录: forget the hang-up and start counting silence again.public void KeepGoing(DateTimeOffset now){Waiting = null;@@ -56,8 +41,6 @@ public sealed class MeetingEndWatchInCall = [];}- /// `calls`: meeting apps reading a microphone now. `said`: the meeting has lines. One without- /// keeps listening for the silence time, then stops quietly. Returns why it ends now, if it does.public Reason? Tick(DateTimeOffset now, IReadOnlyDictionary<string, string> calls, bool said){var c = Settings;@@ -74,7 +57,7 @@ public sealed class MeetingEndWatch{foreach (var (id, name) in calls) InCall[id] = name;bool hungUp = InCall.Count > 0 && InCall.Keys.All(k => !calls.ContainsKey(k));- if (appWaiting && !hungUp) Waiting = null; // rejoined+ if (appWaiting && !hungUp) Waiting = null;if (hungUp && (Waiting is null || Waiting.Reason.Kind == "silence")){var name = InCall.OrderBy(p => p.Key, StringComparer.Ordinal).First().Value;@@ -99,14 +82,8 @@ public sealed class MeetingEndWatchpublic static Silence ParseSilence(string s) => s switch { "end" => Silence.End, "off" => Silence.Off, _ => Silence.Prompt };}-/// Which meeting apps are reading a microphone, from what Windows records for its privacy settings:-/// under HKCU\…\CapabilityAccessManager\ConsentStore\microphone every app that used the mic has a key-/// (desktop apps under NonPackaged, by their path with `#` for `\`; Store apps by package family)-/// whose LastUsedTimeStop is 0 while it has the mic open. The reading is in the app; this is pure.public static class MicUse{- /// Dedicated meeting apps (lower case program or package family prefix) → the name shown.- /// Browsers aren't here, as on the Mac: a browser holding a mic isn't necessarily a meeting.static readonly (string Key, string Name)[] Apps =[("zoom.exe", "Zoom"), ("wemeetapp.exe", "腾讯会议"), ("feishu.exe", "飞书"), ("lark.exe", "Lark"),@@ -114,11 +91,9 @@ public static class MicUse("ciscocollabhost.exe", "Webex"), ("webex.exe", "Webex"), ("cisco.webex", "Webex"),];- /// `entries`: each key's name (a path like "C:#Program Files#Zoom#bin#Zoom.exe" or a package family)- /// and its LastUsedTimeStop. → {program: name} for the meeting apps using a mic now.public static Dictionary<string, string> Calls(IEnumerable<(string Key, long LastUsedTimeStop)> entries){- var byName = new SortedDictionary<string, string>(StringComparer.Ordinal); // one entry per app+ var byName = new SortedDictionary<string, string>(StringComparer.Ordinal);foreach (var (key, stop) in entries){if (stop != 0) continue;diff --git a/windows/src/Cicada.Core/Models.cs b/windows/src/Cicada.Core/Models.csindex 26e49a7..d02ef23 100644--- a/windows/src/Cicada.Core/Models.cs+++ b/windows/src/Cicada.Core/Models.cs@@ -2,47 +2,30 @@ using System.Text.Json.Serialization;namespace Cicada;-// The meeting record, field for field the Mac app's `session.json` (SessionStore.swift, Notes.swift),-// so a record moves between the two unchanged. Properties are declared in ordinal key order because-// the Mac writes sorted keys; nulls are left out, as Swift leaves out nil optionals.-public sealed class TranscriptLine{[JsonPropertyName("dst")] public string? Dst { get; set; }[JsonPropertyName("dstLang")] public string DstLang { get; set; } = "";- /// Words the AI service fixed (Correction); `src` stays what was heard. Absent when none.[JsonPropertyName("fixes")] public List<LineFix>? Fixes { get; set; }- /// "h<n>-<segment>" for heard lines, "m<n>" for the user's own.[JsonPropertyName("id")] public string Id { get; set; } = "";- /// "them" (system audio) or "me" (microphone).[JsonPropertyName("speaker")] public string Speaker { get; set; } = "them";[JsonPropertyName("src")] public string Src { get; set; } = "";[JsonPropertyName("srcLang")] public string SrcLang { get; set; } = "";- /// Seconds from the start of the session.[JsonPropertyName("t")] public double T { get; set; }- /// 电脑和会议室: "room" when the room mic heard it; absent for the computer's audio (and older records).[JsonPropertyName("via")] public string? Via { get; set; }- /// Experimental voice id on the Mac; Windows doesn't tell voices apart yet.[JsonPropertyName("voice")] public int? Voice { get; set; }- /// What the line says once its fixes are in: shown, searched, exported and read by the notes.[JsonIgnore] public string Shown => Fixes is { Count: > 0 } f ? Correction.Apply(f, Src).Text : Src;- /// Shallow: Fixes is shared, so it is only ever replaced with a new list, never changed in place.public TranscriptLine Copy() => (TranscriptLine)MemberwiseClone();}-/// A word the AI service said speech recognition got wrong in a finished line ("莫拉" → "Morpho"),-/// field for field the Mac's LineFix. The flags are written only when true, as Swift leaves out nil.public sealed record LineFix{- /// Waiting for the user (a name sound can't check): not applied until confirmed.[JsonPropertyName("ask")] public bool? Ask { get; init; }[JsonPropertyName("from")] public string From { get; init; } = "";- /// The user said no (改回 or 不对): kept so the same line isn't fixed that way again.[JsonPropertyName("off")] public bool? Off { get; init; }[JsonPropertyName("to")] public string To { get; init; } = "";- /// The user's own: said 对, or wrote it (改这句…). A later pass never drops or overrides it.[JsonPropertyName("user")] public bool? User { get; init; }public LineFix() { }@@ -65,14 +48,11 @@ public sealed class Session[JsonPropertyName("endedAt")] public DateTimeOffset? EndedAt { get; set; }[JsonPropertyName("hasAudio")] public bool HasAudio { get; set; }[JsonPropertyName("id")] public string Id { get; set; } = "";- /// Mac: an imported file still being transcribed. Kept so a Mac record round-trips.[JsonPropertyName("importing")] public bool? Importing { get; set; }[JsonPropertyName("lines")] public List<TranscriptLine> Lines { get; set; } = [];[JsonPropertyName("notes")] public MeetingNotes? Notes { get; set; }[JsonPropertyName("renamed")] public bool? Renamed { get; set; }- /// Mac: heard through the microphone (会议室模式). Windows doesn't record rooms yet.[JsonPropertyName("room")] public bool? Room { get; set; }- /// Mac: the imported file's name, and where its audio is; Windows doesn't import yet.[JsonPropertyName("sourceFile")] public string? SourceFile { get; set; }[JsonPropertyName("sourcePath")] public string? SourcePath { get; set; }[JsonPropertyName("startedAt")] public DateTimeOffset StartedAt { get; set; }@@ -80,18 +60,14 @@ public sealed class Session[JsonPropertyName("voiceGuesses")] public Dictionary<string, VoiceGuess>? VoiceGuesses { get; set; }[JsonPropertyName("voiceNames")] public Dictionary<string, string>? VoiceNames { get; set; }- /// Keys a newer Mac (or port) added that this version doesn't know: written back as read, so- /// opening a record here never loses them. They go after the known keys rather than in order.[JsonExtensionData] public Dictionary<string, System.Text.Json.JsonElement>? Unknown { get; set; }[JsonIgnore] public TimeSpan Duration => (EndedAt ?? DateTimeOffset.Now) - StartedAt;}-/// Written by Ling while the meeting runs, rewritten over the whole transcript when it ends.public sealed class MeetingNotes{[JsonPropertyName("conclusions")] public List<NoteItem> Conclusions { get; set; } = [];- /// How many transcript lines these notes cover.[JsonPropertyName("covered")] public int Covered { get; set; }[JsonPropertyName("final")] public bool Final { get; set; }[JsonPropertyName("summary")] public string Summary { get; set; } = "";@@ -107,7 +83,6 @@ public sealed class MeetingNotespublic sealed class NoteTopic{[JsonPropertyName("fishbone")] public Fishbone? Fishbone { get; set; }- /// When each point was said (its first evidence line), parallel to Points.[JsonPropertyName("pointTimes")] public List<double?>? PointTimes { get; set; }[JsonPropertyName("points")] public List<string> Points { get; set; } = [];[JsonPropertyName("start")] public double Start { get; set; }@@ -127,7 +102,6 @@ public sealed class FishboneBranch{[JsonPropertyName("detail")] public string Detail { get; set; } = "";[JsonPropertyName("label")] public string Label { get; set; } = "";- /// How many transcript lines back this branch; 0 is shown as weak.[JsonPropertyName("support")] public int Support { get; set; }[JsonPropertyName("t")] public double? T { get; set; }}@@ -136,11 +110,9 @@ public sealed class NoteItem{[JsonPropertyName("owner")] public string? Owner { get; set; }[JsonPropertyName("support")] public int Support { get; set; }- /// When it was said (first evidence line).[JsonPropertyName("t")] public double? T { get; set; }[JsonPropertyName("text")] public string Text { get; set; } = "";- /// The owner as stored ("你", "对方", "说话人2" or a name) in the UI language.[JsonIgnore]public string? OwnerShown => Owner switch{@@ -150,27 +122,22 @@ public sealed class NoteItem_ => Owner,};- /// The to-do with its owner after it: "(对方)" in Chinese, " (Them)" in English.[JsonIgnore]public string WithOwner => Text + (OwnerShown is { } o ? Strings.LF("待办的负责人 %@", o) : "");}-/// A name or term as the notes settled on it, and how speech recognition heard it.public sealed class NoteTerm{[JsonPropertyName("heard")] public List<string> Heard { get; set; } = [];[JsonPropertyName("name")] public string Name { get; set; } = "";[JsonPropertyName("note")] public string Note { get; set; } = "";- /// Corrected spellings first: what a reader can't work out alone.public static List<NoteTerm> Ordered(IEnumerable<NoteTerm> terms){var list = terms.ToList();return [.. list.Where(t => t.Heard.Count > 0), .. list.Where(t => t.Heard.Count == 0)];}- /// The reply's terms in the order they were shown before, new ones after: the model often- /// returns the same names reshuffled, which would make the chips jump on every update.public static List<NoteTerm> KeepingOrder(IReadOnlyList<NoteTerm> old, IReadOnlyList<NoteTerm> next){var rank = new Dictionary<string, int>();diff --git a/windows/src/Cicada.Core/Notes.cs b/windows/src/Cicada.Core/Notes.csindex e7e8154..8621541 100644--- a/windows/src/Cicada.Core/Notes.cs+++ b/windows/src/Cicada.Core/Notes.cs@@ -3,14 +3,8 @@ using System.Text.Json.Nodes;namespace Cicada;-/// Keeps the live meeting's notes up to date: every ~45 s with new speech, one Ling call sends the-/// current notes plus the new lines and gets the whole notes back as JSON; a final pass rewrites-/// them over the whole transcript when the meeting ends. A failed or odd reply never replaces good-/// notes. The prompt and parsing are the Mac's (Notes.swift), so both write the same notes.public sealed class NotesEngine{- /// Unreachable: the notes' own request couldn't reach the service (network, proxy, timeout);- /// another request failing, such as naming speakers, never sets it.public enum State { Idle, Updating, NoKey, InvalidKey, RateLimited, Unreachable, Failed }public const double Interval = 45;@@ -21,25 +15,19 @@ public sealed class NotesEnginebool inFlight;string? pendingFinal;DateTime lastAttempt = DateTime.MinValue;- /// The language the shown notes were last written in.string? writtenIn;Timer? timer;public MeetingNotes Notes { get; private set; } = new();public State Status { get; private set; } = State.Idle;- /// cicadactl notesproblem failed|ratelimited|idle: shows what a failed round looks like.public void SimulateStatus(string state) { Status = Enum.TryParse<State>(state, true, out var s) ? s : State.Idle; Changed?.Invoke(); }- /// While a meeting runs and has notes: when the next live update is due.public DateTime? NextUpdate { get { lock (gate) return sessionId is null || Notes.IsEmpty || inFlight ? null : lastAttempt.AddSeconds(Interval); } }- /// The session the notes belong to (stays set after the meeting ends).public string? ShownId { get; private set; }- /// The language notes are written in (English name), from 纪要语言.public Func<string> Language { get; set; } = () => "Simplified Chinese";public event Action? Changed;public NotesEngine(LingClient ling, SessionStore store) { this.ling = ling; this.store = store; }- /// Names for the translation glossary: "江充 (note; misheard as 江松, 江冲)".public IReadOnlyList<string> Glossary() => Notes.Terms.Take(30).Select(t => t.Heard.Count == 0 ? $"{t.Name} ({t.Note})" : $"{t.Name} ({t.Note}; misheard as {string.Join(", ", t.Heard)})").ToList();@@ -57,7 +45,6 @@ public sealed class NotesEngineChanged?.Invoke();}- /// The meeting ended: one last pass over the whole transcript. The task ends when it's written.public Task Finish(){timer?.Dispose(); timer = null;@@ -71,24 +58,17 @@ public sealed class NotesEnginelock (gate){ShownId = id; Notes = store.Get(id)?.Notes ?? new MeetingNotes();- // A round that failed belongs to the meeting it ran for, not to the record opened now.if (sessionId is null && Status is State.Failed or State.Unreachable or State.RateLimited) Status = State.Idle;}Changed?.Invoke();}- /// The finished meeting whose notes 生成纪要 is writing now (Notes.swift › generatingID): its- /// page says so and the button waits, as a long meeting's notes take half a minute and more.public string? GeneratingId { get; private set; }- /// The meeting whose final pass is running now (from 结束 or 生成纪要).string? finalId;- /// A final pass is over, whether it wrote notes or not (存到文件夹 waits for it).public event Action<string>? FinalDone;- /// The final pass for this meeting is running or waiting its turn.public bool Settling(string id) { lock (gate) return finalId == id || pendingFinal == id; }- /// Notes for a finished meeting that has none.public async Task Generate(string id){lock (gate) { if (GeneratingId is not null) return; GeneratingId = id; }@@ -107,15 +87,12 @@ public sealed class NotesEnginelock (gate){if (Status == State.NoKey && ling.Usable) Status = State.Idle;- // The service answers again (the check after a network change, or any other request): the- // banner goes now, not after the next round, which runs on its usual 45 s.if (Status == State.Unreachable && ling.Health.Failure?.Why != AICheck.Reason.Unreachable) Status = State.Idle;id = sessionId;if (id is null || inFlight) return;var s = store.Get(id);if (s is null || s.Lines.Count <= Notes.Covered) return;var since = (DateTime.UtcNow - lastAttempt).TotalSeconds;- // First notes as soon as there is something to say, then every 45 s.bool due = Notes.IsEmpty ? s.Lines.Count >= 3 || since > 20 : since >= Interval;if (!due) return;}@@ -145,16 +122,11 @@ public sealed class NotesEngine{var lines = session.Lines.ToList();var lang = Language();- // The language changed mid-meeting: write the notes again from the start in the new one.- // (The script check can't tell Chinese from Japanese, so extending them would keep the old.)bool fresh = !final && writtenIn is not null && writtenIn != lang;if (fresh) { baseNotes = new MeetingNotes(); Log.Debug($"notes: language now {lang}, rewriting"); }int from = final ? 0 : Math.Min(baseNotes.Covered, lines.Count);var names = SpeakerLabels.Voices ? SpeakerLabels.Names(session) : null;var startedAt = lines.FirstOrDefault()?.T ?? 0;- // A live update returns only the last topics: when it rewrote them all, its reply grew with- // the meeting until, about an hour in, it was cut off at max_tokens or fell into a loop and- // the notes stopped updating. The final pass still rewrites everything once.int frozen = final || fresh ? 0 : Math.Max(0, baseNotes.Topics.Count - EditableTopics);var prompt = Prompt(baseNotes, lines, from, lang, final, names, frozen);var next = final ? await LongFinal(lines, names, lang, startedAt) : null;@@ -207,17 +179,12 @@ public sealed class NotesEngine}}- /// Terms keep only the heard forms the recognizer really wrote (`Src`). The notes read lines- /// with fixes in, so a wrong fix came back as a heard form ("X平台 heard as platform"), went to- /// the translator and the next fix's request as a known mishearing, and was proposed again.public static List<NoteTerm> HeardAsSaid(List<NoteTerm> terms, IReadOnlyList<TranscriptLine> lines){foreach (var t in terms) t.Heard = t.Heard.Where(h => lines.Any(l => l.Src.Contains(h, StringComparison.OrdinalIgnoreCase))).ToList();return terms;}- /// The model echoes points it already had without evidence: keep the times they had, and a- /// point keeps the time it was first heard.public static void CarryTimes(MeetingNotes old, MeetingNotes next){var known = new Dictionary<string, double>();@@ -228,7 +195,6 @@ public sealed class NotesEngine{var times = t.Points.Select((p, i) => Min(t.PointTime(i), known.TryGetValue(p, out var k) ? k : null)).ToList();t.PointTimes = times.Any(x => x is not null) ? times : null;- // A topic starts no later than its first point (the reply dates it from the lines it cites now).if (times.Where(x => x is not null).Min() is { } first && first < t.Start) t.Start = first;}var items = new Dictionary<string, double>();@@ -241,8 +207,6 @@ public sealed class NotesEnginepublic static bool Written(MeetingNotes notes, string language) =>Languages.WrittenIn(notes.Summary + string.Concat(notes.Topics.Select(t => t.Title)), language);- /// A long meeting's final pass: each part noted on its own, all at once, then merged into one.- /// null when a step fails: the caller then makes one pass over the whole transcript, as before.async Task<MeetingNotes?> LongFinal(List<TranscriptLine> lines, IReadOnlyDictionary<int, string>? names, string lang, double startedAt){var parts = Parts(lines);@@ -268,7 +232,6 @@ public sealed class NotesEngineLog.Debug($"notes: final part {i + 1}/{parts.Count} failed, one pass instead");return null;}- // Without its topics: given them, the merge wrote them all back out and was cut off.int a = raw.IndexOf('{'), b = raw.LastIndexOf('}');if (JsonNode.Parse(raw[a..(b + 1)]) is not JsonObject part) return null;part.Remove("topics");@@ -296,22 +259,11 @@ public sealed class NotesEngine// MARK: Live topics (Notes.swift › merge)- /// The most topics the final notes have (the prompt says so too; the model doesn't always listen).public const int MaxTopics = 8;- /// The most topics live notes have. Live notes used to stop at `MaxTopics` and pour everything- /// after into the last topic, whose summary then grew into a wall of "最新…又…补充…"; past this,- /// the two shortest neighbouring settled topics are joined instead, so the newest can start.public const int LiveMaxTopics = 12;- /// A topic summary longer than this is a log the model kept appending to, not one sentence.public const int TopicSummaryLimit = 160;- /// How many of the last topics a live update may rewrite; earlier ones stay as they are.public const int EditableTopics = 2;- /// A live reply's topics after the `frozen` ones it was told to leave alone: with some frozen, at- /// most the editable ones plus one new, from the end (the model sometimes echoes the whole list),- /// never a copy of a frozen one, each summary kept to one sentence; and no more than- /// `LiveMaxTopics` in all (past that, settled neighbours are joined). A reply with no topics of- /// its own keeps the ones it had.public static List<NoteTopic> Merge(IReadOnlyList<NoteTopic> old, int frozen, IReadOnlyList<NoteTopic> returned){var kept = old.Take(frozen).ToList();@@ -323,7 +275,6 @@ public sealed class NotesEnginetail = Capped(tail, LiveMaxTopics - Math.Min(kept.Count, 1));while (kept.Count + tail.Count > LiveMaxTopics && kept.Count >= 2){- // The pair spanning the least time, its end being the next topic's start.var ends = kept.Skip(1).Select(t => t.Start).Append(tail[0].Start).ToList();int i = 0;for (int j = 1; j < kept.Count - 1; j++)@@ -334,8 +285,6 @@ public sealed class NotesEnginereturn Capped(kept.Concat(tail).ToList(), LiveMaxTopics);}- /// Two neighbouring topics as one: both titles and summaries, and up to the 4 points the prompt- /// allows, taken evenly from each.public static NoteTopic Joined(NoteTopic a, NoteTopic b){int fromA = Math.Min(a.Points.Count, Math.Max(2, 4 - b.Points.Count));@@ -350,7 +299,6 @@ public sealed class NotesEngine};}- /// A runaway topic summary cut back to its first sentence (or to the limit, with "…").public static string Shortened(string summary){if (summary.Length <= TopicSummaryLimit) return summary;@@ -359,8 +307,6 @@ public sealed class NotesEnginereturn end >= 0 ? head[..(end + 1)] : head.Trim() + "…";}- /// At most `count` topics (at least one): the points of any after that go into the last kept.- /// The last kept is a copy: it may be one of the shown notes' topics.public static List<NoteTopic> Capped(List<NoteTopic> topics, int count){topics = topics.ToList();@@ -381,7 +327,6 @@ public sealed class NotesEngine// MARK: Prompt (Notes.swift › prompt, word for word)- /// `part`: in a long meeting's final pass, which part `from..lines.Count` is (1-based, of `Of`).public static string Prompt(MeetingNotes notes, IReadOnlyList<TranscriptLine> lines, int from, string language, bool final,IReadOnlyDictionary<int, string>? names = null, int frozen = 0, (int Index, int Of)? part = null){@@ -389,8 +334,6 @@ public sealed class NotesEnginestring Line(int i){var l = lines[i];- // As Notes.swift: a named voice as its name, else 说话人N once voices are told apart,- // 未识别 for a voice not on show.var who = l.Speaker == "me" ? "你" : numbers.TryGetValue(l.Id, out var n) ? names?.GetValueOrDefault(n) ?? $"说话人{n}" : numbers.Count == 0 ? "对方" : "未识别";return $"[L{i + 1} {Languages.Clock(l.T)} {who}] {l.Shown}";}@@ -410,8 +353,6 @@ public sealed class NotesEngineif (context < from) p += "Already covered (context only):\n" + string.Join("\n", Enumerable.Range(context, from - context).Select(Line)) + "\n\n";p += $"{(final ? "Transcript" : "New lines")} (id, mm:ss, speaker 对方=the other side / 你=me / a name or 说话人N=one person on the other side, told apart by voice and possibly wrong / 未识别=someone on the other side not identified, text). Speech recognition makes mistakes, often in names: correct them from context, and write a public figure's name as the news spells it.\n";p += string.Join("\n", Enumerable.Range(from, lines.Count - from).Select(Line));- // The model splits too eagerly when only told how long a topic should be: say plainly- // whether this update may start one.if (final && from < lines.Count){var span = lines[^1].T - lines[from].T;@@ -430,7 +371,6 @@ public sealed class NotesEnginereturn p + "\n\n" + Format(language, numbers.Count > 0, final, frozen);}- /// The reply's JSON shape and the rules for its contents.static string Format(string language, bool voices, bool final, int frozen) =>"Return the full notes as one JSON object with exactly these keys:\n"+ "{\"title\": \"the meeting's name: what it is about, a few words\",\n"@@ -454,8 +394,6 @@ public sealed class NotesEngine+ "- Write about what was said, never about the transcript or recognition quality.\n"+ "- Use empty arrays when there is nothing. No markdown, no text outside the JSON.";- /// The current notes as sent back to the model (no bookkeeping fields). `from`: the first topic- /// sent (earlier ones go as a list of titles).static string CompactJson(MeetingNotes n, int from = 0){var o = new JsonObject();@@ -475,8 +413,6 @@ public sealed class NotesEngine// MARK: Long meetings- /// How a long meeting's final pass is split: over `SplitMinutes`, into equal parts by time of at- /// most `PartMinutes`. One pass covered a 91-minute meeting but only the first hour of a 4-hour one.public const double SplitMinutes = 100, PartMinutes = 60;public static List<Range> Parts(IReadOnlyList<TranscriptLine> lines){@@ -498,14 +434,8 @@ public sealed class NotesEnginereturn bounds.Zip(bounds.Skip(1), (a, b) => a..b).ToList();}- /// Each part's share of the topics: the merge keeps them as they are, so every part has some.public static int PartTopics(int parts) => Math.Max(2, MaxTopics / Math.Max(1, parts));- /// At most `count` of a part's `topics`, neighbours joined: a part's reply often has more topics- /// than asked. Keeping the first ones lost the end of the part, and keeping some spread from first- /// to last kept a topic's "(续)" stub at the part's end and dropped the topic itself. The same- /// subject twice is joined first, under the first one's title; then the pair spanning the least- /// time (to the next topic's start, or `end` for the last), as live notes do.public static List<NoteTopic> Thinned(IReadOnlyList<NoteTopic> topics, int count, double end){var list = topics.ToList();@@ -516,7 +446,6 @@ public sealed class NotesEngineint at = same;if (at < 0){- // The first of equal spans, as the Mac does.at = 0;for (int i = 1; i < list.Count - 1; i++) if (Span(i) < Span(at)) at = i;}@@ -528,7 +457,6 @@ public sealed class NotesEnginereturn list;}- /// A topic title without a trailing bracket ("预算评审(续)", "Budget (cont.)"): what it is about.public static string Subject(string title){var t = title.Trim();@@ -537,9 +465,6 @@ public sealed class NotesEnginereturn open > 0 ? t[..open].Trim() : t;}- /// The whole meeting's title, summary, conclusions, to-dos and terms from its parts' notes (the- /// replies as they came, with their evidence line ids). Asked to merge topics too, the model- /// kept the first parts' and dropped the rest, so topics are joined in code.public static string MergePrompt(IReadOnlyList<string> parts, IReadOnlyList<TranscriptLine> lines, string language, bool voices){var p = "You keep notes for a meeting that has just ended. It was long, so each part was noted on its own; below are those notes, in time order (JSON; evidence ids are transcript lines, L1 the first). Merge them into the notes for the whole meeting.\n"@@ -552,7 +477,6 @@ public sealed class NotesEngine// MARK: Parse- /// Lenient: missing keys become empty, evidence ids are checked against the transcript.public static MeetingNotes? Parse(string raw, IReadOnlyList<double> times, double startedAt){int a = raw.IndexOf('{'), b = raw.LastIndexOf('}');@@ -609,9 +533,6 @@ public sealed class NotesEnginepointTimes.Add(p is JsonObject po2 ? Time(po2["evidence"]) : null);}}- // When it was first said, from its lines: the model's own "start" drifts by tens of- // minutes in a long meeting (a topic said at 51-85 min came back as starting at 23) and is- // sometimes misread (04:49 for 00:49). Never after the last line.var cited = new[] { Time(t["evidence"]) }.Concat(pointTimes).Where(x => x is not null).Select(x => x!.Value).ToList();var start = cited.Count > 0 ? cited.Min() : Num(t["start"]) ?? startedAt;if (times.Count > 0 && start > times[^1]) start = times[^1];@@ -634,7 +555,6 @@ public sealed class NotesEnginevar heard = t["heard"] is JsonArray h ? h.Select(Str).Where(x => x.Length > 0 && x != name).ToList() : [];return new NoteTerm { Name = name, Note = Str(t["note"]), Heard = heard };}).Where(t => t.Name.Length > 0).ToList();- // The model keeps every term it ever had: bound the glossary, keeping the misheard ones.if (n.Terms.Count > 20) n.Terms = NoteTerm.Ordered(n.Terms).Take(20).ToList();return n.IsEmpty ? null : n;}diff --git a/windows/src/Cicada.Core/Recording.cs b/windows/src/Cicada.Core/Recording.csindex 4852245..0c9a023 100644--- a/windows/src/Cicada.Core/Recording.cs+++ b/windows/src/Cicada.Core/Recording.cs@@ -1,39 +1,26 @@namespace Cicada;-/// 保存会议录音: what was heard goes into `system.m4a` beside session.json, as on the Mac-/// (AudioFiles.swift). While the meeting runs it is written as ADTS (`system.aac`), which stays-/// readable up to its last frame if the app is killed; when the meeting ends it is rewrapped into-/// the .m4a, and a partial file left by a crash is rewrapped at the next launch. The encoder is-/// the app's (Media Foundation); Core only decides what goes in and when.public interface IAudioFiles{- /// An AAC (ADTS) file at `path` for 16 kHz mono; null when this PC can't encode.IAudioWriter? Open(string path);- /// `from` (ADTS) into the .m4a `to`, the first `until` seconds only when given. False on failure.bool Rewrap(string from, string to, double? until);}public interface IAudioWriter{void Write(ReadOnlySpan<short> pcm);- /// Writes what is buffered and closes the file.void Close();}-/// 电脑和会议室 keeps one recording, as the Mac does: the room side's samples are added into the-/// PC's at the same place on the meeting's clock (each side counts the samples it gave, gaps-/// filled). The PC's audio waits `Delay` before it is written, so a room buffer that arrives a-/// little after the PC's is still mixed in; what the room says after the PC's last sample follows.public sealed class RoomMix(IAudioWriter writer) : IAudioWriter{- const int Delay = Segmenter.Rate; // 1 s- const int Limit = 30 * Segmenter.Rate; // the PC's audio stalled: older room audio goes+ const int Delay = Segmenter.Rate;+ const int Limit = 30 * Segmenter.Rate;readonly object gate = new();readonly List<short> pc = [], room = [];- long at, roomAt; // where on the clock pc[0] and room[0] are (everything before `at` is written)+ long at, roomAt;bool closed;- /// The PC's audio (the main side), in order.public void Write(ReadOnlySpan<short> pcm){short[] output;@@ -46,7 +33,6 @@ public sealed class RoomMix(IAudioWriter writer) : IAudioWriterif (output.Length > 0) writer.Write(output);}- /// The room side's audio; `start`: its first sample's place on the clock.public void Room(ReadOnlySpan<short> pcm, long start){lock (gate)@@ -54,7 +40,7 @@ public sealed class RoomMix(IAudioWriter writer) : IAudioWriterif (closed) return;var end = roomAt + room.Count;if (room.Count == 0) roomAt = start;- else if (start > end) room.AddRange(new short[start - end]); // the room side stopped a while+ else if (start > end) room.AddRange(new short[start - end]);else if (start < end) pcm = pcm[(int)Math.Min(end - start, pcm.Length)..];room.AddRange(pcm);Drop(at);@@ -62,7 +48,6 @@ public sealed class RoomMix(IAudioWriter writer) : IAudioWriter}}- /// Everything still held goes into the file, then the file closes.public void Close(){List<short> output;@@ -82,7 +67,6 @@ public sealed class RoomMix(IAudioWriter writer) : IAudioWriterwriter.Close();}- /// Room audio for a place already written: too late to mix.void Drop(long upto){var late = (int)Math.Min(room.Count, upto - roomAt);@@ -91,7 +75,6 @@ public sealed class RoomMix(IAudioWriter writer) : IAudioWriterroomAt += late;}- /// The next `n` samples of the PC's audio with the room's added.short[] Take(int n){if (n <= 0) return [];@@ -117,7 +100,6 @@ public static class Recordingpublic static string SystemAudio(string sessionId) => Path.Combine(Paths.Sessions, sessionId, "system.m4a");public static string Partial(string m4a) => Path.ChangeExtension(m4a, ".aac");- /// The file a record plays: its own recording, or an imported file's where it still is.public static string? Playable(Session s){var own = SystemAudio(s.Id);@@ -126,12 +108,6 @@ public static class Recordingreturn null;}- /// Samples of silence that go in before a buffer so the recording keeps the meeting's clock:- /// loopback capture sends nothing while the PC is silent (SystemAudioTap fills only what it- /// notices), a source switch leaves a gap, and a line's `t` is its time since the meeting began.- /// `at`: meeting seconds when the buffer arrived; `fed`: samples already given; `count`: the- /// buffer's. Nothing while the stream is within LoopbackGap.Late of the clock, so a packet that- /// is merely late never puts a gap in a sentence.public static int Behind(double at, long fed, int count){var lag = at - (fed + count) / (double)Segmenter.Rate;diff --git a/windows/src/Cicada.Core/Room.cs b/windows/src/Cicada.Core/Room.csindex 72e2647..2473f64 100644--- a/windows/src/Cicada.Core/Room.cs+++ b/windows/src/Cicada.Core/Room.cs@@ -1,24 +1,15 @@namespace Cicada;-// 听哪里 (the Mac's RoomMic.swift and EchoMatch.swift): 电脑声音, 会议室 (a microphone hears the-// people at the table), or 电脑和会议室 (both, each with its own ListenEngine). The parts that don't-// touch a device live here so they test on the Mac.--/// The Mac's `listenSource` values.public static class ListenSource{public const string System = "system", Room = "room", Both = "both";public static string Parse(string? s) => s is Room or Both ? s : System;}-/// Which microphone hears the room.public static class RoomMicPlan{public sealed record Input(string Id, bool Bluetooth = false, bool Virtual = false);- /// The default input, unless it is the virtual cable (同声传译's) or a Bluetooth headset's (it- /// hears the wearer, not the table, and drops to call quality while its mic is open); then the- /// first other one, a headset only when nothing else is left.public static string? Pick(string? defaultId, IReadOnlyList<Input> inputs){if (inputs.FirstOrDefault(i => i.Id == defaultId) is { Virtual: false, Bluetooth: false } d) return d.Id;@@ -26,10 +17,6 @@ public static class RoomMicPlan}}-/// When a frame counts as speech. The computer's own audio is digital silence between words, so a-/// fixed -40 dBFS works there. A room mic always hears the room (a fan, the street), and a voice-/// across the table can be quieter than that: there the line sits at twice the room's own noise,-/// the quietest moment of each second taken low over the last half minute (VoiceGate in RoomMic.swift).public sealed class VoiceGate{public const double Fixed = 0.01, Lowest = 0.0015;@@ -46,7 +33,6 @@ public sealed class VoiceGate}}- /// Takes one frame's level and length; true when it is over the line.public bool Voiced(double rms, double seconds){var on = rms >= Threshold;@@ -63,19 +49,14 @@ public sealed class VoiceGate}}-/// The room mic as listening hears it: silence while `Muted` (you holding the talk key) or while-/// `Silenced` says so (电脑和会议室's echo gate). Silence rather than nothing keeps the segmenter's-/// clock in step.public sealed class GatedSource : IAudioSource{readonly IAudioSource inner;public Func<bool>? Silenced { get; set; }- /// Each buffer's level (0–1) and length in seconds, before silencing.public Action<double, double>? Heard { get; set; }public volatile bool Muted;public event Action<short[]>? Samples;public event Action<string?>? Ended;- /// The microphone's name, for the log and the panel.public string? Name { get; init; }public GatedSource(IAudioSource inner)@@ -83,7 +64,6 @@ public sealed class GatedSource : IAudioSourcethis.inner = inner;inner.Samples += buf =>{- // What the mic really hears, for EchoGate's measurement, before any silencing.if (Heard is { } heard && buf.Length > 0){double sum = 0;diff --git a/windows/src/Cicada.Core/Segmenter.cs b/windows/src/Cicada.Core/Segmenter.csindex fae2dc6..bf22886 100644--- a/windows/src/Cicada.Core/Segmenter.cs+++ b/windows/src/Cicada.Core/Segmenter.cs@@ -1,59 +1,49 @@namespace Cicada;-/// A stretch of speech to send to Ming: where it starts (seconds since listening began) and its-/// 16 kHz mono samples.public sealed record Segment(int Index, double Start, short[] Samples){public double Seconds => Samples.Length / (double)Segmenter.Rate;}-/// Cuts the system audio into stretches of speech by loudness alone: a pause of 0.6 s ends one,-/// and one that runs to 8 s is cut at its quietest moment in the last 2 s, so a word is split as-/// rarely as possible (Ming has no word timings to put it back together). Not thread-safe: fed-/// from the audio queue only.public sealed class Segmenter{public const int Rate = 16000;- const int Frame = 480; // 30 ms- const int Step10 = 160; // 10 ms: a key click is judged in these, as the Mac's VoiceActivity does- const int Onset = 3; // steps of sound before it counts as speech- public static double Threshold = 0.01; // the Mac AudioRouter's gate (about -40 dBFS)+ const int Frame = 480;+ const int Step10 = 160;+ const int Onset = 3;+ public static double Threshold = 0.01;public static double Pause = 0.6, MaxLength = 8.0, MinSpeech = 0.25;- public static double MinWord = 0.2; // a word on its own (IsWord): this much over gate / 4- public static double Steady = 2.0; // frames' 90th / 10th percentile below this: not speech…- public static double Dips = 2.5; // …unless the median is this far over the 10th, quiet ones held at gate / 8- public static double Short = 2.0; // a sound up to this long, with real quiet (gate / 4) on both sides…- public static double Swell = Math.Pow(10, 10 / 20.0); // …that swells and fades by 10 dB is a word: see IsWord- public static double Fade = Math.Pow(10, 30 / 20.0); // its rise and fade reach this far under its loudest step (or gate / 4 if lower)- public static double Voiced = 0.15; // a word's full frames crossing zero under this often (per sample) have voice in them: see IsVoiced- public static double Above = 0.25; // under this share of its loud frames' energy over 100 Hz: rumble, not speech+ public static double MinWord = 0.2;+ public static double Steady = 2.0;+ public static double Dips = 2.5;+ public static double Short = 2.0;+ public static double Swell = Math.Pow(10, 10 / 20.0);+ public static double Fade = Math.Pow(10, 30 / 20.0);+ public static double Voiced = 0.15;+ public static double Above = 0.25;const double PreRoll = 0.15, Tail = 0.15, CutWindow = 2.0;- // A first-order high-pass at 100 Hz, for how much of a sound is above it (IsRumble).static readonly double HighPass = 1.0 / (1.0 + 2.0 * Math.PI * 100.0 / Rate);- readonly List<short> pending = []; // samples not yet a whole frame- readonly List<short> current = []; // the open segment- readonly List<double> levels = []; // per frame of `current`- readonly List<double> highs = []; // per frame of `current`: its level over 100 Hz- readonly List<bool> speech = []; // per frame of `current`: whether it held speech (IsSpeech)- double hx, hy; // the high-pass's last input and output, carried from frame to frame- readonly Queue<(short[] frame, double level, double high)> before = new(); // recent quiet frames, for the pre-roll- readonly Queue<double> idle = new(); // levels of the last 0.6 s of quiet frames- double? lead; // the quietest of those when the open segment began- long consumed; // samples seen, for timestamps+ readonly List<short> pending = [];+ readonly List<short> current = [];+ readonly List<double> levels = [];+ readonly List<double> highs = [];+ readonly List<bool> speech = [];+ double hx, hy;+ readonly Queue<(short[] frame, double level, double high)> before = new();+ readonly Queue<double> idle = new();+ double? lead;+ long consumed;double currentStart;int quietFrames, loudFrames, index;- int sounding; // 10 ms steps of sound in a row so far- bool carried; // the sound that made the last frame speech began in the frame before- /// 会议室: a microphone's line follows the room's noise (VoiceGate); null keeps the fixed one.- /// Swapped when 听哪里 changes mid-meeting (read once per frame on the audio thread).+ int sounding;+ bool carried;public VoiceGate? Gate { get => gate; set => gate = value; }volatile VoiceGate? gate;double line = Threshold;public Segmenter(VoiceGate? gate = null) { this.gate = gate; }- /// The level that counts as speech right now.public double Line => line;public event Action<Segment>? Emitted;@@ -70,7 +60,6 @@ public sealed class Segmenterpending.RemoveRange(0, whole);}- /// Ends the open segment (listening stopped).public void Flush(){if (current.Count > 0) Close(current.Count - quietFrames * Frame + (int)(Tail * Rate));@@ -83,11 +72,6 @@ public sealed class Segmenterreturn Math.Sqrt(sum / frame.Length) / 32768;}- /// Whether the frame holds speech: sound that has lasted 30 ms, judged in 10 ms steps against the- /// line, so a lone key click (a few ms) neither opens a segment nor breaks the pause that ends one- /// (VoiceActivity.swift's onset); the pre-roll then reaches back to where that sound began. A- /// room's gate learns its noise per frame and takes whole ones, as the Mac's does per block: a- /// voiced 30 ms frame has lasted the onset already.bool IsSpeech(short[] frame, double level, VoiceGate? g){if (g is not null)@@ -132,7 +116,6 @@ public sealed class Segmenterwhile (before.Count > PreRoll * Rate / Frame + 1) before.Dequeue();return;}- // One frame more when the sound began in the last quiet one.while (before.Count > PreRoll * Rate / Frame + (carried ? 1 : 0)) before.Dequeue();currentStart = now - before.Count * Frame / (double)Rate;lead = idle.Count > 0 ? idle.Min() : null;@@ -154,7 +137,6 @@ public sealed class Segmenter}else if (current.Count >= MaxLength * Rate){- // The quietest frame in the last 2 s; the rest starts the next segment.int from = Math.Max(1, levels.Count - (int)(CutWindow * Rate / Frame));int cut = from;for (int i = from; i < levels.Count; i++) if (levels[i] < levels[cut]) cut = i;@@ -162,19 +144,6 @@ public sealed class Segmenter}}- /// Steady sound just over the gate (a fan, hum, hiss) isn't speech: its frames barely vary- /// (90th / 10th percentile about 1.1; speech, even over such a floor, 3 and up). Given one, Ming- /// writes a stock sentence in the hint's language ("I'm going to show you a couple of things").- /// Speech buried under steady noise goes too; system audio rarely carries it. Every frame from- /// the first loud one to the last counts, the quiet ones held at the gate: counting only the- /// loud ones dropped quiet speech (under about -30 dBFS), whose dips fall below the gate.- /// A voice so quiet that its loudest frames barely clear the gate (about -38 dBFS: 6 of 6 lines- /// lost in testing) still pauses between syllables, its quietest tenth of frames far under its- /// median (8 dB and more); noise near the gate stays within about 6 dB of its median. So a flat- /// top is steady only when it has no such dips, measured with quiet frames held at gate / 8.- /// Very low rumble (brown noise with almost nothing over 20 Hz) can look like that and gets- /// through more often than before (about 1 in 3 segments, was 1 in 5); what Ming makes of it- /// still meets the hear filter (Translator.IsNoise).internal static bool IsSteady(IEnumerable<double> frameLevels, double? gate = null){var all = frameLevels.ToList();@@ -188,22 +157,6 @@ public sealed class Segmenterreturn low[(int)(0.5 * (low.Count - 1))] < Dips * low[(int)(0.1 * (low.Count - 1))];}- /// A short word on its own: a sound up to `Short` that rises out of real quiet and falls back- /// into it (under gate / 4, about -52 dBFS, in the 0.6 s before it and in the pause after),- /// and that swells and fades by 10 dB or more: at least 5% of its 10 ms steps (and 3 of them),- /// from where it rises to where it fades, are that far under its 90th percentile. Such a word- /// ("Thanks.", "Good morning everyone,") is one smooth syllable or a run of voiced ones, so the- /// steady test, which looks for dips inside, dropped it even at -26 dBFS; and a quiet one- /// ("Thanks." at -36 dBFS) has under 0.25 s over the gate, so it needs `MinWord` over gate / 4- /// instead (a knock with a 150 ms tail has 0.15 s). A fan, hum or hiss is there on both sides;- /// a short burst of one in silence has at most one low step at each edge (its 5th percentile- /// stays within 2 dB, 9 dB with 50 ms fades), and Ming makes up a sentence for a hum or fan- /// burst. Not for a forced cut, whose end isn't a pause.- /// Where it rises and fades: over gate / 4, or 30 dB under its loudest step if that's lower;- /// over gate / 4 alone, a quiet word lost its rise and fade (an "s" or breath at -55 dBFS) and- /// only its flat top was left. 30 ms frames and their 10th percentile put Samantha's "Good- /// morning everyone." at 7.5 to 11.4 dB depending on where the frames fell, so it came and- /// went with a few ms of lead-in; 10 ms steps and their 5th percentile give it 14.6 to 16.5.internal bool IsWord(List<double> frameLevels, double gate){int first = frameLevels.FindIndex(l => l >= gate), last = frameLevels.FindLastIndex(l => l >= gate);@@ -224,11 +177,6 @@ public sealed class Segmenterreturn low < body.Count && body[(int)(0.9 * (body.Count - 1))] >= Swell * body[low] && IsVoiced(frameLevels);}- /// Whether a word has voice in it: 2 or more of its full frames (within 3 dB of its 90th- /// percentile) cross zero under `Voiced` times a sample. Voiced speech crosses slowly (every- /// voice tested had full frames at 0.01 to 0.06); a hiss crosses about every other sample (0.46- /// and up) and, faded in and out over 0.3 s, swells like a word. Edge frames half silence- /// cross slowly whatever they hold, hence full frames only and more than one.bool IsVoiced(List<double> frameLevels){double full = frameLevels.Order().ElementAt((int)(0.9 * (frameLevels.Count - 1))) / Math.Sqrt(2);@@ -243,7 +191,6 @@ public sealed class Segmenterreturn slow >= 2;}- /// The frame's level over 100 Hz (RMS after the high-pass), the filter running on across frames.double High(short[] frame){double a = HighPass, x0 = hx, y = hy, total = 0;@@ -258,12 +205,6 @@ public sealed class Segmenterreturn frame.Length == 0 ? 0 : Math.Sqrt(total / frame.Length) / 32768;}- /// Rumble, not speech: under a quarter of the loud frames' energy is over 100 Hz. Speech keeps- /// nearly all of it there (-0.3 to -1 dB in testing, the low male voices included); brown noise- /// with almost nothing over 20 Hz keeps -20 to -28 dB, and Ming made a sentence of 15 of 17 such- /// segments ("I'm going to go ahead and start the meeting."), which the loudness rules can't- /// tell from a voice. Brown noise up to about 12 Hz keeps -10 dB and goes too; a 50 Hz hum or a- /// fan keeps about -5 dB and is left to the steady test.internal static bool IsRumble(List<double> frameLevels, List<double> frameHighs, double gate){double full = 0, above = 0;@@ -276,7 +217,6 @@ public sealed class Segmenterreturn above < Above * full;}- /// Emits `current[..end]` and keeps what follows as the start of the next segment.void Close(int end){end = Math.Clamp(end, 0, current.Count);@@ -295,7 +235,6 @@ public sealed class SegmenterquietFrames = 0; loudFrames = 0;if (said) Emitted?.Invoke(new Segment(++index, Math.Round(start, 3), samples));- // A forced cut carries on with the remainder; after a pause the remainder is silence.if (restSpeech.Contains(true)){currentStart = start + end / (double)Rate;diff --git a/windows/src/Cicada.Core/SessionStore.cs b/windows/src/Cicada.Core/SessionStore.csindex 3ed20b6..b1227e5 100644--- a/windows/src/Cicada.Core/SessionStore.cs+++ b/windows/src/Cicada.Core/SessionStore.cs@@ -3,9 +3,6 @@ using System.Text;namespace Cicada;-/// The meeting records: one folder per meeting under Sessions\<yyyyMMdd-HHmmss>\ with-/// session.json, as on the Mac. Saves are debounced by 1.5 s; a meeting with no lines is removed-/// when it ends. Thread-safe; `Changed` fires on whichever thread made the change.public sealed class SessionStore{readonly object gate = new();@@ -13,13 +10,8 @@ public sealed class SessionStorereadonly HashSet<string> dirty = [];Timer? saveTimer;public event Action<string>? Changed;- /// The moment recognised words land in a record: a new line (theirs or mine) or a half sentence- /// that grew. What 结束会议 counts as someone speaking (MeetingEndWatch.Heard).public event Action<string>? Words;- /// A record was written to disk (存到文件夹 follows its changes); on the saving thread.public event Action<string>? Saved;- /// The app's audio encoder (Media Foundation); null where there is none (the Mac CLI, tests- /// that don't set one): meetings are then kept without a recording.public IAudioFiles? Audio { get; set; }public SessionStore() { Load(); }@@ -37,7 +29,6 @@ public sealed class SessionStoretry{if (Json.Read<Session>(File.ReadAllText(file)) is not { } s) continue;- // The app quit mid-meeting: it ended just after its last line (SessionStore.swift › load).s.EndedAt ??= s.Lines.Count > 0 ? s.StartedAt.AddSeconds(s.Lines[^1].T + 5) : s.StartedAt;sessions[s.Id] = s;}@@ -45,7 +36,6 @@ public sealed class SessionStore}}- /// Newest first.public List<Session> All(){lock (gate) return sessions.Values.OrderByDescending(s => s.StartedAt).ToList();@@ -65,13 +55,9 @@ public sealed class SessionStorereturn s;}- /// The stored default title is always Chinese ("会议 11月1日 14:30"), as on the Mac; the UI- /// shows DisplayTitle instead.public static string DefaultTitle(DateTimeOffset at) =>"会议 " + at.ToLocalTime().ToString("M月d日 HH:mm", CultureInfo.InvariantCulture);- /// The user's own title, else the date and the name the notes gave the meeting, else the- /// default title in the UI language (Session.displayTitle).public static string DisplayTitle(Session s){if (s.Renamed ?? !s.Title.StartsWith("会议 ")) return s.Title;@@ -96,16 +82,13 @@ public sealed class SessionStore{int i = s.Lines.FindIndex(l => l.Id == line.Id);if (i < 0) return;- grew = line.Src.Length > s.Lines[i].Src.Length; // a half sentence joined, not a retranslation- // The listening engine keeps its own copy of the line and knows nothing of its fixes- // (SetFixes): a retranslation or a join keeps them.+ grew = line.Src.Length > s.Lines[i].Src.Length;line.Fixes ??= s.Lines[i].Fixes;s.Lines[i] = line;});if (grew) Words?.Invoke(id);}- /// A line's fixes (Correction): what the AI service proposed and the user decided.public void SetFixes(string id, string lineId, IReadOnlyList<LineFix> fixes){Mutate(id, s =>@@ -120,14 +103,11 @@ public sealed class SessionStorepublic void SetNotes(string id, MeetingNotes notes) => Mutate(id, s => s.Notes = notes);- /// Heard through a microphone in the room for some or all of it (SessionStore.swift › markLiveInRoom).public void MarkRoom(string id){if (Get(id) is { Room: not true }) Mutate(id, s => s.Room = true);}- /// An empty title, or the one shown already, goes back to / stays on the automatic one- /// (SessionStore.swift › rename): saving the dialog unchanged mustn't freeze the notes' name.public void Rename(string id, string title){var t = title.Trim();@@ -136,14 +116,8 @@ public sealed class SessionStoreMutate(id, s => { s.Title = t; s.Renamed = true; });}- /// Back to the default title, so the name the notes give the meeting shows again.public void ResetTitle(string id) => Mutate(id, s => { s.Title = DefaultTitle(s.StartedAt); s.Renamed = false; });- /// The meeting ended (at `endedAt` when it ended by itself a while ago): kept if anything was- /// said, removed otherwise.- /// The meeting's recording, if any, is closed by then (ListenEngine.Stop): it is rewrapped into- /// system.m4a in the background, cut at `endedAt` when the meeting ended by itself a while ago- /// (its silent tail), as SessionStore.swift › end does.public void End(string id, DateTimeOffset? endedAt = null){bool empty;@@ -162,8 +136,6 @@ public sealed class SessionStore_ = Task.Run(() => FinishAudio(id, until));}- /// Recordings a meeting didn't get to close (the app was killed or the PC went off): the- /// partial file is rewrapped now, as SessionStore.swift › load does. Call once Audio is set.public void FinishLeftovers(string? live = null){List<string> left;@@ -175,8 +147,6 @@ public sealed class SessionStore}}- /// system.aac into system.m4a. A partial file beside an .m4a means the last rewrap was cut- /// short: it is done again. One that fails leaves the partial file for the next launch.void FinishAudio(string id, double? until){var m4a = Recording.SystemAudio(id);@@ -229,7 +199,6 @@ public sealed class SessionStore}}- /// Writes every changed record now (also on quit).public void Flush(){List<(string id, string json)> writes;@@ -254,7 +223,6 @@ public sealed class SessionStore// MARK: Export- /// The record as Markdown: notes, then the bilingual transcript.public static string Markdown(Session s){var b = new StringBuilder();@@ -266,7 +234,6 @@ public sealed class SessionStorevar names = SpeakerLabels.Names(s);foreach (var l in s.Lines.OrderBy(x => x.T)){- // Your own lines (the talk key) say so: what the meeting heard was their translation (同传).var who = l.Speaker == "me" ? Strings.L("你 · 同传") : numbers.TryGetValue(l.Id, out var num) ? names.GetValueOrDefault(num) ?? Strings.LF("说话人 %lld", num) : null;b.AppendLine($"**{Languages.Clock(l.T)}**{(who is null ? "" : $" {who}:")} {l.Shown} ");if (!string.IsNullOrEmpty(l.Dst) && l.Dst != l.Src && l.Dst != l.Shown) b.AppendLine($"{l.Dst}");@@ -275,7 +242,6 @@ public sealed class SessionStorereturn b.ToString();}- /// The notes alone (复制纪要): title, summary, topics, conclusions, to-dos.public static string NotesMarkdown(Session s) =>s.Notes is { IsEmpty: false } n ? $"# {DisplayTitle(s)}\n\n" + NotesBody(n) : "";diff --git a/windows/src/Cicada.Core/Settings.cs b/windows/src/Cicada.Core/Settings.csindex d12310f..8d5a4fe 100644--- a/windows/src/Cicada.Core/Settings.cs+++ b/windows/src/Cicada.Core/Settings.cs@@ -3,17 +3,11 @@ using System.Text.Json.Serialization;namespace Cicada;-/// 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; } = [];@@ -21,77 +15,43 @@ public sealed class AppSettings[JsonPropertyName("aiCustomBase")] public string AiCustomBase { get; set; } = "";[JsonPropertyName("aiCustomVoiceBase")] public string AiCustomVoiceBase { get; set; } = "";[JsonPropertyName("aiCustomVoice")] public string AiCustomVoice { get; set; } = "";- /// A custom service's hear model at its own address (the Mac's key); empty: the same one.[JsonPropertyName("aiCustomHearBase")] public string AiCustomHearBase { get; set; } = "";- /// 语音和文字只发给你的服务 (the Mac's key): with the custom service, Google Translate is never- /// asked. Kept when another service is picked, but only acts on the custom one (GoogleOff).[JsonPropertyName("aiCustomOnly")] public bool AiCustomOnly { get; set; }- /// A custom service's notes (the Mac's keys): 另一个服务 (its own address, empty: the same one, and- /// its own key in the `custom-notes` key file). Off keeps the address, so switching back and- /// forth loses nothing. The notes model is AiModels["custom.notes"] (empty: the translation model).[JsonPropertyName("aiCustomNotesOwn")] public bool AiCustomNotesOwn { get; set; }[JsonPropertyName("aiCustomNotesBase")] public string AiCustomNotesBase { get; set; } = "";[JsonIgnore] public bool GoogleOff => AiProvider == "custom" && AiCustomOnly;- /// 打开麦克风: "both" while the mic is on, else "system" (the Mac's listenSource values; "room",- /// the mic alone, is the Mac's on macOS 14/15). Not saved: every launch starts with the mic off.[JsonIgnore] public string ListenSourceValue { get; set; } = ListenSource.System;[JsonIgnore] public string Listens => ListenSource.Parse(ListenSourceValue);[JsonIgnore] public bool ListensToRoom => Listens == ListenSource.Room;[JsonIgnore] public bool HearsBoth => Listens == ListenSource.Both;- /// "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.[JsonPropertyName("trayHintShown")] public bool TrayHintShown { get; set; }- /// 共享屏幕时让对方看到: let the notes window and subtitles show up in screen sharing.[JsonPropertyName("showInCapture")] public bool ShowInCapture { get; set; }[JsonPropertyName("onboarded")] public bool Onboarded { get; set; }- /// The setup checklist (主窗口 › 还差几步): the onboarding heard the PC's sound / played the sample.[JsonPropertyName("heardSystemAudio")] public bool HeardSystemAudio { get; set; }[JsonPropertyName("sampleSeen")] public bool SampleSeen { get; set; }- /// The UI language: "system", "zh-Hans", "en", "ja" or "ko".[JsonPropertyName("uiLanguage")] public string UiLanguage { get; set; } = "system";- /// 字幕文字大小, in px.[JsonPropertyName("subtitleSize")] public int SubtitleSize { get; set; } = 24;- /// 保存会议录音 (the Mac's key): keep what was heard as system.m4a in the meeting's folder.[JsonPropertyName("recordAudio")] public bool RecordAudio { get; set; } = true;- /// 存到文件夹 (the Mac's keys): settled meetings are also written as Markdown into exportFolder- /// (a path; empty until one is chosen). FolderExport.cs.[JsonPropertyName("exportOn")] public bool ExportOn { get; set; }[JsonPropertyName("exportFolder")] public string ExportFolder { get; set; } = "";- /// 说话人识别: tell the other side's voices apart (on by default, as on the Mac).[JsonPropertyName("speakerVoices")] public bool SpeakerVoices { get; set; } = true;- /// 会中改正听错的词 (the Mac's key): finished sentences carry the word list to the AI service,- /// which points out misheard words (Correction). On by default; does nothing without a service.[JsonPropertyName("fixMisheard")] public bool FixMisheard { get; set; } = true;- /// 没见过的名字和专称先问我: a new name is asked about once instead of left as heard.[JsonPropertyName("askNames")] public bool AskNames { get; set; } = true;- /// 同声传译: hold the talk key to speak into the meeting in its language.[JsonPropertyName("speak")] public bool Speak { get; set; }- /// The talk key, a TalkKey name ("rcontrol", "f13"…): not every keyboard has right Ctrl.[JsonPropertyName("talkKey")] public string TalkKey { get; set; } = Cicada.TalkKey.Default;- /// 我说的语言: "system" or a source code.[JsonPropertyName("speakFrom")] public string SpeakFrom { get; set; } = "system";- /// 对方听到的语言: "room" (what the other side speaks) or a target code.[JsonPropertyName("speakTo")] public string SpeakTo { get; set; } = "room";- /// The voice for each language the room hears ("en" → "ming:US_Emma", or "system").[JsonPropertyName("speakVoices")] public Dictionary<string, string> SpeakVoices { get; set; } = [];- /// The one-time "知了还在听" notice after the panel is first collapsed while listening.[JsonPropertyName("toldStillListening")] public bool ToldStillListening { get; set; }- /// 结束会议 (MeetingEnd.cs), the Mac's keys: end when the meeting app hangs up; when nobody- /// speaks, "prompt" (count down, then end), "end" or "off", after silenceMinutes.[JsonPropertyName("endWithApp")] public bool EndWithApp { get; set; } = true;[JsonPropertyName("silenceEnd")] public string SilenceEnd { get; set; } = "prompt";[JsonPropertyName("silenceMinutes")] public double SilenceMinutes { get; set; } = 10;- /// When GitHub Releases last answered an update check (UpdateChecker).[JsonPropertyName("updateLastChecked")] public DateTimeOffset? UpdateLastChecked { get; set; }- /// The version the update notification was last shown for: one per version.[JsonPropertyName("updateNotified")] public string? UpdateNotified { get; set; }- /// The startup notification that VB-Cable holds the speaker was shown (CableDefaults.ShouldNotify);- /// cleared when a real speaker is back.[JsonPropertyName("cableSpeakerNotified")] public bool CableSpeakerNotified { 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;diff --git a/windows/src/Cicada.Core/Setup.cs b/windows/src/Cicada.Core/Setup.csindex 3f2454f..93352d5 100644--- a/windows/src/Cicada.Core/Setup.cs+++ b/windows/src/Cicada.Core/Setup.cs@@ -1,19 +1,12 @@namespace Cicada;-/// What a launch of the release exe should do. The downloaded installer is Cicada.exe under another name:-/// a copy that isn't the installed one installs itself into the user's folder (no admin), so-/// autostart, the Start menu and updates always point at one place.public static class SetupPlan{public enum Step{- /// This is the installed copy (or a dev build): start as usual.Run,- /// Nothing installed: ask, then copy in.Install,- /// An older version is installed: offer to replace it.Upgrade,- /// The same or a newer version is installed: open that one instead (never downgrade).Open,}@@ -24,18 +17,13 @@ public static class SetupPlanreturn UpdateChecker.IsNewer(version, installedVersion) ? Step.Upgrade : Step.Open;}- /// Windows paths: case-insensitive, `..` and `/` resolved.public static bool Same(string a, string b){try { return string.Equals(Path.GetFullPath(a).TrimEnd('\\', '/'), Path.GetFullPath(b).TrimEnd('\\', '/'), StringComparison.OrdinalIgnoreCase); }catch { return false; }}- /// The Start menu entry is named in the language of the UI at install time, so people find- /// what they see; the files and paths stay "Cicada" (Chinese names get mangled in downloads).public static string ShortcutName(string language) => language == "zh-Hans" ? "知了" : "Cicada";- /// Every name a shortcut may have had, so a reinstall in another language leaves only one.public static readonly string[] ShortcutNames = ["知了", "Cicada"];- /// Settings › Apps sorts and searches by name: both names, so either language finds it.public const string DisplayName = "知了 Cicada";}diff --git a/windows/src/Cicada.Core/Share.cs b/windows/src/Cicada.Core/Share.csindex 29ca01c..1a8e064 100644--- a/windows/src/Cicada.Core/Share.cs+++ b/windows/src/Cicada.Core/Share.cs@@ -9,14 +9,8 @@ using System.Text.Json.Serialization;namespace Cicada;-// 分享…: a meeting as a link on cicada.indaloop.app, as on the Mac (ShareProjection.swift,-// ShareClient.swift). Only the share document leaves the computer, the same bytes the Mac makes-// (Tests/fixtures/share); server/src/doc.js reads exactly these fields.-public enum ShareScope { Notes, Full }-/// The share document (v1). Never the record's file paths, Ling's guesses at names with the lines-/// they came from, or the record's own bookkeeping. Speakers are 说话人 N unless names are asked for.public sealed record ShareDoc(string Title, string StartedAt, int Duration, List<string> Langs, ShareDoc.NotesPart? Notes, List<ShareDoc.Line> Lines, int Hidden){public sealed record Line(double T, string Who, string Src, string? Dst);@@ -28,11 +22,9 @@ public sealed record ShareDoc(string Title, string StartedAt, int Duration, Listpublic static class ShareProjection{- /// `removed`: indices into the record's lines the user took out; `dropNotes` leaves the notes out.public static ShareDoc Doc(Session s, ShareScope scope, bool names, ISet<int>? removed = null, bool dropNotes = false){removed ??= new HashSet<int>();- // Not gated on 说话人识别, as on the Mac: the numbers come from the record's voices.var numbers = SpeakerLabels.Numbers(s.Lines);var nameMap = names ? SpeakerLabels.Names(s) : [];string Who(TranscriptLine l)@@ -66,11 +58,9 @@ public static class ShareProjectionLanguages(s.Lines), notes, lines, hidden);}- /// The record lines a full share sends, in order: the server's line numbers index this list.public static List<int> Kept(Session s, ShareScope scope, ISet<int> removed) =>scope == ShareScope.Full ? [.. Enumerable.Range(0, s.Lines.Count).Where(i => !removed.Contains(i) && s.Lines[i].Src.Length > 0)] : [];- /// The meeting's usual direction ("en" → "zh"), by the most lines; ties go to the earliest.public static List<string> Languages(IReadOnlyList<TranscriptLine> lines){var count = new Dictionary<string, int>();@@ -90,21 +80,17 @@ public static class ShareProjectionstatic string Base(string code) => (code.Split('-', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ?? code).ToLowerInvariant();- /// One decimal, rounded half away from zero as Swift's `rounded()`: the same bytes everywhere.static double Round(double t) => Math.Round(t * 10, MidpointRounding.AwayFromZero) / 10;- /// Ling wrote "说话人 6" before anyone named them: the name since given (SpeakerLabels.named).public static string Named(string text, IReadOnlyDictionary<int, string> names){if (names.Count == 0 || !(text.Contains("说话人") || text.Contains("Speaker"))) return text;- foreach (var (n, name) in names.OrderByDescending(kv => kv.Key)) // 说话人 12 before 说话人 1+ foreach (var (n, name) in names.OrderByDescending(kv => kv.Key))foreach (var form in new[] { $"说话人 {n}", $"说话人{n}", $"Speaker {n}" })text = text.Replace(form, name, StringComparison.Ordinal);return text;}- /// Compact, sorted keys, slashes unescaped, whole numbers without ".0": Swift's JSONEncoder with- /// [.sortedKeys, .withoutEscapingSlashes], written by hand so no encoder default can drift.public static string Encode(ShareDoc d){var b = new StringBuilder();@@ -159,10 +145,8 @@ public static class ShareProjectionb.Append(']');}- /// Shortest round-trip text; a whole number has no fraction (605, not 605.0).static void Num(StringBuilder b, double v) => b.Append(v.ToString("R", CultureInfo.InvariantCulture));- /// As Swift escapes: quote, backslash and control characters only; everything else as is.static void Str(StringBuilder b, string s){b.Append('"');@@ -183,9 +167,6 @@ public static class ShareProjection}}-/// A meeting shared as a link: what this computer keeps about it. The manage token (needed to turn-/// the link off) and the password live only in Shares/<record id>.json, sealed like the AI keys,-/// never in the record, exports or logs.public sealed class ShareRecord{[JsonPropertyName("createdAt")] public DateTimeOffset CreatedAt { get; set; }@@ -196,9 +177,6 @@ public sealed class ShareRecord[JsonPropertyName("token")] public string Token { get; set; } = "";[JsonPropertyName("url")] public string Url { get; set; } = "";- /// What 生成并复制 and 复制 put on the clipboard, in the UI's language (the Mac's- /// ShareSheet.clipboardText): the title, the link on a line of its own (chat apps then make it- /// a link), the password and how long it stays open.public string Message(string title, DateTimeOffset now){var left = DaysLeft(now);@@ -207,19 +185,15 @@ public sealed class ShareRecordreturn string.Join("\n", Strings.LF("「%@」会议记录", title), Url, last);}- /// Whole days until the link closes, at least 1. The server sets the expiry from its own clock,- /// so a computer a second behind it would round a fresh 7-day link up to 8: an hour's slack.public int DaysLeft(DateTimeOffset now) => Math.Max(1, (int)Math.Ceiling((ExpiresAt - now - TimeSpan.FromHours(1)).TotalDays));}-/// Where the review found a problem: the notes, or lines `from`…`to` of what was sent.public sealed record ShareHit([property: JsonPropertyName("part")] string Part,[property: JsonPropertyName("from")] int? From,[property: JsonPropertyName("to")] int? To,[property: JsonPropertyName("questions")] List<string> Questions){- /// The record's line indices behind the hits, given which record lines were sent (`kept`).public static HashSet<int> RecordLines(IEnumerable<ShareHit> hits, IReadOnlyList<int> kept){var outp = new HashSet<int>();@@ -236,12 +210,9 @@ public static class SharePassword{public const int Iterations = 210_000;- /// PBKDF2-SHA256, 32 bytes: what the browser derives from the password (site/share.js). The- /// server keeps only its hash, so the password itself never leaves either side.public static byte[] Verifier(string password, byte[] salt, int iterations = Iterations) =>Rfc2898DeriveBytes.Pbkdf2(Encoding.UTF8.GetBytes(password), salt, iterations, HashAlgorithmName.SHA256, 32);- /// "ruby-41-lake": easy to read out and type; the server limits how many can be tried.public static string Make(){var w = Words.Split(' ');@@ -251,7 +222,6 @@ public static class SharePasswordconst string Words = "amber apple arrow aspen basil beach birch bloom brook cedar cherry cloud coral comet dawn delta dune ember fern field flint frost grove harbor hazel honey iris island jade lake lark lemon lily linen maple meadow mint moss olive orbit pearl pine plum pond quartz rain reed river ruby sage sand shell silk sky slate snow spruce stone storm sun tide tulip velvet willow wind";}-/// A file only this user can read: DPAPI-sealed on Windows ("dpapi:" + base64, as AIKey), 0600 elsewhere.public static class SecretFile{public static bool Write(IKeyProtector protector, string path, string text)@@ -291,7 +261,6 @@ public static class SecretFile}}-/// Shares/<record id>.json, sealed.public sealed class ShareStore(IKeyProtector protector, string? folder = null){public string Folder => folder ?? Path.Combine(Paths.Root, "Shares");@@ -338,10 +307,6 @@ public abstract record ShareOutcomepublic sealed record Failed(string Code, int? RetryAfter) : ShareOutcome;}-/// Talks to the share service (server/). No accounts: this install is an Ed25519 key made on first-/// use (share-device.json, sealed), registered once with a small proof of work, and every write is-/// signed (method, path, time, nonce, body hash), as server/src/auth.js checks. Not an AI call, so-/// not LingClient: the review runs on the server.public sealed class ShareClient{readonly IKeyProtector protector;@@ -360,7 +325,6 @@ public sealed class ShareClientreadonly string? root;- /// A dev build can point at a local Worker: CICADA_SHARE_SERVER=http://127.0.0.1:8787.public Uri Base => Environment.GetEnvironmentVariable("CICADA_SHARE_SERVER") is { Length: > 0 } s && Uri.TryCreate(s, UriKind.Absolute, out var u)? u : new Uri("https://cicada.indaloop.app");@@ -388,8 +352,6 @@ public sealed class ShareClientvoid SaveDevice(Device d) => SecretFile.Write(protector, DeviceFile, JsonSerializer.Serialize(d, Json.Compact));- /// The key and device id, registering this install with the server first if needed. One at a- /// time: the server allows only a few registrations a day from one address.async Task<(byte[] key, string id)> Registered(bool force = false){await registering.WaitAsync();@@ -418,7 +380,6 @@ public sealed class ShareClientfinally { registering.Release(); }}- /// 20 leading zero bits of sha256(public key ‖ 8-byte big-endian nonce): about a million hashes.public static byte[] ProofOfWork(byte[] pub){var work = new byte[pub.Length + 8];@@ -449,7 +410,6 @@ public sealed class ShareClientvar time = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture);var nonce = B64Url(RandomNumberGenerator.GetBytes(16));var hash = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(body ?? "")));- // The path as it goes on the wire, query included, so the server's URL reads the same.var message = $"{method}\n{req.RequestUri!.PathAndQuery}\n{time}\n{nonce}\n{hash}";req.Headers.TryAddWithoutValidation("X-Cicada-Device", id);req.Headers.TryAddWithoutValidation("X-Cicada-Time", time);@@ -468,7 +428,6 @@ public sealed class ShareClient}}- /// A signed call; registers again once if the server no longer knows this install.async Task<(string body, int status)> Signed(string method, string path, string? body = null, Dictionary<string, string>? headers = null){var signer = await Registered();@@ -481,7 +440,6 @@ public sealed class ShareClientreturn (data, status);}- /// Never throws: the dialog awaits it from an event handler.public async Task<ShareOutcome> Share(Session s, ShareOptions o){try { return await Attempt(s, o); }@@ -507,8 +465,6 @@ public sealed class ShareClientvar v = await Task.Run(() => SharePassword.Verifier(pw, salt));body["password"] = new JsonObject { ["salt"] = B64Url(salt), ["iter"] = SharePassword.Iterations, ["hash"] = B64Url(SHA256.HashData(v)) };}- // The same meeting, content and settings sent again (the answer was lost) gets the same link- // back; any other setting makes a new share.var settings = $"{scope}|{o.Days}|{(o.Names ? "true" : "false")}|{o.Password ?? ""}|{(o.SummaryInPreview ? "true" : "false")}";var idem = s.Id + "-" + Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(doc + settings))[..8]);try@@ -547,14 +503,12 @@ public sealed class ShareClient}}- /// Turns the link off on the server and forgets it here. `sessionId` null: it is being replaced.public async Task<bool> Revoke(ShareRecord r, string? sessionId){bool ok;try{var (data, status) = await Signed("DELETE", "/api/v1/shares/" + r.Id, null, new() { ["Authorization"] = "Bearer " + r.Token });- // 404: already gone (or never ours); either way nothing to keep.ok = status is 204 or 404;if (!ok) Log.Debug($"share: revoke failed {status} {Field(data, "code") ?? "?"}");}diff --git a/windows/src/Cicada.Core/Speak.cs b/windows/src/Cicada.Core/Speak.csindex af20f1e..a448962 100644--- a/windows/src/Cicada.Core/Speak.cs+++ b/windows/src/Cicada.Core/Speak.cs@@ -3,44 +3,30 @@ using System.Security.Cryptography;namespace Cicada;-/// Where the room's voice goes: the virtual mic (VB-Cable's "CABLE Input"), or the speakers for a-/// preview. Takes 16-bit mono PCM at `rate` and returns once it has played.public interface ISpeechSink{- /// Starts a sentence: PCM chunks follow, then End.void Begin(int rate);void Write(byte[] pcm);Task End();- /// Whether there is somewhere to play: the virtual mic can go away between the press and the voice.bool Ready => true;}-/// 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);- /// Whether this PC has a voice for the language (Chinese Windows often has only Chinese ones).bool Has(string language);}-/// 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, 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", 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();@@ -52,28 +38,18 @@ public static class VoiceCatalog_ => [],};- /// The user's own voice (Voices.swift › cloneOption), offered with every language once recorded.public const string CloneId = "clone";public static readonly VoiceOption Clone = new(CloneId, "我自己的声音", "你的音色");- /// `clone`: the user's recording exists and the service clones (Ling, with a working key).public static IReadOnlyList<VoiceOption> Options(string language, AIConfig config, bool windowsHasIt = true, bool clone = false) =>[.. Cloud(language, config), .. windowsHasIt ? [new VoiceOption(SystemId, "Windows", "本机")] : Array.Empty<VoiceOption>(), .. clone ? [Clone] : Array.Empty<VoiceOption>()];- /// What a language uses until the user picks: the service's first voice once it can speak (or- /// when Windows has none for the language), else Windows'.public static string DefaultId(string language, AIConfig config, bool speaks, bool windowsHasIt = true) =>(speaks || !windowsHasIt) && Cloud(language, config) is [var first, ..] ? first.Id : SystemId;- /// The voice chosen for a language, if it is still offered: a Ming voice saved before switching- /// to ZenMux is not sent there, and "system" saved where Windows has no voice for the language- /// (Chinese Windows often has only Chinese ones) left the voice blank and 试听 silent (#22). The- /// user's own voice without its recording or without Ling falls back the same way, and comes- /// back with them (AppModel.voiceID).public static string Chosen(AppSettings settings, string language, AIConfig config, bool speaks, bool windowsHasIt = true, bool clone = false) =>settings.SpeakVoices.TryGetValue(Key(language), out var id) && Options(language, config, windowsHasIt, clone).Any(v => v.Id == id) ? id : DefaultId(language, config, speaks, windowsHasIt);- /// A short line to try a voice with, in the language it will speak.public static string Sample(string language) => Key(language) switch{"zh" => "谢谢大家。我们来看一下上线时间表,并确定谁负责麦克风测试。",@@ -87,9 +63,6 @@ public static class VoiceCatalog};}-/// 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{public enum Phase { Idle, Recording, Translating, Speaking, Failed }@@ -105,11 +78,9 @@ public sealed class SpeakEnginereadonly SemaphoreSlim one = new(1, 1);public Phase State { get; private set; }- /// What the bar shows: what I said, then what the room heard (or why nothing was sent).public string? Said { get; private set; }public string? Heard { get; private set; }public string? Problem { get; private set; }- /// "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;@@ -120,11 +91,8 @@ public sealed class SpeakEnginethis.roomLanguage = roomLanguage; this.openMeeting = openMeeting; this.systemVoice = systemVoice;}- /// The language I speak: the setting, else Windows'.public string MyLanguage => settings.SpeakFrom == "system" ? Languages.FromSystem(System.Globalization.CultureInfo.CurrentUICulture.Name) : settings.SpeakFrom;- /// The room's language (SpeakEngine.swift › targetCode): the chosen one, else the language the- /// other side has been speaking, else English; never my own.public string Target => TargetFor(settings.SpeakTo, roomLanguage(), MyLanguage);public static string TargetFor(string speakTo, string? room, string mine)@@ -136,14 +104,9 @@ public sealed class SpeakEngineDateTimeOffset? pressedAt;double? pressedMono;- /// When the computer's audio was loud, while listening (the echo check); null when not listening.public LoudnessLog? Echo { get; set; }- /// Share of the press the computer may play through before it counts as echo (Linux's 0.5).public const double EchoShare = 0.5;- /// Whether a press is dropped as the meeting's echo: only on the plain mic (SpeakEngine.swift's- /// `pressPlain`). Through echo cancellation the meeting's voices are taken out of the mic, and- /// what is left is me: dropping those presses lost everything said while the other side talked.public static bool EchoDrop(bool echoCancelled, double playedShare) => !echoCancelled && playedShare > EchoShare;public void BeginRecording()@@ -159,15 +122,12 @@ public sealed class SpeakEngineif (State == Phase.Recording) { State = Phase.Idle; Changed?.Invoke(); }}- /// One utterance: `wav` is 16 kHz mono. Returns what the room heard, or null if nothing was sent.- /// `echoCancelled`: the press was heard through Windows' echo cancellation (`EchoCancel`).public async Task<string?> Speak(byte[] wav, ISpeechSink sink, bool echoCancelled = false){await one.WaitAsync();try{var released = DateTime.UtcNow;- // A press nobody spoke in: Ming hears 嗯 in the room's hush and the meeting would hear "Hmm."var measure = PressSpeech.Measure(wav);Log.Debug($"speak: press of {Math.Max(0, wav.Length - 44) / 32000.0:F1} s, {measure.Summary}");if (!measure.Spoken)@@ -177,8 +137,6 @@ public sealed class SpeakEngineChanged?.Invoke();return null;}- // The meeting playing through most of the press: what the mic heard is its echo as much- // as me, and Ming would send the other side's words back to them (measured on the Mac).if (Echo is { } echo){var share = echo.Fraction(pressedMono ?? echo.Now - wav.Length / 32000.0, echo.Now);@@ -205,10 +163,8 @@ public sealed class SpeakEngine}Said = heard.Original;var text = heard.Translation;- // Ming didn't translate it: the text translator gets one try; failing that, silence.if (text is null && heard.Lang != to) text = await translator.Translate(heard.Original, heard.Lang, to, Translator.Kind.Sentence, Priority.Speak);if (string.IsNullOrWhiteSpace(text)) return Fail(Strings.L("这句没翻译成 · 没有说出去"));- // The virtual mic went away during the press: no voice at all, and never the speakers.if (!sink.Ready) return Fail(Strings.L("没有虚拟麦克风 · 没有说出去"));var translatedAt = DateTime.UtcNow;Heard = text;@@ -226,7 +182,6 @@ public sealed class SpeakEnginefinally { one.Release(); }}- /// Something stopped the sentence before it got here (no mic, no virtual mic): say so on the bar.public void Report(string why) => Fail(why);string? Fail(string why)@@ -237,8 +192,6 @@ public sealed class SpeakEnginereturn null;}- /// The sentence joins the meeting being listened to, as the Mac's "me" lines do.- /// Timed from when I started speaking, like the other side's lines.void Record(Heard heard, string text, string to, DateTimeOffset spokeAt){if (openMeeting() is not { } m) return;@@ -250,18 +203,13 @@ public sealed class SpeakEnginestore.Append(m.id, line);}- /// The user's recording for their own voice; null in tests that don't need it.public VoiceReference? Reference { get; set; }- /// Whether the user's own voice can be used now: recorded, and Ling with a working key.public bool CloneReady => ling.Clones && Reference?.Exists == true;- /// The voice a language uses now (the choice, or its fallback).public string ChosenVoice(string language) =>VoiceCatalog.Chosen(settings, language, ling.Config, ling.Speaks, systemVoice.Has(language), CloneReady);- /// The service's voice (Ming's on Ling, or the user's own cloned from their recording), else- /// Windows'. True once some sound went out.public async Task<bool> Voice(string text, string language, ISpeechSink sink){var config = ling.Config;@@ -294,50 +242,31 @@ public sealed class SpeakEngine}}-/// VB-Cable, the virtual mic: downloaded from VB-Audio when the user asks, never bundled, and run-/// only if it is the exact package checked here (as BlackHole is on the Mac).public static class VirtualCable{public const string PackageUrl = "https://download.vb-audio.com/Download_CABLE/VBCABLE_Driver_Pack45.zip";public const string PackageSha256 = "b950e39f01af1d04ea623c8f6d8eb9b6ea5c477c637295fabf20631c85116bfb";- /// The render endpoint the app writes to, and the capture one meeting apps pick as the mic.public const string InputName = "CABLE Input", OutputName = "CABLE Output";public static bool Verify(byte[] package) => Convert.ToHexString(SHA256.HashData(package)).Equals(PackageSha256, StringComparison.OrdinalIgnoreCase);}-/// Windows can make a freshly installed VB-Cable the default speaker (and mic): then everything the-/// computer plays goes into the cable and the user hears nothing. A user took that for Cicada-/// breaking their sound and nearly uninstalled it. Keys are "<flow>/<role>" (render 0, capture 1;-/// console 0, multimedia 1, communications 2), values the endpoint ids.public static class CableDefaults{- /// The defaults to set back after the install: each one the cable took from a real device.public static List<(string Key, string Id)> Restore(IReadOnlyDictionary<string, string> before, IReadOnlyDictionary<string, string> after, Func<string, bool> isCable) =>after.Where(a => isCable(a.Value) && before.TryGetValue(a.Key, out var b) && !isCable(b)).Select(a => (a.Key, before[a.Key])).OrderBy(r => r.Key, StringComparer.Ordinal).ToList();- /// A speaker to go back to when nothing was remembered (installed before this, or outside- /// Cicada): the first that isn't the cable.public static string? Speaker(IEnumerable<(string Id, bool Cable)> speakers) => speakers.FirstOrDefault(s => !s.Cable).Id;- /// The startup notification, once while the cable holds the speaker: someone who routes sound- /// into it on purpose hears about it once; it comes back only after the speaker was real again.public static bool ShouldNotify(bool speakerIsCable, bool notified) => speakerIsCable && !notified;}-/// Whether anyone spoke during a press of the talk key (PressSpeech in SpeakEngine.swift, same-/// numbers): 0.3 s of 30 ms frames over three times the press's own quiet (its quietest tenth),-/// between -44 and -36 dBFS. A silent press came back from Ming as "嗯。" and went out as "Hmm.";-/// a result that is only fillers isn't sent either.public static class PressSpeech{const int Frame = 480;const double Needed = 0.3;- /// What the check saw (PressSpeech.Measure on the Mac): seconds over the line, the press's quiet- /// and the line (RMS, 0–1). Logged per press: echo left after cancellation raises the quiet,- /// and a line held at its −36 dBFS cap is how a soft voice over the meeting gets dropped.public readonly record struct Result(double Voiced, double Floor, double Line){public bool Spoken => Voiced >= Needed;@@ -345,7 +274,6 @@ public static class PressSpeechstatic string Db(double v) => v > 0 ? (20 * Math.Log10(v)).ToString("F0", CultureInfo.InvariantCulture) : "-inf";}- /// `wav`: 16 kHz mono 16-bit, with or without its 44-byte header.public static bool Spoken(byte[] wav) => Measure(wav).Spoken;public static Result Measure(byte[] wav)@@ -367,10 +295,8 @@ public static class PressSpeechstatic readonly HashSet<string> Fillers = ["嗯", "啊", "呃", "哦", "唔", "额", "噢", "哎", "um", "uh", "hmm", "hm", "mm", "mhm", "ah", "oh", "er", "えー", "あの", "음", "어"];- /// Nothing but fillers (嗯, 啊, um, hmm…), whatever the punctuation.public static bool Filler(string text){- // A heading with nothing after it ("翻译结果:", "Translation:"): the model's answer to noise, not a sentence.var trimmed = text.Trim();if (trimmed.Length is > 0 and <= 12 && (trimmed.EndsWith(':') || trimmed.EndsWith(':'))) return true;var words = System.Text.RegularExpressions.Regex.Split(text.ToLowerInvariant(), @"[^\p{L}]+").Where(w => w.Length > 0).ToList();@@ -378,8 +304,6 @@ public static class PressSpeech}}-/// When the computer's audio was loud: (time, loud) per buffer of the listening side, the last-/// minute (Linux's LoudnessLog). Read by the talk key's echo check.public sealed class LoudnessLog(Func<double>? clock = null){readonly Func<double> clock = clock ?? (() => Environment.TickCount64 / 1000.0);@@ -396,7 +320,6 @@ public sealed class LoudnessLog(Func<double>? clock = null)}}- /// Share of the buffers between `start` and `end` that were loud (0 with none).public double Fraction(double start, double end){lock (log)@@ -407,21 +330,13 @@ public sealed class LoudnessLog(Func<double>? clock = null)}}-/// Whether Windows' echo cancellation works on the talk key's mic. A capture stream opened in the-/// communications category gets the endpoint's AEC when its driver (or Windows 11's Voice Clarity)-/// has one, and from build 22000 the stream lists its effects. Only an AEC listed as on counts: not-/// knowing (Windows 10, a driver that lists nothing) is the plain mic, because sending the meeting's-/// own words back to it is the worse mistake.public static class EchoCancel{- /// AUDIO_EFFECT_TYPE_ACOUSTIC_ECHO_CANCELLATION (ksmedia.h).public static readonly Guid Effect = new("6f64adbe-8211-11e2-8c70-2c27d7f001fa");public readonly record struct AudioEffect(Guid Id, bool CanSetState, bool On);- /// `effects`: the stream's list, null when Windows has none to give.public static bool InEffect(IReadOnlyList<AudioEffect>? effects) => effects?.Any(e => e.Id == Effect && e.On) ?? false;- /// Listed but off, and the app may turn it on: worth asking for before the press starts.public static bool CanTurnOn(IReadOnlyList<AudioEffect>? effects) => effects?.Any(e => e.Id == Effect && !e.On && e.CanSetState) ?? false;}diff --git a/windows/src/Cicada.Core/Strings.cs b/windows/src/Cicada.Core/Strings.csindex 8f885b0..48d6f64 100644--- a/windows/src/Cicada.Core/Strings.cs+++ b/windows/src/Cicada.Core/Strings.cs@@ -3,37 +3,24 @@ using System.Text;namespace Cicada;-/// UI text. The Chinese text is the key, as on the Mac, and the translations are the Mac's own-/// `Resources/{en,ja,ko}.lproj/Localizable.strings`, copied next to the app at build time, plus-/// `windows/src/Cicada/Strings/*.lproj/Windows.strings` for text only the Windows app has, and the-/// Mac's `Localizable.stringsdict` for plurals ("1 line", "2 lines"). Placeholders are the Mac's-/// `%@`, filled in order. Never for prompts, logs or stored values.public static class Strings{static Dictionary<string, string> table = [];static Dictionary<string, Plural> plurals = [];- /// A stringsdict entry: the format with `%#@n@` placeholders, and each variable's forms by- /// plural category ("one", "other").public sealed record Plural(string Format, Dictionary<string, Dictionary<string, string>> Forms);public static string Language { get; private set; } = "zh-Hans";- /// Dates in the app's language, not Windows': English Cicada on Chinese Windows writes "Nov 4".public static CultureInfo Culture { get; private set; } = CultureInfo.GetCultureInfo("zh-CN");- /// Loads the table for `language` ("en", "ja", "ko"; anything else is Chinese) from- /// `folder`/<lang>.lproj/Localizable.strings.public static void Load(string folder, string? language = null) =>Load(path => File.Exists(Path.Combine(folder, path)) ? File.ReadAllText(Path.Combine(folder, path), Encoding.UTF8) : null, language);- /// The same from `read("<lang>.lproj/<name>")`: the app reads the tables from inside its exe,- /// so the installer is one file that already speaks the user's language.public static void Load(Func<string, string?> read, string? language = null){var ui = language ?? CultureInfo.CurrentUICulture.Name;var head = ui.Split('-')[0];Language = head is "en" or "ja" or "ko" ? head : "zh-Hans";Culture = CultureInfo.GetCultureInfo(Language switch { "en" => "en-US", "ja" => "ja-JP", "ko" => "ko-KR", _ => "zh-CN" });- // The Mac's table, then the Windows-only strings over it (Windows.strings, same format).table = [];foreach (var name in new[] { "Localizable.strings", "Windows.strings" }){@@ -43,15 +30,11 @@ public static class Stringsplurals = read($"{Language}.lproj/Localizable.stringsdict") is { } dict ? ParsePlurals(dict) : [];}- /// Only English has more than one form among the app's languages: "one" for exactly 1.static string Category(object? n) =>Language == "en" && n is IConvertible c && c.ToDouble(CultureInfo.InvariantCulture) == 1 ? "one" : "other";public static string L(string key) => table.TryGetValue(key, out var v) && v.Length > 0 ? v : key;- /// L() with the Mac's `%@` placeholders: LF("纪要停留在 %@。", clock). A key in the stringsdict- /// takes its plural form for the number: `%#@n@` (or `%2$#@n@`) becomes variable n's "one" or- /// "other" text.public static string LF(string key, params object[] args){var plural = plurals.GetValueOrDefault(key);@@ -60,7 +43,6 @@ public static class Stringsint next = 0;for (int i = 0; i < text.Length; i++){- // %#@n@ or %2$#@n@: the variable's form for its number, with the number in it.int j = i + 1;int? position = null;if (plural is not null && text[i] == '%' && j + 1 < text.Length && char.IsDigit(text[j]) && text[j + 1] == '$') { position = text[j] - '1'; j += 2; }@@ -78,7 +60,6 @@ public static class Stringsb.Append(next < args.Length ? args[next++] : "");i++;}- // The Mac's integer placeholders (Swift interpolation of an Int becomes %lld).else if (text[i] == '%' && i + 3 < text.Length && text.AsSpan(i + 1, 3) is "lld"){b.Append(next < args.Length ? args[next++] : "");@@ -90,22 +71,18 @@ public static class Stringsb.Append(n >= 0 && n < args.Length ? args[n] : "");i += 3;}- // A numbered integer: "All %2$lld places heard as %1$@".else if (text[i] == '%' && i + 5 < text.Length && char.IsDigit(text[i + 1]) && text[i + 2] == '$' && text.AsSpan(i + 3, 3) is "lld"){int n = text[i + 1] - '1';b.Append(n >= 0 && n < args.Length ? args[n] : "");i += 5;}- // A percent sign, written %% in a format ("正在下载 %@:%lld%%").else if (text[i] == '%' && i + 1 < text.Length && text[i + 1] == '%') { b.Append('%'); i++; }else b.Append(text[i]);}return b.ToString();}- /// The Mac's Localizable.stringsdict (an XML plist of dicts and strings) as key → Plural. A- /// small reader of its own: XmlReader refuses the plist's DOCTYPE unless told to skip DTDs.public static Dictionary<string, Plural> ParsePlurals(string xml){int i = 0;@@ -154,7 +131,6 @@ public static class Stringsreturn result;}- /// `"key" = "value";` lines, with /* */ and // comments and \" \\ \n escapes.public static Dictionary<string, string> Parse(string text){var result = new Dictionary<string, string>();diff --git a/windows/src/Cicada.Core/Support.cs b/windows/src/Cicada.Core/Support.csindex 0383ad5..408fc91 100644--- a/windows/src/Cicada.Core/Support.cs+++ b/windows/src/Cicada.Core/Support.cs@@ -3,8 +3,6 @@ using System.Globalization;namespace Cicada;-/// Where the app keeps its files: %APPDATA%\Cicada (release) or "Cicada Dev" (dev builds, so a-/// dev build never touches real records). Tests and the CLI point it elsewhere with CICADA_HOME.public static class Paths{public static bool Dev { get; set; } = Environment.GetEnvironmentVariable("CICADA_DEV") == "1";@@ -22,12 +20,10 @@ public static class Pathspublic static string Sessions => Path.Combine(Root, "Sessions");public static string Settings => Path.Combine(Root, "settings.json");- /// 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");}-/// The debug log (`%TEMP%\cicada-dev-debug.log`): timings and states, never meeting text or the key.public static class Log{static readonly object Gate = new();@@ -46,7 +42,6 @@ public static class Logpublic sealed record Lang(string Name, string Code);-/// The languages the Mac app offers (Languages.swift), as translation codes.public static class Languages{public static readonly Lang[] Sources =@@ -61,7 +56,6 @@ public static class Languagesnew("한국어", "ko"), new("Español", "es"), new("Français", "fr"), new("Deutsch", "de"), new("Português", "pt"),];- /// "Simplified Chinese", "Japanese": the names prompts use.public static string EnglishName(string code) => code switch{"zh-CN" => "Simplified Chinese",@@ -74,7 +68,6 @@ public static class Languagestry { return CultureInfo.GetCultureInfo(code); } catch { return null; }}- /// A system UI language ("zh-Hans-CN", "zh-TW", "en-US") as a translation code.public static string FromSystem(string name){var parts = name.Split('-');@@ -82,7 +75,6 @@ public static class Languagesreturn parts.Contains("Hant") || parts.Contains("TW") || parts.Contains("HK") || parts.Contains("MO") ? "zh-TW" : "zh-CN";}- /// Normalizes what Ming says the language is ("zh", "zh-Hans", "cmn") to a source code.public static string Normalize(string? reported, string fallback){if (string.IsNullOrWhiteSpace(reported)) return fallback;@@ -95,8 +87,6 @@ public static class Languagesstatic bool IsCjk(Rune r) => r.Value is >= 0x3040 and <= 0x9FFF or >= 0xAC00 and <= 0xD7AF;- /// Whether text is in the target's script: Chinese, Japanese and Korean targets need some CJK,- /// others must not be mostly CJK (TranslationService.cleanTranslation's check).public static bool InScript(string text, string target){int letters = 0, cjk = 0;@@ -111,7 +101,6 @@ public static class Languagesreturn wantsCjk ? cjk > 0 : cjk * 2 <= letters;}- /// Notes' check: CJK languages need a fair share (names and numbers stay Latin).public static bool WrittenIn(string text, string englishLanguage){int letters = 0, cjk = 0;diff --git a/windows/src/Cicada.Core/TalkKey.cs b/windows/src/Cicada.Core/TalkKey.csindex 625eba8..774b8c3 100644--- a/windows/src/Cicada.Core/TalkKey.cs+++ b/windows/src/Cicada.Core/TalkKey.cs@@ -1,15 +1,9 @@namespace Cicada;-/// The key held to talk (同声传译). Many laptop and compact keyboards have no right Ctrl, so it can-/// be changed in 设置 › 同声传译. Settings keep a stable name, not a virtual-key code or a label.public static class TalkKey{public const string Default = "rcontrol";- /// One key that can be the talk key. `Label` is the Chinese localization key (or a key name that- /// reads the same in every language); `Modifier` keys are passed on to other apps and only count- /// when held alone, the others are kept from them while they are the talk key (Caps Lock would- /// switch case, the menu key open a menu, Insert switch overtype).public sealed record Key(string Name, int Vk, string Label, bool Modifier);public static readonly IReadOnlyList<Key> All =@@ -26,25 +20,19 @@ public static class TalkKey.. Enumerable.Range(1, 24).Select(n => new Key($"f{n}", 0x6F + n, $"F{n}", false)),];- /// The saved name's key; an unknown or empty one is right Ctrl.public static Key Named(string? name) => All.FirstOrDefault(k => k.Name == name) ?? All[0];public static Key? FromVk(int vk) => All.FirstOrDefault(k => k.Vk == vk);- /// What pressing `vk` while choosing a talk key does: the key, or why it can't be one (a Chinese- /// localization key). Esc is handled before this (it cancels).public static (Key? Key, string? Refused) Choose(int vk) => vk switch{0x5B or 0x5C => (null, "Windows 键会打开开始菜单,换一个吧"),- // Alt: released alone it opens the window's menu, and right Alt is AltGr on many layouts.0x12 or 0xA4 or 0xA5 => (null, "Alt 松开时会打开窗口的菜单,换一个吧"),- // VK_CONTROL / VK_SHIFT without a side: what an injected or remapped key may report.0x11 => (Named("rcontrol"), null),0x10 => (Named("rshift"), null),_ => FromVk(vk) is { } k ? (k, null) : (null, "打字时会用到这个键,换一个不常用的吧"),};- /// The grey line under 按住说话 for a key that is also used for other things, else null.public static string? Note(Key key) => key.Name switch{"lcontrol" => "只有单独按住才算,Ctrl C 这类快捷键不会开始说话",diff --git a/windows/src/Cicada.Core/TranscriptSearch.cs b/windows/src/Cicada.Core/TranscriptSearch.csindex 653ddc6..0fee148 100644--- a/windows/src/Cicada.Core/TranscriptSearch.cs+++ b/windows/src/Cicada.Core/TranscriptSearch.cs@@ -1,13 +1,9 @@namespace Cicada;-/// Searching a meeting's lines (the Mac's TranscriptSearch.swift): the records' Ctrl+F finds the-/// same lines as on the Mac, misheard names included, and marks them the same way (#33).public static class TranscriptSearch{- // Ordinal: a match is exactly as long as its term, so the marks land on it.const StringComparison Fold = StringComparison.OrdinalIgnoreCase;- /// The query, plus every way the notes say that name was heard (江充 also finds 江松).public static List<string> Terms(string query, IEnumerable<NoteTerm>? notes){var q = query.Trim();@@ -25,12 +21,9 @@ public static class TranscriptSearchpublic static bool Matches(TranscriptLine l, IReadOnlyList<string> terms) =>terms.Any(t => l.Shown.Contains(t, Fold) || (l.Dst?.Contains(t, Fold) ?? false));- /// The ids of the lines a search finds, in order.public static List<string> Matches(IEnumerable<TranscriptLine> lines, IReadOnlyList<string> terms) =>terms.Count == 0 ? [] : lines.Where(l => Matches(l, terms)).Select(l => l.Id).ToList();- /// Where the terms are in `text`, as (start, length) spans in order, overlaps merged: the- /// parts to mark.public static List<(int Start, int Length)> Spans(string text, IReadOnlyList<string> terms){var marked = new bool[text.Length];diff --git a/windows/src/Cicada.Core/Translator.cs b/windows/src/Cicada.Core/Translator.csindex be838ac..30463cc 100644--- a/windows/src/Cicada.Core/Translator.cs+++ b/windows/src/Cicada.Core/Translator.cs@@ -2,24 +2,15 @@ using System.Text.Json;namespace Cicada;-/// 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 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);- // Tests hand in their own handler, so they never reach the real Google.readonly HttpClient Http = google is null ? Shared : MakeHttp(google);DateTime googleBackoffUntil = DateTime.MinValue;bool googleOff, sentencesUntranslated;- /// Set by the app (语音和文字只发给你的服务, custom service only): Google is never asked, so the- /// text stays with the user's service. A stale Google backoff goes with it either way.public bool GoogleOff{get => googleOff;@@ -33,8 +24,6 @@ public sealed class Translator(LingClient ling, HttpMessageHandler? google = nul}}- /// With Google left out, the last finished sentence went untranslated (the service failed): the- /// notes window says new lines show the original until it answers again.public bool SentencesUntranslated{get => sentencesUntranslated;@@ -48,7 +37,6 @@ public sealed class Translator(LingClient ling, HttpMessageHandler? google = nulpublic event Action? Changed;- /// Names and terms the notes have settled on, e.g. "江充 (…; misheard as 江松)".public Func<IReadOnlyList<string>> Glossary { get; set; } = () => [];static HttpClient MakeHttp(HttpMessageHandler? handler)@@ -61,13 +49,8 @@ public sealed class Translator(LingClient ling, HttpMessageHandler? google = nul// MARK: Hearing- /// One stretch of speech (16 kHz mono WAV) heard and interpreted. `hint` is the language the- /// meeting has been in, which keeps Ming from flipping on a short or accented stretch. Null- /// when there was no speech or the reply wasn't in the three-line form; never a guess.- /// `priority` is Speak for what the user says, so it goes ahead of the meeting's lines.public async Task<Heard?> Hear(byte[] wav, string target, string? hint, Priority priority = Priority.Translate, CancellationToken cancel = default){- // 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 config = ling.Config;@@ -76,24 +59,14 @@ public sealed class Translator(LingClient ling, HttpMessageHandler? google = nulreturn 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));- /// Ming writes something for every stretch it is sent, speech or not (it can't be asked for- /// NONE, see HearInstruction): hold music, a ringback tone, a fan or typing came back as "嗯。",- /// "嗯,嗯,嗯…" or "滴答" ×800. That is noise: fillers only, one short sound six or more times- /// over, or more than anyone says in `seconds` (0: unknown). A short real answer ("对",- /// "好的", "喂,能听到吗") stays. Same rules and lists as the Android and Linux ports.public static bool IsNoise(string original, double seconds = 0){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();@@ -105,7 +78,6 @@ public sealed class Translator(LingClient ling, HttpMessageHandler? google = nulif (word.Length > 0) words.Add(word.ToString());if (words.Count == 0) return true;if (words.All(IsFillerWord)) return true;- // Each CJK character is a unit, as a word is elsewhere.var units = words.SelectMany(w => w.Any(IsCjk) ? w.Select(c => c.ToString()) : [w]).ToList();var n = units.Count;for (var p = 1; p <= 4; p++)@@ -113,8 +85,6 @@ public sealed class Translator(LingClient ling, HttpMessageHandler? google = nulreturn seconds > 0 && n > Math.Max(12.0, 12 * seconds);}- /// 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 = [@@ -130,7 +100,6 @@ public sealed class Translator(LingClient ling, HttpMessageHandler? google = nul"음", "어", "아", "응", "흠", "으",];- /// Made of fillers only, a held sound shortened first: "嗯嗯嗯", "hmmmm"; "えーと" is not.static bool IsFillerWord(string raw){var w = new System.Text.StringBuilder();@@ -145,9 +114,6 @@ public sealed class Translator(LingClient ling, HttpMessageHandler? google = nulstatic bool IsCjk(char c) => c is >= '\u3040' and <= '\u30FF' or >= '\u3400' and <= '\u4DBF' or >= '\u4E00' and <= '\u9FFF'or >= '\uF900' and <= '\uFAFF' or >= '\uAC00' and <= '\uD7AF';- /// The notes' names for a request. Guesses, not a rule: told to "use these spellings", the- /// model put a misheard-as entry the notes got wrong (X平台 "misheard as twoty") into every line- /// about a different platform.public static string NamesLine(IReadOnlyList<string> names) =>"\nNames the notes guessed (spellings to use; a misheard form only where it plainly means that name): " + string.Join("; ", names);@@ -160,17 +126,12 @@ public sealed class Translator(LingClient ling, HttpMessageHandler? google = nulreturn p;}- /// Tested wording: adding "NONE if there is no speech" or "the same text if already in it"- /// gets the gateway's canned "作为一个人工智能语言模型…" refusal instead of an answer.public static string HearInstruction(string target) =>"Reply in exactly three lines:\n"+ "LANG: <BCP-47 code of the spoken language, e.g. en, zh-CN, ja>\n"+ "ORIGINAL: <exactly what was said, in the spoken language>\n"+ $"TRANSLATION: <its translation into {Languages.EnglishName(target)}>";- /// `LANG: … / ORIGINAL: … / TRANSLATION: …`. Drops replies without an original, "NONE" (music,- /// silence), and translations not in the target's script; a dropped translation leaves the- /// original for the text translator to try.public static Heard? ParseHeard(string reply, string target, string? hint, double seconds = 0){string? lang = null, original = null, translation = null;@@ -203,11 +164,6 @@ public sealed class Translator(LingClient ling, HttpMessageHandler? google = nullong lastUnreachableTry = DateTime.MinValue.Ticks;- /// A text service that answers nothing (a home server switched off, its hear model served- /// elsewhere) costs every sentence its timeout before Google gets it, so subtitles run seconds- /// late. While the check says unreachable, one sentence in 15 s still goes to it, so a server- /// that is back is noticed without waiting for a check. (Only the hear address unreachable:- /// text is fine, it goes on being tried.)bool LingWorthTrying(){if (ling.Health.Failure is not { Why: AICheck.Reason.Unreachable, Step: not AICheck.StepId.Hear }) return true;@@ -216,20 +172,9 @@ public sealed class Translator(LingClient ling, HttpMessageHandler? google = nulreturn now - last >= TimeSpan.TicksPerSecond * 15 && Interlocked.CompareExchange(ref lastUnreachableTry, now, last) == last;}- /// The AI service (finished sentences only) → Google. Null when both fail. With GoogleOff the- /// service alone: drafts get nothing (they never go to the service) and show the original.- /// What a finished sentence's request carries so the service can also point out misheard words- /// (改正听错的词): the meeting's title once it has one (the field tells "质押" from "制约"), the- /// user's word list, the lines just before as shown, on a second pass the lines after it, and- /// the notes' summary so far.public sealed record FixContext(string? Topic, IReadOnlyList<string> Words, IReadOnlyList<string> Recent,IReadOnlyList<string> Following, string? Summary);- /// The translation and the misheard words in one request (TranslationService.viaLingFixing, the- /// prompt word for word). No JSON mode: some hosts refuse it, and the retry without it would- /// cost a second round trip; the prompt asks for JSON instead, and "no analysis" stops the- /// model thinking aloud first. Proposals only: Correction.Decide picks which to take. Null when- /// the service failed or didn't answer in that shape (often thinking aloud, never a subtitle).public async Task<(string Translation, List<Correction.Edit> Edits)?> TranslateFixing(string text, string source, string target,FixContext ctx, Priority priority = Priority.Translate){@@ -250,7 +195,6 @@ public sealed class Translator(LingClient ling, HttpMessageHandler? google = nulprompt += "\nSubtitle: " + text;try{- // A live line's translation, even at Notes priority: it goes to translation's model and server.var out_ = await ling.Chat(prompt, "JSON only.", priority, maxTokens: 600, timeout: 6, notes: false);if (out_.Length == 0) return null;if (Correction.Parse(out_, text) is not { } parsed)@@ -265,8 +209,6 @@ public sealed class Translator(LingClient ling, HttpMessageHandler? google = nulcatch (LingException e) { Log.Debug($"translate ling failed: {e.Message}"); return null; }}- /// `lingTried`: the service was just asked (with fixes) and failed: straight to Google, as the- /// Mac falls through to its next provider.public async Task<string?> Translate(string text, string source, string target, Kind kind, Priority priority = Priority.Translate, bool lingTried = false){if (source == target) return text;@@ -292,7 +234,6 @@ public sealed class Translator(LingClient ling, HttpMessageHandler? google = nul}if (GoogleOff){- // Left out on purpose: no attempt, so nothing counts as Google failing.if (kind != Kind.Draft) SentencesUntranslated = true;return null;}@@ -322,15 +263,11 @@ public sealed class Translator(LingClient ling, HttpMessageHandler? google = nulreturn result.Length == 0 ? null : result;}- /// "Translate." in each target language, letters only and lowercased. Port of instructionEchoes.static readonly HashSet<string> InstructionEchoes = ["翻译", "翻譯", "translate", "翻訳", "翻訳して", "翻訳する", "翻訳してください", "번역", "번역해", "번역하세요", "번역해주세요","traducir", "traduce", "traduzca", "traduire", "traduisez", "traduis", "übersetzen", "übersetze", "traduzir", "traduza",];- /// Ling sometimes comments on a garbled subtitle instead of translating it ("The subtitle- /// appears to be…"). Remark lines go, a "Translation:" label is stripped, and what is left must- /// be in the target's script; null lets the next provider try. Port of cleanTranslation.public static string? CleanTranslation(string reply, string target){string[] opener = ["here is", "here's", "the subtitle", "this subtitle", "the text", "this text", "the original",@@ -362,8 +299,6 @@ public sealed class Translator(LingClient ling, HttpMessageHandler? google = nul}output = output.Trim();if (output.Length == 0) return null;- // Ling translated the fixed "Translate." instruction instead of the subtitle ("翻译。" for an empty- // subtitle, or for "Translate this into Chinese please."); the next provider translates it.if (InstructionEchoes.Contains(new string(output.ToLowerInvariant().Where(char.IsLetter).ToArray()))) return null;return Languages.InScript(output, target) ? output : null;}diff --git a/windows/src/Cicada.Core/UpdateChecker.cs b/windows/src/Cicada.Core/UpdateChecker.csindex 7b60835..b1130b0 100644--- a/windows/src/Cicada.Core/UpdateChecker.cs+++ b/windows/src/Cicada.Core/UpdateChecker.cs@@ -5,16 +5,8 @@ using System.Text.Json.Serialization;namespace Cicada;-/// Checks GitHub Releases for a Windows build newer than the running one, as the Mac's-/// UpdateChecker: at launch, then whenever the last answer is 4 hours old (a 15-minute tick, so a-/// laptop that sleeps a lot still checks), and when the tray panel opens once it is an hour old.-/// Failures (offline, rate-limited, the repository not public: 404) are silent. This only finds-/// the update; the app offers the release's installer (Cicada-<v>-Windows-<arch>.exe) for download,-/// which upgrades the installed copy when opened.public sealed class UpdateChecker{- /// `Setup` is this PC's installer when the release has one; `Size` is the download's;- /// `Checksums` the release's checksums.txt, which the in-app download is checked against.public sealed record Update(string Version, string Page, string? Zip, long Size, string? Setup = null, string? Checksums = null){public string? Download => Setup ?? Zip;@@ -23,25 +15,16 @@ public sealed class UpdateCheckerpublic static readonly TimeSpan Every = TimeSpan.FromHours(4);public static readonly TimeSpan Stale = TimeSpan.FromHours(1);- /// `CICADA_UPDATE_FEED` (or the `updatefeed` debug command) points at another release JSON,- /// a list or a single release; a file path or file:// URL works, for testing.- /// The list, not `releases/latest`: a release that ships only the Mac, Android or Linux has no- /// Windows zip, so the newest Windows release may be further down.public string Feed { get; set; } = Environment.GetEnvironmentVariable("CICADA_UPDATE_FEED") is { Length: > 0 } f? f : "https://api.github.com/repos/wquguru/cicada/releases?per_page=20";- /// The running version, three parts ("1.4.0"), from VERSION via Directory.Build.props.public string Current { get; set; } = "0";- /// The newer release, or null (none, or not checked yet).public Update? Available { get; private set; }- /// When the feed last answered; kept in settings across launches.public DateTimeOffset? LastChecked { get; private set; }public event Action? Changed;- /// How long the feed, checksums.txt or the installer's headers may take to answer.public static readonly TimeSpan Within = TimeSpan.FromSeconds(30);- /// The download fails when no bytes arrive for this long (not when it is merely slow).public TimeSpan Stall { get; set; } = TimeSpan.FromSeconds(30);readonly HttpClient http;@@ -54,10 +37,7 @@ public sealed class UpdateCheckerLastChecked = lastChecked;this.remember = remember;http = new HttpClient(handler ?? Handler());- // No overall timeout: an 85 MB installer on a slow line takes minutes. Each request has its- // own limit instead (Within), and the download a stall limit (Stall).http.Timeout = System.Threading.Timeout.InfiniteTimeSpan;- // GitHub's API refuses requests without a User-Agent.http.DefaultRequestHeaders.UserAgent.ParseAdd("Cicada-Windows");http.DefaultRequestHeaders.Accept.ParseAdd("application/vnd.github+json");}@@ -71,10 +51,8 @@ public sealed class UpdateCheckerpublic Task CheckIfDue(TimeSpan age) => Due(LastChecked, DateTimeOffset.UtcNow, age) ? Check() : Task.CompletedTask;public static bool Due(DateTimeOffset? last, DateTimeOffset now, TimeSpan age) =>- // A clock set back leaves `last` in the future: check rather than wait for it.last is not { } l || now - l >= age || l > now;- /// False when the feed couldn't be reached or answered with something unexpected.public async Task<bool> Check(){if (Interlocked.Exchange(ref checking, 1) == 1) return true;@@ -104,10 +82,6 @@ public sealed class UpdateCheckerreturn await r.Content.ReadAsStringAsync(cts.Token);}- /// The default handler: sockets with a 4 MB receive buffer instead of Windows' 64 KB default.- /// On the test VM's throttled direct path to GitHub it was never slower in paired runs and- /// sometimes several times faster (once 14 MB/s against 0.07); the path itself swung so much- /// that the gain isn't pinned down. A system proxy still applies: the callback then connects to it.static SocketsHttpHandler Handler() => new(){ConnectCallback = async (context, cancel) =>@@ -118,7 +92,6 @@ public sealed class UpdateChecker},};- /// The zip this PC should run: ARM64 on an ARM PC (even when this copy is the emulated x64 one).public static string Arch => RuntimeInformation.OSArchitecture == Architecture.Arm64 ? "ARM64" : "x64";public static List<Release>? Decode(string text)@@ -136,9 +109,6 @@ public sealed class UpdateCheckercatch (JsonException) { return null; }}- /// The newest published release with a Windows build (installer or zip). A release without one- /// only carries other platforms (Windows had no change), so it is skipped. On ARM, an x64-only- /// release still counts.public static Update? NewestWindows(IEnumerable<Release> releases, string arch){Update? best = null;@@ -156,18 +126,12 @@ public sealed class UpdateCheckerstatic bool IsZip(string name, string arch) => name.StartsWith("Cicada-") && name.EndsWith($"-Windows-{arch}.zip");}- /// The installer's release asset, named like every platform's file: Cicada-1.2.0-Windows-x64.exe.- /// 1.1.0 named it Cicada-Setup.exe / Cicada-Setup-arm64.exe and only finds those, so releases- /// still carry copies under the old names (release.yml) and this accepts both.public static bool IsSetup(string name, string arch) =>(name.StartsWith("Cicada-") && name.EndsWith($"-Windows-{arch}.exe")) || name == LegacySetupName(arch);public static string LegacySetupName(string arch) => arch == "ARM64" ? "Cicada-Setup-arm64.exe" : "Cicada-Setup.exe";- /// One notification per version (the version last told is kept in settings), and none while- /// listening: the next stop tells. Full screen and screen sharing are Windows' Do Not Disturb.public static bool ShouldNotify(string version, string? notified, bool busy) => !busy && version != notified;- /// The SHA-256 of `name` in a sha256sum listing ("<hex> <name>", or "<hex> *<name>").public static string? ChecksumFor(string text, string name){foreach (var line in text.Split('\n'))@@ -178,10 +142,6 @@ public sealed class UpdateCheckerreturn null;}- /// Downloads the release's installer into a fresh temp folder and checks it against- /// checksums.txt; returns its path. Fetched by the app, not the browser, the file carries no- /// mark of the web, so SmartScreen doesn't stop the unsigned installer. Throws Failure (a- /// string key) when there's nothing to install or the file doesn't match.public async Task<string> Download(Update u, Action<double>? progress = null){if (u.Setup is null || u.Checksums is null) throw new Failure("这个版本没有可安装的文件");@@ -199,7 +159,6 @@ public sealed class UpdateChecker}catch (Exception e) when (e is HttpRequestException or IOException or OperationCanceledException){- // Why, for the log: a stall, a refused connection, a 404…var why = e is OperationCanceledException ? (stage == "installer" && e.Data["stalled"] is true ? $"nothing arrived for {Stall.TotalSeconds:0} s" : "timed out") : e.Message;Log.Debug($"update: download failed at {stage}: {e.GetType().Name}: {why}{(e.InnerException is { } inner ? $" ({inner.GetType().Name}: {inner.Message})" : "")}");try { Directory.Delete(folder, true); } catch { }@@ -216,8 +175,6 @@ public sealed class UpdateCheckerreturn file;}- /// Removes installers left from earlier updates (each ~80 MB). Called at launch: by then the- /// installer that ran has quit, or it's still letting go and the next launch gets it.public static void CleanDownloads(string? temp = null){try@@ -242,14 +199,12 @@ public sealed class UpdateCheckerlong got = 0; int n, last = -1;while (true){- // The limit restarts with every read: slow is fine, stopped is not.cts.CancelAfter(Stall);try { n = await src.ReadAsync(buffer, cts.Token); }catch (OperationCanceledException e) { e.Data["stalled"] = true; Log.Debug($"update: stalled after {got} of {total} bytes"); throw; }if (n == 0) break;await dst.WriteAsync(buffer.AsMemory(0, n));got += n;- // Whole percents only: each one re-renders the flyout and settings.if (total > 0 && (int)(got * 100 / total) is var pct && pct != last) { last = pct; progress?.Invoke(Math.Min(1, (double)got / total)); }}if (r.Content.Headers.ContentLength is { } length && got != length) throw new IOException($"the connection ended after {got} of {length} bytes");@@ -257,10 +212,8 @@ public sealed class UpdateCheckerLog.Debug($"update: fetched {got / 1e6:0.0} MB in {seconds:0.0} s ({got / 1e6 / seconds:0.0} MB/s)");}- /// Why installing didn't work: a shared string key, said to the user (the browser fallback opens).public sealed class Failure(string key) : Exception(key) { public string Key => Message; }- /// Dotted numeric versions: "2.10.0" is newer than "2.9.1".public static bool IsNewer(string a, string b){var x = a.Split('.').Select(p => int.TryParse(p, out var n) ? n : 0).ToArray();diff --git a/windows/src/Cicada.Core/Vocabulary.cs b/windows/src/Cicada.Core/Vocabulary.csindex 1857597..73427f2 100644--- a/windows/src/Cicada.Core/Vocabulary.cs+++ b/windows/src/Cicada.Core/Vocabulary.cs@@ -4,18 +4,12 @@ using System.Text.Json.Serialization;namespace Cicada;-/// 词表: the spellings the user stands behind, and how speech recognition has misheard each. Only-/// these let a new name be fixed without asking: names the notes guess are often wrong, so they-/// stay suggestions until the user confirms one. One JSON file beside the records-/// (vocabulary.json, the Mac's format); not a secret, so not one of the key files. Thread-safe.public sealed class Vocabulary{public sealed class Term{[JsonPropertyName("fixes")] public int Fixes { get; set; }- /// Wrong forms the recognizer produced, as confirmed or typed by the user.[JsonPropertyName("heard")] public List<string> Heard { get; set; } = [];- /// "user" (added or imported), "live" (confirmed during a meeting).[JsonPropertyName("source")] public string Source { get; set; } = "user";[JsonPropertyName("used")] public DateTimeOffset? Used { get; set; }[JsonPropertyName("word")] public string Word { get; set; } = "";@@ -23,7 +17,6 @@ public sealed class Vocabularypublic Term Clone() => new() { Fixes = Fixes, Heard = [.. Heard], Source = Source, Used = Used, Word = Word };}- /// More would make every sentence's request long, and more terms means more wrong swaps.public const int Limit = 300;readonly object gate = new();@@ -43,10 +36,8 @@ public sealed class Vocabularypublic static string DefaultPath => Path.Combine(Paths.Root, "vocabulary.json");- /// A copy of the list, in its order.public List<Term> Terms { get { lock (gate) return terms.Select(t => t.Clone()).ToList(); } }- /// Same word whatever its width, case or spacing ("AAVE" is "aave").public static string Key(string s) =>string.Join(" ", s.Normalize(NormalizationForm.FormKC).ToLowerInvariant().Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries));@@ -58,9 +49,6 @@ public sealed class Vocabularylock (gate) return Find(word) is { } t && t.Heard.Any(x => Key(x) == h);}- /// What a fix can teach the list, or null: both sides trimmed of spaces and punctuation, no- /// punctuation inside, short, and a real swap. An edit that only adds or drops words around the- /// heard ones ("我来" → "OK我来") or ends on a full stop ("持。" → "讲。") teaches nothing.public static (string Heard, string Word)? Learnable(string heard, string word){static bool Edge(Rune r) => Rune.IsWhiteSpace(r) || Rune.IsPunctuation(r) || Rune.IsSymbol(r);@@ -80,9 +68,6 @@ public sealed class Vocabularyreturn (h, w);}- /// The user said yes to a fix (or added it): the word, and the form it was heard as. A pair- /// that isn't a word for a word (`Learnable`) adds the word only, or nothing. A yes in a meeting- /// never teaches a translation (平台 → platform): it would rewrite that word everywhere after.public void Confirm(string heard, string word, string source = "live"){if (heard.Length > 0)@@ -101,7 +86,6 @@ public sealed class VocabularySave();}- /// A heard form the user turned down twice stops being one.public void Forget(string heard, string word){lock (gate)@@ -112,7 +96,6 @@ public sealed class VocabularySave();}- /// 词表 › click a word: its spelling changes; what it was heard as stays with it.public void Rename(string word, string to){var n = to.Trim();@@ -121,7 +104,6 @@ public sealed class Vocabularyif (n.Length == 0 || Correction.Length(n) > 40 || Find(word) is not { } t) return;if (Find(n) is { } other && other != t){- // Renamed onto a word already there: the two become one.foreach (var h in t.Heard) if (!other.Heard.Any(x => Key(x) == Key(h))) other.Heard.Add(h);terms.Remove(t);}@@ -130,14 +112,12 @@ public sealed class VocabularySave();}- /// The other words a heard form already belongs to ("莫拉" is Morpho's).public List<string> Owners(string heard, string? except = null){lock (gate)return terms.Where(t => t.Heard.Any(x => Key(x) == Key(heard)) && Key(t.Word) != Key(except ?? "")).Select(t => t.Word).ToList();}- /// Back where it was, after 撤销 on a delete.public void Insert(Term term, int index){lock (gate)@@ -148,7 +128,6 @@ public sealed class VocabularySave();}- /// 撤销: the list as it was.public void Restore(List<Term> saved){lock (gate) terms = saved.Select(t => t.Clone()).ToList();@@ -172,7 +151,6 @@ public sealed class VocabularySave();}- /// For the request: the most recently useful first, "Morpho (heard as 莫拉, 莫法)".public List<string> PromptLines(){lock (gate)@@ -180,8 +158,6 @@ public sealed class Vocabulary.Select(t => t.Heard.Count == 0 ? t.Word : $"{t.Word} (heard as {string.Join(", ", t.Heard)})").ToList();}- /// 粘贴导入: one per line, heard forms after "=" ("Morpho = 莫拉、莫法"). Lines too long or empty- /// are reported by number; a word already there gains the new heard forms.public sealed record ImportResult(int Added, int Updated, List<int> Skipped){public override string ToString() => $"added={Added} updated={Updated} skipped=[{string.Join(",", Skipped)}]";@@ -206,7 +182,6 @@ public sealed class Vocabularyreturn out_;}- /// What 粘贴导入 would do, before it does it (the sheet's counts and its button).public ImportResult Preview(string text){int added = 0, updated = 0;diff --git a/windows/src/Cicada.Core/VoiceClone.cs b/windows/src/Cicada.Core/VoiceClone.csindex 984e7b9..3ab2b8b 100644--- a/windows/src/Cicada.Core/VoiceClone.cs+++ b/windows/src/Cicada.Core/VoiceClone.cs@@ -2,14 +2,8 @@ using System.Text;namespace Cicada;-/// The recording Ming clones the user's voice from (Voices.swift › VoiceReference): `voice\reference.wav`-/// (16 kHz mono, 10–15 s) and `voice\reference.txt` (what it says, as Ming heard it) under the app's-/// folder, sealed with DPAPI like the keys. Never in a record, an export or the log; it leaves the-/// PC only inside a speech request to Ling.public sealed class VoiceReference(IKeyProtector protector, string? folder = null){- /// Shorter than the Mac's 8–30 s (#32): every cloned sentence sends the whole clip again, so a- /// long one makes each sentence later. At 15 s the recording stops by itself.public const double MinSeconds = 10, MaxSeconds = 15;public string Folder => folder ?? Path.Combine(Paths.Root, "voice");@@ -20,17 +14,14 @@ public sealed class VoiceReference(IKeyProtector protector, string? folder = nulreadonly object gate = new();(DateTime at, byte[]? wav, string? text)? cache;- /// Fired when the recording is saved or removed.public event Action? Changed;public bool Exists => Load() is { wav: not null, text: { Length: > 0 } };public string? Text => Load().text;public byte[]? Wav => Load().wav;- /// Seconds in the saved clip (16 kHz mono 16-bit after a 44-byte header).public double Duration => Wav is { } w ? Math.Max(0, w.Length - 44) / 32000.0 : 0;- /// What Ming needs: the clip as a data URI and its transcript.public (string Audio, string Text)? Reference() =>Load() is { wav: { } w, text: { Length: > 0 } t } ? ("data:audio/wav;base64," + Convert.ToBase64String(w), t) : null;@@ -60,7 +51,6 @@ public sealed class VoiceReference(IKeyProtector protector, string? folder = nulstring Seal(byte[] data) => Sealed + Convert.ToBase64String(protector.Tag == "plain" ? data : protector.Protect(data));- /// Keeps `wav` trimmed of the quiet at its ends (a trailing pause makes Ming's clone silent).public void Save(byte[] wav, string text){wav = VoicePace.Trim(wav);@@ -91,7 +81,6 @@ public sealed class VoiceReference(IKeyProtector protector, string? folder = nul(DateTime at, bool slow)? slow;- /// The saved recording is read too slowly (worked out once per recording).public bool SavedIsSlow{get@@ -105,12 +94,8 @@ public sealed class VoiceReference(IKeyProtector protector, string? folder = nul}}-/// How fast a recording is read (Voices.swift › VoiceReference's pace): Ming copies the clip's pace-/// into every sentence, so a recital at 1.7 characters a second made each sentence about 4× as long.public static class VoicePace{- /// Characters (Chinese, Japanese, Korean) or words a second below which the clone is too slow- /// for a meeting; an ordinary pace gives 3.5–5 and 2.3–3.public const double SlowCharacters = 2.5, SlowWords = 1.6;public static double? Pace(string text, float[] samples, double sampleRate)@@ -127,17 +112,11 @@ public static class VoicePacereturn pace < (characters * 2 >= tokens.Count ? SlowCharacters : SlowWords);}- /// Seconds from the first to the last 20 ms window within 35 dB of the loudest one.public static double? SpeechSpan(float[] samples, double sampleRate) =>SpeechWindows(samples, sampleRate) is var (first, last, size) ? (last - first + 1) * (double)size / sampleRate : null;- /// Quiet kept each side of the reading when trimming.public const double TrimPad = 0.2;- /// A recording (16 kHz mono WAV) without the quiet before and after the reading, 0.2 s kept each- /// side (linux voice_reference.trim). Ming copies the clip's ending: a second of silence after- /// the last word (the pause before 读完了) made every cloned sentence come back silent- /// (measured 2026-11 against Ling: 8.2 s of nothing instead of 3.5 s of voice).public static byte[] Trim(byte[] wav, int rate = 16000){var start = wav.Length >= 44 && wav[0] == 'R' && wav[1] == 'I' ? 44 : 0;@@ -150,8 +129,6 @@ public static class VoicePacereturn Cicada.Wav.Bytes(pcm, rate);}- /// The first and last 20 ms windows within 35 dB of the loudest one, and the window size; null- /// when it is all quiet.static (int first, int last, int size)? SpeechWindows(float[] samples, double sampleRate){var size = Math.Max(1, (int)(sampleRate * 0.02));@@ -170,7 +147,6 @@ public static class VoicePacereturn (levels.FindIndex(l => l >= floor), levels.FindLastIndex(l => l >= floor), size);}- /// Words, and each CJK character on its own (SpeakTest.swift › SpeakScore.tokens).public static List<string> Tokens(string text){var out_ = new List<string>();@@ -188,7 +164,6 @@ public static class VoicePacepublic static bool IsCjk(char c) => c is (>= '' and <= 'ヿ') or (>= '㐀' and <= '䶿') or (>= '一' and <= '鿿') or (>= '가' and <= '') or (>= '豈' and <= '');- /// A 16-bit mono WAV (or bare PCM) as samples in −1…1.public static float[] Samples(byte[] wav){var start = wav.Length >= 44 && wav[0] == 'R' && wav[1] == 'I' ? 44 : 0;@@ -199,14 +174,10 @@ public static class VoicePace}}-/// What a recording for the clone comes to (the Mac's VoiceRecorder.finish): ready with its-/// transcript, or why not. Kept apart from the microphone so it can be tested.public static class VoiceCloneCheck{public enum Outcome { Ready, TooShort, NotHeard, Slow }- /// `wav` comes back trimmed of the quiet at its ends (VoicePace.Trim): that is what is kept, and- /// the 10 s minimum is of the reading itself, not of the pause before 读完了.public static async Task<(Outcome outcome, string text, byte[] wav)> Check(byte[] recorded, Func<byte[], Task<string?>> transcribe){var wav = VoicePace.Trim(recorded);@@ -228,7 +199,6 @@ public static class VoiceCloneCheckreturn (Outcome.Ready, text);}- /// The passage to read, in the user's own language (Voices.swift › VoiceReference.passage).public static string Passage(string language) => VoiceCatalog.Key(language) switch{"zh" => "大家好,我是这次会议的主持人。今天我们主要讨论新产品的上线计划,包括时间安排、测试范围和市场推广。请大家先看一下屏幕上的议程。",diff --git a/windows/src/Cicada.Core/Voices.cs b/windows/src/Cicada.Core/Voices.csindex 7f18840..b81445d 100644--- a/windows/src/Cicada.Core/Voices.cs+++ b/windows/src/Cicada.Core/Voices.cs@@ -1,19 +1,11 @@namespace Cicada;-/// 说话人识别: telling the other side's voices apart, as the Mac does (SpeakerID.swift). A line's/// audio becomes a voiceprint (WeSpeaker ResNet34-LM, VoxCeleb, CC BY 4.0, compressed to int8 by-/// scripts/compress-voiceprint.py), voiceprints are grouped as lines arrive, and a voice gets a-/// number once it has said enough. Everything runs on this PC; only the numbers are stored.public interface IVoiceprint{- /// A unit-length voiceprint of 16 kHz mono audio, or null (too short, or no model).float[]? Embed(short[] samples);}-/// Kaldi log-mel filterbank, as `torchaudio.compliance.kaldi.fbank` computes it with the defaults the-/// model was trained on: 16 kHz, 25 ms Povey windows every 10 ms, DC removed, pre-emphasis 0.97,-/// 512-point power spectrum, 80 mel bins from 20 Hz to 8 kHz, natural log. Then, as in training,-/// each bin's mean over the clip is taken away.public static class Fbank{public const int Bins = 80, FrameLength = 400, Shift = 160, FftSize = 512;@@ -21,7 +13,6 @@ public static class Fbankstatic readonly double[] window = Enumerable.Range(0, FrameLength).Select(i => Math.Pow(0.5 - 0.5 * Math.Cos(2 * Math.PI * i / (FrameLength - 1)), 0.85)).ToArray();- // `Bins` rows of FftSize/2+1 weights (the Nyquist column is always zero, as in Kaldi).static readonly double[,] banks = MakeBanks();static double[,] MakeBanks()@@ -43,7 +34,6 @@ public static class Fbankreturn w;}- /// Frames × Bins, row-major, mean-normalised; null when too short for a voiceprint (0.5 s).public static float[]? Features(short[] samples){if (samples.Length < MinSeconds * 16000) return null;@@ -72,7 +62,7 @@ public static class Fbank{double e = 0;for (int k = 0; k < cols; k++) e += banks[b, k] * power[k];- outp[f * Bins + b] = (float)Math.Log(Math.Max(e, 1.1920929e-07 /* Float.ulpOfOne, as the Mac */));+ outp[f * Bins + b] = (float)Math.Log(Math.Max(e, 1.1920929e-07));}}for (int b = 0; b < Bins; b++)@@ -85,7 +75,6 @@ public static class Fbankreturn outp;}- /// In-place radix-2 FFT.static void Fft(double[] re, double[] im){int n = re.Length;@@ -115,9 +104,6 @@ public static class Fbank}}-/// Groups voiceprints as lines arrive, never revising a line already labelled. A line joins the-/// closest voice when similar enough; a long line unlike every voice starts a new one; anything-/// else stays unlabelled (对方). Tuned on AMI dev meetings (the Mac's VoiceClusterer).public sealed class VoiceClusterer{public const double NewSeconds = 2.0;@@ -148,19 +134,12 @@ public sealed class VoiceClusterer}}-/// What the transcript shows for the other side's lines (the Mac's SpeakerLabels). A voice gets a-/// number only once it has `ShownAfter` lines, and only when at least two voices have, so a-/// one-to-one call stays 对方. Numbers follow the order voices got there, so a number never moves.public static class SpeakerLabels{public const int ShownAfter = 5;- /// 说话人识别 is on (AppSettings.SpeakerVoices; TranscriptExport.voices on the Mac): when off,- /// notes and exports name no speakers. Kept in step by the app.public static bool Voices { get; set; } = true;- /// Speaker number → the name the user gave it, else Ling's guess (SpeakerLabels.names); an- /// empty name the user set clears the guess.public static Dictionary<int, string> Names(Session s){var outp = new Dictionary<int, string>();@@ -174,7 +153,6 @@ public static class SpeakerLabelsreturn outp;}- /// Long enough to say whose voice it is: three words, or four characters of CJK.public static bool Substantive(string text){var words = text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries).Count(w => w.Any(char.IsLetter));@@ -182,7 +160,6 @@ public static class SpeakerLabelsreturn text.Count(c => c is >= '一' and <= '鿿' or >= '㐀' and <= '䶿' or >= '' and <= 'ヿ' or >= '가' and <= '힣') >= 4;}- /// Voice id → 1-based speaker number, for the voices on show.public static Dictionary<int, int> VoiceNumbers(IReadOnlyList<TranscriptLine> lines){var count = new Dictionary<int, int>();@@ -198,7 +175,6 @@ public static class SpeakerLabelsreturn reached.OrderBy(kv => kv.Value).Select((kv, n) => (kv.Key, n + 1)).ToDictionary(x => x.Key, x => x.Item2);}- /// Line id → 1-based speaker number; lines without one show as 对方.public static Dictionary<string, int> Numbers(IReadOnlyList<TranscriptLine> lines){var number = VoiceNumbers(lines);diff --git a/windows/src/Cicada/AICheckView.cs b/windows/src/Cicada/AICheckView.csindex 3087526..7665424 100644--- a/windows/src/Cicada/AICheckView.cs+++ b/windows/src/Cicada/AICheckView.cs@@ -6,18 +6,12 @@ using static Cicada.Strings;namespace Cicada.App;-/// The AI service's check, step by step (AICheck; the Mac's AICheckView.swift): settings and the-/// onboarding show the same list. Every step that ran shows its result; the one that failed says-/// why in one line and offers the one thing that fixes it (one dark button, at most one other).static class AICheckView{static readonly SolidColorBrush OkPale = Frozen(0xE3, 0xF1, 0xE8);static SolidColorBrush Frozen(byte r, byte g, byte b) { var x = new SolidColorBrush(Color.FromRgb(r, g, b)); x.Freeze(); return x; }- /// `changeKey` opens the key field (settings: 更换; onboarding: back to pasting). The settings- /// have 重新检查 beside the key already; the onboarding needs it in the failed step. `compact`- /// (the onboarding, under two numbered rows): only the steps that have a result.public static FrameworkElement Steps(Controller app, Action changeKey, bool recheckInStep, bool compact = false){var ling = app.Ling;@@ -62,11 +56,9 @@ static class AICheckViewreturn dock;}- /// Why it failed, the proxy box when the network is the trouble, and what fixes it.static void Problem(Controller app, AICheck check, StackPanel into, Action changeKey, bool recheckInStep){var ling = app.Ling;- // A hear model at its own address: the one it couldn't reach is that one.var host = check.Failure?.Step == AICheck.StepId.Hear ? ling.HearHost : ling.ServiceHost;if (check.Message(ling.ServiceLabel, host, ling.Config.TextModel, ling.HearName) is { } why){@@ -88,7 +80,6 @@ static class AICheckViewinto.Children.Add(row);}- /// One primary fix and at most one other.static List<(string Title, Action Run)> Actions(Controller app, AICheck check, Action changeKey, bool recheckInStep){if (check.Failure is not { } f) return [];@@ -98,7 +89,6 @@ static class AICheckViewswitch (f.Why){case AICheck.Reason.Unreachable:- // A proxy has nothing to do with a server on this PC or the local network.if (AIProvider.IsNearby(ling.ServiceHost)) return recheck;return [(L("怎么设置代理"), () => Open(AICheck.HelpUrl)), .. recheck];case AICheck.Reason.InvalidKey or AICheck.Reason.MgmtKey:@@ -115,7 +105,6 @@ static class AICheckView}}- /// Where to add money: OpenRouter's credits page, else the service's own site.public static string TopUp(AIProvider p) => p.Id == "openrouter" ? "https://openrouter.ai/settings/credits" : p.Site ?? "https://zenmux.ai";public static void Open(string url)@@ -124,7 +113,6 @@ static class AICheckViewcatch (Exception e) { Log.Debug($"ai: open failed {e.GetType().Name}"); }}- /// The round mark before a step: a tick, a cross, "!" for busy, "…" while running, "–" for the rest.static FrameworkElement Disc(AICheck.Kind kind){var (bg, fg) = kind switch@@ -148,8 +136,6 @@ static class AICheckViewreturn g;}- /// All passed, in one line: "已连接 · 文字 1.8 秒 · 听 2.1 秒", or when the newest evidence came- /// from a meeting, "正常 · 12 分钟前开会时用过". Null otherwise.public static string? Summary(AICheck check){if (!check.Passed || check.IsBusy) return null;@@ -161,7 +147,6 @@ static class AICheckViewreturn string.Join(" · ", parts);}- /// The settings' status line, named after the step that failed: a missing model is not a connection problem.public static string? Status(AICheck check) => check.IsRunning ? L("正在检查…"): check.Failure is { Why: not AICheck.Reason.Busy } f ? f.Step switch{diff --git a/windows/src/Cicada/App.cs b/windows/src/Cicada/App.csindex bfc0248..2fe54b0 100644--- a/windows/src/Cicada/App.cs+++ b/windows/src/Cicada/App.cs@@ -15,7 +15,6 @@ static class Programstatic int Main(string[] args){Paths.Dev = Paths.Dev || args.Contains("--dev");- // Before the single-instance check: the installer must run while the installed copy does.if (!Paths.Dev){if (args.Contains("--uninstall")) return SetupWindow.Run(SetupWindow.Mode.Uninstall);@@ -26,13 +25,10 @@ static class Programcase SetupPlan.Step.Open: Native.LetOthersTakeForeground(); Install.Launch("--opened"); return 0;}}- // One Cicada per user: a second launch just opens the records of the running one.using var single = new Mutex(true, Paths.Dev ? "com.wquguru.cicada.dev" : Install.Mutex, out bool first);if (!first) { Native.LetOthersTakeForeground(); DebugServer.Send(args.Contains("--opened") ? "setup opened" : "show records"); return 0; }Controller.Arrived = args.FirstOrDefault(a => a is "--installed" or "--updated" or "--opened");var app = new Application { ShutdownMode = ShutdownMode.OnExplicitShutdown };- // WPF's own Windows 11 (Fluent) look for the stock controls: menus, combo boxes, text boxes,- // check boxes and scroll bars. Light only for now; Cicada draws its own surfaces on top.#pragma warning disable WPF0001app.ThemeMode = ThemeMode.Light;#pragma warning restore WPF0001@@ -43,13 +39,10 @@ static class Program}}-/// Wires the engines to the windows, as AppModel does on the Mac. Engine events arrive on worker-/// threads; everything here that touches UI runs on the dispatcher.sealed class Controller{readonly Application application;public readonly AppSettings Settings = AppSettings.Load();- /// 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();@@ -61,45 +54,30 @@ sealed class Controllerpublic readonly UpdateChecker Updates;public readonly Vocabulary Vocabulary;public readonly LiveFixes Fixes;- /// 存到文件夹 (设置 › 隐私与启动): settled meetings written as Markdown into a folder.public readonly FolderExporter FolderExport;- /// 分享…: the share service, its device key and the links made (sealed files, never the record).public readonly ShareClient Sharing = new(new DpapiProtector(), "windows", Version);- /// 我自己的声音: the recording Ming clones the user's voice from, sealed like the keys.public readonly VoiceReference OwnVoice = new(new DpapiProtector());- /// Dev (`silentlisten`): the language `heard` lines are in.public string? SilentLang;- /// Started with Windows (--background): stay in the tray. Opened by hand, the main window shows.public bool Background { get; init; }Onboarding? onboarding;- /// 检查更新 in settings: null, or the result of the last manual check for a few seconds.public string? UpdateCheck { get; private set; }bool checksUpdates;- /// The tray panel opened: check in the background once the last answer is an hour old.public void PanelOpened() { if (checksUpdates) _ = Updates.CheckIfDue(UpdateChecker.Stale); }public static string Version => typeof(Controller).Assembly.GetName().Version?.ToString(3) ?? "0";- /// How the installer started this copy: --installed, --updated or --opened (it was already installed).public static string? Arrived;PushToTalk? talk;SpeakBar? speakBar;- /// The press's microphone: through echo cancellation, or the plain one when that won't open.EchoMic? echoMic;bool echoLogged;DeviceRecorder? mic;- /// Dev builds: a WAV that stands in for the microphone (the VM has none).string? fakeMic;- /// Dev builds: the input the talk key reads instead of the microphone (`talkmic CABLE Output`).string? talkMic;readonly Forms.NotifyIcon tray = new();System.Drawing.Icon? idleIcon, liveIcon, updateIcon;- /// Something only the user can fix (AICheck.Blocking), said beyond the panel: the tray's orange- /// dot and tooltip, and once a meeting a notification while the notes panel is put away.public string? Problem { get; private set; }bool problemNotified;- /// The installer's download progress (0…1) while an update is being fetched, and why the last one failed.public double? UpdateProgress { get; private set; }public string? UpdateFailure { get; private set; }- /// Whether the browser took the download over after the in-app one failed (it may not open).public bool UpdatePageOpened { get; private set; }Action? balloonClicked;Hotkey? hotkey;@@ -109,14 +87,10 @@ sealed class ControllerMainWindow? mainWindow;SettingsWindow? settingsWindow;Dispatcher Dispatch => application.Dispatcher;- // 结束会议 (MeetingEnd.cs): `Ending` while a meeting is about to end by itself, `AutoEnded` after- // one did (the tray says so, and the next call starts a new meeting).MeetingEndWatch? endWatch;public MeetingEndWatch.Pending? Ending { get; private set; }public bool AutoEnded { get; private set; }- /// 结束这场会议? is showing in the notes window or subtitle bar (AppModel.requestStop).public bool ConfirmingEnd { get; private set; }- /// Dev: meeting apps pretending to be in a call, and (silence, countdown, grace) in seconds.public Dictionary<string, string>? FakeCalls;public (double Silence, double Countdown, double Grace)? EndTimes;bool readingCalls;@@ -139,12 +113,9 @@ sealed class ControllerSpeak.Changed += () => Dispatch.BeginInvoke(() => { speakBar ??= new SpeakBar(this); speakBar.Refresh(); });Speak.Reference = OwnVoice;Listen.Voiceprint = new WinVoiceprint();- // No voices on the room side: its numbers would collide with the PC's.- // The talk key's echo check: the meeting playing through a press is sent back otherwise.var loudness = new LoudnessLog();Listen.Loudness = loudness;Speak.Echo = loudness;- // 改正听错的词: the word list beside the records, and the fixes both sides' lines take.Vocabulary = new Vocabulary(Vocabulary.DefaultPath);Fixes = new LiveFixes(Store, Vocabulary, Settings);Fixes.Changed += Changed;@@ -156,8 +127,6 @@ sealed class ControllerNotes.Changed += Changed;Store.Changed += _ => Changed();Store.Words += id => Dispatch.BeginInvoke(() => HeardWords(id));- // 存到文件夹: written once a record is settled, rewritten when it changes. Its state is the- // dispatcher's, as the Mac's is the main actor's.FolderExport = new FolderExporter(Store, Settings){Post = a => Dispatch.BeginInvoke(a),@@ -174,7 +143,6 @@ sealed class Controllerpublic void Launch(){- // Process loopback and capture exclusion both arrived in Windows 10 2004 (build 19041).if (Environment.OSVersion.Version.Build < 19041){MessageBox.Show(L("知了需要 Windows 10 2004 或更新的版本。"), L("知了"));@@ -183,7 +151,6 @@ sealed class Controller}Log.Debug($"app: launch {(Paths.Dev ? "dev" : "release")} {Environment.OSVersion.Version}");SetUpTray();- // 保存会议录音: Windows' AAC encoder; a recording the last run didn't close is finished now.Store.Audio = new MediaFoundationAudio();Store.FinishLeftovers();hotkey = new Hotkey(() => Dispatch.BeginInvoke(() => _ = ToggleListening()));@@ -195,19 +162,14 @@ sealed class ControllerLog.Debug($"audio: speakers {Endpoints.Default(Endpoints.Flow.Render)?.Name ?? "none"}, mic {Endpoints.Microphone()?.Name ?? "none"}, cable {(Endpoints.Cable() is null ? "absent" : "present")}");DebugServer.Start(this);WatchNetwork();- // 存到文件夹: what is still waiting, now and whenever Cicada comes forward (a folder fixed- // in Windows 安全中心 meanwhile).FolderExport.Retry();application.Activated += (_, _) => FolderExport.Retry();- // A dev build isn't what a release replaces: it checks only when pointed at a test feed.UpdateChecker.CleanDownloads();if (!Paths.Dev || Environment.GetEnvironmentVariable("CICADA_UPDATE_FEED") is { Length: > 0 }) { checksUpdates = true; Updates.Start(); }var watch = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };watch.Tick += (_, _) => _ = WatchEnd();watch.Start();if (AutoStart.Enabled) AutoStart.Refresh();- // The Mac shows its main window when opened by hand; a Windows user who double-clicks the- // exe expects a window too, not just a tray icon. Not set up yet: the onboarding on top.if (!Background || !Settings.Onboarded) ShowRecords();if (!Settings.Onboarded){@@ -224,9 +186,6 @@ sealed class Controller}}- /// VB-Cable holds the speaker (installed before Cicada gave it back, or outside Cicada): the user- /// hears nothing and may blame Cicada. Said once (CableDefaults.ShouldNotify); a click gives a- /// real speaker back.public void NotifyCableSpeaker(){var onCable = Endpoints.SpeakerIsCable();@@ -243,7 +202,6 @@ sealed class ControllerSettings.Save();}- /// The installer ran again with this version (or an older one) already here: bring the main window.public void FromInstaller(){ShowRecords();@@ -259,11 +217,8 @@ sealed class ControllerUpdateTray();});- /// Only update news re-renders settings: Changed fires on every line heard.void UpdatesChanged() => Dispatch.BeginInvoke(() => { Changed(); settingsWindow?.UpdatesChanged(); NotifyUpdate(); });- /// One Windows notification per version, for people who never open the tray panel; a click- /// installs. Held while listening or speaking: StopListening tells.void NotifyUpdate(){if (Updates.Available is not { } u) return;@@ -284,14 +239,11 @@ sealed class Controllertray.Icon = idleIcon;tray.Text = L("知了");tray.Visible = true;- // Left click: the panel, or while listening the notes window (both live in this corner, so- // the panel would cover the notes). Right click: the menu, any time.tray.MouseUp += (_, e) =>{if (e.Button == Forms.MouseButtons.Left) Dispatch.BeginInvoke(() => { if (Listen.Listening && Settings.View == "notes") ToggleNotes(); else ShowFlyout(); });else if (e.Button == Forms.MouseButtons.Right) Dispatch.BeginInvoke(ShowMenu);};- // Cleared before the run: a click may show the next notification, with its own action.tray.BalloonTipClicked += (_, _) => Dispatch.BeginInvoke(() => { var c = balloonClicked; balloonClicked = null; c?.Invoke(); });UpdateTray();}@@ -306,8 +258,6 @@ sealed class Controllercatch { return System.Drawing.SystemIcons.Application; }}- /// The logo with a dot on its corner: orange while listening or something needs fixing, grey- /// for a new version (it can wait).static System.Drawing.Icon WithDot(System.Drawing.Icon icon, System.Drawing.Color colour){using var bmp = new System.Drawing.Bitmap(32, 32);@@ -326,19 +276,13 @@ sealed class Controllervoid UpdateTray(){CheckProblem();- // Orange says 正在听 or something to fix (the Mac's problem badge), grey a new version;- // the tooltip names the problem first.tray.Icon = Listen.Listening || Problem is not null ? liveIcon : Updates.Available is not null ? updateIcon : idleIcon;var text = Problem is { } p ? L("知了") + " · " + p: Listen.Listening ? L("知了") + " · " + L("正在听"): Updates.Available is { } u ? L("知了") + " · " + LF("有新版本 %@", u.Version) : L("知了");- // NotifyIcon.Text throws past 127 characters (a long model id in the title).tray.Text = text.Length > 127 ? text[..126] + "…" : text;}- /// On every change: the tray's problem, and its one notification a meeting. Only while- /// listening, and only when the notes panel isn't up (its banner says so; the subtitle bar has- /// none). Never a dialog: it would take the focus from the meeting app.void CheckProblem(){var p = Ling.HasKey && Ling.Health.Blocking ? AIProblem()?.Title : null;@@ -359,7 +303,6 @@ sealed class Controllerflyout.Toggle();}- /// The right-click menu needs a window of ours in front, or it won't close on an outside click.public void ShowMenu(){menuHost ??= new Window { WindowStyle = WindowStyle.None, AllowsTransparency = true, Background = System.Windows.Media.Brushes.Transparent, ShowInTaskbar = false, Width = 1, Height = 1, Left = -10000, Top = -10000, Topmost = true };@@ -373,8 +316,6 @@ sealed class Controlleritem.Click += (_, _) => act();return item;}- // The Mac's status menu: what the AI service needs from the user, where it stands, then what- // to do, then the windows, then 退出.if (AIProblem() is { } ai){var (problem, detail) = ai;@@ -391,7 +332,6 @@ sealed class Controllerif (Settings.View == "notes") menu.Items.Add(NotesVisible ? Item(L("隐藏纪要窗"), ToggleNotes) : Item(L("显示纪要"), ShowNotes));}else menu.Items.Add(Item(L("开始听"), () => _ = ToggleListening(), Hotkey.Label.Replace('+', ' ')));- // 麦克风: one checkable item for what 听哪里's three were.var micItem = Item(L("麦克风"), () => SetMic(!MicOn));micItem.IsCheckable = true; micItem.IsChecked = MicOn;menu.Items.Add(micItem);@@ -406,22 +346,18 @@ sealed class Controllermenu.IsOpen = true;}- /// 存到文件夹 couldn't write after a meeting (not inside a folder controlled folder access- /// protects: Windows says that itself). Once until a write works again.void NotifyFolderDenied(){if (FolderExport.Folder is not { } folder) return;Toast(L("纪要没存到文件夹"), LF("知了没有权限写入 %@。点按去设置", FolderExportUi.ShortPath(folder)), ShowFolderSettings);}- /// 设置 › 隐私与启动, where 会后存一份 says what is wrong.public void ShowFolderSettings(){ShowSettings();SettingsPage("privacy");}- /// A Windows notification from the tray icon; a click on it runs `clicked`.public void Toast(string title, string body, Action? clicked = null){balloonClicked = clicked;@@ -437,29 +373,21 @@ sealed class Controllerelse await StartChecked(NewSource);}- /// What 听哪里 says to listen to: the PC's audio, or the room through a microphone.public IAudioSource NewSource() => Settings.ListensToRoom ? RoomSource() : new SystemAudioTap();- /// The room mic, muted while you hold the talk key. Dev: a WAV stands in (the VM has no mic).GatedSource RoomSource(){if (fakeRoom is { } wav) return new GatedSource(new FileAudioSource(wav)) { Name = "fake" };return new GatedSource(new MicSource(Endpoints.RoomMic)) { Muted = Speak.State == SpeakEngine.Phase.Recording };}- /// The room mic listening hears right now, if any (muted while you speak).readonly List<GatedSource> roomSources = [];- /// Dev builds: a WAV the room mic hears instead of a microphone.string? fakeRoom;public void SetFakeRoom(string? path) { fakeRoom = path; Log.Debug($"room: fake mic {(path is null ? "off" : "on")}"); }- /// Dev builds: what the echo measurement says, instead of measuring (the VM has no speakers).bool? fakeEcho;public void SetFakeEcho(bool? on) { fakeEcho = on; if (Listen.Echo is { } e) e.Gate.Forced = on; Log.Debug($"room: echo sim {on?.ToString() ?? "real"}"); }- /// 打开麦克风 / 关闭麦克风 (AppModel.setMic on the Mac): the PC's audio is always heard; the mic- /// adds the people in the room to the same meeting. Not kept for the next launch: listening- /// never starts with the microphone open. Turning it on while nothing is heard starts listening.public bool MicOn => Settings.HearsBoth;public void SetMic(bool on)@@ -482,9 +410,7 @@ sealed class Controller// MARK: 电脑和会议室- /// The room side of 电脑和会议室: its own engine on the room mic, adding to the same meeting.public readonly ListenEngine RoomListen;- /// 电脑和会议室 but Windows won't give Cicada the microphone: the PC's side keeps recording.public bool HybridMicDenied { get; private set; }@@ -512,7 +438,6 @@ sealed class Controller}else if (reason == "none") Toast(L("没有可用的麦克风"), L("电脑声音照常在记"));else Toast(L("会议室的麦克风断开了"), L("电脑声音照常在记"));- // The mic is really off now: say so in the tray and the menu, not only stop hearing it.if (reason == "denied") { _ = StopRoomSide(); Changed(); } else SetMic(false);});};@@ -529,8 +454,6 @@ sealed class ControllerLog.Debug("hybrid: room side stopped");}- /// A source about to be listened to: a room mic is remembered (the talk key mutes it), and one- /// that can't go on says why.IAudioSource Watch(IAudioSource source){if (source is GatedSource room) roomSources.Add(room);@@ -554,12 +477,6 @@ sealed class Controllerreturn source;}- /// The user's 开始听: blocked only by a failure the last result knows of. A hear model that- /// can't hear asks to switch to the recommended one; an unreachable service is looked at once- /// more, but only waited for briefly (a check that can't connect takes 10–20 s): still unknown- /// then, the dialog says what the last check found and its 重新检查并开始 waits in place, with- /// 正在检查… on the button. Unknown or busy starts as usual. A dialog comes after a yield, so- /// the debug pipe that asked for the start replies first; a start that needs none has happened by then.public async Task StartChecked(Func<IAudioSource> source){if (Listen.Listening || starting) return;@@ -596,8 +513,6 @@ sealed class Controllerstring Body(AICheck h) => (h.Message(Ling.ServiceLabel, Ling.ServiceHost, Ling.Config.TextModel, Ling.HearName) ?? "")+ (h.ProxyLine(Ling.ServiceLabel, Ling.ServiceHost) is { } proxy ? "\n" + proxy : "");await Task.Yield();- // 重新检查并开始: the check already under way (or one that finished reachable while the- // dialog was up), else a new one; reachable closes the dialog.async Task<string?> Retry(){var under = recheck;@@ -611,7 +526,6 @@ sealed class Controllerif (choice == 2) ShowAISettings();else if (choice == 1){- // Reached now; the check may still have found something else (a deaf model): ask again.starting = false;await StartChecked(source);}@@ -623,15 +537,10 @@ sealed class Controller}bool starting;- /// How long 开始听 waits for a fresh look at an unreachable service before asking.static readonly TimeSpan QuickLook = TimeSpan.FromSeconds(2);- /// A window of ours to put a dialog over; null (the screen's centre) from the tray.Window? VisibleWindow() => new Window?[] { settingsWindow, mainWindow, onboarding }.FirstOrDefault(w => w?.IsVisible == true && w.WindowState != WindowState.Minimized);- /// The user's 结束 (buttons, menu, hotkey): a meeting with lines ends only after asking, in the- /// notes window or subtitle bar, which never take focus, so no modal dialog fights them for it.- /// An empty one just stops.public void RequestStop(){if (!Listen.Listening) return;@@ -661,14 +570,12 @@ sealed class ControllerShowNotes();}- /// The meeting being ended: Quit waits for it, or a meeting ended a moment before quitting- /// (its last sentences still out at the AI service) was never closed and came back empty.Task stopping = Task.CompletedTask;public Task StopListening(DateTimeOffset? endedAt = null, bool auto = false){var t = Stopping(endedAt, auto);- if (!t.IsCompleted) stopping = t; // a second, empty stop mustn't hide the one still running+ if (!t.IsCompleted) stopping = t;return t;}@@ -685,7 +592,7 @@ sealed class Controllerawait Listen.Stop(endedAt);if (id is not null) FolderExport.Ended(id);Changed();- NotifyUpdate(); // held while the meeting was on+ NotifyUpdate();if (id is not null) _ = TellWhenNotesReady(id);}@@ -697,7 +604,6 @@ sealed class Controllerreturn EndTimes is { } t ? c with { SilenceAfter = t.Silence, Countdown = t.Countdown, AppGrace = t.Grace } : c;}- /// Words recognised in the live meeting (theirs or mine): the silence countdown stops now.void HeardWords(string id){if (endWatch is null || !Listen.Listening || id != Listen.SessionId) return;@@ -705,8 +611,6 @@ sealed class ControllerSetEnding(endWatch.Waiting);}- /// Every 2 s: while listening, whether the meeting is over; after one ended by itself, whether a- /// meeting app started the next call. The registry is read off the UI thread.async Task WatchEnd(){bool live = Listen.Listening && endWatch is not null, after = !Listen.Listening && AutoEnded;@@ -740,13 +644,10 @@ sealed class ControllerChanged();}- /// Ends where the meeting really ended: a little after the last words, or at the hang-up if that- /// was later.async Task AutoEnd(MeetingEndWatch.Reason reason, MeetingEndWatch w){if (reason.Kind == "nobody"){- // Nothing to keep or summarise: back to 开始听, not 会议已自动结束.Log.Debug($"meeting end: nobody spoke for {(int)w.Settings.SilenceAfter} s, stopped");await StopListening();return;@@ -759,7 +660,6 @@ sealed class Controllerawait StopListening(at, auto: true);}- /// 继续记录 on the ending prompt.public void KeepRecording(){endWatch?.KeepGoing(DateTimeOffset.Now);@@ -773,7 +673,6 @@ sealed class Controllerpublic static int EndingLeft(MeetingEndWatch.Pending p) => Math.Max(0, (int)Math.Round((p.Deadline - DateTimeOffset.Now).TotalSeconds));- /// The final notes take a few seconds after 结束; say so once they're written.async Task TellWhenNotesReady(string id){for (int i = 0; i < 120; i++)@@ -789,7 +688,6 @@ sealed class Controller}}- /// The panel was closed while listening: the first time, say that listening goes on.public void CollapsedWhileListening(){if (!Listen.Listening || Settings.ToldStillListening) return;@@ -797,8 +695,6 @@ sealed class ControllerToast(L("知了还在听"), L("点任务栏右下角的知了图标再打开纪要。"), ShowNotes);}- /// The onboarding sample: heard straight from the file (Cicada's own sound is left out of- /// the system capture) while it plays aloud for the user.public async Task PlaySample(){if (Bundled.Sample() is not { } wav || Listen.Listening) return;@@ -808,21 +704,19 @@ sealed class ControllerStartListening(source);try { new SoundPlayer(wav).Play(); } catch (Exception e) { Log.Debug($"sample: play failed {e.GetType().Name}"); }await done.Task;- await Task.Delay(3000); // the last segment's reply+ await Task.Delay(3000);await StopListening();}// MARK: Speaking (同声传译)public bool NotesVisible => notesWindow?.IsVisible == true;- /// Where the notes panel is on screen, when it shows as a panel: the talk bar keeps out of it.public Rect? NotesBounds => NotesVisible && Settings.View == "notes"? new Rect(notesWindow!.Left, notesWindow.Top, notesWindow.ActualWidth, notesWindow.ActualHeight) : null;public void SetFakeMic(string? path) { fakeMic = path; Log.Debug($"speak: fake mic {(path is null ? "off" : "on")}"); }public void SetTalkMic(string? name) { talkMic = name; Log.Debug($"speak: talk mic {name ?? "default"}"); }- /// Dev: what the meeting hears. Records "CABLE Output" for `seconds` into `path` ("8 C:\x.wav").public async Task RecordCable(string arg){var parts = arg.Split(' ', 2);@@ -841,7 +735,6 @@ sealed class Controllerif (!Settings.Speak || Speak.State is SpeakEngine.Phase.Recording or SpeakEngine.Phase.Translating) 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; }- // With a fake mic the WAV is what is sent; a dev talk mic still opens, to run the real capture.if (fakeMic is null || talkMic is not null){if (TalkMic() is not { } m) { if (fakeMic is null) { Speak.Report(L("没找到麦克风")); return; } }@@ -851,17 +744,12 @@ sealed class Controller}}Speak.BeginRecording();- // What you say isn't someone in the room.foreach (var r in roomSources) r.Muted = true;}- /// The press's microphone: through Windows' echo cancellation when it opens, so what I say while- /// the other side talks on the speakers is sent (EchoMic); the plain mic when it doesn't. Null,- /// or why the mic can't be had ("denied").string? OpenTalkMic(Endpoints.Device m){var speakers = Endpoints.Default(Endpoints.Flow.Render);- // The cable is where my own voice goes, never the meeting's speakers.var reference = speakers is not null && speakers.Id != Endpoints.Cable()?.Id ? speakers.Id : null;var aec = new EchoMic(m.Id, reference);aec.Start();@@ -880,15 +768,12 @@ sealed class Controllerreturn null;}- /// The talk key's microphone. Dev: `talkmic <name>` picks any input (the VM's only one is CABLE Output).Endpoints.Device? TalkMic() => talkMic is { } name? Endpoints.All(Endpoints.Flow.Capture).FirstOrDefault(d => d.Description == name || d.Name.StartsWith(name)): Endpoints.Microphone();- /// Ends the press's recording: what it heard, and whether through echo cancellation.(short[] pcm, bool echoCancelled) StopTalkMic(){- // As logged when the press began (a stream still opening then counts as plain), and still so.var cancelled = echoLogged && echoMic?.EchoCancelled == true;echoLogged = false;var pcm = echoMic?.Stop() ?? mic?.Stop() ?? [];@@ -897,7 +782,6 @@ sealed class Controllerreturn (pcm, cancelled);}- /// Another key went down while a modifier talk key was held (Ctrl C): a shortcut, not talking.void PressInterrupted(){foreach (var r in roomSources) r.Muted = false;@@ -907,7 +791,6 @@ sealed class ControllerLog.Debug("talk: interrupted by another key");}- /// 更改 the talk key: the next key pressed anywhere comes to `chosen` (on the UI thread).public void ChooseTalkKey(Action<int> chosen){if (talk is null) return;@@ -930,9 +813,7 @@ sealed class Controllerif (Speak.State != SpeakEngine.Phase.Recording) return;var (recorded, echoCancelled) = StopTalkMic();var pcm = fakeMic is { } f ? Wav.Read(f) : recorded;- // A tap, not a sentence.if (pcm.Length < Segmenter.Rate * 3 / 10) { Speak.Cancel(); return; }- // Held but nothing said (a muted mic): Ming would make something up from the hiss.if (pcm.Max(x => Math.Abs((int)x)) < 300) { Speak.Report(L("没听到你说话,没有发出去")); return; }_ = Speak.Speak(Wav.Bytes(pcm), new DeviceSpeaker(Endpoints.Cable), echoCancelled);}@@ -942,8 +823,6 @@ sealed class Controllerpublic bool Previewing => previewing is not null;public void StopPreview() => previewing?.Stop();- /// 试听: a voice speaks its sample line on the speakers (not into the meeting). It used to fail- /// without a word (#22); now the result says why, for the line under the voice.public async Task<PreviewResult> Preview(string language){previewing?.Stop();@@ -974,14 +853,11 @@ sealed class Controller// MARK: 我自己的声音- /// The microphone a recording for the user's own voice comes from: the talk key's.public Endpoints.Device? OwnVoiceMic() => TalkMic();- /// What a recording says, as the hear model (Ming on Ling) hears it; null when it heard nothing.public async Task<string?> Transcribe(byte[] wav) =>(await Translator.Hear(wav, Speak.Target, Speak.MyLanguage, Priority.Speak))?.Original;- /// Plays a recording (16 kHz mono WAV) on the speakers; 停止 is StopPreview.public async Task PlayRecording(byte[] wav){previewing?.Stop();@@ -997,8 +873,6 @@ sealed class Controllerfinally { if (previewing == speaker) previewing = null; }}- /// The review's 用你的声音说…: the language's sample line in a voice cloned from a recording not- /// yet kept, on the speakers. True once something played.public async Task<bool> PreviewOwnVoice(byte[] wav, string text, string language){previewing?.Stop();@@ -1024,7 +898,6 @@ sealed class Controllerreturn chunks > 0;}- /// Keeps a recording as the user's own voice and uses it for `language` (VoiceCloneSheet.save).public void SaveOwnVoice(byte[] wav, string text, string language){OwnVoice.Save(wav, text);@@ -1034,7 +907,6 @@ sealed class ControllerChanged();}- /// 删除: the recording goes, and every language that used it gets its default back.public void RemoveOwnVoice(){OwnVoice.Remove();@@ -1046,7 +918,6 @@ sealed class Controller// MARK: Windows- /// The tray icon while listening: the notes window comes and goes.public void HideNotes(){if (NotesVisible) ToggleNotes();@@ -1058,7 +929,6 @@ sealed class ControllerChanged();}- /// The first time a window's × is clicked: closing it doesn't quit, Cicada stays in the tray.public void WindowClosed(){if (Settings.TrayHintShown) return;@@ -1075,28 +945,21 @@ sealed class Controller// MARK: Setup (the main window's 还差几步 and the title bar's pill)- /// The setup steps, as the onboarding numbers them: what is done, by what really happened- /// rather than by "the onboarding was finished".public (bool Key, bool Audio, bool Sample) SetupDone => (Ling.HasKey && !KeyStepFailed, Settings.HeardSystemAudio || Settings.Onboarded, Settings.SampleSeen || Settings.Onboarded);- /// The AI service's last result is a failure only the user can fix (not "still checking", not- /// busy, not a server error, not a balance running low): 还差几步 shows it as not done yet.public bool KeyStepFailed => Ling.Health is { NeedsUser: true, Failure: not null };- /// Steps left before listening works; 0 once set up. 同声传译 is optional and never counted.public int SetupLeft{get{var (k, a, sm) = SetupDone;if (Settings.Onboarded && k) return 0;- // Set up once, and the service broke later: that one step is left.if (Settings.Onboarded && Ling.HasKey) return 1;return (k ? 0 : 1) + (a ? 0 : 1) + (sm ? 0 : 1);}}- /// The onboarding, at `step` or at the first step not done; one window at a time.public void ShowOnboarding(int? step = null){var (k, a, _) = SetupDone;@@ -1116,7 +979,6 @@ sealed class Controllerpublic void ShowRecords() => ShowRecords(null);- /// Debug pipe: a record opened at a tab, and the player in it.public void OpenRecord(string id, string tab) { ShowRecords(id); mainWindow?.Select(id, tab); }public void Play(string arg) => mainWindow?.DebugPlay(arg);public JsonObject DebugSearch(string? text, int step)@@ -1125,7 +987,6 @@ sealed class Controllerreturn mainWindow!.DebugSearch(text, step);}- /// 分享…: the dialog over the records window (or the screen's centre without it).public ShareDialog ShareSheet(Session s){ShareDialog.Current?.Close();@@ -1151,15 +1012,12 @@ sealed class Controller}public void SettingsPage(string id) => settingsWindow?.Show(id);- /// The open settings window, for the debug pipe's preview and talkkey.public SettingsWindow? OpenSettings => settingsWindow;- /// Debug: 改这句… on a record's line; 词表 › 粘贴导入 with `text` pasted in.public void DebugEditLine(string id, string line) { ShowRecords(id); mainWindow?.DebugEdit(id, line); }public void DebugPaste(string text) { ShowSettings(); SettingsPage("words"); settingsWindow?.DebugImport(text); }// 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;@@ -1168,12 +1026,10 @@ sealed class ControllerAIChanged();}- /// 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;- // A custom service's notes model: "" is the translation model's.else if (kind == "notes"){if (model.Length > 0) Settings.AiModels["custom.notes"] = model; else Settings.AiModels.Remove("custom.notes");@@ -1188,14 +1044,12 @@ sealed class ControllerAIChanged();}- /// 设置 › AI 服务, opened at its page (the fix for every AI problem the app names).public void ShowAISettings(){ShowSettings();SettingsPage("ai");}- /// One click on 换成推荐的: the service's first recommended text or hear model, then a fresh check.public void UseRecommended(AICheck.StepId step){if (Ling.Recommended(step) is not { } id) return;@@ -1203,7 +1057,6 @@ sealed class ControllerSetAIModel(step == AICheck.StepId.Hear ? "hear" : "text", id);}- /// A key pasted for one service that belongs to another (改用 OpenRouter): switch, keep it there, check.public void SwitchService(string provider, string key){if (AIProvider.Named(provider).Id != provider) return;@@ -1213,8 +1066,6 @@ sealed class ControllerAIChanged();}- /// "改用 Ling" where another service is out of reach: only when a Ling key is already saved,- /// so the one click works without a trip to the settings.public bool CanSwitchToLing => Settings.AiProvider != "ling" && Key.Read("ling") is not null;public void SwitchToLing()@@ -1224,8 +1075,6 @@ sealed class ControllerSetAIProvider("ling");}- /// What the tray says first when the AI service needs the user (title, detail); null otherwise.- /// On Windows the service hears too, so a dead service means no subtitles either.public (string Title, string Detail)? AIProblem(){var h = Ling.Health;@@ -1244,8 +1093,6 @@ sealed class Controller};}- /// Network changes (Wi-Fi back, a proxy app's TUN, a cable): 3 s for it to settle, then the AI- /// service is looked at again if it was unreachable. No timer: nothing is checked while it stays the same.void WatchNetwork(){var settle = new DispatcherTimer { Interval = TimeSpan.FromSeconds(3) };@@ -1255,10 +1102,6 @@ sealed class ControllerSystem.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged += (_, e) => { if (e.IsAvailable) Changed(); };}- /// Turning the system proxy on or off (or pointing it elsewhere) changes no address, so the- /// watch above misses it. While the service is unreachable (and through the check that follows)- /// the proxy settings are read every 3 s (three registry values; HttpClient follows them by- /// itself) and a change is checked like a network change. Not polled otherwise. ProxyWatch decides.void WatchProxy(){var h = Ling.Health;@@ -1283,7 +1126,6 @@ sealed class ControllerDispatcherTimer? proxyPoll;readonly ProxyWatch proxyWatch = new();- /// The service, its address, models or key changed: forget the old check and check again.public void AIChanged(){Translator.GoogleOff = Settings.GoogleOff;@@ -1292,7 +1134,6 @@ sealed class ControllerChanged();}- /// 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;@@ -1342,9 +1183,6 @@ sealed class Controller// MARK: Updates- /// 安装: Cicada downloads the installer itself and checks it against checksums.txt, then opens- /// it; its 更新知了 window quits this copy, replaces it and reopens (--updated). A release with- /// only the zip, or a failed download, falls back to the browser.public async void InstallUpdate(){if (Updates.Available is not { } u || UpdateProgress is not null) return;@@ -1369,7 +1207,6 @@ sealed class Controller}}- /// 下载: the browser fetches this PC's installer or zip (or opens the release page when there is none).public bool DownloadUpdate(){if (Updates.Available is not { } u) return false;@@ -1379,14 +1216,12 @@ sealed class Controllerpublic void OpenReleaseNotes() { if (Updates.Available is { } u) Open(u.Page); }- /// False when no browser took it (none set, or Windows refused).public static bool Open(string url){try { System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(url) { UseShellExecute = true }); return true; }catch (Exception e) { Log.Debug($"update: open failed {e.GetType().Name}: {e.Message}"); return false; }}- /// 检查更新: says 正在检查… / 已是最新版本 / 连不上 GitHub for a few seconds.public async Task CheckForUpdates(){if (UpdateCheck == L("正在检查…")) return;@@ -1418,8 +1253,6 @@ sealed class Controllerapplication.Shutdown();}- /// For the debug pipe: what a test needs to see (never meeting text).- /// 存到文件夹 for the debug pipe (paths and file names, never meeting text).public JsonObject ExportState(){var ex = FolderExport;@@ -1483,22 +1316,6 @@ sealed class Controller};}-/// Debug commands over a named pipe (\\.\pipe\cicada-dev), dev builds only: the Windows-/// counterpart of the Mac's `tools/lsctl`. One command per connection, one JSON line back.-/// state | start | stop | feed <wav> | sample | view notes|subtitles | capture on|off-/// listensource system|room|both | fakeroom <wav>|off (a WAV the room mic hears; the VM has no mic)-/// 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)-/// ownvoice <wav>[|<text>] | ownvoice remove | ownvoice dialog [<wav>] | voice <lang>=<id> (我自己的声音)-/// open <id> [transcript] | play <seconds>|toggle|speed|follow|row <i> | recordaudio on|off (保存会议录音 and 回放)-/// aacencode <wav>|<out.aac> | aacrewrap <in.aac>|<out.m4a>[|<seconds>]-/// ai-check | ai-check-sim <reason|lowBalance|off> (unreachable, invalidKey, noCredit, noModel, deaf, busy…)-/// ai-custom-only on|off (语音和文字只发给你的服务; acts with the custom service only)-/// 改正听错的词: silentlisten [lang] | heard <text> (a finished sentence, no audio) | fixes on|off | asknames on|off-/// vocabadd <word = heard、…|…> | vocabremove <word> | vocabstate | fixstate [@id] | fixanswer yes|no [@id]-/// fixlater | fixrevert <line> [@id] | fixedit <line>=<text>[|one][|keep0] [@id] | fixundostatic class DebugServer{static string Pipe => Paths.Dev ? "cicada-dev" : "cicada";@@ -1516,8 +1333,6 @@ static class DebugServerusing var reader = new StreamReader(server);using var writer = new StreamWriter(server) { AutoFlush = true };var line = reader.ReadLine() ?? "";- // A release build only takes a second launch's and the installer's few commands; the- // rest is for dev builds.if (!Paths.Dev && line is not ("show records" or "setup status" or "setup quit" or "setup opened")) { writer.WriteLine("{\"error\":\"dev builds only\"}"); continue; }var reply = app.Dispatcher().Invoke(() => Run(app, line));writer.WriteLine(reply.ToJsonString());@@ -1536,11 +1351,9 @@ static class DebugServer{var parts = line.Trim().Split(' ', 2);var arg = parts.Length > 1 ? parts[1].Trim() : "";- // The installer asks for status every 2 seconds while its window is open: not worth a line each.if (line != "setup status") Log.Debug($"debug: {parts[0]}");switch (parts[0]){- // The installer (Install.cs): is a meeting on, quit for the new copy, show yourself.case "setup": return arg switch{"status" => new JsonObject { ["listening"] = app.Listen.Listening },@@ -1548,12 +1361,11 @@ static class DebugServer_ => Opened(app),};case "start": _ = app.StartChecked(app.NewSource); break;- // mic:<on|off> is the button; listenSource:<system|room|both> the old names for it.case "mic" or "listensource": app.SetMic(arg is "on" or "both" or "room"); break;case "roomechosim": app.SetFakeEcho(arg is "real" or "" ? null : arg != "off"); break;case "fakeroom": app.SetFakeRoom(arg is "" or "off" ? null : arg); break;case "stop": _ = app.StopListening(); break;- case "end": app.RequestStop(); break; // the user's 结束: asks first when anything was said+ case "end": app.RequestStop(); break;case "notesproblem": app.Notes.SimulateStatus(arg); break;case "feed": _ = app.StartChecked(() => new FileAudioSource(arg)); break;case "sample": _ = app.PlaySample(); break;@@ -1574,9 +1386,6 @@ 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;- // 我自己的声音 without a microphone: "ownvoice <wav>[|<what it says>]" checks a recording as- // the dialog does (heard by Ming unless the words are given) and keeps it; "ownvoice remove"- // is 删除; "ownvoice dialog [<wav>]" opens the recording dialog (with a WAV: as if just read).case "ownvoice":{if (arg == "remove") { app.RemoveOwnVoice(); return new JsonObject { ["ownVoice"] = app.OwnVoice.Exists }; }@@ -1598,7 +1407,6 @@ static class DebugServer});break;}- // voice <lang>=<id>: 线上的人听到的声音 for a language ("voice en=clone", "voice zh=ming:灵小雅").case "voice":{var kv = arg.Split('=', 2);@@ -1606,10 +1414,8 @@ static class DebugServerreturn new JsonObject { ["voice"] = app.Speak.ChosenVoice(kv[0]), ["clone"] = app.Speak.CloneReady };}case "provider": app.SetAIProvider(arg); break;- // switchtoling: the 改用 Ling on a status line (logs why when it isn't offered).case "switchtoling": Log.Debug($"switchtoling offered={app.CanSwitchToLing}"); app.SwitchToLing(); break;case "ai-check":- // ai-check: a check now; ai-check-sim <reason|lowBalance|off>: every check ends this way (screenshots)._ = app.Ling.Check();break;case "ai-check-sim":@@ -1618,7 +1424,6 @@ static class DebugServer_ = app.Ling.Check();break;case "ai-custom-only": app.Settings.AiCustomOnly = arg == "on"; app.Settings.Save(); app.AIChanged(); break;- // 纪要 on a custom service: "ai-notes same|own [address]" (the notes model: ai-model notes <id>).case "ai-notes":{var p = arg.Split(' ', 2);@@ -1634,35 +1439,26 @@ static class DebugServerbreak;}case "speakers": app.Settings.SpeakerVoices = arg == "on"; app.Settings.Save(); app.SettingsChanged(); break;- // speaker: the defaults and whether the cable holds the speaker; "cable" hands it the speaker- // (what Windows may do on install), "install" does that and then the installer's give-back,- // "restore" is 恢复声音, "notify" the startup notification again.case "speaker":if (arg is "cable" or "install"){var before = Endpoints.Defaults();var to = Endpoints.Cable()!.Id;for (var role = 0; role < 3; role++) Endpoints.SetDefault(to, role);- if (arg == "install") _ = CableInstaller.GiveBackDefaults(before); // about 4 s; ask "speaker" after+ if (arg == "install") _ = CableInstaller.GiveBackDefaults(before);}else if (arg == "restore") Endpoints.RestoreSpeaker();else if (arg == "notify") { app.Settings.CableSpeakerNotified = false; app.NotifyCableSpeaker(); }return new JsonObject { ["onCable"] = Endpoints.SpeakerIsCable(), ["speaker"] = Endpoints.Default(Endpoints.Flow.Render)?.Name, ["notified"] = app.Settings.CableSpeakerNotified,["defaults"] = string.Join(" ", Endpoints.Defaults().OrderBy(d => d.Key).Select(d => $"{d.Key}={(Endpoints.CableIds().Contains(d.Value) ? "cable" : "real")}")) };case "fakemic": app.SetFakeMic(arg == "off" ? null : arg); break;- // talkmic <name>: the talk key reads this input (with fakemic the WAV is still what is sent).case "talkmic": app.SetTalkMic(arg is "" or "off" ? null : arg); break;case "record": _ = app.RecordCable(arg); break;- // 回放: "open <id> [transcript]", "play <seconds>|toggle|speed|follow|row <i>" (follow: 回到正在播放; row: a line- // clicked), "recordaudio on|off".- case "rename": { var p = arg.Split(' ', 2); app.Store.Rename(p[0], p.Length > 1 ? p[1] : ""); break; } // rename <id> <title> ("" back to automatic)+ case "rename": { var p = arg.Split(' ', 2); app.Store.Rename(p[0], p.Length > 1 ? p[1] : ""); break; }case "open": { var p = arg.Split(' '); app.OpenRecord(p[0], p.Length > 1 ? p[1] : "notes"); break; }case "play": app.Play(arg); break;- // The records' Ctrl+F (#33): "search <text>" types into it (opens the records), "searchstep 1|-1" is- // Enter / the arrows. Logged as "main search:" with the meetings found, the lines found and where it is.case "search": return app.DebugSearch(arg, 0);case "searchstep": return app.DebugSearch(null, int.TryParse(arg, out var searchStep) ? searchStep : 1);- // 存到文件夹: export [state] | on | off | folder <path> | choose | all | retrycase "export":{var p = arg.Split(' ', 2);@@ -1671,7 +1467,7 @@ static class DebugServercase "on": if (app.FolderExport.Folder is { } f) app.FolderExport.Choose(f); else app.FolderExport.Choose(FolderExportFormat.DefaultFolder()); break;case "off": app.FolderExport.TurnOff(); break;case "folder" when p.Length > 1: app.FolderExport.Choose(p[1].Trim().Trim('"')); break;- case "choose": // modal: shown after the reply, or the pipe would wait for it+ case "choose":app.ShowFolderSettings();app.Dispatcher().BeginInvoke(() => { if (FolderExportUi.Choose(app.OpenSettings, app.FolderExport.Folder) is { } picked) app.FolderExport.Choose(picked); });break;@@ -1681,7 +1477,6 @@ static class DebugServerreturn app.ExportState();}case "recordaudio": app.Settings.RecordAudio = arg == "on"; app.Settings.Save(); app.SettingsChanged(); break;- // 保存会议录音 on its own: "aacencode <wav>|<out.aac>", "aacrewrap <in.aac>|<out.m4a>[|<seconds>]".case "aacencode":{var p = arg.Split('|');@@ -1697,12 +1492,10 @@ static class DebugServervar p = arg.Split('|');return new JsonObject { ["ok"] = app.Store.Audio?.Rewrap(p[0], p[1], p.Length > 2 ? double.Parse(p[2], System.Globalization.CultureInfo.InvariantCulture) : null) ?? false };}- // preview: 试听 in the open settings (its result line shows there), else on its own.case "preview":if (arg.Length == 0 && app.OpenSettings is { } sw) _ = sw.RunPreview();else _ = app.Preview(arg.Length > 0 ? arg : app.Speak.Target);break;- // talkkey <name>: set it; talkkey choose: settings' 更改 (the next key pressed).case "talkkey":if (arg == "choose") app.OpenSettings?.StartChoosingKey();else if (TalkKey.All.FirstOrDefault(k => k.Name == arg) is { } tk) app.SetTalkKey(tk);@@ -1719,11 +1512,9 @@ static class DebugServercase "updatefeed": app.Updates.Feed = arg; _ = app.CheckForUpdates(); break;case "updateinstall": app.InstallUpdate(); break;case "checkupdate": _ = app.CheckForUpdates(); break;- // 改正听错的词 (AppModel.debugCommand's fix commands). A command acts on the meeting being- // listened to, else the newest; "… @<id>" names another.case "silentlisten": app.SilentLang = arg.Length > 0 ? arg : "zh-CN"; app.StartListening(new SilentSource()); break;case "heard": app.Listen.DebugHeard(arg, app.SilentLang ?? "zh-CN"); break;- case "target": app.SetTarget(arg.Length > 0 ? arg : "system"); break; // 翻译成: a code, or system+ case "target": app.SetTarget(arg.Length > 0 ? arg : "system"); break;case "fixes": app.Settings.FixMisheard = arg != "off"; app.Settings.Save(); app.SettingsChanged(); break;case "asknames": app.Settings.AskNames = arg != "off"; app.Settings.Save(); app.SettingsChanged(); break;case "vocabadd": return new JsonObject { ["result"] = app.Vocabulary.Import(arg.Replace('|', '\n')).ToString() };@@ -1745,20 +1536,20 @@ static class DebugServer$"{l.Id} [{string.Join(", ", l.Fixes!.Select(f => $"{f.From}→{f.To}{(f.Ask == true ? "?" : f.Off == true ? "✗" : f.User == true ? "✓" : "")}"))}] {l.Shown} | {l.Dst}").ToArray()),};}- case "fixanswer": // fixanswer yes|no [@id]+ case "fixanswer":{var (id, rest) = FixTarget(app, arg);if ((app.Fixes.Asking(id)?.Fix ?? app.Fixes.Pending(id).Select(p => p.Fix).FirstOrDefault()) is { } f) app.Fixes.Answer(f, rest == "yes", id);break;}case "fixlater": { var (id, _) = FixTarget(app, arg); if (app.Fixes.Asking(id) is { } ask) app.Fixes.Later(ask.Fix, id); break; }- case "fixrevert": // fixrevert <line id> [@id]: the line's first applied fix+ case "fixrevert":{var (id, lineId) = FixTarget(app, arg);if (app.Store.Get(id)?.Lines.FirstOrDefault(l => l.Id == lineId)?.Fixes?.FirstOrDefault(f => f.Applied) is { } f) app.Fixes.Revert(f, lineId, id);break;}- case "fixedit": // fixedit <line id>=<new text>[|one][|keep0] [@id]+ case "fixedit":{var (id, rest) = FixTarget(app, arg);var p = rest.Split('=', 2);@@ -1767,12 +1558,10 @@ static class DebugServerreturn new JsonObject { ["changed"] = app.Fixes.Edit(p[0], id, opts[0], everywhere: !opts.Contains("one"), remember: !opts.Contains("keep0")) };}case "fixundo": app.Fixes.Undo(); break;- case "fixeditor": { var (id, lineId) = FixTarget(app, arg); app.DebugEditLine(id, lineId); break; } // fixeditor <line> [@id]- case "vocabpaste": app.DebugPaste(arg); break; // vocabpaste <line|line…>: 粘贴导入, filled in, not imported+ case "fixeditor": { var (id, lineId) = FixTarget(app, arg); app.DebugEditLine(id, lineId); break; }+ case "vocabpaste": app.DebugPaste(arg); break;case "share":{- // share <record id>[,full][,pw] shares a meeting as the dialog would (CICADA_SHARE_SERVER- // points a dev build at a local Worker); unshare <record id> turns it off.var p = arg.Split(',');if (app.Store.Get(p[0]) is not { } s) return new JsonObject { ["error"] = "no such record" };var o = new ShareOptions@@ -1799,10 +1588,6 @@ static class DebugServer_ = Task.Run(async () => Log.Debug($"share: revoked {await app.Sharing.Revoke(r, arg)}"));break;}- // sharesheet <record id>[,full][,pw][,names][,30|365][,more][,go] opens 分享… (more presses 更改,- // go 生成并复制); sharesheet leaveout presses 去掉这些内容后分享; on the done step- // sharesheet copy|copylink|copypw|menu presses 复制, its menu's items, or opens the menu;- // sharesheet alone closes it.case "sharesheet" or "shareSheet":{var p = arg.Split(',', StringSplitOptions.RemoveEmptyEntries);@@ -1814,7 +1599,6 @@ static class DebugServerapp.Dispatcher().BeginInvoke(() => app.ShareSheet(s).Debug(p));break;}- // shareinfo <record id>: the link kept for it (dev builds only, never logged) and the open dialog's step.case "shareinfo":{var r = app.Sharing.Store.Read(arg);@@ -1830,8 +1614,6 @@ static class DebugServerreturn app.State();}- /// The meeting a fix command acts on ("… @<id>", else the one being listened to, else the- /// newest), and the rest of its argument.static (string Id, string Arg) FixTarget(Controller app, string arg){var at = arg.LastIndexOf(" @", StringComparison.Ordinal);@@ -1840,7 +1622,6 @@ static class DebugServerreturn (app.Listen.SessionId ?? app.Store.All().FirstOrDefault()?.Id ?? "", arg);}- /// Sends one command to the running app (a second launch uses it to bring records forward).public static string? Send(string command){trydiff --git a/windows/src/Cicada/Bundled.cs b/windows/src/Cicada/Bundled.csindex fcf246a..4917222 100644--- a/windows/src/Cicada/Bundled.cs+++ b/windows/src/Cicada/Bundled.cs@@ -2,15 +2,11 @@ using System.Text;namespace Cicada.App;-/// Files carried inside Cicada.exe (EmbeddedResource in Cicada.csproj), so the exe alone is the-/// whole app: the installer is downloaded as one file and installs by copying itself.static class Bundled{static readonly System.Reflection.Assembly Self = typeof(Bundled).Assembly;- // MSBuild writes %(RecursiveDir) with the build machine's separator: "en.lproj\" on Windows CI.static readonly Dictionary<string, string> Names = Self.GetManifestResourceNames().ToDictionary(n => n.Replace('\\', '/'), n => n);- /// "en.lproj/Localizable.strings" and the like, for Strings.Load.public static string? Strings(string path){if (!Names.TryGetValue("strings/" + path, out var name) || Self.GetManifestResourceStream(name) is not { } s) return null;@@ -18,8 +14,6 @@ static class Bundledreturn reader.ReadToEnd();}- /// The onboarding sample as a file (SoundPlayer and FileAudioSource both want a path), written- /// to the temp folder the first time it's asked for.public static string? Sample(){var path = Path.Combine(Path.GetTempPath(), $"cicada-sample-{Controller.Version}.wav");diff --git a/windows/src/Cicada/Dialogs.cs b/windows/src/Cicada/Dialogs.csindex 4ae7a2f..815a1d3 100644--- a/windows/src/Cicada/Dialogs.cs+++ b/windows/src/Cicada/Dialogs.cs@@ -6,24 +6,16 @@ using static Cicada.Strings;namespace Cicada.App;-/// Windows 11 ContentDialogs: a title, a line or a field, and two equal buttons on a grey band,-/// primary first. Enter takes the primary button, Esc cancels.static class Dialogs{- /// Asks before something that can't be undone. True when the user agreed.public static bool Confirm(Window owner, string title, string body, string ok, bool danger){var text = Ui.Text(body, 14, Palette.Body);return Show(owner, title, text, ok, danger, null) is not null;}- /// Something to know, with one button.public static void Tell(Window owner, string title, string body) => Show(owner, title, Ui.Text(body, 14, Palette.Body), L("知道了"), danger: false, null, single: true);- /// Two ways on, both named (开始听 blocked: 换成推荐的并开始 / 打开设置): 1 for `primary`, 2 for- /// `other`, 0 when closed. No `primary`: just `other` and 取消. No owner: the screen's centre.- /// `retry` makes `primary` work in place (重新检查并开始): the dialog stays with 正在检查… on the- /// button, then closes as 1 when it returns null, or shows the body it returns and waits again.public static int Choose(Window? owner, string title, string body, string? primary, string other, Func<Task<string?>>? retry = null){int chosen = 0;@@ -35,7 +27,6 @@ static class Dialogsreturn r is not null ? 1 : chosen;}- /// A one-line answer: the new text (maybe empty), or null when cancelled.public static string? Prompt(Window owner, string title, string value, string? hint, string ok){var box = new TextBox { Text = value };@@ -45,8 +36,6 @@ static class Dialogsreturn Show(owner, title, content, ok, danger: false, box);}- /// One of a few options, each a bordered row (the Mac's FolderChoice): its index, or null when- /// cancelled. The first is chosen to start with.public static int? Pick(Window? owner, string title, IReadOnlyList<(string Title, string? Detail)> options, string ok){int pick = 0;@@ -65,7 +54,6 @@ static class Dialogsvar index = i;var text = options[i].Detail is { } d ? Ui.Stack(2, Ui.Text(options[i].Title, 13, Palette.Ink), Ui.Helper(d)) : Ui.Stack(2, Ui.Text(options[i].Title, 13, Palette.Ink));var row = new Border { CornerRadius = new CornerRadius(9), Padding = new Thickness(12, 10, 12, 10), Margin = new Thickness(0, 0, 0, 8), Background = Palette.Surface, Cursor = Cursors.Hand, Child = text };- // Down, and handled: the dialog drags itself on a press, which would swallow the release.row.MouseLeftButtonDown += (_, e) => { pick = index; Restyle(); e.Handled = true; };System.Windows.Automation.AutomationProperties.SetName(row, options[i].Title);rows.Add(row);@@ -102,7 +90,6 @@ static class Dialogs}primary = Ui.Button(ok, Accept, danger ? Ui.Kind.Danger : Ui.Kind.Primary);cancel = secondary ?? Ui.Button(L("取消"), dialog.Close);- // A named second way on isn't 取消: Esc just closes.primary.IsDefault = true; cancel.IsCancel = secondary is null;if (secondary is not null) dialog.KeyDown += (_, e) => { if (e.Key == Key.Escape) dialog.Close(); };var buttons = new Grid();diff --git a/windows/src/Cicada/EchoMic.cs b/windows/src/Cicada/EchoMic.csindex 582b173..ebc1cc0 100644--- a/windows/src/Cicada/EchoMic.cs+++ b/windows/src/Cicada/EchoMic.cs@@ -2,15 +2,6 @@ using System.Runtime.InteropServices;namespace Cicada.App;-/// The talk key's microphone through Windows' echo cancellation (VoiceMic.swift on the Mac): a-/// WASAPI capture stream in the communications category, so the endpoint's AEC (its driver's, or-/// Windows 11's Voice Clarity) takes the meeting playing on the speakers out of what I say. From-/// build 22621 the AEC is pointed at those speakers; from 22000 the stream says which effects run-/// (`EchoCancel.InEffect`). Records at 16 kHz mono until Stop, like DeviceRecorder.-///-/// EchoCancelled is true only when the stream lists an AEC that is on: then SpeakEngine skips the-/// echo drop. Otherwise (Windows 10, a driver without AEC, a virtual mic) the press is the plain-/// mic's and is dropped as before when the meeting played through it.sealed class EchoMic{readonly string id;@@ -18,13 +9,10 @@ sealed class EchoMicreadonly List<short> samples = [];Thread? thread;volatile bool running;- /// "denied" (Windows' microphone privacy switch), or why the stream wouldn't open.public string? Error { get; private set; }public bool EchoCancelled { get; private set; }- /// For the log: what Windows said about echo cancellation on this stream.public string Detail { get; private set; } = "";- /// `reference`: the render endpoint the meeting plays on; null leaves the choice to Windows.public EchoMic(string id, string? reference) { this.id = id; this.reference = reference; }public void Start()@@ -50,17 +38,13 @@ sealed class EchoMictry{client = Endpoints.Activate(id);- // Before Initialize: the category picks the endpoint's communications processing.- // Options stay 0: RAW would turn off the very processing wanted here.- var props = new AudioClientProperties { cbSize = 16, bIsOffload = 0, eCategory = 3 /* AudioCategory_Communications */, Options = 0 };+ var props = new AudioClientProperties { cbSize = 16, bIsOffload = 0, eCategory = 3, Options = 0 };Marshal.ThrowExceptionForHR(((IAudioClient2)client).SetClientProperties(ref props));var fmt = Endpoints.Pcm16(16000);int hr = client.Initialize(0, Endpoints.AutoConvert, 2_000_000, 0, fmt, IntPtr.Zero);Marshal.FreeHGlobal(fmt);Marshal.ThrowExceptionForHR(hr);var notes = new List<string>();- // The speakers the meeting plays on as the AEC's reference (22621+). E_NOINTERFACE: no- // AEC here, or one that picks its own reference; neither is an error.var iid = typeof(IAcousticEchoCancellationControl).GUID;if (client.GetService(ref iid, out var c) == 0 && c is IAcousticEchoCancellationControl control){@@ -94,7 +78,6 @@ sealed class EchoMic}catch (Exception e){- // 0x80070005: Windows' microphone privacy switch is off for desktop apps.Error = e.HResult == unchecked((int)0x80070005) ? "denied" : $"0x{e.HResult:X8}";EchoCancelled = false;Log.Debug($"echo mic: failed 0x{e.HResult:X8}");@@ -103,8 +86,6 @@ sealed class EchoMicfinally { if (client is not null) Marshal.ReleaseComObject(client); }}- /// The stream's effects (22000+), with an AEC that is off but may be set turned on first; null- /// when Windows can't list them.static List<EchoCancel.AudioEffect>? Effects(IAudioClient client, List<string> notes){var iid = typeof(IAudioEffectsManager).GUID;@@ -112,7 +93,7 @@ sealed class EchoMicvar list = Read(manager);if (list is not null && EchoCancel.CanTurnOn(list)){- var hr = manager.SetAudioEffectState(EchoCancel.Effect, 1 /* AUDIO_EFFECT_STATE_ON */);+ var hr = manager.SetAudioEffectState(EchoCancel.Effect, 1);notes.Add(hr == 0 ? "turned AEC on" : $"AEC on failed 0x{hr:X8}");list = Read(manager);}@@ -125,7 +106,6 @@ sealed class EchoMicvar list = new List<EchoCancel.AudioEffect>();try{- // AUDIO_EFFECT: GUID id, BOOL canSetState, AUDIO_EFFECT_STATE state: 24 bytes.for (int i = 0; i < n; i++){var e = Marshal.PtrToStructure<AudioEffect>(p + i * Marshal.SizeOf<AudioEffect>());@@ -147,7 +127,6 @@ sealed class EchoMic[StructLayout(LayoutKind.Sequential)]struct AudioEffect { public Guid id; public int canSetState; public int state; }- /// IAudioClient's methods again, in order: a ComImport interface doesn't inherit vtable slots.[ComImport, Guid("726778CD-F60A-4eda-82DE-E47610CD78AA"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]interface IAudioClient2{diff --git a/windows/src/Cicada/FixViews.cs b/windows/src/Cicada/FixViews.csindex f87353c..dd940b1 100644--- a/windows/src/Cicada/FixViews.cs+++ b/windows/src/Cicada/FixViews.cs@@ -7,10 +7,6 @@ using static Cicada.Strings;namespace Cicada.App;-/// 改正听错的词's pieces, shared by the notes window and the meeting record (the Mac's FixViews.swift-/// and NotesViews.swift › FixedWords, FixConfirmCard, joinFixed): the line with its fixed words-/// underlined, what each was heard as with 改回, the 这样改对吗? card, the banner over a finished-/// meeting, and the toast with 撤销.static class FixViews{static readonly SolidColorBrush ChipFill = Frozen(0xF2, 0xF3, 0xF5);@@ -26,8 +22,6 @@ static class FixViewsreturn c;}- /// The line as shown, each fixed word with a dotted underline; words waiting for the user- /// (这样改对吗?) on a pale wash, as heard.public static TextBlock LineText(TranscriptLine l, double size, Brush color){var t = Ui.Text("", size, color);@@ -50,9 +44,6 @@ static class FixViewsreturn t;}- /// The records' search (#33, TranscriptSearch.highlighted on the Mac): every term in `t` on the- /// pale accent; in the match being looked at, solid accent with white text. The runs are split- /// where a mark starts or ends, keeping their own look (a fixed word's underline) otherwise.public static T Mark<T>(T t, IReadOnlyList<string> terms, bool current) where T : TextBlock{if (terms.Count == 0) return t;@@ -87,8 +78,6 @@ static class FixViewsreturn t;}- /// Under a paragraph: each fixed word, what it was heard as, and 改回. `edit`: 改这句… after them- /// (the meeting record).public static FrameworkElement FixedWords(TranscriptLine l, Action<LineFix> revert, Action? edit = null){var wrap = new WrapPanel { Margin = new Thickness(0, 4, 0, 0) };@@ -120,9 +109,6 @@ static class FixViewsreturn wrap;}- /// 这样改对吗?: a name sound couldn't check, asked about once. Clicks only: the notes window- /// never takes focus. 对 fixes every line waiting on it and adds it to the word list; × puts it- /// off until after the meeting (稍后再看).public static FrameworkElement ConfirmCard(TranscriptLine line, LineFix fix, int count, Action<bool> answer, Action? later){var c = Correction.Label(fix);@@ -164,8 +150,6 @@ static class FixViewsstatic Button Small(Button b) { b.MinWidth = 0; b.Padding = new Thickness(14, 0, 14, 0); return b; }- /// Above a finished meeting's transcript: how many words were fixed, and the ones waiting for- /// the user, one at a time (对 / 不对 / 改成…). Nothing once there was nothing to fix.public static FrameworkElement? Banner(Session s, LiveFixes fixes, Action<string> show, Action<TranscriptLine, string> edit){var waiting = fixes.Pending(s.Id);@@ -200,7 +184,6 @@ static class FixViewsstatic readonly SolidColorBrush AccentWash = Frozen(0xFE, 0xF6, 0xF3);- /// The last fix decision said back for a few seconds, with 撤销 (null when there is none).public static FrameworkElement? Toast(LiveFixes fixes){if (fixes.Toast is not { } t) return null;@@ -222,9 +205,6 @@ static class FixViews};}- /// 改这句… in the meeting record: the line as shown, to rewrite. What changed becomes the- /// user's own fix, on every line heard the same way or only this one; Enter applies, Esc- /// cancels.public sealed class Editor : StackPanel{readonly TranscriptLine line;@@ -275,7 +255,6 @@ static class FixViewsone.Checked += (_, _) => { everywhere = false; Options(); };stack.Children.Add(all); stack.Children.Add(one);}- // Only a word for a word can teach the list: an added or dropped word can't.if (same.Swap){var remember = new CheckBox { Content = L("记进词表,以后自动改"), IsChecked = keep, FontSize = 12, Margin = new Thickness(0, 6, 0, 0), IsEnabled = same.Count <= 1 || everywhere };diff --git a/windows/src/Cicada/FolderExportViews.cs b/windows/src/Cicada/FolderExportViews.csindex 71fb908..357da0e 100644--- a/windows/src/Cicada/FolderExportViews.cs+++ b/windows/src/Cicada/FolderExportViews.cs@@ -8,8 +8,6 @@ using static Cicada.Strings;namespace Cicada.App;-/// 存到文件夹 (FolderExport.cs): the folder as Explorer names it, the choice of folder, and the-/// record's line under its title. As the Mac's FolderExportViews.swift.static class FolderExportUi{[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]@@ -22,18 +20,14 @@ static class FolderExportUi[DllImport("shell32.dll", CharSet = CharSet.Unicode)] static extern IntPtr SHGetFileInfo(string path, uint attributes, ref FileInfo info, uint size, uint flags);const uint DisplayNameFlag = 0x200;- /// Explorer's name for a folder ("文档" for Documents, "Windows (C:)" for a drive); null when it- /// isn't there.static string? ShellName(string path){var info = new FileInfo();return SHGetFileInfo(path, 0, ref info, (uint)Marshal.SizeOf<FileInfo>(), DisplayNameFlag) != IntPtr.Zero && info.DisplayName is { Length: > 0 } n ? n : null;}- /// "文档 › Cicada".public static string ShortPath(string folder) => FolderExportFormat.ShortPath(folder, ShellName);- /// Not SettingsWindow.OpenFolder: that makes the folder, and on a drive that's gone it would throw.public static void Open(string folder){if (!Directory.Exists(folder)) return;@@ -46,14 +40,12 @@ static class FolderExportUielse if (Path.GetDirectoryName(file) is { } dir) Open(dir);}- /// Windows 安全中心 › 勒索软件防护, where controlled folder access lets an app through.public static void OpenSecurity(){try { Process.Start(new ProcessStartInfo("windowsdefender://ransomwareprotection") { UseShellExecute = true }); }catch (Exception e) { Log.Debug($"folder export: security page not opened {e.GetType().Name}"); }}- /// 存到哪里: an Obsidian vault first (a new Cicada folder in it), then 文档 › Cicada, or any folder.public static string? Choose(Window? owner, string? current){var options = new List<(string Title, string? Detail, string? Path)>();@@ -70,8 +62,6 @@ static class FolderExportUireturn dialog.ShowDialog(owner) == true ? dialog.FolderName : null;}- /// The record's line under its title: where its file is, or why it isn't there yet. Null when- /// there is nothing to say.public static FrameworkElement? Line(Controller app, Session s){var ex = app.FolderExport;@@ -90,13 +80,10 @@ static class FolderExportUireturn line;}- /// What the line shows, for MainWindow's PageKey.public static string Key(Controller app, string id) =>$"{app.FolderExport.On}|{app.FolderExport.FileFor(id)}|{app.FolderExport.IsPending(id)}|{app.FolderExport.Trouble?.Kind}";}-/// 设置 › 隐私与启动 › 会后存一份 (the Mac has it in 通用, under the records' location, which on-/// Windows is this page).sealed partial class SettingsWindow{IEnumerable<FrameworkElement> ExportCards()@@ -112,7 +99,6 @@ sealed partial class SettingsWindowvar shortPath = FolderExportUi.ShortPath(folder);if (ex.Checking) cards.Add(Card(null, LF("正在确认能写入 %@…", shortPath), null, new Border()));else if (ex.Trouble is { } problem) cards.Add(ProblemRow(problem, folder, shortPath));- // Ui.Row spaces only the children it is given.var place = new List<UIElement>();if (FolderExportFormat.Vault(folder) is not null) place.Add(Ui.Badge(L("Obsidian 库")));place.Add(Ui.Button(L("打开"), () => FolderExportUi.Open(folder), height: 32));@@ -127,13 +113,10 @@ sealed partial class SettingsWindowvar local = at.ToLocalTime();var last = Ui.Text(LF("上次存于 %@ · %@", local.ToString(L("M月d日 HH:mm"), Strings.Culture), name), 12, Palette.Tertiary, wrap: false);last.TextTrimming = TextTrimming.CharacterEllipsis;- // Section sets each part's margin: the indent goes on a wrapper.yield return new Border { Padding = new Thickness(6, 0, 0, 0), Child = last };}}- /// Access denied looks the same whoever said no; inside the folders controlled folder access- /// protects, Windows 安全中心 is the likely fix.FrameworkElement ProblemRow(FolderExporter.Problem problem, string folder, string shortPath){var waiting = app.FolderExport.State.Pending.Count;@@ -179,6 +162,5 @@ sealed partial class SettingsWindowRender();}- /// The exporter's state changed: only 隐私与启动 shows it.public void ExportChanged() { if (current == "privacy") Render(); }}diff --git a/windows/src/Cicada/Install.cs b/windows/src/Cicada/Install.csindex e9894a5..a6355a1 100644--- a/windows/src/Cicada/Install.cs+++ b/windows/src/Cicada/Install.cs@@ -5,19 +5,13 @@ using Microsoft.Win32;namespace Cicada.App;-/// The release build installed for this user only, so nothing asks for admin rights: the exe in-/// %LOCALAPPDATA%\Programs\Cicada, a Start menu shortcut, the Run key for 开机时启动知了 and an-/// entry in Settings › Apps whose 卸载 runs `Cicada.exe --uninstall`. The windows are SetupWindow.static class Install{public static string Folder => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Cicada");public static string Exe => Path.Combine(Folder, "Cicada.exe");const string UninstallKey = @"Software\Microsoft\Windows\CurrentVersion\Uninstall\Cicada";- /// The release build's single-instance mutex (Program.Main).public const string Mutex = "com.wquguru.cicada";- /// The installed version, from Settings › Apps' entry (the exe's own version resource isn't- /// written when the app is built on the Mac). Null when nothing is installed.public static string? InstalledVersion(){if (!File.Exists(Exe)) return null;@@ -25,10 +19,8 @@ static class Installcatch { return "0"; }}- /// The running Cicada (installed, or an old copy from a zip), through its pipe: null when none.public static bool? Listening() => DebugServer.Send("setup status") is { } reply ? reply.Contains("\"listening\":true") : null;- /// Asks the running Cicada to quit (it ends a meeting first and saves it), and waits until it has.static void QuitRunning(){if (DebugServer.Send("setup quit") is null && !Running()) return;@@ -48,28 +40,23 @@ static class Installreturn false;}- /// Copies this exe in, then registers it. `step` reports 1–3 as each part is done. First install:- /// the two choices. An upgrade (`choices` null) keeps the shortcut and autostart as they were.public static void Run((bool StartMenu, bool AutoStart)? choices, Action<int> step){var self = Environment.ProcessPath ?? throw new IOException("no exe path");Directory.CreateDirectory(Folder);- // Copied beside the old one first, so a full disk or a scanner holding the file leaves the- // installed copy as it was.var next = Exe + ".new";File.Copy(self, next, overwrite: true);QuitRunning();for (int i = 0; ; i++){try { File.Move(next, Exe, overwrite: true); break; }- catch (IOException) when (i < 20) { Thread.Sleep(250); } // the old process is still letting go of it+ catch (IOException) when (i < 20) { Thread.Sleep(250); }catch (UnauthorizedAccessException) when (i < 20) { Thread.Sleep(250); }}step(1);var hadShortcut = Shortcuts().Any(File.Exists);if (choices?.StartMenu ?? hadShortcut) Shortcut(); else foreach (var f in Shortcuts()) File.Delete(f);step(2);- // A copy from a zip may have left the Run key pointing into Downloads: point it here.AutoStart.Set(Exe, choices?.AutoStart ?? AutoStart.Enabled);Register();step(3);@@ -82,8 +69,6 @@ static class Installcatch (Exception e) { Log.Debug($"setup: launch failed {e.GetType().Name}"); }}- /// Removes the app; the records, settings and key too unless `keepRecords`. The folder itself- /// goes once this process has exited (a running exe can't delete itself): RemoveFolderLater.public static void Uninstall(bool keepRecords){QuitRunning();@@ -94,7 +79,6 @@ static class InstallLog.Debug($"setup: uninstalled, records {(keepRecords ? "kept" : "removed")}");}- /// A hidden cmd that waits for this process to go, then deletes the install folder.public static void RemoveFolderLater(){if (!Directory.Exists(Folder)) return;@@ -131,7 +115,6 @@ static class Installfinally { Marshal.FinalReleaseComObject(link); }}- /// Settings › Apps: no 修改 or 修复, just 卸载.static void Register(){using var k = Registry.CurrentUser.CreateSubKey(UninstallKey);diff --git a/windows/src/Cicada/MainWindow.cs b/windows/src/Cicada/MainWindow.csindex 9d68de1..8a8da02 100644--- a/windows/src/Cicada/MainWindow.cs+++ b/windows/src/Cicada/MainWindow.cs@@ -6,7 +6,6 @@ using static Cicada.Strings;namespace Cicada.App;-/// How a meeting is described in lists: "10:03 · 23 分钟 · 待办 2".static class Records{public static string Meta(Session s, Controller app)@@ -17,7 +16,6 @@ static class Records? local.ToString("HH:mm", Culture): local.ToString(L("M月d日"), Culture);var parts = new List<string> { day, LF("%@ 分钟", Math.Max(1, (int)Math.Round(s.Duration.TotalMinutes))) };- // The Mac marks these with a mic and a display; a word reads the same here.if (Places.HeardBoth(s.Lines)) parts.Add(L("电脑和会议室"));if (s.Notes?.Todos.Count is > 0 and var n) parts.Add(LF("待办 %@", n));return string.Join(" · ", parts);@@ -31,10 +29,6 @@ static class Records}}-/// 会议记录, as the Mac's main window with no title bar: a grey list of one-line titles grouped by-/// day, the chosen one on a white pill, and the meeting set out like a document on one white-/// sheet: when and how long over a big title, 纪要 / 文字记录, the conclusions and to-dos in one-/// grey block, the summary, then the numbered topics.sealed class MainWindow : Window{readonly Controller app;@@ -44,7 +38,6 @@ sealed class MainWindow : Windowstring? selected;string tab = "notes";double? jumpTo;- /// A line to show, marked for a moment (the fix banner's 听成 … → …?).string? jumpLine;string? shownKey;bool refreshQueued;@@ -53,8 +46,6 @@ sealed class MainWindow : Windowreadonly DispatcherTimer tick = new() { Interval = TimeSpan.FromMilliseconds(120) };readonly double[] levels = new double[8];FrameworkElement? left;- // The pill is rebuilt only when what it says changes (a rebuild between press and release- // would lose the click); the bars and the clock move in place.string? pillKey;readonly List<System.Windows.Shapes.Rectangle> bars = [];TextBlock? clock;@@ -65,7 +56,6 @@ sealed class MainWindow : Windowselected = select;Title = L("会议记录") + " · " + L("知了");Width = 1180; Height = Math.Min(780, SystemParameters.WorkArea.Height - 24); MinWidth = 860; MinHeight = 520;- // One white sheet, as the Mac's main window: no cards, no second layer.Background = Palette.Surface; FontFamily = Palette.Font; Icon = AppIcon.Image;WindowStartupLocation = WindowStartupLocation.CenterScreen;@@ -73,7 +63,6 @@ sealed class MainWindow : Windowgrid.ColumnDefinitions.Add(listColumn);grid.ColumnDefinitions.Add(new ColumnDefinition());- // The search box, with its icon and placeholder drawn over itvar placeholder = Ui.Text(L("搜索标题、纪要和原话"), 13, Palette.Secondary, wrap: false);placeholder.IsHitTestVisible = false; placeholder.Margin = new Thickness(31, 0, 0, 0); placeholder.VerticalAlignment = VerticalAlignment.Center;var glass = Ui.Icon(Icons.Search, 16, Palette.Secondary);@@ -97,14 +86,12 @@ sealed class MainWindow : Window{if (e.Key == System.Windows.Input.Key.F && System.Windows.Input.Keyboard.Modifiers == System.Windows.Input.ModifierKeys.Control) { search.Focus(); search.SelectAll(); e.Handled = true; }else if (e.Key == System.Windows.Input.Key.Escape && search.IsKeyboardFocused) { search.Text = ""; e.Handled = true; }- // Enter goes to the next line found in the shown meeting (Shift+Enter: the one before).else if (e.Key == System.Windows.Input.Key.Enter && search.IsKeyboardFocused){Step(System.Windows.Input.Keyboard.Modifiers == System.Windows.Input.ModifierKeys.Shift ? -1 : 1);e.Handled = true;}};- // 本场 n / N under the search box, only while the shown meeting has lines found.matchText.VerticalAlignment = VerticalAlignment.Center;matchText.Typography.NumeralAlignment = FontNumeralAlignment.Tabular;var prev = Ui.IconButton(Icons.ChevronUp, L("上一个"), () => Step(-1), Palette.Secondary, 26, 14);@@ -118,7 +105,6 @@ sealed class MainWindow : WindowmatchBar.Visibility = Visibility.Collapsed;DockPanel.SetDock(matchBar, Dock.Top);- // The list pane on the ground's grey, the logo where the title bar was.var logo = AppIcon.Small(20);logo.HorizontalAlignment = HorizontalAlignment.Left; logo.Margin = new Thickness(18, 14, 0, 6);var left = new DockPanel { Background = Palette.Mica };@@ -133,12 +119,10 @@ sealed class MainWindow : Windowvar right = new Border { Background = Palette.Surface, Child = detail };Grid.SetColumn(right, 1);grid.Children.Add(left); grid.Children.Add(right);- // The Mac's toolbar pill, centred in the title bar: the brand is the listening switch.System.Windows.Shell.WindowChrome.SetIsHitTestVisibleInChrome(pill, true);Grid.SetColumnSpan(pill, 2);grid.Children.Add(pill);Content = Ui.Frameless(this, grid);- // The pill's clock and level move while listening; nothing else needs a timer.tick.Tick += (_, _) => { if (app.Listen.Listening) Pill(); else { tick.Stop(); Pill(); } };Closed += (_, _) => { tick.Stop(); ClosePlayer(); };playTick.Tick += (_, _) => UpdatePlayer();@@ -167,9 +151,7 @@ sealed class MainWindow : Windowreadonly DockPanel matchBar = new();readonly TextBlock matchText = Ui.Text("", 12, Palette.Secondary, wrap: false);- /// Which of the shown meeting's lines found the search is on.int matchIndex;- /// The query changed or another meeting was opened: start again at the first line found.bool searchMoved;List<string> SearchTerms(Session? s) => s is null ? [] : TranscriptSearch.Terms(search.Text, s.Notes?.Terms);@@ -177,7 +159,6 @@ sealed class MainWindow : Windowstring? CurrentMatch(Session? s) { var f = Found(s); return f.Count == 0 ? null : f[Math.Min(matchIndex, f.Count - 1)]; }Session? Shown => selected is null ? null : app.Store.Get(selected);- /// A search that finds lines in the shown meeting opens its transcript at the first one.void ShowMatches(){searchMoved = false;@@ -190,7 +171,7 @@ sealed class MainWindow : Windowvar n = Found(Shown).Count;if (n == 0) return;matchIndex = (Math.Min(matchIndex, n - 1) + d + n) % n;- centredFound = null; // Enter goes to the line even when it is the only one+ centredFound = null;tab = "transcript";UpdateMatchBar();ShowDetail();@@ -203,7 +184,6 @@ sealed class MainWindow : Windowif (n > 0) matchText.Text = LF("本场 %lld / %lld", Math.Min(matchIndex, n - 1) + 1, n);}- /// Debug `search <text>` / `searchstep <1|-1>`: types into the search box or steps, as Enter does.public System.Text.Json.Nodes.JsonObject DebugSearch(string? text, int step){if (text is not null) search.Text = text; else Step(step);@@ -218,7 +198,6 @@ sealed class MainWindow : Window{Pill();var all = app.Store.All();- // No meetings yet: only the welcome. An empty list and search box are noise.listColumn.Width = new GridLength(all.Count == 0 ? 0 : 260);if (left is not null) left.Visibility = all.Count == 0 ? Visibility.Collapsed : Visibility.Visible;var q = search.Text.Trim();@@ -237,14 +216,12 @@ sealed class MainWindow : Window}list.Children.Add(Item(s));}- // An empty page replaces the meeting, so the next real one must draw again.if (all.Count == 0) { selected = null; shownKey = null; detail.Content = Welcome(); UpdateMatchBar(); return; }if (shown.Count == 0) { shownKey = null; detail.Content = Empty(L("没有找到"), ""); matchBar.Visibility = Visibility.Collapsed; return; }if (selected is null || shown.All(s => s.Id != selected)) { selected = shown[0].Id; if (q.Length > 0) searchMoved = true; }if (searchMoved) ShowMatches();UpdateMatchBar();foreach (var child in list.Children.OfType<Button>()) Paint(child);- // Store changes come in a burst while a meeting runs; redraw the open page only if it changed.if (PageKey() == shownKey) { ShowToast(); return; }ShowDetail();}@@ -275,13 +252,11 @@ sealed class MainWindow : Windowvoid Paint(Button b){var on = (string)b.Tag == selected;- // The Mac's list: the chosen meeting on a white pill on the grey pane.b.Background = on ? Palette.Surface : Brushes.Transparent;var label = b.Content as TextBlock ?? (b.Content as Panel)?.Children.OfType<TextBlock>().FirstOrDefault();if (label is not null) label.FontWeight = on ? FontWeights.Bold : FontWeights.Normal;}- /// A list row: white and raised when chosen, a grey wash under the mouse otherwise.static ControlTemplate RowTemplate(){var t = new ControlTemplate(typeof(Button));@@ -301,8 +276,6 @@ sealed class MainWindow : Window// MARK: Welcome and the pill- /// No meetings yet (Views.swift › welcome): the logo, one line and the one thing to do; or,- /// not set up yet, what is left, each step opening the onboarding where it is.FrameworkElement Welcome(){var s = new StackPanel { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, MaxWidth = 480, Margin = new Thickness(24, 40, 24, 60) };@@ -333,13 +306,10 @@ sealed class MainWindow : Window{var (key, audio, sample) = app.SetupDone;var first = !key ? 0 : !audio ? 1 : !sample ? 2 : 3;- // The key is in but the service turned it down (or can't be reached, or can't hear): the- // reason, and the settings page that fixes it.var ling = app.Ling;var broken = app.KeyStepFailed ? ling.Health.Message(ling.ServiceLabel, ling.ServiceHost, ling.Config.TextModel, ling.HearName) : null;(string title, string detail, bool done)[] steps =[- // A service whose check passed ticks it; another service is named (接上 ZenMux).(ling.Config.IsLing ? L("接上 Ling") : LF("接上 %@", ling.Config.Name), broken ?? (key ? L("key 已加密存在这台电脑上") : L("识别、翻译和纪要都靠它,约 1 分钟")), key),(L("听一下电脑里的声音"), L("放一段测试声音,看音量条动起来"), audio),(L("看看效果"), L("一段 9 秒的英文会议,字幕和纪要一句句出来"), sample),@@ -377,8 +347,6 @@ sealed class MainWindow : Windowstatic FrameworkElement Center(FrameworkElement e) { e.HorizontalAlignment = HorizontalAlignment.Center; e.VerticalAlignment = VerticalAlignment.Center; return e; }}- /// The title bar's switch (ListenPill.swift), led by the logo: a white pill while idle or not- /// set up, an ink one with the level, the time and 结束 while listening.void Pill(){var listen = app.Listen;@@ -441,7 +409,6 @@ sealed class MainWindow : Windowreturn new Border { Background = Palette.Ink, CornerRadius = new CornerRadius(16), Height = 32, Padding = new Thickness(5, 0, 4, 0), Child = Ui.Row(0, show, end) };}- /// A rounded button with no theme chrome: the pill and its parts.static Button Capsule(UIElement content, Brush background, Brush? border, double height, Thickness padding, Action click, string name){var b = new Button { Content = content, Height = height, Padding = padding, Background = background, BorderBrush = border ?? Brushes.Transparent, BorderThickness = new Thickness(border is null ? 0 : 1), Cursor = System.Windows.Input.Cursors.Hand, Focusable = false };@@ -471,7 +438,6 @@ sealed class MainWindow : Windowreturn s;}- /// What the open page shows; a store change that leaves it the same doesn't redraw it.string? PageKey() => selected is not null && app.Store.Get(selected) is { } cur? $"{selected}|{tab}|{SessionStore.DisplayTitle(cur)}|{cur.Lines.Count}|{cur.Notes?.Covered}|{cur.Notes?.Final}|{app.Listen.Listening}|{app.Notes.GeneratingId == selected}|{cur.HasAudio}|{Recording.Playable(cur)}|{app.Settings.RecordAudio}|{FixKey(cur)}|{cur.Lines.Sum(l => l.Dst?.Length ?? 0)}|{FolderExportUi.Key(app, selected)}|{search.Text.Trim()}|{matchIndex}": null;@@ -486,7 +452,6 @@ sealed class MainWindow : Windowredrawing = keep is not null;var top = new StackPanel();- // When, how long, and from what into what, above the title.var local = s.StartedAt.ToLocalTime();var spoken = s.Lines.Select(l => l.SrcLang).FirstOrDefault(x => x is not null);var into = s.Lines.Select(l => l.DstLang).FirstOrDefault(x => x is not null);@@ -500,7 +465,6 @@ sealed class MainWindow : Windowvar rename = Ui.IconButton(Icons.Pencil, L("重命名"), () => Rename(s), Palette.Tertiary, 30, 15);var titleRow = Ui.Row(6, title, rename);titleRow.Margin = new Thickness(0, 6, 0, 0);- // As the Mac's context menu: only when the notes have a name to go back to.if ((s.Renamed ?? !s.Title.StartsWith("会议 ")) && !string.IsNullOrEmpty(s.Notes?.Title)){var reset = Ui.LinkText(L("恢复自动标题"), () => app.Store.ResetTitle(s.Id));@@ -509,13 +473,10 @@ sealed class MainWindow : WindowtitleRow.Children.Add(reset);}top.Children.Add(titleRow);- // 存到文件夹: where its file is, or why it isn't there yet.if (!live && FolderExportUi.Line(app, s) is { } exported) top.Children.Add(exported);if (PlayerArea(s, live) is { } audio) top.Children.Add(audio);- // Under the page, not in its header: the controls stay while the transcript scrolls.var footer = player is not null ? PlayerFooter() : null;- // 纪要 / 文字记录 on the left, what to do with it on the right, one hairline under both.FrameworkElement Tabs(double size) => Ui.Tabs([("notes", L("纪要")), ("transcript", s.Lines.Count > 0 ? $"{L("文字记录")} {s.Lines.Count}" : L("文字记录"))], tab, t => { tab = t; ShowDetail(); }, size);var tabs = Tabs(15);var tools = Tools(s, live);@@ -524,10 +485,8 @@ sealed class MainWindow : Windowtop.Children.Add(bar);top.Children.Add(new Border { Height = 1, Background = Palette.Line });- // One centred column, like a page: content runs into the old title bar's height.var page = new StackPanel { MaxWidth = 700, Margin = new Thickness(48, 56, 48, 48) };page.Children.Add(top);- // The notes have no lines to light: the rows (and 回到正在播放) go with the transcript.if (tab != "transcript") { rows.Clear(); lit = -1; hovered = null; barTick.Stop(); }var body = tab == "transcript" ? Transcript(s) : Notes(s, live);body.Margin = new Thickness(0, 28, 0, 0);@@ -535,8 +494,6 @@ sealed class MainWindow : Windowvar scroll = new ScrollViewer { VerticalScrollBarVisibility = ScrollBarVisibility.Auto, Content = page };pageScroll = scroll; pageScrollKey = thisPage;- // Once the title block scrolls away, a slim bar on top keeps the title (a click goes back- // up), the tabs and the tools in view: the Mac's pinned bar.var pinnedTitle = Ui.Text(SessionStore.DisplayTitle(s), 14, Palette.Ink, FontWeights.Bold, wrap: false);pinnedTitle.TextTrimming = TextTrimming.CharacterEllipsis;pinnedTitle.VerticalAlignment = VerticalAlignment.Center;@@ -555,8 +512,6 @@ sealed class MainWindow : Window{Background = Palette.Surface, BorderBrush = Palette.Line, BorderThickness = new Thickness(0, 0, 0, 1),VerticalAlignment = VerticalAlignment.Top, Visibility = Visibility.Collapsed, Child = pinnedRow,- // Under the 44 px caption strip (the pill and window buttons), which it paints white so- // the lines don't scroll behind the pill.Padding = new Thickness(0, 44, 0, 0), Margin = new Thickness(0, 0, SystemParameters.VerticalScrollBarWidth, 0),};scroll.ScrollChanged += (_, _) =>@@ -567,12 +522,9 @@ sealed class MainWindow : Windowif (pendingJump is { } jump) { pendingJump = null; jump(scroll); }else if (keep is { } y){- // The new page has no extent until laid out, so the offset goes back on once it is.void Keep(object? _, RoutedEventArgs __) { scroll.Loaded -= Keep; scroll.ScrollToVerticalOffset(y); }scroll.Loaded += Keep;}- // Scrolling by hand while it plays stops the transcript following the recording. Only input- // counts (wheel and touchpad, the scroll bar, keys, touch): the page's own scrolling doesn't.scroll.PreviewMouseWheel += (_, _) => UserScrolled();scroll.AddHandler(System.Windows.Controls.Primitives.ScrollBar.ScrollEvent, new System.Windows.Controls.Primitives.ScrollEventHandler((_, _) => UserScrolled()), true);scroll.PreviewKeyDown += (_, e) =>@@ -581,7 +533,6 @@ sealed class MainWindow : Windowor System.Windows.Input.Key.Down or System.Windows.Input.Key.Home or System.Windows.Input.Key.End) UserScrolled();};scroll.ManipulationStarted += (_, _) => UserScrolled();- // The last fix decision with 撤销, along the bottom of the page.toastHost.Margin = new Thickness(0, 0, 0, 18);toastHost.VerticalAlignment = VerticalAlignment.Bottom; toastHost.HorizontalAlignment = HorizontalAlignment.Center;if (toastHost.Parent is Grid old) old.Children.Remove(toastHost);@@ -607,7 +558,6 @@ sealed class MainWindow : WindowtoastHost.Content = FixViews.Toast(app.Fixes);}- /// 生成纪要 or 复制纪要, 导出… and ···, beside the tabs (and again in the pinned bar).StackPanel Tools(Session s, bool live){var tools = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Top };@@ -631,7 +581,6 @@ sealed class MainWindow : Windowtools.Children.Add(copy);}tools.Children.Add(Spaced(Small(Ui.Button(L("导出…"), () => Export(s), Ui.Kind.Standard, height: 32)), 8));- // Not while the meeting is still going, nor with nothing in it.var share = Small(Ui.Button(L("分享…"), () => app.ShareSheet(s), Ui.Kind.Standard, height: 32));share.IsEnabled = !live && (s.Lines.Count > 0 || hasNotes);tools.Children.Add(Spaced(share, 8));@@ -661,7 +610,6 @@ sealed class MainWindow : Windowvar article = new StackPanel();void Jump(double t) { tab = "transcript"; jumpTo = t; ShowDetail(); }- // The conclusions first, in one quiet grey block; to-dos with an open circle.var items = n.Conclusions.Select(c => (c, todo: false)).Concat(n.Todos.Select(t => (c: t, todo: true))).ToList();if (items.Count > 0){@@ -697,7 +645,6 @@ sealed class MainWindow : Windowarticle.Children.Add(sum);}- // The topics as numbered rows between hairlines.if (n.Topics.Count > 0){var label = Ui.Text(L("议题"), 13, Palette.Secondary);@@ -740,7 +687,6 @@ sealed class MainWindow : Windowreturn article;}- // 改这句…: the line being rewritten and what the editor opens with.string? editingLine;string editingStart = "";@@ -752,14 +698,12 @@ sealed class MainWindow : Windowvoid EditDone() { editingLine = null; ShowDetail(); }- /// Debug: 改这句… on line `line` of record `id`, as from its menu.public void DebugEdit(string id, string line){selected = id;if (app.Store.Get(id)?.Lines.FirstOrDefault(l => l.Id == line) is { } l) EditLine(l, l.Shown);}- /// A fix count and state per record, so a decision redraws the page.static string FixKey(Session s) => string.Join(",", s.Lines.Where(l => l.Fixes is not null).Select(l => string.Join("", l.Fixes!.Select(f => $"{f.From}>{f.To}{(f.Ask == true ? "?" : "")}{(f.Off == true ? "x" : "")}{(f.User == true ? "u" : "")};"))));FrameworkElement Transcript(Session s)@@ -768,21 +712,17 @@ sealed class MainWindow : WindowPlayRow? target = null;rows.Clear(); lit = -1; hovered = null;Action<double>? play = player is not null ? PlayFrom : null;- // 改正听错的词: over a finished meeting, the fixes waiting for the user and how many were made.var live = app.Listen.Listening && app.Listen.SessionId == s.Id;if (!live && FixViews.Banner(s, app.Fixes, id => { jumpLine = id; ShowDetail(); }, EditLine) is { } banner){banner.Margin = new Thickness(0, 0, 0, 14);body.Children.Add(banner);}- // The line nearest the topic's time (older notes may hold a time no line has), or the one asked for.var nearest = jumpLine is { } jl ? s.Lines.FirstOrDefault(l => l.Id == jl): jumpTo is { } t0 && s.Lines.Count > 0 ? s.Lines.MinBy(l => Math.Abs(l.T - t0)) : null;- // The search's terms and the line found being looked at, which the page opens on (centred).var terms = SearchTerms(s);var found = CurrentMatch(s);PlayRow? foundRow = null;- // Opened at a line while the recording plays: stay there (回到正在播放 goes back).if ((nearest is not null || found is not null) && playing) following = false;foreach (var (l, who, ink, place) in NotesWindow.Speakers(s.Lines, app.Settings.SpeakerVoices)){@@ -799,14 +739,11 @@ sealed class MainWindow : Windowif (l.Id == found) foundRow = r;body.Children.Add(r.Card);}- // Centred when the search moves to it or the page opens, not on every redraw: a live- // meeting's next line mustn't pull the reader back from wherever they scrolled.var foundKey = found is null ? null : $"{s.Id}|{search.Text.Trim()}|{found}";var centre = foundKey != centredFound || !redrawing;centredFound = foundKey;if (target is null && centre && foundRow is { Card: var foundCard }){- // Measured once laid out, as below.pendingJump = scroll =>{void Jump(object? _, RoutedEventArgs __) { foundCard.Loaded -= Jump; Center(foundCard); }@@ -815,11 +752,9 @@ sealed class MainWindow : Window}if (target is { } marked){- // A topic's time opens the transcript at what was said then, marked for a moment.marked.Marked = true;Paint(marked);var row = marked.Card;- // Measured once laid out: before that every row is at the top.pendingJump = scroll =>{void Jump(object? _, RoutedEventArgs __)@@ -842,8 +777,6 @@ sealed class MainWindow : Windowstatic TextBlock? FindTime(Panel row) =>row.Children.OfType<Panel>().FirstOrDefault()?.Children.OfType<TextBlock>().FirstOrDefault(t => (t.Tag as string) == "time");- /// A transcript line in the record: the row on a rounded fill (the line playing, or under the- /// pointer when a click would play it) with the playing bars at its right edge.sealed class PlayRow(double t, Border card, TextBlock? time, StackPanel bars, bool playable){public double T = t;@@ -855,7 +788,6 @@ sealed class MainWindow : WindowPlayRow Row(TranscriptLine l, Panel line, bool playable){- // The row's own bottom gap goes inside the fill, half above and half below the text.line.Margin = new Thickness(0, line.Margin.Top, 0, line.Margin.Bottom / 2);var bars = new StackPanel { Orientation = Orientation.Horizontal, Height = 12, Width = 13, VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(8, line.Margin.Top + 3, 0, 0), Visibility = Visibility.Hidden };for (int i = 0; i < 3; i++)@@ -875,8 +807,6 @@ sealed class MainWindow : Windowif (!playable) { bars.Visibility = Visibility.Collapsed; return r; }card.MouseEnter += (_, _) => { hovered = r; Paint(r); };card.MouseLeave += (_, _) => { if (hovered == r) hovered = null; Paint(r); };- // A click anywhere on the line plays from it: a press and release without moving (a drag- // is left alone), not on the time or the line's links, which act on their own.Point? down = null;card.PreviewMouseLeftButtonDown += (_, e) => down = OnLink(e.OriginalSource as DependencyObject, card) ? null : e.GetPosition(card);card.MouseLeftButtonUp += (_, e) =>@@ -890,7 +820,6 @@ sealed class MainWindow : Windowreturn r;}- /// The time, 改回 and 改这句… are links (a hand cursor) or buttons that handle their own click.static bool OnLink(DependencyObject? d, FrameworkElement stop){for (; d is not null && d != stop; d = d is Visual or System.Windows.Media.Media3D.Visual3D ? VisualTreeHelper.GetParent(d) : LogicalTreeHelper.GetParent(d))@@ -899,8 +828,6 @@ sealed class MainWindow : Windowreturn false;}- /// The line playing on the pale accent with its time in the accent and, while it plays, the- /// bars; under the pointer a light fill and ▶ before the time; else as it was.void Paint(PlayRow r){var current = lit >= 0 && lit < rows.Count && rows[lit] == r;@@ -918,8 +845,6 @@ sealed class MainWindow : Windowtime.Inlines.Add(new System.Windows.Documents.Run(clock));}- /// The bars beside the playing line bounce (as the Mac's PlayingBars); held still when the- /// system turns animations off.void Bounce(){if (lit < 0 || lit >= rows.Count) return;@@ -932,8 +857,6 @@ sealed class MainWindow : Window// MARK: 回放- // One player for the open record, kept while the page redraws (lines and notes arriving) and- // closed when another record opens, the record is deleted or the window closes.MediaPlayer? player;string? playerPath;bool playing, opened;@@ -941,25 +864,16 @@ sealed class MainWindow : Windowdouble? pendingSeek;readonly DispatcherTimer playTick = new() { Interval = TimeSpan.FromMilliseconds(200) };ScrollViewer? pageScroll;- /// Which meeting and tab `pageScroll` shows: the same page drawn again (a live meeting's new- /// line, the notes updating) stays where the reader had it instead of going back to the top.string? pageScrollKey;- /// This draw is the same page again (set by ShowDetail for Transcript).bool redrawing;- /// The search's line the page last centred: a redraw that leaves it the same doesn't pull back to it.string? centredFound;- // The transcript's lines with their times, in time order, the one at the playhead and the one- // under the pointer.readonly List<PlayRow> rows = [];int lit = -1;PlayRow? hovered;readonly DispatcherTimer barTick = new() { Interval = TimeSpan.FromMilliseconds(50) };- /// The transcript keeps the playing line in view. Scrolling it by hand stops that until a line- /// is picked, the bar is used or 回到正在播放 is pressed: following would yank the page away.bool following = true;Button? backButton;TextBlock? backText;- // The bar's moving parts, rebuilt with the page.TextBlock? nowText, lengthText, speedText;Border? played;FrameworkElement? thumb;@@ -967,8 +881,6 @@ sealed class MainWindow : WindowButton? playButton;double fallbackLength;- /// Under the title: the player for a recording; while live, that it plays afterwards; else- /// why there is none (and where to turn recording on).FrameworkElement? PlayerArea(Session s, bool live){FrameworkElement Note(FrameworkElement e) { e.Margin = new Thickness(0, 12, 0, 0); return e; }@@ -981,7 +893,6 @@ sealed class MainWindow : Windowif (path is null){ClosePlayer();- // Just ended: system.aac is being rewrapped into system.m4a, a moment.if (File.Exists(Recording.Partial(Recording.SystemAudio(s.Id)))) return null;if (s.HasAudio || s.SourcePath is not null) return Note(Ui.Text(L("找不到录音,没法播放"), 12, Palette.Secondary));if (s.Lines.Count == 0) return null;@@ -997,7 +908,7 @@ sealed class MainWindow : Windowplayer.MediaOpened += (_, _) =>{opened = true;- if (!playing) player!.Pause(); // MediaPlayer starts playing by itself once opened+ if (!playing) player!.Pause();if (pendingSeek is { } t) { pendingSeek = null; player!.Position = TimeSpan.FromSeconds(t); }UpdatePlayer();};@@ -1011,7 +922,6 @@ sealed class MainWindow : Windowreturn null;}- /// The player along the bottom of the record, on white under a hairline.FrameworkElement PlayerFooter(){var bar = PlayerBar();@@ -1020,7 +930,6 @@ sealed class MainWindow : Windowreturn new Border { Background = Palette.Surface, BorderBrush = Palette.Line, BorderThickness = new Thickness(0, 1, 0, 0), Child = bar };}- /// Scrolled away from what is playing: one way back, at the bottom of the transcript.FrameworkElement BackToPlaying(){backText = Ui.Text("", 13, Brushes.White, FontWeights.SemiBold, wrap: false);@@ -1043,7 +952,6 @@ sealed class MainWindow : Windowif (show) backText.Text = L("回到正在播放") + " · " + Languages.Clock(rows[lit].T);}- /// The transcript was scrolled by hand while it plays.void UserScrolled(){if (!following || !playing || player is null || tab != "transcript") return;@@ -1052,7 +960,6 @@ sealed class MainWindow : WindowUpdateBack();}- /// 回到正在播放 (and a line picked, or the bar used): follow again, from the playing line.void Follow(){var was = following;@@ -1072,7 +979,6 @@ sealed class MainWindow : Windowvar speedButton = Capsule(speedText, Palette.Surface, Palette.Line, 26, new Thickness(9, 0, 9, 0), CycleSpeed, L("播放速度"));speedButton.ToolTip = L("播放速度");- // The slider: a grey rail, the played part in the accent, a round handle; click or drag.var rail = new Border { Height = 4, CornerRadius = new CornerRadius(2), Background = Palette.Line, VerticalAlignment = VerticalAlignment.Center };played = new Border { Height = 4, CornerRadius = new CornerRadius(2), Background = Palette.Live, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Width = 0 };thumb = new System.Windows.Shapes.Ellipse { Width = 12, Height = 12, Fill = Palette.Live, Stroke = Brushes.White, StrokeThickness = 2, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left };@@ -1128,7 +1034,6 @@ sealed class MainWindow : WindowUpdatePlayer(reveal: playing);}- /// A line's time: play from there.void PlayFrom(double t){if (player is null) return;@@ -1145,14 +1050,12 @@ sealed class MainWindow : Windowif (player is null) return;t = Math.Clamp(t, 0, Math.Max(0, Length()));if (opened) player.Position = TimeSpan.FromSeconds(t); else pendingSeek = t;- // A seek (the bar, or a line picked) follows the recording again.var resume = !following;following = true;UpdatePlayer();if (resume && lit >= 0 && lit < rows.Count) Center(rows[lit].Card);}- /// Played to the end: back to the start, paused.void Ended(){if (player is null) return;@@ -1170,16 +1073,13 @@ sealed class MainWindow : Windowif (speedText is not null) speedText.Text = SpeedLabel();}- /// The bar and the lit line follow the playhead (every 200 ms while playing).void UpdatePlayer() => UpdatePlayer(false);- /// `reveal`: playing just started, so the lit line is scrolled to even if it was lit already.void UpdatePlayer(bool reveal){if (player is null) return;var now = Now();var length = Length();- // MediaEnded doesn't always come (a PC with no sound device plays on past the end).if (playing && opened && length > 0 && now >= length) { Ended(); return; }if (nowText is not null) nowText.Text = Languages.Clock(now);if (lengthText is not null) lengthText.Text = Languages.Clock(length);@@ -1200,15 +1100,12 @@ sealed class MainWindow : Windowplayed.Width = x;thumb.Margin = new Thickness(Math.Max(0, Math.Min(track.ActualWidth - thumb.Width, x - thumb.Width / 2)), 0, 0, 0);}- // The line being said: the last one starting by now (a little ahead, so it lights as it- // begins); once playback has begun it stays lit while paused.var at = playing || now > 0 ? rows.FindLastIndex(r => r.T <= now + 0.2) : -1;var was = lit;lit = at;if (was != at && was >= 0 && was < rows.Count) Paint(rows[was]);if (at >= 0){- // Every tick: the bars come and go with play and pause.Paint(rows[at]);if (playing && following && (at != was || reveal)) Center(rows[at].Card);}@@ -1216,7 +1113,6 @@ sealed class MainWindow : WindowUpdateBack();}- /// Scrolls the playing line to the middle of the transcript.void Center(FrameworkElement row){if (pageScroll is not { } scroll || !row.IsLoaded) return;@@ -1241,14 +1137,11 @@ sealed class MainWindow : Windowfollowing = true;}- /// For the debug pipe: where playback is, the lit line (index and time), whether the transcript- /// follows it (and 回到正在播放 shows), and the line under the pointer.public string PlayerState() => player is null ? "none": $"{(playing ? "playing" : "paused")} {Now():F1}/{Length():F1} x{speed} line {lit}{(lit >= 0 && lit < rows.Count ? $"@{rows[lit].T:F1}" : "")}"+ $" following {(following ? "yes" : "no")} back {(backButton?.Visibility == Visibility.Visible ? "shown" : "hidden")}"+ $" hover {(hovered is { } h ? rows.IndexOf(h) : -1)} offset {pageScroll?.VerticalOffset:F0}";- /// "follow": 回到正在播放, as clicked; "row <i>": line i clicked.public void DebugPlay(string arg){if (arg == "toggle") TogglePlay();@@ -1293,9 +1186,9 @@ sealed class MainWindow : Window{if (Dialogs.Confirm(this, L("删除这次会议?"), LF("“%@”的纪要和文字记录都会删掉,没法恢复。", SessionStore.DisplayTitle(s)), L("删除"), danger: true)){- ClosePlayer(); // it holds the recording open+ ClosePlayer();app.Store.Delete(s.Id);- app.FolderExport.Deleted(s.Id); // its file in the folder stays+ app.FolderExport.Deleted(s.Id);}}}diff --git a/windows/src/Cicada/MediaFoundation.cs b/windows/src/Cicada/MediaFoundation.csindex 78bca76..30fd5fc 100644--- a/windows/src/Cicada/MediaFoundation.cs+++ b/windows/src/Cicada/MediaFoundation.cs@@ -2,14 +2,8 @@ using System.Runtime.InteropServices;namespace Cicada.App;-/// 保存会议录音 with Windows' own AAC encoder (Media Foundation's sink writer): no package, nothing-/// to install. The COM calls go through the vtables by slot (the interfaces are long and only a-/// few methods are used), so each `Slot` number below is that method's place in its interface.unsafe sealed class MediaFoundationAudio : IAudioFiles{- // The Mac's recordings are AAC mono at ~32 kbps. Windows 11 encodes 16 kHz at 32 kbps; the- // encoder's documentation promises only 44.1/48 kHz from 96 kbps, so a PC that refuses gets- // those, the 16 kHz upsampled by three.static readonly (int Rate, uint Bytes)[] Formats = [(16000, 4000), (48000, 4000), (16000, 12000), (48000, 12000)];static readonly Lazy<bool> Started = new(() =>{@@ -17,7 +11,6 @@ unsafe sealed class MediaFoundationAudio : IAudioFilesif (hr != 0) Log.Debug($"audio: Media Foundation unavailable 0x{hr:X8}");return hr == 0;});- /// The format the encoder took last time, so later meetings don't try again.static (int Rate, uint Bytes)? chosen;public IAudioWriter? Open(string path)@@ -41,7 +34,6 @@ unsafe sealed class MediaFoundationAudio : IAudioFilesreturn null;}- /// The ADTS frames into an MP4 track as they are: no re-encoding, so an hour takes a moment.public bool Rewrap(string from, string to, double? until){if (!Started.Value) return false;@@ -70,7 +62,6 @@ unsafe sealed class MediaFoundationAudio : IAudioFilesAacType(type, config.Rate, (uint)(bytes / seconds), (uint)config.Channels);SetUInt32(type, PayloadType, 0);SetUInt32(type, ProfileLevel, 0x29);- // HEAACWAVEINFO after its WAVEFORMATEX: raw frames (payload 0), then the AudioSpecificConfig.var info = new byte[12 + config.SpecificConfig.Length];info[2] = 0x29;config.SpecificConfig.CopyTo(info, 12);@@ -123,7 +114,6 @@ unsafe sealed class MediaFoundationAudio : IAudioFilesSetUInt32(t, NumChannels, channels); SetUInt32(t, AvgBytesPerSecond, bytes);}- /// One meeting's ADTS file, 16 kHz mono in.sealed class AacWriter : IAudioWriter{IntPtr writer;@@ -178,7 +168,6 @@ unsafe sealed class MediaFoundationAudio : IAudioFilesvar o = (short*)data;if (factor == 1) pcm.CopyTo(new Span<short>(o, count));else- // Straight lines between the 16 kHz samples: the encoder's low-pass does the rest.for (int i = 0, j = 0; i < pcm.Length; i++){int a = previous, b = pcm[i];@@ -221,7 +210,6 @@ unsafe sealed class MediaFoundationAudio : IAudioFilesstatic void* Slot(IntPtr p, int i) => (*(void***)p)[i];static uint Release(IntPtr p) => ((delegate* unmanaged[Stdcall]<IntPtr, uint>)Slot(p, 2))(p);- // IMFAttributes (IMFMediaType and IMFSample start with it)static int SetBlob(IntPtr a, Guid key, byte[] blob){fixed (byte* p = blob) return ((delegate* unmanaged[Stdcall]<IntPtr, Guid*, byte*, uint, int>)Slot(a, 26))(a, &key, p, (uint)blob.Length);@@ -229,17 +217,14 @@ unsafe sealed class MediaFoundationAudio : IAudioFilesstatic int SetUInt32(IntPtr a, Guid key, uint v) => ((delegate* unmanaged[Stdcall]<IntPtr, Guid*, uint, int>)Slot(a, 21))(a, &key, v);static int SetGuid(IntPtr a, Guid key, Guid v) => ((delegate* unmanaged[Stdcall]<IntPtr, Guid*, Guid*, int>)Slot(a, 24))(a, &key, &v);- // IMFSamplestatic int SetSampleTime(IntPtr s, long t) => ((delegate* unmanaged[Stdcall]<IntPtr, long, int>)Slot(s, 36))(s, t);static int SetSampleDuration(IntPtr s, long d) => ((delegate* unmanaged[Stdcall]<IntPtr, long, int>)Slot(s, 38))(s, d);static int AddBuffer(IntPtr s, IntPtr b) => ((delegate* unmanaged[Stdcall]<IntPtr, IntPtr, int>)Slot(s, 42))(s, b);- // IMFMediaBufferstatic int Lock(IntPtr b, byte** data, uint* max, uint* current) => ((delegate* unmanaged[Stdcall]<IntPtr, byte**, uint*, uint*, int>)Slot(b, 3))(b, data, max, current);static int Unlock(IntPtr b) => ((delegate* unmanaged[Stdcall]<IntPtr, int>)Slot(b, 4))(b);static int SetCurrentLength(IntPtr b, uint n) => ((delegate* unmanaged[Stdcall]<IntPtr, uint, int>)Slot(b, 6))(b, n);- // IMFSinkWriterstatic int AddStream(IntPtr w, IntPtr type, uint* index) => ((delegate* unmanaged[Stdcall]<IntPtr, IntPtr, uint*, int>)Slot(w, 3))(w, type, index);static int SetInputMediaType(IntPtr w, uint index, IntPtr type, IntPtr parameters) => ((delegate* unmanaged[Stdcall]<IntPtr, uint, IntPtr, IntPtr, int>)Slot(w, 4))(w, index, type, parameters);static int BeginWriting(IntPtr w) => ((delegate* unmanaged[Stdcall]<IntPtr, int>)Slot(w, 5))(w);diff --git a/windows/src/Cicada/MicSource.cs b/windows/src/Cicada/MicSource.csindex d6dd19a..e9f733f 100644--- a/windows/src/Cicada/MicSource.cs+++ b/windows/src/Cicada/MicSource.cs@@ -2,11 +2,6 @@ using System.Runtime.InteropServices;namespace Cicada.App;-/// 会议室: a microphone as a listening source, 16 kHz mono (Windows converts), handed on as it comes-/// in (DeviceRecorder keeps it all instead). A device pulled out or switched off ends its stream:-/// the room mic is picked again and capture goes on, so the room doesn't go quiet for the rest of-/// the meeting. Ends with "denied" when Windows' microphone privacy switch is off for desktop apps,-/// "none" when no microphone is left.sealed class MicSource : IAudioSource{readonly Func<Endpoints.Device?> pick;@@ -14,7 +9,6 @@ sealed class MicSource : IAudioSourcevolatile bool running;public event Action<short[]>? Samples;public event Action<string?>? Ended;- /// The microphone in use.public string? DeviceName { get; private set; }public MicSource(Func<Endpoints.Device?> pick) { this.pick = pick; }@@ -50,7 +44,6 @@ sealed class MicSource : IAudioSource}catch (Exception e){- // 0x88890004 AUDCLNT_E_DEVICE_INVALIDATED: unplugged, disabled, or its format changed.Log.Debug($"mic: {device.Name} stopped 0x{e.HResult:X8}, picking the room mic again");failures = DateTime.UtcNow - started > TimeSpan.FromSeconds(10) ? 1 : failures + 1;if (failures > 5) { Ended?.Invoke(e.Message); return; }@@ -66,7 +59,6 @@ sealed class MicSource : IAudioSource{client = Endpoints.Activate(id);var fmt = Endpoints.Pcm16(16000);- // A 1 s buffer, as the system tap's: a capture thread held up a moment loses nothing.int hr = client.Initialize(0, Endpoints.AutoConvert, 10_000_000, 0, fmt, IntPtr.Zero);Marshal.FreeHGlobal(fmt);Marshal.ThrowExceptionForHR(hr);diff --git a/windows/src/Cicada/ModelPicker.cs b/windows/src/Cicada/ModelPicker.csindex 19c72cd..7a38961 100644--- a/windows/src/Cicada/ModelPicker.cs+++ b/windows/src/Cicada/ModelPicker.cs@@ -8,11 +8,6 @@ using static Cicada.Strings;namespace Cicada.App;-/// A custom service's model once its `/models` listed some (AISettings.swift › ModelPicker): a-/// button that opens the list with a search box on top. A name the service doesn't list can be-/// typed (an alias, a model it hides): 用 X(列表里没有). Return takes the only match, else what-/// was typed. `sameLabel` is a first choice that clears the value (和翻译模型一样). Without a list-/// the settings show a plain field instead (SettingsWindow.ModelField).static class ModelPicker{public static FrameworkElement Make(string value, string? sameLabel, IReadOnlyList<string> catalog, string host,@@ -25,7 +20,6 @@ static class ModelPickervar chevron = Ui.Icon(Icons.Chevron, 14, Palette.Secondary, stroke: 1.8);chevron.Margin = new Thickness(8, 0, 0, 0);DockPanel.SetDock(chevron, Dock.Right);- // Ui.Choice's look; its own menu would open beside the popup.var button = new Button{Content = new DockPanel { LastChildFill = true, Children = { chevron, label } }, Width = width, Height = 34,diff --git a/windows/src/Cicada/Native.cs b/windows/src/Cicada/Native.csindex 7f78b56..021476b 100644--- a/windows/src/Cicada/Native.cs+++ b/windows/src/Cicada/Native.cs@@ -4,8 +4,6 @@ using System.Windows.Interop;namespace Cicada.App;-/// Win32 bits WPF doesn't expose: windows that never take focus and stay out of screen captures,-/// and DPAPI for the key file.static class Native{const int GWL_EXSTYLE = -20;@@ -18,12 +16,8 @@ static class Native[DllImport("user32.dll")] static extern bool SetWindowDisplayAffinity(IntPtr hwnd, uint affinity);[DllImport("user32.dll")] static extern bool AllowSetForegroundWindow(int processId);- /// A second launch has the foreground (the user just opened it); this lets the running Cicada- /// bring its records window forward instead of flashing in the taskbar behind other windows.- public static void LetOthersTakeForeground() => AllowSetForegroundWindow(-1 /* ASFW_ANY */);+ public static void LetOthersTakeForeground() => AllowSetForegroundWindow(-1);- /// Makes a window like the Mac's non-activating panel: clicks and drags work, but the app the- /// user is in keeps the keyboard focus, and the window isn't in Alt+Tab or the taskbar.public static void MakeNonActivating(Window window){var hwnd = new WindowInteropHelper(window).EnsureHandle();@@ -40,22 +34,17 @@ static class Native[DllImport("dwmapi.dll")] static extern int DwmExtendFrameIntoClientArea(IntPtr hwnd, ref Margins margins);[StructLayout(LayoutKind.Sequential)] struct Margins { public int Left, Right, Top, Bottom; }- /// A frameless window drawn by DWM: Windows 11's rounded corners and soft shadow, composited on- /// the GPU. (A transparent WPF window would have to draw its own shadow, in software, on every- /// change.) On Windows 10 the corners stay square.public static void UseSystemFrame(Window window, bool dark = false){var hwnd = new WindowInteropHelper(window).EnsureHandle();- int round = 2; // DWMWCP_ROUND- DwmSetWindowAttribute(hwnd, 33 /* DWMWA_WINDOW_CORNER_PREFERENCE */, ref round, sizeof(int));+ int round = 2;+ DwmSetWindowAttribute(hwnd, 33, ref round, sizeof(int));int on = dark ? 1 : 0;- DwmSetWindowAttribute(hwnd, 20 /* DWMWA_USE_IMMERSIVE_DARK_MODE */, ref on, sizeof(int));- // A one-pixel frame margin is what gives a frameless window DWM's shadow.+ DwmSetWindowAttribute(hwnd, 20, ref on, sizeof(int));var m = new Margins { Left = 0, Right = 0, Top = 1, Bottom = 0 };DwmExtendFrameIntoClientArea(hwnd, ref m);}- /// Out of screenshots and screen sharing (Windows 10 2004+), unless the user lets the other side see it.public static bool SetCaptureVisible(Window window, bool visible){var hwnd = new WindowInteropHelper(window).EnsureHandle();@@ -65,7 +54,6 @@ static class Native}}-/// DPAPI, current user: the key file can only be opened by this Windows account.sealed class DpapiProtector : IKeyProtector{public string Tag => "dpapi";diff --git a/windows/src/Cicada/NotesWindow.cs b/windows/src/Cicada/NotesWindow.csindex a607ccb..cd401fc 100644--- a/windows/src/Cicada/NotesWindow.cs+++ b/windows/src/Cicada/NotesWindow.cs@@ -7,32 +7,22 @@ using static Cicada.Strings;namespace Cicada.App;-/// The window shown while listening: the live notes panel (default) or the subtitle bar. Like the-/// Mac's it never takes focus (the user keeps typing in their meeting app) and stays out of screen-/// captures unless 共享屏幕时让对方看到 is on, which it then says plainly.sealed class NotesWindow : Window{readonly Controller app;readonly DispatcherTimer clock = new() { Interval = TimeSpan.FromSeconds(1) };- // Hosts kept between renders: the clock redraws only the header, and the body keeps its scroll.ContentControl header = new(), bars = new(), live = new(), tabs = new(), footer = new();ScrollViewer scroll = new();string? builtFor;string tab = "notes";- /// Whether Windows agreed to keep the window out of captures; if not, it says it may be seen.bool hiddenFromCapture;bool renderQueued, placedSubtitles;- // Rebuilt only when what they show changes, so a click never lands on a button that a- // re-render just replaced; the clock and the countdown are text updated in place.string? headerKey, tabsKey, barsKey;readonly TextBlock clockText = Ui.Text("", 13, Palette.Secondary, wrap: false), dueText = Ui.Text("", 12, Palette.Tertiary, wrap: false);public NotesWindow(Controller app){this.app = app;- // Transparent, so it can have the Mac's 16-point corners (Windows' own frame stops at 8). WPF- // redraws such a window in software, so nothing here animates: the clock is the one redraw a- // second, and the shadow is plain rings (Ui.Floating), not a blur.WindowStyle = WindowStyle.None;AllowsTransparency = true;Background = Brushes.Transparent;@@ -47,11 +37,9 @@ sealed class NotesWindow : WindowNative.MakeNonActivating(this);ApplyCaptureSetting();};- // Drag from anywhere that isn't a control (buttons and links mark the press handled).MouseLeftButtonDown += (_, e) => { if (e.ButtonState == MouseButtonState.Pressed) try { DragMove(); } catch { } };clock.Tick += (_, _) => { Tick(); Pulse(); };IsVisibleChanged += (_, _) => { if (IsVisible) clock.Start(); else clock.Stop(); };- // The subtitle bar fits its text and grows upward, so its bottom edge stays put.SizeChanged += (_, e) =>{if (!Subtitles || !e.HeightChanged) return;@@ -64,7 +52,6 @@ sealed class NotesWindow : Windowbool Subtitles => app.Settings.View == "subtitles";- /// The panel along the right edge, the subtitle bar along the bottom, on the primary work area.public void Place(){var area = SystemParameters.WorkArea;@@ -91,7 +78,6 @@ sealed class NotesWindow : WindowRender();}- /// Changes come from engine threads: coalesce them into one render on the UI thread.public void Refresh(){if (renderQueued) return;@@ -122,8 +108,6 @@ sealed class NotesWindow : Windowreadonly TextBlock endingDetail = Ui.Text("", 12, Palette.Secondary);readonly TextBlock endingNotice = Ui.Text("", 13, Brushes.White, FontWeights.SemiBold, wrap: false);- /// 已经 10 分钟没人说话 · 60 秒后结束 (MeetingEndingStrip): what will happen, and 继续记录 / 现在结束.- /// The window never takes focus, so a click lands on the buttons at once.FrameworkElement EndingStrip(){if (!app.Listen.Listening) return new Border();@@ -142,8 +126,6 @@ sealed class NotesWindow : Windowreturn new Border { Background = Palette.AccentPale, CornerRadius = new CornerRadius(12), Padding = new Thickness(14), Margin = new Thickness(12, 0, 12, 8), Child = stack };}- /// 结束这场会议? (NotesWindow.swift › meetingBar): below the header, away from the 结束 button,- /// so a double click can't confirm it; no timeout, so it never vanishes under the pointer.FrameworkElement ConfirmEnd(){var stack = Ui.Stack(3, Ui.Text(L("结束这场会议?"), 14, Palette.Ink, FontWeights.Bold), Ui.Text(ConfirmEndDetail(), 12, Palette.Secondary));@@ -195,7 +177,6 @@ sealed class NotesWindow : Windowvar offset = scroll.VerticalOffset;soundBars.Clear();scroll.Content = tab == "transcript" ? Transcript() : NotesBody();- // The transcript follows new lines while the reader is at its end; otherwise nothing jumps.if (tab == "transcript" && atBottom) scroll.ScrollToEnd(); else scroll.ScrollToVerticalOffset(offset);}@@ -205,13 +186,9 @@ sealed class NotesWindow : Window{var dock = new DockPanel();void Top(UIElement e) { DockPanel.SetDock(e, Dock.Top); dock.Children.Add(e); }- // The Mac's layout: the header, 纪要 / 文字记录 as a two-part switch, the notes, and the- // sentence being said now on a dark card along the bottom, where the eye rests.Top(header);Top(ending);Top(bars);- // 这样改对吗? above both tabs: the window opens on 纪要, where a card in the transcript- // would never be seen.Top(ask);tabs.Margin = new Thickness(12, 0, 12, 0);Top(tabs);@@ -220,7 +197,6 @@ sealed class NotesWindow : Windowlive.Margin = new Thickness(12, 8, 12, 0);DockPanel.SetDock(live, Dock.Bottom);dock.Children.Add(live);- // The last fix decision with 撤销, just above the sentence being said.toast.HorizontalAlignment = HorizontalAlignment.Center;toast.Margin = new Thickness(12, 8, 12, 0);DockPanel.SetDock(toast, Dock.Bottom);@@ -239,7 +215,6 @@ sealed class NotesWindow : Windowbuttons.Children.Add(Ui.IconButton(Icons.Notes, L("换成纪要"), () => app.SetView("notes"), Palette.NightText, 32, 16, onDark: true));if (listen.Listening){- // 打开麦克风 (the Mac's bar has it while editing; this bar takes clicks anyway).var mic = Ui.IconButton(Icons.Mic, app.MicOn ? L("关闭麦克风") : L("打开麦克风"), () => app.SetMic(!app.MicOn),app.MicOn ? NightAccent : Palette.NightText, 32, 15, onDark: true);if (app.MicOn) mic.Background = new SolidColorBrush(Color.FromArgb(0x33, 0xE8, 0x55, 0x2B));@@ -274,20 +249,15 @@ sealed class NotesWindow : Windowmain.MinWidth = 0; main.Padding = new Thickness(12, 0, 12, 0);if (listen.Listening){- // The Mac's header buttons are 12 pt: at 14 the English "Turn off mic" and "End" pushed- // 收起 out of the window.Snug(main);right.Children.Add(Gap(Snug(TrayFlyout.MicButton(app, panel: false)), 8));}right.Children.Add(Gap(main, 8));right.Children.Add(Gap(Ui.IconButton("M5,10 H15", L("收起(继续听)"), Collapse, Palette.Body, 34, 16), 4));- // The buttons are docked first so a long status in a wide language clips the clock, never 收起.var row = new DockPanel { LastChildFill = false };DockPanel.SetDock(right, Dock.Right); DockPanel.SetDock(left, Dock.Left);row.Children.Add(right); row.Children.Add(left);left.ClipToBounds = true;- // Too narrow for the word and the clock (English with the mic button): the live dot and- // the clock say it on their own.if (listening is not null)row.SizeChanged += (_, e) =>{@@ -301,15 +271,10 @@ sealed class NotesWindow : Windowreturn row;}- /// 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); }- // AI trouble is one status line each (NotesWindow.swift › banner): a dot, what waits for- // what · what still works, at most one action. The service hears the meeting here, so its- // failing stops the subtitles as well: hearing's line comes first and the notes' own lines- // only add what it doesn't already say.(string, Action)? useLing = app.CanSwitchToLing ? (L("改用 Ling"), app.SwitchToLing) : null;var problem = app.Listen.Problem;if (problem is { } p)@@ -317,17 +282,12 @@ sealed class NotesWindow : Windowvar ling = app.Ling;var (title, body, settings) = ListenEngine.Words(p, app.Listen.ProblemStatus, ServiceLabel(), ling.HearName);var text = (title is null ? body : title.TrimEnd('。', '.') + " · " + body).TrimEnd('。', '.');- // Can't reach it: picks up by itself once it answers; the proxy hint is in 设置 › AI 服务.if (p is LingException.Kind.Network or LingException.Kind.Timeout) Add(Ui.StatusLine(Ui.Tone.Waiting, text, useLing));- // Busy or erring (a 5xx): it passes by itself, nothing to press.else if (p == LingException.Kind.RateLimited || ListenEngine.IsServerError(p, app.Listen.ProblemStatus)) Add(Ui.StatusLine(Ui.Tone.Waiting, text));else if (settings) Add(Ui.StatusLine(Ui.Tone.NeedsYou, text, (p is LingException.Kind.InvalidKey or LingException.Kind.NoKey ? L("换 key") : L("设置"), app.ShowAISettings)));- // Anything else (a garbled reply, Ling's 400) also picks up by itself; 重试 asks now.else Add(Ui.StatusLine(Ui.Tone.Waiting, text, (L("重试"), () => { app.Listen.ClearProblem(); _ = app.Ling.Check(); })));}var unreachable = app.Ling.Health.Failure?.Why == AICheck.Reason.Unreachable;- // 语音和文字只发给你的服务, and finished sentences go untranslated: it picks up by itself, and- // no 改用 Ling (that would send the meeting elsewhere). When hearing failed, its line says so.var notesWait = app.Notes.Status is NotesEngine.State.Unreachable or NotesEngine.State.Updating && unreachable;var stalled = problem is null && app.Listen.Listening && app.Translator.GoogleOff && app.Translator.SentencesUntranslated;if (stalled)@@ -336,18 +296,12 @@ sealed class NotesWindow : Windowif (app.Listen.Listening)switch (app.Notes.Status){- // Hearing goes ahead of the notes, so it is usually still fine: unless its line says otherwise.case NotesEngine.State.RateLimited when problem is null:Add(Ui.StatusLine(Ui.Tone.Waiting, LF("%@ 很忙 · 纪要稍后补上,字幕照常", ServiceLabel())));break;- // Both: the notes' own request failed, and the service doesn't answer anything; notes that- // only timed out while translations still came back retry on the next round. The retry- // that follows (Updating) hangs as long as a timeout: the line stays meanwhile. When- // hearing can't reach it either, its line above says so already.case NotesEngine.State.Unreachable or NotesEngine.State.Updating when unreachable && !stalled:if (problem is not (LingException.Kind.Network or LingException.Kind.Timeout)){- // A hear model served at another address still brings subtitles.var until = NotesCoveredUntil();var text = !app.Ling.Config.HearElsewhere ? LF("字幕和纪要等 %@ 恢复 · 连上后自动继续", ServiceLabel()): until > 0 ? LF("纪要等 %@ 恢复 · 停在 %@,字幕照常", ServiceLabel(), Languages.Clock(until))@@ -359,7 +313,6 @@ sealed class NotesWindow : WindowAdd(Ui.StatusLine(Ui.Tone.Info, L("这轮纪要没写好 · 下轮自动补上")));break;}- // Shown to others on purpose: the footer's 对方可见 says so. Not hidden though asked: a warning.if (!app.Settings.ShowInCapture && !hiddenFromCapture)Add(Ui.InfoBar(Ui.Severity.Warning, null, L("Windows 没能把这个窗口从屏幕共享里藏起来,对方可能看得到。")));return stack;@@ -367,7 +320,6 @@ sealed class NotesWindow : Windowstring ServiceLabel() => app.Ling.ServiceLabel;- /// When the last line the notes cover was said (0: nothing covered yet).double NotesCoveredUntil(){var lines = app.Listen.SessionId is { } id ? app.Store.Get(id)?.Lines : null;@@ -375,8 +327,6 @@ sealed class NotesWindow : Windowreturn lines is not null && covered > 0 && covered <= lines.Count ? lines[covered - 1].T : 0;}- /// The newest line on the Mac's dark card: who in their colour and 正在说 while Ming works on the- /// next, the original small, its translation large and bold.FrameworkElement LiveCard(){var listen = app.Listen;@@ -401,7 +351,6 @@ sealed class NotesWindow : Windowreturn new Border { Background = Palette.Night, CornerRadius = new CornerRadius(14), Padding = new Thickness(16, 14, 16, 14), Child = stack, MinHeight = 96 };}- /// Text on the dark card: the accent lifted for contrast, and the original a light grey.static readonly SolidColorBrush NightAccent = new(Color.FromRgb(0xFF, 0x8A, 0x5C)), NightBody = new(Color.FromRgb(0xD9, 0xDC, 0xE1));FrameworkElement TabRow()@@ -426,9 +375,6 @@ sealed class NotesWindow : Window{var heard = app.Listen.SessionId is { } id ? app.Store.Get(id)?.Lines.Count ?? 0 : 0;var status = app.Notes.Status;- // NotesWindow.swift › notesPane: while listening the placeholder stays up after lines- // arrive, until a request is actually out (the first waits for a few lines or 20 s);- // a key problem says so instead.var keyProblem = status is NotesEngine.State.NoKey or NotesEngine.State.InvalidKey;if (app.Listen.Listening && !keyProblem && !(status == NotesEngine.State.Updating && heard > 0)) return Listening(heard);var (title, hint) = status switch@@ -475,15 +421,11 @@ sealed class NotesWindow : Window// MARK: Listening, no notes asked for yet (NotesViews.swift › NotesListeningView)- // Stepped once a second by the clock, like Ui.LiveDot: this window is redrawn in software, so a- // WPF animation would redraw it every frame. Holds only what the current render shows.readonly List<ScaleTransform> soundBars = [];readonly SolidColorBrush skeleton = new(SkeletonBase);int beat;static readonly Color SkeletonBase = Color.FromRgb(0xEE, 0xF0, 0xF3), SkeletonLight = Color.FromRgb(0xF7, 0xF8, 0xFA);- // The Mac's placeholder grey, its accentPale at 70% on white, and its chip fill.static readonly SolidColorBrush Placeholder = Frozen(0xB8, 0xBD, 0xC6), ListeningRow = Frozen(0xFE, 0xF1, 0xEC), ChipFill = Frozen(0xF2, 0xF3, 0xF5);- // How tall each sound bar stands, step by step; each bar runs two steps ahead of the one before.static readonly double[] levels = [0.35, 0.7, 1, 0.6, 0.3, 0.85, 0.5];static SolidColorBrush Frozen(byte r, byte g, byte b) { var x = new SolidColorBrush(Color.FromRgb(r, g, b)); x.Freeze(); return x; }@@ -496,8 +438,6 @@ sealed class NotesWindow : Windowskeleton.Color = beat % 2 == 0 ? SkeletonBase : SkeletonLight;}- /// One quiet status row, then the notes' own shape waiting to be filled, so the first version- /// lands where the reader is already looking.FrameworkElement Listening(int heard){var body = new StackPanel { Margin = new Thickness(0, 4, 0, 0) };@@ -534,7 +474,6 @@ sealed class NotesWindow : Windowvar topics = Ui.Stack(12, Ui.Text(L("议题"), 15, Placeholder, FontWeights.Bold), TopicSlot("00:00", [0.52, 0.88, 0.7]), later);body.Children.Add(Gap(topics, 22, top: true));- // Wraps: the English chips don't fit one line in a narrow window.var chips = new WrapPanel { Margin = new Thickness(0, 26, 0, 0) };var lead = Ui.Text(L("会整理出"), 12, Palette.Tertiary, wrap: false);lead.Margin = new Thickness(0, 4, 6, 10);@@ -545,7 +484,6 @@ sealed class NotesWindow : Windowreturn body;}- /// A placeholder line `fraction` of the width across, pulsing with the clock.FrameworkElement SkeletonBar(double fraction, double height){var grid = new Grid { Height = height };@@ -555,7 +493,6 @@ sealed class NotesWindow : Windowreturn grid;}- /// A topic still to come: its time, then a heading and points as bars, in a dashed outline.FrameworkElement TopicSlot(string time, double[] lines){var bars = new StackPanel();@@ -567,7 +504,6 @@ sealed class NotesWindow : WindowDockPanel.SetDock(clock, Dock.Left);dock.Children.Add(clock); dock.Children.Add(bars);var grid = new Grid();- // Dash lengths are in stroke widths: the Mac's 5 / 4 points at 1.5.grid.Children.Add(new System.Windows.Shapes.Rectangle { Stroke = Palette.Line, StrokeThickness = 1.5, StrokeDashArray = new DoubleCollection { 5 / 1.5, 4 / 1.5 }, RadiusX = 12, RadiusY = 12 });grid.Children.Add(dock);return grid;@@ -577,8 +513,6 @@ sealed class NotesWindow : Window{var lines = app.Listen.SessionId is { } id ? app.Store.Get(id)?.Lines ?? [] : [];var body = new StackPanel();- // Stored as they arrive (the notes count them); shown in time order, so a sentence I said- // sits between the other side's, which come back from Ming a little later.var sid = app.Listen.SessionId;var latest = lines.Count > 0 ? lines[^1].Id : null;foreach (var (l, who, ink, place) in Speakers(lines, app.Settings.SpeakerVoices))@@ -586,9 +520,6 @@ sealed class NotesWindow : Windowreturn body;}- /// Lines in time order with who said them, named only where the speaker changes (as chat apps- /// do): 你 for what I said into the meeting, 说话人 N once voices are told apart. A meeting that- /// heard the PC and the room says 现场 / 线上 where that changes too (`place`).internal static IEnumerable<(TranscriptLine line, string? who, Brush? ink, bool place)> Speakers(IReadOnlyList<TranscriptLine> lines, bool voices){var numbers = voices ? SpeakerLabels.Numbers(lines) : [];@@ -604,20 +535,13 @@ sealed class NotesWindow : Windowplace = both && l.Speaker != "me";if (key == "me") { who = L("你"); ink = Palette.AccentText; }else if (numbers.TryGetValue(l.Id, out var m)) { who = LF("说话人 %lld", m); ink = Palette.Speaker(m); }- else if (numbers.Count > 0 && l.Via != "room") { who = L("未识别"); ink = Palette.Tertiary; } // the room side tells no voices apart+ else if (numbers.Count > 0 && l.Via != "room") { who = L("未识别"); ink = Palette.Tertiary; }}last = key;yield return (l, who, ink, place);}}- /// One line of the transcript as on the Mac: who (in their colour) and when, the original in- /// grey, the translation in ink. With `play` (a record with its recording) the time is a link- /// that plays from there; it is tagged "time" so the player can light it.- /// 改正听错的词: the fixed words are underlined; pointing at the line (or `open`, the line being- /// said: hover in a window that never takes focus isn't to be counted on) shows what each was- /// heard as with 改回 (`revert`), and 改这句… (`edit`, the meeting record). `editor` takes the- /// original's place while the line is being rewritten.internal static FrameworkElement TranscriptRow(TranscriptLine l, string? who = null, Brush? ink = null, bool place = false, Action<double>? play = null,Action<LineFix>? revert = null, bool open = false, Action? edit = null, FrameworkElement? editor = null,IReadOnlyList<string>? terms = null, bool found = false)@@ -645,7 +569,6 @@ sealed class NotesWindow : Windowtext.Children.Add(Gap(editor, 3, top: true));return text;}- // `terms`: the records' search marks what it found (`found`: the match being looked at).terms ??= [];text.Children.Add(Gap(FixViews.Mark(FixViews.LineText(l, translated ? 13 : 15, translated ? Palette.Secondary : Palette.Ink), terms, found), 3, top: true));if (translated) text.Children.Add(Gap(FixViews.Mark(Ui.Text(l.Dst!, 15, Palette.Ink), terms, found), 2, top: true));@@ -664,8 +587,6 @@ sealed class NotesWindow : Windowreturn text;}- /// Your own line (SpeakerViews.swift › MeTag): said with the talk key, so what the other side- /// heard was its translation; 你 and an outlined 同传.static FrameworkElement MeTag(string who, Brush? ink){var tag = Ui.Row(5, Ui.Text(who, 12, ink ?? Palette.AccentText, FontWeights.SemiBold, wrap: false), new Border@@ -678,7 +599,6 @@ sealed class NotesWindow : Windowreturn tag;}- /// 现场 / 线上 (SpeakerViews.swift › PlaceTag): the room's filled, the PC's outlined.internal static FrameworkElement PlaceTag(TranscriptLine l){var room = l.Via == "room";@@ -691,12 +611,9 @@ sealed class NotesWindow : Window};}- // 改正听错的词: the card and the toast, rebuilt only when what they show changes.ContentControl ask = new(), toast = new();string? askKey, toastKey;- /// 这样改对吗? for the first name waiting. Not while the window is shown to the other side- /// (共享屏幕时让对方看到): names wait for after the meeting then.FrameworkElement? AskCard((TranscriptLine Line, LineFix Fix, int Position, int Of)? asking){if (asking is not { } a || app.Listen.SessionId is not { } id) return null;@@ -705,7 +622,6 @@ sealed class NotesWindow : Windowreturn card;}- /// Who can see this window, and when the notes change next.FrameworkElement Footer(){var visible = app.Settings.ShowInCapture || !hiddenFromCapture;@@ -734,25 +650,21 @@ sealed class NotesWindow : Windowreturn Ui.Floating(new Border { Padding = new Thickness(22, 14, 14, 16), Child = grid }, new SolidColorBrush(Color.FromArgb(0xF2, 0x1B, 0x1D, 0x22)), 16, dark: true);}- /// The bar as on the Mac: who and the original on one small line, the translation big and bold.FrameworkElement SubtitleLine(){var listen = app.Listen;var session = listen.SessionId is { } id ? app.Store.Get(id) : null;var line = session?.Lines.LastOrDefault();var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 12, 0) };- // Asked to end: the one time the bar carries buttons, as the panel's card does.if (listen.Listening && app.ConfirmingEnd){text.Children.Add(Ui.Text(L("结束这场会议?"), 15, Brushes.White, FontWeights.Bold));text.Children.Add(Gap(Ui.Text(ConfirmEndDetail(), 12, Palette.NightText), 2, top: true));- // On the dark bar the ink button would vanish: 结束会议 takes the 结束 button's pale look.var buttons = Ui.Row(8, Ui.Button(L("继续记录"), app.CancelStop, height: 32), Ui.Button(L("结束会议"), () => _ = app.StopListening(), Ui.Kind.Pale, Icons.Stop, 32, iconFill: true));buttons.Margin = new Thickness(0, 8, 0, 0);text.Children.Add(buttons);return text;}- // The subtitle bar has no room for buttons: it says what will happen (the Mac's notice).if (listen.Listening && app.Ending is not null){Detach(endingNotice);@@ -784,7 +696,6 @@ sealed class NotesWindow : Windowreturn e;}- /// A header button at the Mac's size: 13 px label, 10 px sides.static Button Snug(Button b){b.Padding = new Thickness(10, 0, 10, 0);@@ -804,7 +715,6 @@ sealed class NotesWindow : Windowreturn dock;}- /// A to-do: an empty box (notes are read-only here), the task, and who has it.internal static FrameworkElement Todo(NoteItem todo){var dock = new DockPanel();diff --git a/windows/src/Cicada/Onboarding.cs b/windows/src/Cicada/Onboarding.csindex 57269df..b5ce69a 100644--- a/windows/src/Cicada/Onboarding.cs+++ b/windows/src/Cicada/Onboarding.cs@@ -8,11 +8,6 @@ using static Cicada.Strings;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 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;@@ -24,19 +19,14 @@ sealed class Onboarding : Windowreadonly double[] levels = new double[9];double level, peak;bool autoStart = true, playing;- // 同声传译 is on while its step is showing (so 右 Ctrl can be tried); this is what it was before.bool? speakBefore;- // Step 1: the key field and what we know about itreadonly PasswordBox keyBox = new() { FontSize = 14, MinHeight = 34, VerticalContentAlignment = VerticalAlignment.Center };readonly TextBox keyText = new() { FontSize = 14, MinHeight = 34, VerticalContentAlignment = VerticalAlignment.Center, Visibility = Visibility.Collapsed };readonly ContentControl keyStatus = new();bool checking;- // A pasted key's prefix said something (a management key, another service's): that stays until the next paste.bool hinting;- /// Opened by the installer: step 1 says so, and 开机时启动知了 shows what the installer set.readonly bool installed;- /// The first page after installing carries 已装好: the installer's window becomes this one.readonly int badgeStep;public Onboarding(Controller app, bool installed = false)@@ -51,7 +41,6 @@ sealed class Onboarding : Windowvar dock = new DockPanel();DockPanel.SetDock(stepper, Dock.Top);DockPanel.SetDock(footer, Dock.Bottom);- // The page scrolls if it must (a failed check's reason and proxy hint under the key).dock.Children.Add(stepper); dock.Children.Add(footer);dock.Children.Add(new ScrollViewer { Content = page, VerticalScrollBarVisibility = ScrollBarVisibility.Auto });Content = Ui.Frameless(this, dock, resizable: false, captionHeight: 24);@@ -68,7 +57,6 @@ sealed class Onboarding : WindowRender();}- /// Dev: open on a given step (cicadactl show onboarding <n>).public Onboarding At(int to) { Go(to); return this; }void Go(int to)@@ -88,7 +76,6 @@ sealed class Onboarding : WindowRender();}- /// Leaving 同声传译: keep it on (继续, with the virtual mic in), or put back what it was.void LeaveSpeak(bool keep){if (speakBefore is not { } before) return;@@ -97,7 +84,6 @@ 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()@@ -108,8 +94,6 @@ sealed class Onboarding : Windowfooter.Content = Footer();}- // The Mac's setup layout (Onboarding.swift): the logo and a bar per step along the top. The last- // page isn't a step: the logo alone.FrameworkElement Stepper(){var grid = new Grid { Margin = new Thickness(64, 36, 64, 0) };@@ -151,14 +135,12 @@ sealed class Onboarding : Windowreturn s;}- /// The Mac's white step card: 18-point corners, no line on the grey ground.static Border StepCard(UIElement child, Thickness? padding = null) => new(){Background = Brushes.White, CornerRadius = new CornerRadius(18),Padding = padding ?? new Thickness(22, 20, 22, 20), Child = child,};- /// Two cards side by side, the first wider.static Grid Columns(UIElement main, UIElement side, double sideWidth = 236){var g = new Grid();@@ -170,7 +152,6 @@ sealed class Onboarding : Windowreturn g;}- /// The lead of a numbered row: a grey disc with the number, or a green-tinted tick once it's done.static FrameworkElement Disc(int n, bool done = false){var disc = new Grid { Width = 26, Height = 26, VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(0, 0, 14, 0) };@@ -180,7 +161,6 @@ sealed class Onboarding : Windowreturn disc;}- /// A numbered row in a step card: the disc, a line in ink, a grey line, and maybe a control.static FrameworkElement Numbered(FrameworkElement lead, string title, string? detail, UIElement? right = null, UIElement? below = null){var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center };@@ -213,7 +193,6 @@ sealed class Onboarding : Window}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);@@ -277,9 +256,7 @@ sealed class Onboarding : Window// 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)@@ -309,7 +286,6 @@ sealed class Onboarding : Windowreturn Page(L("用其他服务"), L("听、纪要和翻译都能用,模型已经选好。"), card);}- /// The key field with its reveal button, and 粘贴并检查.DockPanel KeyRow(string placeholder){var reveal = Ui.IconButton(Icons.Eye, L("显示 key"), () =>@@ -356,10 +332,8 @@ sealed class Onboarding : Windowasync Task SaveKey(){var text = keyBox.Password.Trim();- // 继续 is always allowed once a key is in: a failed check stays in 还差几步 and the settings.if (text.Length == 0 && app.Ling.HasKey) { Go(1); return; }if (!text.StartsWith("sk-")) { Status(false, L("要粘贴 sk- 开头的那串")); return; }- // The prefix says whose key it is (SettingsWindow.SaveKey does the same).if (AICheck.Owner(text) is { } whose){var (owner, management) = whose;@@ -391,8 +365,6 @@ sealed class Onboarding : Windowif (app.Ling.Health.Passed) { await Task.Delay(600); if (step == 0) Go(1); }}- /// What the last check found, under the key: a tick when it passed (busy too), else where it- /// broke and the one thing that fixes it, as in the settings.void ShowCheck(){var ling = app.Ling;@@ -404,7 +376,6 @@ sealed class Onboarding : Windowelse keyStatus.Content = AICheckView.Steps(app, () => { keyBox.Clear(); keyStatus.Content = null; keyBox.Focus(); }, recheckInStep: true, compact: true);}- /// A check finished or a meeting request reported back while the key page is open.void LingChanged() => Dispatcher.BeginInvoke(() => { if (step == 0 && !checking && keyBox.Password.Length == 0) ShowCheck(); });// MARK: 2 · System audio@@ -437,7 +408,6 @@ sealed class Onboarding : WindowUi.Spread(Ui.Stack(2, Ui.Text(L("没有声音在放?"), 14, Palette.Ink, wrap: false), Ui.Helper(L("放 3 秒测试声音,从默认扬声器出来"))), test),},});- // The two sounds side by side: people try speaking first, but this step hears the PC.var sources = new Grid { Margin = new Thickness(0, 12, 0, 0) };sources.ColumnDefinitions.Add(new ColumnDefinition());sources.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(12) });@@ -449,7 +419,6 @@ sealed class Onboarding : Windowreturn Page(L("让知了听到电脑里的声音"), L("会议里对方说的话从电脑扬声器放出来,字幕和纪要都从这里来。Windows 上不用授权。"), card, sources);}- /// One of the two sounds: where it goes, outlined in ink when it is this step's.static FrameworkElement Source(string title, FrameworkElement badge, string[] flow, bool on){var path = new WrapPanel { Margin = new Thickness(0, 8, 0, 0) };@@ -473,16 +442,12 @@ sealed class Onboarding : Windowdouble sum = 0;foreach (var s in buf) sum += (double)s * s;var rms = buf.Length == 0 ? 0 : Math.Sqrt(sum / buf.Length) / 32768;- // The loudest buffer since the last bar, not the last one (often a silent fill).level = Math.Max(level, rms);peak = Math.Max(peak, rms);}bool testing;- /// 放一段测试声音: the sample's first seconds through the default speakers. The listening tap- /// leaves Cicada's own sound out, so a second tap that hears only Cicada feeds the same bars:- /// they still move only if Windows really hands the PC's sound over.async Task PlayTest(){if (testing || Bundled.Sample() is not { } wav) return;@@ -508,10 +473,8 @@ sealed class Onboarding : Window}}- /// A few bars of the last moment's loudness, newest on the right, in the accent once there's sound.void Meter(){- // A rolling history of the loudness, eased so a word reads as a rise and fall, not one spike.Array.Copy(levels, 1, levels, 0, levels.Length - 1);levels[^1] = Math.Max(Loudness(level), levels[^2] * 0.7);level = 0;@@ -530,7 +493,6 @@ sealed class Onboarding : Window}}- /// -50 dBFS (a quiet room) to 0 dBFS on a log scale, so speech sits mid-bar instead of pinning it.static double Loudness(double rms) => rms <= 0 ? 0 : Math.Clamp((20 * Math.Log10(rms) + 50) / 50, 0, 1);// MARK: 3 · Try it@@ -554,7 +516,6 @@ sealed class Onboarding : Windowasync Task PlaySample(){- // The notes panel opens along the right edge; keep the wizard's buttons clear of it.var area = SystemParameters.WorkArea;var room = area.Right - 440 - area.Left;Left = Math.Max(area.Left + 8, Math.Min(Left, room - Width));@@ -604,7 +565,6 @@ sealed class Onboarding : Windowreturn Page(L("线上开会时要说外语吗?"), LF("按住%@说话,线上的人听到翻译后的声音。不需要可以跳过。", PushToTalk.Label), card);}- /// After the install: where the computer's sound plays, so nobody thinks Cicada took it.FrameworkElement? SpeakerNote() =>Endpoints.SpeakerIsCable() ? CableInstaller.SpeakerStrip(this, Render): Endpoints.Default(Endpoints.Flow.Render) is { } d ? Ui.Text(LF("电脑声音照常从 %@ 播放", d.Name), 13, Palette.Secondary) : null;@@ -629,7 +589,6 @@ sealed class Onboarding : Window// MARK: Done · where the icon lives- /// Text that wraps on the left of a button that keeps its full width (English runs wider).static FrameworkElement Beside(FrameworkElement text, FrameworkElement button){var d = new DockPanel();@@ -669,7 +628,6 @@ sealed class Onboarding : Windowreturn Page(L("好了,知了住在任务栏右下角"), L("Windows 会先把新图标收进 ^ 里。拖出来放在时钟旁边,开会时一眼就能看到。"), Columns(pin, keys, 260));}- /// The corner of the taskbar: the ^ overflow with 知了 in it, and a dashed arrow to beside the clock.static FrameworkElement TrayPicture(){var c = new Canvas { Height = 150, ClipToBounds = true };diff --git a/windows/src/Cicada/Platform.cs b/windows/src/Cicada/Platform.csindex ba9f17d..d41dc32 100644--- a/windows/src/Cicada/Platform.cs+++ b/windows/src/Cicada/Platform.cs@@ -4,7 +4,6 @@ using Microsoft.Win32;namespace Cicada.App;-/// Ctrl+Alt+L anywhere: start or end listening. A message-only window receives WM_HOTKEY.sealed class Hotkey : IDisposable{public const string Label = "Ctrl+Alt+L";@@ -12,13 +11,12 @@ sealed class Hotkey : IDisposableconst uint ModAlt = 0x1, ModControl = 0x2, ModNoRepeat = 0x4000, VkL = 0x4C;readonly HwndSource source;readonly Action pressed;- /// False when another app already holds the combination (Settings says so).public bool Registered { get; }public Hotkey(Action pressed){this.pressed = pressed;- source = new HwndSource(new HwndSourceParameters("CicadaHotkey") { ParentWindow = new IntPtr(-3) /* HWND_MESSAGE */, Width = 0, Height = 0 });+ source = new HwndSource(new HwndSourceParameters("CicadaHotkey") { ParentWindow = new IntPtr(-3), Width = 0, Height = 0 });source.AddHook(Hook);Registered = RegisterHotKey(source.Handle, Id, ModControl | ModAlt | ModNoRepeat, VkL);Log.Debug($"hotkey: {(Registered ? "registered" : "taken")} {Label}");@@ -40,15 +38,12 @@ sealed class Hotkey : IDisposable[DllImport("user32.dll")] static extern bool UnregisterHotKey(IntPtr hwnd, int id);}-/// 开机时启动知了: the per-user Run key, so no admin rights. The dev build has its own entry.static class AutoStart{const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";static string Name => Paths.Dev ? "Cicada Dev" : "Cicada";- // --background: started with Windows, so stay in the tray; opened by hand, the main window shows.static string Command(string exe) => $"\"{exe}\" --background" + (Paths.Dev ? " --dev" : "");- /// Rewrites an entry made before --background existed, which would open the main window at sign-in.public static void Refresh(){try@@ -70,7 +65,6 @@ static class AutoStartset => Set(Environment.ProcessPath ?? "", value);}- /// The installer sets it for the copy it put in place, not for itself in Downloads.public static void Set(string exe, bool on){try@@ -83,18 +77,11 @@ static class AutoStart}}-/// The default playback device's name ("扬声器 (Realtek High Definition Audio)") for onboarding.-/// Through Endpoints, never a second [ComImport] MMDeviceEnumerator: the enumerator is one COM object-/// per process, and while an RCW of another class for it lives, `new` of Endpoints' class throws-/// InvalidCastException, so the virtual cable looked uninstalled after onboarding's sound step.static class AudioDevice{public static string? DefaultName() => Endpoints.Default(Endpoints.Flow.Render)?.Name;}-/// The meeting apps reading a microphone now (MicUse in Cicada.Core reads the entries): what-/// Windows keeps for Settings › 隐私和安全性 › 麦克风, whose LastUsedTimeStop is 0 while an app has-/// the mic open. Both desktop apps (NonPackaged) and Store apps (the new Teams).static class MicReaders{const string Root = @"Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\microphone";@@ -112,7 +99,6 @@ static class MicReaders{if (name == "NonPackaged") continue;using var k = parent.OpenSubKey(name);- // An app granted the mic but never used has both times 0: not in a call.if (k?.GetValue("LastUsedTimeStop") is long stop && k.GetValue("LastUsedTimeStart") is long start && start > 0)entries.Add((name, stop));}@@ -125,13 +111,10 @@ static class MicReaders}}-/// Windows' own proxy settings (Settings › Network & internet › Proxy, which proxy apps switch on as-/// "system proxy"): only read, to word the "can't reach" hint. Cicada never sets or uses one itself.static class WinProxy{const string Key = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";- /// A manual proxy, or an auto-config (PAC) script, is on.public static bool SystemOn(){try@@ -142,7 +125,6 @@ static class WinProxycatch (Exception e) { Log.Debug($"proxy: unreadable ({e.GetType().Name})"); return false; }}- /// The settings that decide where requests go, as one string to compare (WatchProxy).public static string Snapshot(){trydiff --git a/windows/src/Cicada/SettingsWindow.cs b/windows/src/Cicada/SettingsWindow.csindex 1955bdc..a73fbe9 100644--- a/windows/src/Cicada/SettingsWindow.cs+++ b/windows/src/Cicada/SettingsWindow.cs@@ -6,9 +6,6 @@ using static Cicada.Strings;namespace Cicada.App;-/// 设置, as the Mac's settings window with no title bar: the categories as plain words on the left,-/// the chosen one on a white pill, and its page on the right under a big title, the settings in-/// white cards on the grey ground with each control at the right.sealed partial class SettingsWindow : Window{readonly Controller app;@@ -17,18 +14,13 @@ sealed partial class SettingsWindow : Windowreadonly Dictionary<string, FrameworkElement> sections = [];readonly PasswordBox keyBox = new();bool editingKey;- // A custom service's notes key (另一个服务), typed until 保存并检查; 更换 shows the field again.readonly PasswordBox notesKeyBox = new();bool editingNotesKey;string current = "ai";- // AI 服务: 自己选模型 unfolded, and a model being typed by hand ("hear", "text", "voice").bool modelsOpen;string? typing;- // A custom service's address and models as typed, kept across re-renders until 保存并检查.readonly Dictionary<string, TextBox> customFields = [];- // 其他(兼容 OpenAI): the per-use rows unfolded ("text", "voice", "hear"); null until the page first shows.HashSet<string>? open;- /// A pasted key that belongs elsewhere: what it is, and (another service's key) where it fits.(string Text, string? Service, string Key)? keyHint;public SettingsWindow(Controller app)@@ -52,7 +44,6 @@ sealed partial class SettingsWindow : Windowapp.Ling.Changed += OnLingChanged;app.OwnVoice.Changed += OnLingChanged;Closed += (_, _) => { app.Ling.Changed -= OnLingChanged; app.OwnVoice.Changed -= OnLingChanged; };- // While a talk key is being chosen no key reaches any app: leaving the window ends it.Deactivated += (_, _) => StopChoosingKey();Closed += (_, _) => { if (choosingKey) app.StopChoosingTalkKey(); };Render();@@ -87,7 +78,6 @@ sealed partial class SettingsWindow : WindowCard(Icons.Power, L("开机时启动知了"), null, Ui.Switch(AutoStart.Enabled, v => AutoStart.Enabled = v, L("开机时启动知了"))),Card(Icons.Folder, L("会议记录存放位置"), $"{Paths.Sessions} · {L("和 Mac 版格式相同")}", Ui.Button(L("打开文件夹"), () => OpenFolder(Paths.Sessions), height: 32))),.. ExportCards()]);- // 卸载 as in Settings › Apps, with the same confirmation; only an installed copy offers it.FrameworkElement[] about =[Card(null, LF("知了 %@", Controller.Version), UpdateDetail(), UpdateControl(), AppIcon.Small(24)),@@ -104,17 +94,12 @@ sealed partial class SettingsWindow : Windowstring? shownPage;- /// The page column is one width whatever it shows (a check running, failed or passed): 640, or- /// less in a narrow window. Sized by its content it jumped between states.double PageWidth() => scroll.ViewportWidth > 0 ? Math.Min(640, scroll.ViewportWidth) : 640;- /// What to do with the download: the installer upgrades itself; an older release has only the zip.public static string UpdateHint(UpdateChecker.Update u) => u.Setup is not null ? L("安装后自动重新打开") : L("下载后解压,替换旧的知了");static 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`; `ai models` unfolds- /// 自己选模型; the old `ling` is AI 服务).public void Show(string id){var parts = id.Split(' ');@@ -123,10 +108,8 @@ sealed partial class SettingsWindow : WindowRender();}- /// An update was found or a check finished: only 关于 shows it.public void UpdatesChanged() { if (current == "about") Render(); }- // The Mac's AppRows version row: what the last check found, and 检查更新 or 下载.string? UpdateDetail(){if (app.Updates.Available is { } u)@@ -194,14 +177,11 @@ sealed partial class SettingsWindow : Windowreturn t;}- /// One category's page: only the chosen one is shown, under its name in big type (and, for- /// 同声传译, its on/off switch beside it).void Section(StackPanel page, string id, string title, params FrameworkElement[] groups){if (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; editingNotesKey = false; notesKeyBox.Clear(); typing = null; keyHint = null; customFields.Clear(); open = null; app.SetAIProvider(v); }, 220));h.Margin = new Thickness(0, 0, 0, 20);@@ -210,10 +190,8 @@ sealed partial class SettingsWindow : Windowforeach (var g in groups) { g.Margin = new Thickness(0, 0, 0, 12); page.Children.Add(g); }}- /// A grey label over a group, as the Mac's settings sections.static FrameworkElement Label(string text) { var t = Ui.Text(text, 13, Palette.Secondary); t.Margin = new Thickness(6, 8, 0, 0); return t; }- /// Cards that belong together on one white card, with hairlines between them.static FrameworkElement Group(params FrameworkElement[] cards){var s = new StackPanel();@@ -222,10 +200,8 @@ sealed partial class SettingsWindow : Windowreturn new Border { Background = Palette.Surface, CornerRadius = new CornerRadius(16), Child = s, Padding = new Thickness(0, 2, 0, 2) };}- /// One setting: icon, name, one grey line, and its control on the right.static FrameworkElement Card(string? icon, string title, string? description, FrameworkElement control, FrameworkElement? image = null){- // No icons: the Mac's rows are words and a control. (`icon` stays for the call sites.)_ = icon;var dock = new DockPanel { MinHeight = 40, Margin = new Thickness(0, 10, 0, 10) };if (image is not null) { image.Margin = new Thickness(0, 0, 14, 0); DockPanel.SetDock(image, Dock.Left); dock.Children.Add(image); }@@ -242,8 +218,6 @@ sealed partial class SettingsWindow : Windowstring? cableProgress;- /// 同声传译: the switch, the virtual mic, the two languages and the room's voice.- /// 结束会议: when a meeting ends by itself (MeetingEnd.cs), as the Mac's settings say it.FrameworkElement EndCards(){var s = app.Settings;@@ -275,8 +249,6 @@ sealed partial class SettingsWindow : Windowvar voice = Ui.Row(8,Ui.Choice(voices, chosen, v => { s.SpeakVoices[VoiceCatalog.Key(target)] = v; previewNote = null; Save(); Render(); }, 280),Ui.Button(app.Previewing ? L("停止") : L("试听"), () => { if (app.Previewing) app.StopPreview(); else _ = RunPreview(); }, height: 32));- // No voice at all for the language (Windows has none, the service speaks none): say so before- // 试听 is pressed, as it would after.var note = previewNote ?? (voices.Count == 0 ? PreviewNote(Controller.PreviewResult.NoVoice, target) : null);var mine = Languages.Sources.FirstOrDefault(x => x.Code == Languages.FromSystem(System.Globalization.CultureInfo.CurrentUICulture.Name))?.Name ?? "";var key = PushToTalk.Current;@@ -304,7 +276,6 @@ sealed partial class SettingsWindow : Windowelse yield return Group(mic);}- // 按住说话's 更改: waiting for a key, and why the last one pressed can't be it.bool choosingKey;string? keyRefused;@@ -334,7 +305,6 @@ sealed partial class SettingsWindow : WindowRender();}- /// "按下想用的键…" in a dashed accent box where the keycap was.static FrameworkElement ChoosingKeyBox(){var box = new Grid { Width = 176, Height = 36 };@@ -346,9 +316,6 @@ sealed partial class SettingsWindow : Windowreturn box;}- /// 我自己的声音 (VoicePicker.swift › cloneRow), under the voice: 录制 before there is a recording;- /// then its length and how close it will sound, with 重录 and 删除; greyed with 去换成 Ling on a- /// service that can't clone. Choosing it is the voice menu's last item.FrameworkElement OwnVoiceCard(string target, bool chosen){var own = app.OwnVoice;@@ -372,7 +339,6 @@ sealed partial class SettingsWindow : Windowreturn CardWith(Ui.Text(L("我自己的声音"), 14, Palette.Ink), L("录 15 秒原声,对方听到你的音色,晚约 3 秒"), record);}- /// A Card whose title is already a TextBlock (greyed or bold).static FrameworkElement CardWith(TextBlock title, string description, FrameworkElement control){var card = (DockPanel)Card(null, "", description, control);@@ -388,7 +354,6 @@ sealed partial class SettingsWindow : WindowRender();}- // 试听's result, shown under the voice until another voice is picked or 试听 is pressed again.(string Title, string Help, bool VoiceSettings)? previewNote;public async Task RunPreview()@@ -413,7 +378,6 @@ sealed partial class SettingsWindow : Windowstatic FrameworkElement PreviewNoteBox((string Title, string Help, bool VoiceSettings) note){- // One wrapping line with the link inline: English runs wider than the card.var help = Ui.Helper(note.Help);help.TextWrapping = TextWrapping.Wrap;if (note.VoiceSettings)@@ -443,9 +407,6 @@ sealed partial 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;@@ -475,9 +436,6 @@ sealed partial class SettingsWindow : Windowyield return foot;}- /// 现在能用的 (AISettings.swift › usage), with 听对方 first: on the ports the service hears.- /// Only what the last result supports: when the service can't be reached (or the key fails)- /// nothing says "用 ZenMux" in green. Windows has no voice of the user's own on any service.IEnumerable<FrameworkElement> UsesRows(){var ling = app.Ling;@@ -511,13 +469,9 @@ sealed partial class SettingsWindow : Window: notesOn ? Row(L("实时纪要"), uses, "ok", L("会中每 45 秒更新")): Row(L("实时纪要"), off, "off", reason == AICheck.Reason.NoJSON ? L("这个服务不支持 JSON") : reason == AICheck.Reason.NoModel ? L("换一个模型后可用") : later);yield return textOn ? Row(L("翻译"), uses, "ok", L("整句用它;不行时换 Google")) : Row(L("翻译"), "Google", "off", ling.HasKey ? L("先用 Google 翻译") : L("没有 key 时照常可用"));- // 改正听错的词 (the Mac hides this row where the service hears, as here: Windows has no other- // way to hear, so it is shown, and says what it costs: Ming's translation leaves no text- // request to ride on, so each finished line is one more).var fixOn = textOn && app.Settings.FixMisheard;yield return Row(L("改正听错的词"), fixOn ? uses : textOn ? L("已关") : off, fixOn ? "ok" : "off",fixOn ? L("每句话说完多发一次文字请求") : textOn ? L("在“词表”里打开") : later);- // Windows speaks when the service can't, as the Mac does with its own voice.var speaks = ling.Speaks && !down;yield return speaks ? Row(L("同传声音"), uses, "ok", ling.LastVoice is { } last ? (last.Ok ? L("上次同传时正常") : L("上次同传没出声,用了 Windows 的声音")) : c.IsLing ? L("Ming 的声音") : c.VoiceModel!): down ? Row(L("同传声音"), L("本机"), "local", L("先用 Windows 的声音"))@@ -525,7 +479,6 @@ sealed partial class SettingsWindow : Window: Row(L("同传声音"), L("本机"), "local", L("填好 key 前用 Windows 的声音"));}- /// 自己选模型: what hears, what writes, what speaks for this service.IEnumerable<FrameworkElement> ModelRows(){var c = app.Ling.Config;@@ -541,8 +494,6 @@ sealed partial class SettingsWindow : Windowif (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)@@ -559,12 +510,10 @@ sealed partial class SettingsWindow : Windowif (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 };@@ -582,10 +531,6 @@ sealed partial class SettingsWindow : Window// MARK: Own service- /// 其他(兼容 OpenAI) (AISettings.swift › customPage): one card with a row per use, each at its- /// own address if need be (a text model, a hear model and a speech model often run as separate- /// servers), each saying whether it works and how fast. What isn't set up or doesn't work yet- /// opens where it needs filling in.IEnumerable<FrameworkElement> CustomCards(){var ling = app.Ling;@@ -600,7 +545,6 @@ sealed partial class SettingsWindow : Windowvar lockLine = Ui.Helper(LF("仅保存在本机当前账户下,仅发送至 %@", KeyHosts()));lockLine.Margin = new Thickness(6, -4, 0, 0);yield return lockLine;- // What it costs depends on where it runs; what is sent where is the port's own line (it hears through the service).var cost = c.Base is { } b && AIProvider.IsNearby(b) ? L("跑在你自己的机器上,不按量计费。") : L("费用以这个服务为准。");var foot = Ui.Helper(cost + (app.Settings.AiCustomOnly? LF("会议的语音和文字只发给 %@,不经过 Google 等外部服务。", CustomHosts())@@ -609,9 +553,6 @@ sealed partial class SettingsWindow : Windowyield return foot;}- /// 语音和文字只发给你的服务 (AISettings.swift › onlyRow): Google is never asked. The grey line says- /// what it costs, and while the service can't be reached, that new lines show the original- /// (Windows has no translation of its own to stand in).FrameworkElement OnlyRow(){var s = app.Settings;@@ -623,11 +564,8 @@ sealed partial class SettingsWindow : WindowUi.Switch(s.AiCustomOnly, v => { s.AiCustomOnly = v; s.Save(); app.AIChanged(); Render(); }, L("语音和文字只发给你的服务")));}- /// Where the custom service's audio and text go: one host when text, hearing, voice and notes- /// share it, two by name.string CustomHosts() => Hosts(notes: true);- /// Where the custom service's key is sent: every use's address, the notes' only while they share it.string KeyHosts() => Hosts(notes: !app.Ling.NotesHasOwnKey);string Hosts(bool notes)@@ -643,7 +581,6 @@ sealed partial class SettingsWindow : Windowstatic string HostOf(string? url) => url is not null && Uri.TryCreate(url, UriKind.Absolute, out var u) ? u.Host : "";- /// A row that opens to its fields: a state dot, the use, what it runs on, and how it's doing.FrameworkElement SectionHeader(string id, string title, string detail, Brush dot, string? trailing, Brush? trailingColor = null){var isOpen = open!.Contains(id);@@ -674,7 +611,6 @@ sealed partial class SettingsWindow : Windowreturn dock;}- /// A row's fields, under its title.static FrameworkElement Body(params FrameworkElement[] parts){var s = new StackPanel { Margin = new Thickness(20, 0, 0, 12) };@@ -699,9 +635,6 @@ sealed partial class SettingsWindow : Windowstatic string Secs(double s) => s.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture);- /// 翻译和纪要 (AISettings.swift › textSection): 翻译's address, key and model; then 纪要, the- /// same service (another model at most) or another one with its own address and key; how long- /// a sentence took and whether the model thinks; the steps when something failed.FrameworkElement TextSection(){var ling = app.Ling;@@ -709,7 +642,6 @@ sealed partial class SettingsWindow : Windowvar s = app.Settings;var check = ling.Health;var textFailed = check.Failure is { Step: not AICheck.StepId.Hear };- // Translation works, the notes' own model or server doesn't.var notesDown = !textFailed && check.NotesFailed;var trailing = check.IsRunning ? L("正在检查…"): textFailed && ling.HasKey ? AICheckView.Status(check)@@ -750,7 +682,6 @@ sealed partial class SettingsWindow : Windowreturn new StackPanel { Children = { header, Body([.. parts]) } };}- /// "192.168.1.20 · qwen-mt-turbo", then the notes' model, or their own server after a bar.string TextDetail(){var ling = app.Ling;@@ -763,9 +694,6 @@ sealed partial class SettingsWindow : Windowreturn n.TextModel == c.TextModel ? line : line + $" · {n.TextModel}";}- /// 纪要: the same service as translation, or another one with its own address and key (switching- /// back keeps what was typed); then the notes' model, 和翻译模型一样 first. The grey line says what- /// it's for, or in red why notes can't be written.IEnumerable<FrameworkElement> NotesGroup(){var ling = app.Ling;@@ -791,7 +719,6 @@ sealed partial class SettingsWindow : Window: Line(L("用来写实时纪要、识别说话人,默认和翻译用同一个"), Palette.Tertiary);}- /// A group's name in the 翻译和纪要 row (翻译, 纪要), with its control on the right.static FrameworkElement GroupTitle(string text, FrameworkElement? control = null){var title = Ui.Text(text, 14, Palette.Ink, FontWeights.SemiBold, wrap: false);@@ -801,8 +728,6 @@ sealed partial class SettingsWindow : Windowreturn row;}- /// As typed (AISettings.swift › textSection): an http address out on the internet is refused,- /// and without a key no check runs to say so.static FrameworkElement BadAddressLine(TextBox box){var bad = Line(L("地址要用 https;这台电脑和局域网里的服务可以用 http。"), Palette.Danger);@@ -812,8 +737,6 @@ sealed partial class SettingsWindow : Windowreturn bad;}- /// A custom service's model: the names its `/models` lists (ModelPicker, picking saves and- /// checks), or without a list a field saved by 保存并检查, with 重新获取 to ask for the list again.FrameworkElement ModelField(string name, string value, string hint, string? sameLabel, IReadOnlyList<string> catalog, string host,Action refetch, Action<string> pick){@@ -827,7 +750,6 @@ sealed partial class SettingsWindow : Windowreturn host.Length == 0 ? field : Ui.Row(8, field, Ui.Button(L("重新获取"), refetch, height: 34));}- /// After a check with notes apart: one row each, what it runs and how it did.FrameworkElement CheckRows(AICheck.Speed t){var c = app.Ling.Config;@@ -876,12 +798,10 @@ sealed partial class SettingsWindow : Window};}- // The grey hint in a custom service's key field (a PasswordBox has none), shown while it's empty.TextBlock? keyPlaceholder;void KeyPlaceholder() { if (keyPlaceholder is { } h) h.Visibility = keyBox.Password.Length == 0 ? Visibility.Visible : Visibility.Collapsed; }TextBlock? notesKeyPlaceholder;- /// The key of a custom service: optional on this computer and the local network.FrameworkElement CustomKey(){var saved = app.Key.Read();@@ -898,13 +818,10 @@ sealed partial class SettingsWindow : WindowKeyPlaceholder();Ui.StyleField(keyBox);var frame = Ui.FieldFrame(new Grid { Children = { keyBox, hint } }, keyBox);- // Wide enough for the hint in English, Japanese and Korean ("Optional on this PC or your local network").frame.Width = 340; frame.Height = 34;return frame;}- /// The notes' own key (另一个服务): empty, the key above is used; saved by 保存并检查, sent only- /// to the notes' address. A refused one is framed red.FrameworkElement NotesKey(){var ling = app.Ling;@@ -925,7 +842,6 @@ sealed partial class SettingsWindow : Windowreturn frame;}- /// 同传声音: a speech model (`/audio/speech`), its voice and address; else Windows speaks.FrameworkElement VoiceSection(){var ling = app.Ling;@@ -954,8 +870,6 @@ sealed partial class SettingsWindow : Window};}- /// 听对方: the hear model (it takes audio in: listening and 我说 both use it) and its own- /// address if it runs elsewhere; the status is the check's hear step.FrameworkElement HearSection(){var ling = app.Ling;@@ -995,7 +909,6 @@ sealed partial class SettingsWindow : Windowvar check = ling.Health;var key = ling.CurrentKey();var title = key is { Length: > 0 } ? AIKey.Masked(key) : key is not null ? L("本机服务,不用 key") : p.Id == "custom" ? L("还没填好") : L("还没填 API key");- // One line under the key: what failed (the steps below say why), busy, or all passed in short.string? desc = null;Brush color = Palette.Secondary;if (key is not null)@@ -1025,7 +938,6 @@ sealed partial class SettingsWindow : Windowif (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 = color;var rows = new List<FrameworkElement> { card };- // A pasted key that belongs elsewhere, before it is saved: what it is, and where it fits.if (keyHint is { } kh){var (hintText, service, pasted) = kh;@@ -1036,7 +948,6 @@ sealed partial class SettingsWindow : Windowhint.Margin = new Thickness(0, 0, 0, 12);rows.Add(hint);}- // Where it broke and the one thing that fixes it; all passed folds into the line above.if (key is not null && (check.IsRunning || check.Failure is not null || check.IsBusy || check.At is not null && !check.Passed))rows.Add(AICheckView.Steps(app, ChangeKey, recheckInStep: false));if (check.BalanceLine(ling.ServiceName) is { } low)@@ -1044,7 +955,6 @@ sealed partial class SettingsWindow : Windowvar strip = Ui.Spread(Ui.Text(low, 13, Palette.WarnIcon), Ui.Button(L("去充值"), () => AICheckView.Open(AICheckView.TopUp(p)), height: 30));rows.Add(new Border { Background = Palette.WarnBg, CornerRadius = new CornerRadius(10), Padding = new Thickness(12, 8, 8, 8), Margin = new Thickness(0, 4, 0, 12), Child = strip });}- // Where to get one, while there is none.if (p.Site is { } site && key is null)rows.Add(Card(null, LF("打开 %@", c.Name), new Uri(site).Host, Ui.IconButton(Icons.OpenExternal, LF("打开 %@", c.Name), () => Process.Start(new ProcessStartInfo(site) { UseShellExecute = true }), Palette.Secondary, 32, 16)));return Group([.. rows]);@@ -1057,7 +967,6 @@ sealed partial class SettingsWindow : Windowvar 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", ""));@@ -1067,13 +976,11 @@ sealed partial class SettingsWindow : Windows.AiCustomVoiceBase = F("voiceBase", s.AiCustomVoiceBase);s.AiCustomHearBase = F("hearBase", s.AiCustomHearBase);s.AiCustomNotesBase = F("notesBase", s.AiCustomNotesBase);- // The notes model typed by hand (no list): empty is the translation model.if (customFields.TryGetValue("notesModel", out var nm)){if (nm.Text.Trim().Length > 0) s.AiModels["custom.notes"] = nm.Text.Trim(); else s.AiModels.Remove("custom.notes");}s.Save();- // Notes' own key (另一个服务): saved here too; it goes only to the notes' address.if (s.AiCustomNotesOwn && notesKeyBox.Password.Trim().Length > 0 && app.Ling.SaveNotesKey(notesKeyBox.Password)){notesKeyBox.Clear();@@ -1082,16 +989,12 @@ sealed partial class SettingsWindow : Window}var text = keyBox.Password.Trim();keyHint = null;- // The prefix says whose key it is: a management key can't call models, and another- // service's key goes there with one click (never a silent switch). A custom address may- // well take an aggregator's key.if (s.AiProvider != "custom" && AICheck.Owner(text) is { } whose){var (owner, management) = whose;if (management) { keyHint = (L("这是 ZenMux 的管理 key,不能用来调用模型。请粘贴 sk-payg 开头的 key。"), null, ""); Render(); return; }if (owner != s.AiProvider) { keyHint = (LF("这是 %@ 的 key。", AIProvider.Named(owner).Name), owner, text); Render(); return; }}- // Ling's and the aggregators' keys start with sk-; a company gateway's may not.if (text.Length > 0 && (s.AiProvider == "custom" || text.StartsWith("sk-"))){if (!app.Key.Save(text)) return;diff --git a/windows/src/Cicada/SetupWindow.cs b/windows/src/Cicada/SetupWindow.csindex 18e6f2f..a525132 100644--- a/windows/src/Cicada/SetupWindow.cs+++ b/windows/src/Cicada/SetupWindow.cs@@ -7,9 +7,6 @@ using static Cicada.Strings;namespace Cicada.App;-/// Install, upgrade and uninstall (Install.cs does the work), in onboarding's look: the logo, a big-/// heading with one grey line, one white card, the action bottom right. Installing has one button-/// and two ticks; once done the installed copy opens onboarding, so there's no "finished" page.sealed class SetupWindow : Window{public enum Mode { Install, Upgrade, Uninstall }@@ -21,12 +18,10 @@ sealed class SetupWindow : Windowint done;string? error;bool startMenu = true, autoStart = true, keepRecords = true;- /// The running Cicada is listening: an upgrade waits, an uninstall says it ends the meeting.bool busy;readonly ContentControl body = new();readonly DispatcherTimer poll = new() { Interval = TimeSpan.FromSeconds(2) };- /// Runs the window as the whole process (no tray, no engines) and returns the exit code.public static int Run(Mode mode){var app = new Application { ShutdownMode = ShutdownMode.OnMainWindowClose };@@ -34,7 +29,6 @@ sealed class SetupWindow : Windowapp.ThemeMode = ThemeMode.Light;#pragma warning restore WPF0001app.DispatcherUnhandledException += (_, e) => { Log.Debug($"setup: unhandled {e.Exception.GetType().Name}: {e.Exception.Message}"); e.Handled = true; };- // An upgrade or uninstall speaks the language the user picked; a first install the system's.var ui = AppSettings.Load().UiLanguage;Strings.Load(Bundled.Strings, ui == "system" ? null : ui);Log.Debug($"setup: {mode} {Controller.Version} from {Environment.ProcessPath}");@@ -130,7 +124,6 @@ sealed class SetupWindow : Windowreturn;}if (mode == Mode.Uninstall) { phase = Phase.Done; Render(); return; }- // Let the last tick show, then the installed copy takes over (onboarding, or a toast).await Task.Delay(500);Install.Launch(mode == Mode.Install ? "--installed" : "--updated");Close();diff --git a/windows/src/Cicada/ShareDialog.cs b/windows/src/Cicada/ShareDialog.csindex b6791ad..164ba9e 100644--- a/windows/src/Cicada/ShareDialog.cs+++ b/windows/src/Cicada/ShareDialog.cs@@ -6,9 +6,6 @@ using static Cicada.Strings;namespace Cicada.App;-/// 分享…: a meeting as a link on cicada.indaloop.app (the Mac's ShareSheet). Settings, then the-/// server's review, then the link (and its password) or what the review stopped. A meeting already-/// shared opens on its link. Drawn in the chrome of Dialogs, its content swapped per step.sealed class ShareDialog : Window{enum Step { Settings, Working, Blocked, Done, Failed }@@ -30,7 +27,6 @@ sealed class ShareDialog : Windowbool HasNotes => session.Notes is { IsEmpty: false };- /// The open one, for the debug pipe (`sharesheet`).public static ShareDialog? Current { get; private set; }public ShareDialog(Controller app, Session session, Window? owner)@@ -101,7 +97,6 @@ sealed class ShareDialog : Window}else{- // The choices already made, in one line; 更改 opens them in place.var change = Ui.Button(L("更改"), () => { showOptions = true; Render(); }, height: 28);change.MinWidth = 0; change.Padding = new Thickness(12, 0, 12, 0); change.Margin = new Thickness(8, 0, 0, 0);var line = Ui.Text(Summary, 13, Palette.Secondary, wrap: false);@@ -124,8 +119,6 @@ sealed class ShareDialog : Windowdays == 365 ? L("1 年有效") : LF("%lld 天有效", days),names ? L("显示名字") : L("不显示名字"));- /// Takes the dialog's settings from the debug pipe: `sharesheet <id>[,full][,pw][,names][,30][,more][,go]`- /// (more presses 更改); on the done step, `copy`, `copylink` and `copypw` press 复制 and its menu's items.public void Debug(IReadOnlyCollection<string> p){if (step == Step.Done && record is { } r)@@ -148,7 +141,6 @@ sealed class ShareDialog : Windowif (p.Contains("go")) Go();}- /// Debug: the blocked step's 去掉这些内容后分享.public void DebugLeaveOut() { if (step == Step.Blocked && LeftAfterRemoving()) LeaveOut(); }public string StepName => step.ToString().ToLowerInvariant();@@ -222,8 +214,6 @@ sealed class ShareDialog : WindowGo();}- /// Would anything be left to share once the flagged parts are out? (A notes-only share whose- /// notes were flagged has nothing; the server would refuse an empty document.)bool LeftAfterRemoving(){var notesLeft = HasNotes && !dropNotes && !hits.Any(h => h.Part == "notes");@@ -235,7 +225,6 @@ sealed class ShareDialog : WindowFrameworkElement HitRow(ShareHit h){- // A list in the reader's language (the Mac's ListFormatter): 、 in Chinese and Japanese, ", " otherwise.var what = string.Join(Strings.Culture.TwoLetterISOLanguageName is "zh" or "ja" ? "、" : ", ", h.Questions.Select(Category));string place, quote;if (h.Part == "notes")@@ -311,9 +300,6 @@ sealed class ShareDialog : Windowreturn p;}- /// The link and, under it, the password in one grey box; beside it one 复制 that copies both as- /// one message, its arrow either alone for whoever sends them apart (the Mac's Menu with a- /// primary action). Without a password it is a plain button.FrameworkElement Link(ShareRecord r){TextBox Value(string text, Brush color) => new()@@ -421,7 +407,6 @@ sealed class ShareDialog : Windowreturn r;}- /// Equal buttons on one row, the last (primary) on the right, as Dialogs.static Grid Buttons(params Button[] buttons){var g = new Grid();diff --git a/windows/src/Cicada/SpeakBar.cs b/windows/src/Cicada/SpeakBar.csindex 5958157..07f5b0b 100644--- a/windows/src/Cicada/SpeakBar.cs+++ b/windows/src/Cicada/SpeakBar.cs@@ -6,9 +6,6 @@ using static Cicada.Strings;namespace Cicada.App;-/// The pill while I speak: the key, a level, 正在听你说 while it's held, then what I said and what-/// the room heard, or why nothing went out. Like the notes panel it never takes focus and stays out of-/// screen captures; it sits above the taskbar (above the subtitle bar when that is showing).sealed class SpeakBar : Window{readonly Controller app;@@ -36,8 +33,6 @@ sealed class SpeakBar : WindowLeft = area.Left + (area.Width - ActualWidth) / 2;var above = app.Settings.View == "subtitles" && app.NotesVisible ? 150 : 16;Top = area.Bottom - ActualHeight - above + Ui.ShadowRoom;- // Centred, it would sit over the notes panel's live card on a small screen: centre it in the- // wider free side instead, if it fits there.if (app.NotesBounds is { } n && new Rect(Left, Top, ActualWidth, ActualHeight).IntersectsWith(n)){double leftRoom = n.Left - area.Left, rightRoom = area.Right - n.Right;@@ -83,7 +78,6 @@ sealed class SpeakBar : WindowPlace();}- /// 右 Ctrl as a pill: the accent while held, a dim one after.static FrameworkElement Key(bool held) => new Border{CornerRadius = new CornerRadius(14), Padding = new Thickness(11, 4, 11, 5), VerticalAlignment = VerticalAlignment.Center,@@ -91,8 +85,6 @@ sealed class SpeakBar : WindowChild = Ui.Text(PushToTalk.Label, 13, Brushes.White, FontWeights.Bold, wrap: false),};- /// 同传, outlined like the notes' MeTag: what goes out is the translation, as the Mac's subtitle- /// bar says with 同传 · 你在说….static FrameworkElement Interpreted() => new Border{BorderBrush = new SolidColorBrush(Color.FromArgb(0x99, 0xFF, 0x8A, 0x5C)), BorderThickness = new Thickness(1),@@ -100,7 +92,6 @@ sealed class SpeakBar : WindowChild = Ui.Text(L("同传"), 11, new SolidColorBrush(Color.FromRgb(0xFF, 0x8A, 0x5C)), wrap: false),};- /// A still level mark: an animated one would redraw this software-rendered window every frame.static FrameworkElement Wave(){var row = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center };@@ -109,8 +100,6 @@ sealed class SpeakBar : Windowreturn row;}- /// The key, then what was said taking whatever width is left, then the status at the right: in a- /// plain row a long sentence pushed the status out past the bar's edge.static FrameworkElement Fill(FrameworkElement key, FrameworkElement said, FrameworkElement status){var dock = new DockPanel { LastChildFill = true };diff --git a/windows/src/Cicada/Speaking.cs b/windows/src/Cicada/Speaking.csindex d4dd4cd..70aacb1 100644--- a/windows/src/Cicada/Speaking.cs+++ b/windows/src/Cicada/Speaking.cs@@ -7,7 +7,6 @@ using System.Windows.Controls;namespace Cicada.App;-/// Windows' own voice (OneCore), for when Ming's can't speak: always there, no key needed.sealed class WindowsVoice : ISystemVoice{public async Task<(byte[] pcm, int rate)?> Speak(string text, string language)@@ -19,7 +18,6 @@ sealed class WindowsVoice : ISystemVoicevar voice = Windows.Media.SpeechSynthesis.SpeechSynthesizer.AllVoices.Where(v => v.Language.StartsWith(language, StringComparison.OrdinalIgnoreCase) || v.Language.StartsWith(head, StringComparison.OrdinalIgnoreCase)).OrderByDescending(v => v.Language.Equals(language, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();- // No voice for the language: say nothing rather than read it in another language's voice.if (voice is null) { Log.Debug($"windows voice: none for {language}"); return null; }synth.Voice = voice;using var stream = await synth.SynthesizeTextToStreamAsync(text);@@ -44,7 +42,6 @@ sealed class WindowsVoice : ISystemVoicecatch { return false; }}- /// The PCM inside a 16-bit WAV, mixed to mono, at its own rate.static (byte[], int)? Pcm(byte[] wav){if (wav.Length < 44) return null;@@ -73,26 +70,17 @@ sealed class WindowsVoice : ISystemVoice}}-/// Hold the talk key (right Ctrl unless changed) to talk, anywhere. RegisterHotKey can't see a key-/// being let go, so this is a low-level keyboard hook. A modifier talk key is passed on to other-/// apps and only counts held alone: another key pressed meanwhile (Ctrl C) ends the press as-/// Interrupted. Any other talk key (Caps Lock, F13…) is kept from them. (Alt can't be one: released-/// alone it opens the window's menu, and right Alt is AltGr on many keyboards.)sealed class PushToTalk : IDisposable{- /// The key in use, read by every label that names it.public static TalkKey.Key Current { get; set; } = TalkKey.Named(null);public static string Label => Strings.L(Current.Label);const int WhKeyboardLl = 13, WmKeyDown = 0x100, WmKeyUp = 0x101, WmSysKeyDown = 0x104, WmSysKeyUp = 0x105;- readonly HookProc proc; // held, or the GC collects it and Windows calls freed memory+ readonly HookProc proc;readonly IntPtr hook;bool down, combo;public event Action? Pressed, Released, Interrupted;- /// Choosing a new talk key: the next key pressed comes here (its virtual-key code) and until- /// then no key reaches any app. Whoever sets it clears it when the choosing ends.public Action<int>? Capture;- // 同声传译 on: with it off a Caps Lock or F5 talk key goes on working as itself.readonly Func<bool> enabled;public PushToTalk(Func<bool> enabled)@@ -137,12 +125,8 @@ sealed class PushToTalk : IDisposable[DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern IntPtr GetModuleHandle(string? name);}-/// Installs VB-Cable: VB-Audio's own package, downloaded when the user asks, checked against the-/// pinned SHA-256 before anything runs, then its installer with Windows' admin prompt.static class CableInstaller{- /// 电脑没声了? in onboarding and settings: shown while the cable holds the speaker, one button- /// gives a real speaker back.public static FrameworkElement SpeakerStrip(Window owner, Action changed){var text = new StackPanel { Children = { Ui.Text(Strings.L("电脑没声了?"), 14, Palette.Ink), Ui.Text(Strings.L("Windows 把播放设备改成了 CABLE Input"), 13, Palette.WarnIcon) } };@@ -175,9 +159,7 @@ static class CableInstaller}catch (Exception e) { Log.Debug($"cable: extract failed {e.GetType().Name}"); return Result.Failed; }progress(Strings.L("正在安装…"));- // Windows may hand the new cable the default speaker and mic (CableDefaults): remember them.var before = Endpoints.Defaults();- // The x64 installer also puts the ARM64 driver on Windows on ARM.var setup = Path.Combine(dir, Environment.Is64BitOperatingSystem ? "VBCABLE_Setup_x64.exe" : "VBCABLE_Setup.exe");try{@@ -196,8 +178,6 @@ static class CableInstallerreturn Result.Failed;}- /// Windows switches the default a moment after the endpoint appears, not always at once: look- /// for a few seconds.internal static async Task GiveBackDefaults(Dictionary<string, string> before){for (int i = 0; i < 8; i++)diff --git a/windows/src/Cicada/SystemAudioTap.cs b/windows/src/Cicada/SystemAudioTap.csindex 954791a..1c50735 100644--- a/windows/src/Cicada/SystemAudioTap.cs+++ b/windows/src/Cicada/SystemAudioTap.cs@@ -2,10 +2,6 @@ using System.Runtime.InteropServices;namespace Cicada.App;-/// Everything the PC plays except Cicada itself: WASAPI process loopback with this process's tree-/// excluded (Windows 10 2004+), the counterpart of the Mac's Core Audio process tap. Asks Windows-/// for 16 kHz mono directly and falls back to 48 kHz stereo converted here. The capture thread-/// only hands buffers on; ListenEngine queues them.sealed class SystemAudioTap : IAudioSource{const string LoopbackDevice = "VAD\\Process_Loopback";@@ -14,8 +10,6 @@ sealed class SystemAudioTap : IAudioSourceThread? thread;volatile bool running;- /// Only Cicada's own sound instead of everything else: the onboarding's test sound, which the- /// normal tap leaves out by design. Proves process loopback works on this PC all the same.public bool OnlySelf { get; init; }public event Action<short[]>? Samples;public event Action<string?>? Ended;@@ -34,8 +28,6 @@ sealed class SystemAudioTap : IAudioSourcethread?.Join(1000);}- /// A capture that breaks (the Windows Audio service restarting, a driver or a dock's audio- /// resetting) opens again; only one that keeps failing ends listening, with its reason.void Run(){int failures = 0;@@ -67,7 +59,6 @@ sealed class SystemAudioTap : IAudioSourcevar fmt = WaveFormat.Pcm16(r, c);var p = Marshal.AllocHGlobal(Marshal.SizeOf<WaveFormat>());Marshal.StructureToPtr(fmt, p, false);- // A 1 s buffer (100 ns units): a capture thread held up for a moment must not lose audio.int hr = client.Initialize(0, StreamLoopback | StreamEventCallback | AutoConvertPcm | SrcDefaultQuality, 10_000_000, 0, p, IntPtr.Zero);Marshal.FreeHGlobal(p);if (hr == 0) { rate = r; channels = c; break; }@@ -86,8 +77,6 @@ sealed class SystemAudioTap : IAudioSourceMarshal.ThrowExceptionForHR(client.Start());try{- // Loopback sends nothing while nothing plays, so we feed silence ourselves (LoopbackGap:- // only after a second without a packet, or a late packet splits its sentence in two).var lastPacket = DateTime.UtcNow; var fedUntil = lastPacket;int gaps = 0;while (running)@@ -103,11 +92,8 @@ sealed class SystemAudioTap : IAudioSource}continue;}- // How long packets stall here (a VM): a stall over LoopbackGap.Late puts a gap in a sentence.var waited = (DateTime.UtcNow - lastPacket).TotalMilliseconds;if (waited >= 300 && fedUntil == lastPacket) Log.Debug($"tap: packets late by {waited:F0} ms");- // A failing call (the device invalidated, the audio service gone) must throw: ending the- // loop quietly would feed silence for the rest of the meeting.while (true){Marshal.ThrowExceptionForHR(capture.GetNextPacketSize(out var packet));@@ -146,7 +132,7 @@ sealed class SystemAudioTap : IAudioSourceIAudioClient Activate(){- var p = new ActivationParams { ActivationType = 1, TargetProcessId = (uint)Environment.ProcessId, ProcessLoopbackMode = OnlySelf ? 0 /* include tree */ : 1 /* exclude tree */ };+ var p = new ActivationParams { ActivationType = 1, TargetProcessId = (uint)Environment.ProcessId, ProcessLoopbackMode = OnlySelf ? 0 : 1 };int size = Marshal.SizeOf<ActivationParams>();var blob = Marshal.AllocHGlobal(size);Marshal.StructureToPtr(p, blob, false);@@ -168,7 +154,6 @@ sealed class SystemAudioTap : IAudioSourcestatic extern int ActivateAudioInterfaceAsync(string path, ref Guid riid, ref PropVariantBlob activationParams,IActivateAudioInterfaceCompletionHandler handler, out IActivateAudioInterfaceAsyncOperation op);- // Must be agile, or activation fails with E_ILLEGAL_METHOD_CALL.[ComVisible(true)]sealed class Completion : IActivateAudioInterfaceCompletionHandler, IAgileObject{diff --git a/windows/src/Cicada/TrayFlyout.cs b/windows/src/Cicada/TrayFlyout.csindex 4cdde39..aaa7f74 100644--- a/windows/src/Cicada/TrayFlyout.cs+++ b/windows/src/Cicada/TrayFlyout.cs@@ -6,9 +6,6 @@ using static Cicada.Strings;namespace Cicada.App;-/// Left-click on the tray icon when not listening (while listening the click shows or hides the-/// notes window instead, which sits in the same corner): Cicada's home, the counterpart of the-/// Mac's menu bar panel. It rises above the notification area and goes away when it loses focus.sealed class TrayFlyout : Window{readonly Controller app;@@ -19,7 +16,6 @@ sealed class TrayFlyout : Windowpublic TrayFlyout(Controller app){this.app = app;- // The Mac panel's 16-point corners and soft shadow (Ui.Floating), so a transparent window.WindowStyle = WindowStyle.None; AllowsTransparency = true; Background = Brushes.Transparent;Topmost = true; ShowInTaskbar = false; ResizeMode = ResizeMode.NoResize;Width = 360 + 2 * Ui.ShadowRoom; SizeToContent = SizeToContent.Height; FontFamily = Palette.Font; Title = L("知了");@@ -31,8 +27,6 @@ sealed class TrayFlyout : WindowIsVisibleChanged += (_, _) => { if (IsVisible) clock.Start(); else clock.Stop(); };}- /// Opens, or closes when it is already open (a second click on the icon). A click that just- /// closed it by taking focus away doesn't reopen it straight away.public void Toggle(){if (IsVisible) { Hide(); return; }@@ -44,7 +38,6 @@ sealed class TrayFlyout : WindowActivate();}- /// Next to the notification area, on whichever edge the taskbar is.void Anchor(){var area = SystemParameters.WorkArea;@@ -56,9 +49,6 @@ sealed class TrayFlyout : Windowvoid Do(Action act) { Hide(); act(); }- // The Mac's menu bar panel (Views.swift › MenuPanel): who and how it is, the one big button,- // the choices made before a meeting on grey rows, 同声传译, what shows while listening, and two- // buttons at the bottom. Two weights only (Palette.Strong).FrameworkElement Build(){var listen = app.Listen;@@ -76,8 +66,6 @@ sealed class TrayFlyout : Windowvar head = Ui.Spread(title, Ui.IconButton(Icons.Gear, L("打开设置"), () => Do(app.ShowSettings), Palette.Body, 36, 18));stack.Children.Add(head);- // A newer release (the Mac's UpdateBanner), right under the header: Cicada downloads the- // installer, checks it and opens it.if (app.Updates.Available is { } update){var size = update.Size > 0 ? $"{update.Size / 1_048_576.0:0} MB · " : "";@@ -100,8 +88,6 @@ sealed class TrayFlyout : Windowstack.Children.Add(strip);}- // The AI service needs the user (can't reach it, the key, money, a model gone or deaf; the- // Mac's AIServiceStrip). On Windows the service hears too, so it comes before 开始听.if (app.AIProblem() is { } ai){var text = Ui.Stack(2, Ui.Text(ai.Title, 13, Palette.AccentText, Palette.Strong), Ui.Text(ai.Detail, 11, Palette.Secondary));@@ -113,11 +99,9 @@ sealed class TrayFlyout : Windowstack.Children.Add(new Border { Background = Palette.AccentPale, CornerRadius = new CornerRadius(9), Padding = new Thickness(10), Margin = new Thickness(0, 14, 0, 0), Child = dock });}- // The one thing to dovar main = new StackPanel { Margin = new Thickness(0, 18, 0, 0) };if (listen.Listening && app.Ending is { } p){- // About to end by itself (MeetingEndingStrip, compact): the panel takes no focus either.var strip = Ui.Stack(3, Ui.Text(app.EndingTitle(p), 13, Palette.Ink, FontWeights.Bold),Ui.Text(LF("%lld 秒后结束会议并整理纪要", Controller.EndingLeft(p)), 12, Palette.Secondary));var keep = Ui.Row(8, Ui.Button(L("继续记录"), app.KeepRecording, Ui.Kind.Primary, height: 32),@@ -150,11 +134,9 @@ sealed class TrayFlyout : Window}stack.Children.Add(main);- // The choice people change before a meetingvar spoken = Languages.Targets.FirstOrDefault(t => t.Code == Languages.FromSystem(System.Globalization.CultureInfo.CurrentUICulture.Name))?.Code;var target = s.Target == "system" ? spoken ?? "zh-Hans" : s.Target;stack.Children.Add(Gap(ChoiceRow(L("翻译成"), Ui.TargetName(target), s.Target == "system" ? L("跟随系统") : null, Ui.TargetOptions(), s.Target, app.SetTarget), 12));- // 麦克风 (the Mac panel's row): turning it on mid-meeting adds the room to the same meeting.var micText = Ui.Stack(2, Ui.Text(L("麦克风"), 14, Palette.Ink, Palette.Strong, wrap: false),Ui.Text(app.MicOn ? L("桌边的人说话也会记下") : L("关着 · 只听电脑声音"), 12, Palette.Secondary));stack.Children.Add(Gap(Ui.Spread(micText, MicButton(app, panel: true)), 14));@@ -169,7 +151,6 @@ sealed class TrayFlyout : Windowstack.Children.Add(new Border { Background = Palette.AccentPale, CornerRadius = new CornerRadius(9), Padding = new Thickness(10), Margin = new Thickness(0, 10, 0, 0), Child = dock });}- // 同声传译stack.Children.Add(Rule());var cable = Endpoints.Cable() is not null;var speakState = s.Speak && cable && app.Ling.HasKey@@ -181,7 +162,6 @@ sealed class TrayFlyout : WindowUi.Text(LF("对方听到 %@", Ui.TargetName(app.Speak.Target)), 12, Palette.Secondary, wrap: false)));stack.Children.Add(Gap(new Border { BorderBrush = Palette.Line, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(12), Padding = new Thickness(12, 10, 12, 10), Child = talk, Opacity = s.Speak ? 1 : 0.7 }, 10));- // What shows while listeningstack.Children.Add(Rule());stack.Children.Add(Ui.Text(L("听的时候显示"), 14, Palette.Ink, Palette.Strong, wrap: false));var tiles = new System.Windows.Controls.Primitives.UniformGrid { Rows = 1, Margin = new Thickness(0, 10, 0, 0) };@@ -189,7 +169,6 @@ sealed class TrayFlyout : Windowtiles.Children.Add(Tile("subtitles", L("字幕条"), BarPicture()));stack.Children.Add(tiles);- // Two buttons along the bottomstack.Children.Add(Rule());var foot = new Grid();foot.ColumnDefinitions.Add(new ColumnDefinition());@@ -203,9 +182,6 @@ sealed class TrayFlyout : Windowreturn stack;}- /// 打开麦克风 / 关闭麦克风, the same switch in the panel and the notes window (MicButton on the- /// Mac): in the panel the ink button while off, a quiet one while on; in the notes window a pale- /// one beside 结束, tinted while on.public static Button MicButton(Controller app, bool panel){var on = app.MicOn;@@ -219,19 +195,16 @@ sealed class TrayFlyout : Windowstatic FrameworkElement Rule() => new Border { Height = 1, Background = Palette.Line, Margin = new Thickness(0, 16, 0, 16) };- /// The shortcut inside the ink button: a keycap drawn for a dark ground.static FrameworkElement DarkKey(string keys) => new Border{BorderBrush = new SolidColorBrush(Color.FromArgb(0x55, 0xFF, 0xFF, 0xFF)), BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(5),Padding = new Thickness(6, 1, 6, 2), Child = Ui.Text(keys, 12, Palette.NightText, wrap: false),};- /// A grey row: what it is on the left in grey, the choice in ink with maybe a pale tag, a chevron;- /// a click opens the choices.FrameworkElement ChoiceRow(string label, string value, string? tag, IEnumerable<(string value, string label)> options, string selected, Action<string> changed){var name = Ui.Text(label, 13, Palette.Secondary, wrap: false);- name.MinWidth = 76; name.Margin = new Thickness(0, 0, 12, 0); // "Translate to" runs wider than 翻译成+ name.MinWidth = 76; name.Margin = new Thickness(0, 0, 12, 0);var shown = Ui.Row(8, Ui.Text(value, 15, Palette.Ink, wrap: false));if (tag is not null) ((StackPanel)shown).Children.Add(Gap2(Ui.Badge(tag)));var chevron = Ui.Icon(Icons.Chevron, 14, Palette.Secondary, stroke: 1.6);@@ -257,7 +230,6 @@ sealed class TrayFlyout : Windowstatic FrameworkElement Gap2(FrameworkElement e) { e.Margin = new Thickness(8, 0, 0, 0); return e; }}- /// One of 纪要 / 字幕条: a small picture of what shows on screen, the chosen one outlined in ink.FrameworkElement Tile(string view, string label, FrameworkElement picture){var on = app.Settings.View == view;@@ -284,8 +256,6 @@ sealed class TrayFlyout : WindowHorizontalAlignment = HorizontalAlignment.Center, Child = inside,};- /// A button surface with the bound background and border; hover darkens or dims it. The theme's- /// Button style aligns left, so every button built on it says Stretch itself.static ControlTemplate Surface(double radius, bool dim){var t = new ControlTemplate(typeof(Button));diff --git a/windows/src/Cicada/Ui.cs b/windows/src/Cicada/Ui.csindex b4df557..6de86b2 100644--- a/windows/src/Cicada/Ui.cs+++ b/windows/src/Cicada/Ui.cs@@ -8,9 +8,6 @@ using static Cicada.Strings;namespace Cicada.App;-/// Cicada's palette on Windows 11 shapes: the Mac's ground, ink and one orange for "live", plus the-/// Fluent roles (strokes, subtle fills, info bars). Orange text and fills use darker shades of the-/// accent so they pass 4.5:1; #E8552B itself is only for the live dot.static class Palette{static SolidColorBrush B(uint rgb) { var x = new SolidColorBrush(Color.FromRgb((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb)); x.Freeze(); return x; }@@ -31,8 +28,6 @@ static class Palettepublic static readonly SolidColorBrush AccentFill = B(0xC9441D);public static readonly SolidColorBrush AccentPale = B(0xFDEBE4);public static readonly SolidColorBrush AccentText = B(0xA8370F);- /// 回放: a line's time as a link, the line at the playhead (the Mac's accentPale), the player- /// bar's box, and a line under the pointer that a click would play (the Mac's raised).public static readonly SolidColorBrush TimeLink = B(0xB33B14);public static readonly SolidColorBrush Playing = B(0xFCEDE7);public static readonly SolidColorBrush PlayerFill = B(0xF5F6F8);@@ -47,22 +42,14 @@ static class Palettepublic static readonly SolidColorBrush Night = B(0x15171C);public static readonly SolidColorBrush Toggle = B(0xD9DBE0);public static readonly SolidColorBrush FieldLine = B(0xD1D4D9);- /// The Mac's ground for windows (onboarding, settings), a shade lighter than the panels' fill.public static readonly SolidColorBrush Page = B(0xF7F8FA);- /// The Mac's pale error and warning washes.public static readonly SolidColorBrush NightText = B(0xB4B9C2);- /// 说话人 1, 2, 3… cycling after four (the Mac's SpeakerColor): not the accent (live, and 你),- /// distinct in lightness, all ≥ 4.5:1 on white.static readonly SolidColorBrush[] inks = [B(0x0F7B6C), B(0x7A4CC2), B(0xB03A7A), B(0x8A5A00)];public static SolidColorBrush Speaker(int n) => inks[(Math.Max(1, n) - 1) % inks.Length];public static readonly FontFamily Font = new("Segoe UI Variable Text, Segoe UI, Microsoft YaHei UI, Yu Gothic UI, Malgun Gothic");- /// Two weights only. Microsoft YaHei UI, which draws all the Chinese, has Regular and Bold and- /// nothing between: a semibold label renders Bold and the window reads black and cramped. So- /// levels come from size and grey, and Bold is for headings and the one main button.public static readonly FontWeight Strong = FontWeights.Bold;}-/// Stroke icons on a 20×20 grid (Fluent's outline style), drawn with Ui.Icon.static class Icons{public const string Close = "M5,5 L15,15 M15,5 L5,15";@@ -108,11 +95,9 @@ static class UiFontFamily = Palette.Font,};- // The Mac's headings are bold, not semibold: they carry the page.public static TextBlock Heading(string text, double size = 15) => Text(text, size, Palette.Ink, FontWeights.Bold);public static TextBlock Helper(string text) => Text(text, 12, Palette.Secondary);- /// A 20×20 stroke icon, or a filled one, scaled to `size`.public static FrameworkElement Icon(string data, double size = 16, Brush? color = null, bool fill = false, double stroke = 1.5){var path = new System.Windows.Shapes.Path { Data = Geometry.Parse(data), StrokeLineJoin = PenLineJoin.Round, StrokeStartLineCap = PenLineCap.Round, StrokeEndLineCap = PenLineCap.Round };@@ -146,7 +131,6 @@ static class Uireturn s;}- /// A row whose last child sits at the right edge: [left…] ··· [right].public static DockPanel Spread(UIElement left, UIElement right){var d = new DockPanel { LastChildFill = false };@@ -157,9 +141,6 @@ static class Uipublic enum Kind { Standard, Primary, Accent, Subtle, Danger, Pale }- /// The Mac's buttons (Views.swift › SoftButton and friends): Standard is a soft grey fill with no- /// border, Primary ink, Accent live orange (开始听 only), Subtle no fill until hover, Danger red,- /// Pale the 结束 pill. Corners 10, or 12 on the big ones; filled labels bold, the rest regular.public static Button Button(string label, Action onClick, Kind kind = Kind.Standard, string? icon = null, double height = 36, bool iconFill = false, bool iconAfter = false){var (bg, fg) = kind switch@@ -190,9 +171,6 @@ static class Uireturn b;}- /// A split button, as Windows' own: the label does the usual thing, the chevron beside it opens- /// a menu of the alternatives. One soft-grey button with a hairline between the halves; `Open`- /// is the chevron's click, for the debug pipe.public static (FrameworkElement Button, Action Open) SplitButton(string label, Action onClick, IReadOnlyList<(string label, Action act)> items, double height = 32){Button Half(UIElement content, Thickness padding)@@ -211,7 +189,6 @@ static class Uifor (int i = 0; i < 3; i++) g.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });Grid.SetColumn(line, 1); Grid.SetColumn(arrow, 2);g.Children.Add(main); g.Children.Add(line); g.Children.Add(arrow);- // The halves are square; the whole is clipped to the usual 10-point corners.g.SizeChanged += (_, e) => g.Clip = new RectangleGeometry(new Rect(e.NewSize), 10, 10);void Open(){@@ -228,14 +205,11 @@ static class Uireturn (g, Open);}- /// A square icon-only button with a tooltip and an accessible name.public static Button IconButton(string icon, string name, Action onClick, Brush? color = null, double size = 40, double iconSize = 16, bool fill = false, bool onDark = false){var b = new Button{Content = Icon(icon, iconSize, color ?? Palette.Body, fill), Width = size, Height = size, Background = Brushes.Transparent,- // No padding: the Fluent theme's 11 a side leaves a 34-wide button 12 for a 16 icon, and- // the Viewbox clips its right edge.BorderThickness = new Thickness(0), Cursor = Cursors.Hand, ToolTip = name, Padding = new Thickness(0),};b.Template = Template(plain: true, onDark: onDark, radius: 10);@@ -246,7 +220,6 @@ static class Uistatic void AutomationName(UIElement e, string name) => System.Windows.Automation.AutomationProperties.SetName(e, name);- /// Rounded, no Windows 7 chrome. Plain buttons get a grey wash on hover; filled ones dim a little.public static ControlTemplate Template(bool plain, bool onDark = false, Type? target = null, double radius = 10, bool soft = false){var t = new ControlTemplate(target ?? typeof(Button));@@ -265,7 +238,6 @@ static class Uivar pressed = new Trigger { Property = ButtonBase.IsPressedProperty, Value = true };if (plain){- // A soft button darkens to the line grey; a subtle one gets the ground's fill.var wash = onDark ? new SolidColorBrush(Color.FromArgb(0x26, 0xFF, 0xFF, 0xFF)) : soft ? Palette.Line : (Brush)Palette.Mica;hover.Setters.Add(new Setter(Border.BackgroundProperty, wash, "bg"));pressed.Setters.Add(new Setter(Border.BackgroundProperty, onDark ? new SolidColorBrush(Color.FromArgb(0x40, 0xFF, 0xFF, 0xFF)) : Palette.Line, "bg"));@@ -281,8 +253,6 @@ static class Uireturn t;}- /// A text link in the accent's text shade. Acts on press and marks it handled, so the notes- /// window doesn't start a drag instead.public static TextBlock LinkText(string label, Action onClick, double size = 13){var t = Text(label, size, Palette.AccentText, wrap: false);@@ -295,10 +265,6 @@ static class Uipublic static FrameworkElement Dot(Brush color, double size = 8) => new Ellipse { Width = size, Height = size, Fill = color, VerticalAlignment = VerticalAlignment.Center };- /// The live dot, dimming and brightening once a second while listening. Not a WPF animation:- /// the notes panel and subtitle bar are transparent, shadowed windows that WPF redraws in- /// software, and an animation redraws them every frame (3.5 cores in a VM, starving the very- /// audio being listened to). One step a second costs one redraw a second.public static FrameworkElement LiveDot(double size = 8){var dot = new Ellipse { Width = size, Height = size, Fill = Palette.Live, VerticalAlignment = VerticalAlignment.Center };@@ -318,18 +284,14 @@ static class Uireturn t;}- /// A small pill: 对方可见 and the like.public static Border Badge(string text, Brush? bg = null, Brush? fg = null) => new(){Background = bg ?? Palette.AccentPale, CornerRadius = new CornerRadius(9), Padding = new Thickness(9, 3, 9, 4), VerticalAlignment = VerticalAlignment.Center,Child = Text(text, 12, fg ?? Palette.AccentText, wrap: false),};- /// Room around a floating window's card for its shadow.public const double ShadowRoom = 14;- /// A floating window's surface as on the Mac: 16-point corners and a soft shadow. The shadow is- /// a few translucent rings, not a blur effect: a blur is redrawn in software on every change.public static FrameworkElement Floating(UIElement content, Brush background, double radius = 16, bool dark = false){var grid = new Grid { Margin = new Thickness(ShadowRoom - 6, ShadowRoom - 4, ShadowRoom - 6, ShadowRoom - 8) };@@ -358,7 +320,6 @@ static class UiPadding = padding ?? new Thickness(20), Child = child,};- /// The design's check box: an ink box, not the theme's blue one; still a CheckBox for keys and readers.public static CheckBox Check(string label, bool on, Action<bool> changed){var box = new Border { Width = 18, Height = 18, CornerRadius = new CornerRadius(4) };@@ -383,7 +344,6 @@ static class Uipublic enum Severity { Error, Warning }- /// Fluent's InfoBar: an icon, a bold title, one line of body, and up to one action.public static Border InfoBar(Severity severity, string? title, string body, UIElement? action = null){var error = severity == Severity.Error;@@ -410,14 +370,9 @@ static class Uipublic enum Tone { Waiting, NeedsYou, Info }- /// #C98A00: WarnIcon is too dark to tell from the text at 6 px.static readonly SolidColorBrush waitingDot = Frozen(Color.FromRgb(0xC9, 0x8A, 0x00));static SolidColorBrush Frozen(Color c) { var b = new SolidColorBrush(c); b.Freeze(); return b; }- /// A service in trouble, said the same way wherever it shows (Views.swift › StatusLine): a dot,- /// what waits for what · what still works, and at most one action. Colour sits in the dot only,- /// so a passing wait doesn't read as a fault: yellow waits and comes back by itself, red needs- /// you, grey is just so you know.public static Border StatusLine(Tone tone, string text, (string Title, Action Run)? action = null){var dot = Dot(tone switch { Tone.Waiting => waitingDot, Tone.NeedsYou => Palette.Danger, _ => Palette.Tertiary }, 6);@@ -449,7 +404,6 @@ static class Ui};}- /// The Mac's switch: an ink track when on, a grey one when off, a white knob; no 开/关 beside it.public static FrameworkElement Switch(bool on, Action<bool> changed, string name){var knob = new Ellipse { Width = 18, Height = 18, Fill = Brushes.White, Stroke = new SolidColorBrush(Color.FromArgb(0x1A, 0, 0, 0)), StrokeThickness = 0.5 };@@ -467,9 +421,6 @@ static class Uireturn toggle;}- /// A segmented control: one choice of a few, the chosen one raised on a grey track.- /// No blur on the raised one (the notes panel redraws in software): a white fill and a hairline.- /// `fill` spreads the options over the full width in equal parts, as the notes panel's 纪要 / 文字记录.public static FrameworkElement Segmented(IEnumerable<(string value, string label)> options, string selected, Action<string> changed, bool fill = false, double height = 30){var track = new Border { Background = Palette.Mica, CornerRadius = new CornerRadius(10), Padding = new Thickness(3) };@@ -498,7 +449,6 @@ static class Uireturn track;}- /// Pivot-style tabs: text with an ink underline on the chosen one.public static FrameworkElement Tabs(IEnumerable<(string value, string label)> options, string selected, Action<string> changed, double size = 14){var row = new StackPanel { Orientation = Orientation.Horizontal };@@ -516,8 +466,6 @@ static class Uireturn row;}- /// A pop-up button, as the Mac's pickers: the chosen value on a soft fill with a chevron, and a- /// menu of the choices, the chosen one checked. (Windows' own combo box looks out of place here.)public static Button Choice(IEnumerable<(string value, string label)> options, string selected, Action<string> changed, double width = 200){var list = options.ToList();@@ -550,10 +498,8 @@ static class Uireturn b;}- /// A text field as on the Mac: white, 10-point corners, a light line, generous padding.public static Border Field(Control box) => FieldFrame(StyleField(box), box);- /// The frame alone, around anything (a field with a button inside it); `focus` lights it.public static Border FieldFrame(UIElement child, Control? focus = null){var border = new Border { Background = Brushes.White, BorderBrush = Palette.FieldLine, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(10), Height = 40, Padding = new Thickness(12, 0, 12, 0), Child = child };@@ -565,7 +511,6 @@ static class Uireturn border;}- /// The text control itself, without Windows' frame.public static Control StyleField(Control box){box.BorderThickness = new Thickness(0);@@ -581,8 +526,6 @@ static class Uireturn box;}- /// A key as printed on the keyboard (右 Ctrl, Ctrl Alt L): white, a hairline, a thicker bottom- /// edge. `big` is the one the user is asked to press.public static Border Keycap(string label, bool big = false) => new(){Background = Brushes.White, BorderBrush = Palette.ControlStroke, BorderThickness = new Thickness(1, 1, 1, big ? 3 : 2),@@ -590,13 +533,8 @@ static class UiChild = Text(label, big ? 15 : 12, Palette.Ink, big ? FontWeights.Bold : FontWeights.Normal, wrap: false),};- /// Shortcut text ("Ctrl+Alt+L") as keycaps: Ctrl Alt L.public static Border Shortcut(string keys) => Keycap(keys.Replace('+', ' '));- /// A window without Windows' title bar, as the Mac's: the content runs to the top edge and only- /// the three caption buttons stay, drawn by us at the top right. WindowChrome keeps what the- /// system frame gave: dragging by the top strip, snap, resizing at the edges, and on Windows 11- /// DWM's rounded corners and shadow (a one-pixel glass frame).public static FrameworkElement Frameless(Window w, FrameworkElement content, bool resizable = true, double captionHeight = 44, Action? close = null){System.Windows.Shell.WindowChrome.SetWindowChrome(w, new System.Windows.Shell.WindowChrome@@ -635,7 +573,6 @@ static class Uibuttons.Children.Add(Caption("M5.5,5.5 H14.5 V14.5 H5.5 Z", L("最大化"), () => w.WindowState = w.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized));buttons.Children.Add(Caption(Icons.Close, L("关闭"), close ?? w.Close, danger: true));var root = new Grid { Children = { content, buttons } };- // Maximized, Windows puts the frame's invisible border off screen; keep the content inside.void Fit() => root.Margin = w.WindowState == WindowState.Maximized ? new Thickness(7) : new Thickness(0);w.StateChanged += (_, _) => Fit();return root;@@ -647,7 +584,6 @@ static class Uipublic static string TargetName(string code) => Languages.Targets.FirstOrDefault(t => t.Code == code)?.Name ?? code;- /// The name of a spoken language as people write it ("English", "日本語").public static string SpokenName(string? code){if (code is null) return "";@@ -666,7 +602,6 @@ static class AppIconcatch { return null; }}- /// The icon at `size`, from the .ico's largest frame (its first is 16 px and blurs when scaled up).public static Image Small(double size = 16) { var i = new Image { Source = size > 20 ? Large ?? Image : Image, Width = size, Height = size, VerticalAlignment = VerticalAlignment.Center }; RenderOptions.SetBitmapScalingMode(i, BitmapScalingMode.HighQuality); return i; }static readonly System.Windows.Media.Imaging.BitmapSource? Large = LoadLarge();diff --git a/windows/src/Cicada/VoiceCloneDialog.cs b/windows/src/Cicada/VoiceCloneDialog.csindex aca3b6d..6c9ea02 100644--- a/windows/src/Cicada/VoiceCloneDialog.cs+++ b/windows/src/Cicada/VoiceCloneDialog.cs@@ -7,9 +7,6 @@ using static Cicada.Strings;namespace Cicada.App;-/// 我自己的声音's recording, the Mac's VoiceCloneSheet in a Windows 11 dialog: read a passage for-/// 10–15 s (it stops by itself at 15) → Ming hears what was said → listen to the recording and to the-/// clone speaking the room's language → 用这个声音 keeps it. Nothing is kept until then.sealed class VoiceCloneDialog{enum Phase { Idle, Recording, Checking, Failed, Ready }@@ -27,7 +24,6 @@ sealed class VoiceCloneDialogDateTime started;double seconds;bool saved, playingOriginal, playingClone;- // Updated ten times a second while recording, without rebuilding the dialog.ColumnDefinition? levelOn, levelOff, timeOn, timeOff;TextBlock? clock;@@ -53,8 +49,6 @@ sealed class VoiceCloneDialogwindow.Closed += (_, _) => { StopRecording(); app.StopPreview(); };}- /// Shows the dialog; true when a recording was kept. `recorded`: a WAV taken as just read (the- /// debug pipe's `ownvoice dialog <wav>`, for a machine without a microphone).public static bool Open(Controller app, string target, byte[]? recorded){var d = new VoiceCloneDialog(app, target, app.OpenSettings);@@ -84,7 +78,6 @@ sealed class VoiceCloneDialogstack.Children.Add(Spaced(new Border { Background = Palette.Mica, CornerRadius = new CornerRadius(10), Padding = new Thickness(16, 14, 16, 14), Child = passage }, 16));stack.Children.Add(Spaced(Ui.Text(L("这是我自己的声音。只在我说话时用它替我翻译。"), 12, Palette.Secondary), 12));- // The level and the time read so far; the range under them.var level = Bar(Palette.Live, 6, out levelOn, out levelOff);clock = Ui.Text(Clock(seconds), 13, Palette.Ink, FontWeights.SemiBold, wrap: false);clock.Margin = new Thickness(12, 0, 0, 0);@@ -153,7 +146,6 @@ sealed class VoiceCloneDialogawait Check(Wav.Bytes(pcm));}- /// The Mac's VoiceRecorder.finish: long enough, heard, and read at a meeting's pace.async Task Check(byte[] recorded){wav = recorded;@@ -161,7 +153,6 @@ sealed class VoiceCloneDialogphase = Phase.Checking;Render();var (outcome, text, trimmed) = await VoiceCloneCheck.Check(recorded, app.Transcribe);- // What is played back, previewed and kept: the reading without the quiet at its ends.wav = trimmed;seconds = Math.Max(0, trimmed.Length - 44) / 32000.0;transcript = text;@@ -188,7 +179,6 @@ sealed class VoiceCloneDialogFrameworkElement Review(){var stack = new StackPanel();- // A way out without keeping it: this step's two buttons are 重录 and 用这个声音.var close = Ui.IconButton(Icons.Close, L("关闭"), window.Close, Palette.Secondary, size: 32, iconSize: 14);close.VerticalAlignment = VerticalAlignment.Top;close.Margin = new Thickness(8, -4, -8, 0);@@ -264,7 +254,6 @@ sealed class VoiceCloneDialogstatic string Clock(double s) => $"{(int)s / 60}:{(int)s % 60:00}";- /// A bar filled from the left by two star columns; Show sets the share.static Grid Bar(Brush fill, double height, out ColumnDefinition on, out ColumnDefinition off, Brush? track = null){var grid = new Grid { Height = height, VerticalAlignment = VerticalAlignment.Center };@@ -294,7 +283,6 @@ sealed class VoiceCloneDialogif (clock is not null) clock.Text = Clock(seconds);}- /// Two equal buttons, the main one on the right (Dialogs.Show's band).static Grid Buttons(FrameworkElement cancel, FrameworkElement primary){var grid = new Grid();diff --git a/windows/src/Cicada/Wasapi.cs b/windows/src/Cicada/Wasapi.csindex 725d875..52d903f 100644--- a/windows/src/Cicada/Wasapi.cs+++ b/windows/src/Cicada/Wasapi.cs@@ -2,22 +2,18 @@ using System.Runtime.InteropServices;namespace Cicada.App;-/// Audio devices by name, and plain WASAPI capture and playback on them: the microphone (what I-/// say), the virtual cable's "CABLE Input" (what the meeting hears), the speakers (previews).-/// SystemAudioTap is the other half, the process loopback.static class Endpoints{public enum Flow { Render = 0, Capture = 1 }public sealed record Device(string Id, string Name, string Description);- /// Active devices: Name is "扬声器 (Realtek…)", Description the short "CABLE Input".public static List<Device> All(Flow flow){var list = new List<Device>();try{var e = (IMMDeviceEnumerator)new MMDeviceEnumerator();- Marshal.ThrowExceptionForHR(e.EnumAudioEndpoints((int)flow, 1 /* ACTIVE */, out var all));+ Marshal.ThrowExceptionForHR(e.EnumAudioEndpoints((int)flow, 1, out var all));all.GetCount(out var n);for (uint i = 0; i < n; i++){@@ -35,25 +31,20 @@ static class Endpointstry{var e = (IMMDeviceEnumerator)new MMDeviceEnumerator();- if (e.GetDefaultAudioEndpoint((int)flow, 1 /* eMultimedia */, out var d) != 0) return null;+ if (e.GetDefaultAudioEndpoint((int)flow, 1, out var d) != 0) return null;d.GetId(out var id);return new Device(id, Prop(d, 14) ?? id, Prop(d, 2) ?? "");}catch { return null; }}- /// The virtual cable's playback side, which meeting apps hear as the "CABLE Output" mic.public static Device? Cable() => All(Flow.Render).FirstOrDefault(d => d.Description == VirtualCable.InputName || d.Name.StartsWith(VirtualCable.InputName));public static Device? CableOutput() => All(Flow.Capture).FirstOrDefault(d => d.Description == VirtualCable.OutputName || d.Name.StartsWith(VirtualCable.OutputName));- /// Any end of VB-Cable, "CABLE In 16ch" too (the pack installs it beside CABLE Input, and- /// Windows can make it the default speaker as well).public static bool IsCable(Device d) =>d.Description is VirtualCable.InputName or VirtualCable.OutputName || d.Name.StartsWith(VirtualCable.InputName) || d.Name.StartsWith(VirtualCable.OutputName)|| d.Name.Contains("VB-Audio Virtual Cable", StringComparison.OrdinalIgnoreCase);- /// Every default (CableDefaults' "<flow>/<role>" keys): the playback and recording device for- /// games and system sounds, for media and for calls.public static Dictionary<string, string> Defaults(){var map = new Dictionary<string, string>();@@ -68,14 +59,10 @@ static class Endpointsreturn map;}- /// Ids of the cable's two ends, for CableDefaults.public static HashSet<string> CableIds() => [.. All(Flow.Render).Concat(All(Flow.Capture)).Where(IsCable).Select(d => d.Id)];- /// What the user hears through is the cable: they hear nothing.public static bool SpeakerIsCable() => Default(Flow.Render) is { } d && IsCable(d);- /// Makes `id` the default for one role, as the Sound control panel does. IPolicyConfig isn't- /// documented, but it is what Windows' own panel calls and has stayed put since Windows 7.public static bool SetDefault(string id, int role){try@@ -88,8 +75,6 @@ static class Endpointscatch (Exception ex) { Log.Debug($"endpoints: set default failed {ex.GetType().Name}"); return false; }}- /// Back to a real speaker for every role (CableDefaults.Speaker): when nothing from before the- /// install was remembered.public static bool RestoreSpeaker(){if (CableDefaults.Speaker(All(Flow.Render).Select(d => (d.Id, IsCable(d)))) is not { } id) { Log.Debug("cable: no other speaker"); return false; }@@ -98,7 +83,6 @@ static class Endpointsreturn ok && !SpeakerIsCable();}- /// A microphone, never the cable's own output (that would be the room hearing itself).public static Device? Microphone(){var d = Default(Flow.Capture);@@ -106,22 +90,19 @@ static class Endpointsreturn All(Flow.Capture).FirstOrDefault(x => x.Description != VirtualCable.OutputName && !x.Name.StartsWith(VirtualCable.OutputName));}- /// 会议室: the microphone that hears the table (RoomMicPlan): the default, unless that is the- /// virtual cable or a Bluetooth headset.public static Device? RoomMic(){var inputs = new List<(Device d, RoomMicPlan.Input plan)>();try{var e = (IMMDeviceEnumerator)new MMDeviceEnumerator();- Marshal.ThrowExceptionForHR(e.EnumAudioEndpoints((int)Flow.Capture, 1 /* ACTIVE */, out var all));+ Marshal.ThrowExceptionForHR(e.EnumAudioEndpoints((int)Flow.Capture, 1, out var all));all.GetCount(out var n);for (uint i = 0; i < n; i++){all.Item(i, out var d);d.GetId(out var id);var device = new Device(id, Prop(d, 14) ?? id, Prop(d, 2) ?? "");- // PKEY_Device_EnumeratorName: BTHENUM, BTHHFENUM, BTHLEDEVICE for Bluetooth.var bus = Prop(d, 24) ?? "";var virtualCable = device.Description == VirtualCable.OutputName || device.Name.StartsWith(VirtualCable.OutputName);inputs.Add((device, new RoomMicPlan.Input(id, bus.StartsWith("BTH", StringComparison.OrdinalIgnoreCase), virtualCable)));@@ -147,7 +128,7 @@ static class Endpointsvar e = (IMMDeviceEnumerator)new MMDeviceEnumerator();Marshal.ThrowExceptionForHR(e.GetDevice(id, out var d));var iid = typeof(IAudioClient).GUID;- Marshal.ThrowExceptionForHR(d.Activate(ref iid, 23 /* CLSCTX_ALL */, IntPtr.Zero, out var o));+ Marshal.ThrowExceptionForHR(d.Activate(ref iid, 23, IntPtr.Zero, out var o));return (IAudioClient)o;}@@ -162,7 +143,7 @@ static class Endpointsreturn p;}- internal const uint AutoConvert = 0x80000000 | 0x08000000; // AUTOCONVERTPCM | SRC_DEFAULT_QUALITY+ internal const uint AutoConvert = 0x80000000 | 0x08000000;// MARK: COM@@ -202,7 +183,6 @@ static class Endpoints[ComImport, Guid("870AF99C-171D-4F9E-AF0D-E63DF40C2BC9")] class PolicyConfigClient { }- /// Only SetDefaultEndpoint is called; the slots before it keep the vtable in order.[ComImport, Guid("F8679F50-850A-41CF-9C72-430F290290C8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]interface IPolicyConfig{@@ -257,8 +237,6 @@ interface IAudioRenderClient[PreserveSig] int ReleaseBuffer(uint frames, uint flags);}-/// Records one device at 16 kHz mono (Windows converts) until Stop: the mic while the key is held,-/// or CABLE Output in tests (what the meeting would hear).sealed class DeviceRecorder{readonly string id;@@ -266,7 +244,6 @@ sealed class DeviceRecorderThread? thread;volatile bool running;public string? Error { get; private set; }- /// The last packet's peak, 0–1 (scaled as the Mac's recorder meter): for a level bar.public volatile float Level;public DeviceRecorder(string id) { this.id = id; }@@ -322,7 +299,6 @@ sealed class DeviceRecorder}catch (Exception e){- // 0x80070005: Windows' microphone privacy switch is off for desktop apps.Error = e.HResult == unchecked((int)0x80070005) ? "denied" : e.GetType().Name;Log.Debug($"recorder: failed 0x{e.HResult:X8}");ready.Set();@@ -331,9 +307,6 @@ sealed class DeviceRecorder}}-/// Plays a sentence on one device: the virtual cable for the room, the speakers for a preview.-/// Chunks are queued as they stream in and played as soon as the first arrives; End waits for the-/// last sample to be heard.sealed class DeviceSpeaker : ISpeechSink{readonly Func<Endpoints.Device?> device;@@ -343,7 +316,6 @@ sealed class DeviceSpeaker : ISpeechSinkTaskCompletionSource? done;int rate;public string? DeviceName { get; private set; }- /// The device was there but wouldn't play (or vanished): nothing, or not all, was heard.public bool Failed { get; private set; }public bool Stopped => stopped;@@ -351,7 +323,6 @@ sealed class DeviceSpeaker : ISpeechSinkpublic bool Ready => device() is not null;- /// 试听's 停止: what is queued is dropped and End returns; later chunks are ignored.public void Stop(){stopped = true; ending = true;@@ -402,8 +373,6 @@ sealed class DeviceSpeaker : ISpeechSink{lock (queue) { if (queue.Count > 0) { pending = queue.Dequeue(); offset = 0; } }}- // Half a sample left over can't be played: without this the loop spun on it forever,- // End never returned and the talk key stayed on 正在说给对方听….if (pending.Length - offset == 1) offset = pending.Length;if (offset < pending.Length && room > 0){diff --git a/windows/src/Cicada/WinVoiceprint.cs b/windows/src/Cicada/WinVoiceprint.csindex 1fa992f..948ebb6 100644--- a/windows/src/Cicada/WinVoiceprint.cs+++ b/windows/src/Cicada/WinVoiceprint.cs@@ -2,8 +2,6 @@ using Windows.AI.MachineLearning;namespace Cicada.App;-/// The voiceprint model on Windows' built-in Windows ML (no runtime to ship). Loaded on first use-/// from inside the exe; one inference at a time, about 0.15 s for a 5 s line.sealed class WinVoiceprint : IVoiceprint{readonly object one = new();@@ -41,7 +39,6 @@ sealed class WinVoiceprint : IVoiceprintusing var res = typeof(WinVoiceprint).Assembly.GetManifestResourceStream("voiceprint.onnx") ?? throw new FileNotFoundException("voiceprint.onnx");var bytes = new byte[res.Length];res.ReadExactly(bytes);- // Written through a DataWriter: a .NET stream wrapper would close the WinRT stream with it.var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();using (var w = new Windows.Storage.Streams.DataWriter(stream.GetOutputStreamAt(0))){diff --git a/windows/src/Cicada/WordListSettings.cs b/windows/src/Cicada/WordListSettings.csindex d7a0c48..b1c36e8 100644--- a/windows/src/Cicada/WordListSettings.cs+++ b/windows/src/Cicada/WordListSettings.cs@@ -7,19 +7,13 @@ using static Cicada.Strings;namespace Cicada.App;-/// 设置 › 词表 (the Mac's WordListSettings.swift): the switches for 改正听错的词, and the word list-/// itself: each word, what it has been heard as, where it came from and how often it fixed a line.-/// Everything is edited in place; changes count from the next sentence on.sealed partial class SettingsWindow{string wordQuery = "";- /// A deleted word, shown in its place with 撤销 for a few seconds.(Vocabulary.Term Term, int Index)? deleted;DateTime deletedAt;- /// The word whose spelling is being changed, and what was typed as a heard form per word.string? renaming;readonly Dictionary<string, string> newHeard = [];- /// A heard form typed under a word that another word already has: whose it should be.(string Word, string Heard, string Owner)? conflict;FrameworkElement[] WordCards()@@ -78,7 +72,6 @@ sealed partial class SettingsWindowrows.Add(row);}var q = Vocabulary.Key(wordQuery);- // Most recently useful first, then the rest newest first.var shown = Enumerable.Reverse(terms).OrderByDescending(t => t.Used ?? DateTimeOffset.MinValue).Where(t => q.Length == 0 || Vocabulary.Key(t.Word).Contains(q) || t.Heard.Any(h => Vocabulary.Key(h).Contains(q)));foreach (var t in shown) rows.Add(WordRow(t, terms));@@ -91,7 +84,6 @@ sealed partial class SettingsWindowvoid FocusSearch(){- // The page is drawn again on each key: give the search box its focus back.var box = FindChild<TextBox>(scroll, b => System.Windows.Automation.AutomationProperties.GetName(b) == L("搜索词表"));if (box is not null) { box.Focus(); box.CaretIndex = box.Text.Length; }}@@ -107,8 +99,6 @@ sealed partial class SettingsWindowreturn null;}- /// One word: its spelling (a click changes it), what it was heard as (× takes one off, a field- /// adds one), where it came from, how often it fixed a line, and delete.FrameworkElement WordRow(Vocabulary.Term t, List<Vocabulary.Term> all){FrameworkElement word;@@ -147,7 +137,6 @@ sealed partial class SettingsWindow{BorderBrush = Palette.FieldLine, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(5), Margin = new Thickness(0, 2, 4, 2),Child = new Grid { Children = { add, hint } },- // Only while pointed at (or typed in): hidden, it would still take room and wrap the forms.Visibility = add.Text.Length > 0 ? Visibility.Visible : Visibility.Collapsed,};add.BorderThickness = new Thickness(0); add.Background = Brushes.Transparent;@@ -222,8 +211,6 @@ sealed partial class SettingsWindowRender();}- /// 粘贴导入: many words at once, each line one word, heard forms after "=". The counts follow- /// what is pasted, and the button says how many go in.void ImportWords(){var dialog = new Window@@ -299,10 +286,8 @@ sealed partial class SettingsWindowimporting = null;}- /// The paste dialog while it is open (the debug pipe types into it).Window? importing;- /// Debug: paste `text` into an open 粘贴导入, or open it first.public void DebugImport(string text){if (importing is null) { Dispatcher.BeginInvoke(ImportWords); Dispatcher.BeginInvoke(() => DebugImport(text), System.Windows.Threading.DispatcherPriority.ApplicationIdle); return; }diff --git a/windows/tests/Cicada.Tests/Program.cs b/windows/tests/Cicada.Tests/Program.csindex 4238fbb..42fd44f 100644--- a/windows/tests/Cicada.Tests/Program.cs+++ b/windows/tests/Cicada.Tests/Program.cs@@ -1,6 +1,3 @@-// Unit tests for Cicada.Core: `scripts/test.sh` (or `dotnet run --project tests/Cicada.Tests`).-// Each test is a method below; a failed Check throws and the runner reports it. No network:-// LingClient runs against a fake handler.using System.Net;using System.Reflection;using System.Text;@@ -175,8 +172,8 @@ static class Tests{var calls = MicUse.Calls([("C:#Program Files#Zoom#bin#Zoom.exe", 0), ("C:#Users#me#AppData#Roaming#Zoom#bin#Zoom.exe", 0),- ("C:#Program Files (x86)#Tencent#WeMeet#wemeetapp.exe", 133_000_000_000), // used earlier, closed now- ("C:#Program Files#Google#Chrome#Application#chrome.exe", 0), // a browser isn't a meeting app+ ("C:#Program Files (x86)#Tencent#WeMeet#wemeetapp.exe", 133_000_000_000),+ ("C:#Program Files#Google#Chrome#Application#chrome.exe", 0),("MSTeams_8wekyb3d8bbwe", 0),("C:#Program Files (x86)#WXWork#WXWork.exe", 0),]);@@ -272,8 +269,6 @@ static class TestsCheck(JsonNode.DeepEquals(JsonNode.Parse(mac), JsonNode.Parse(Json.Write(s))), "written back unchanged");}- /// 改正听错的词: a Mac record whose lines carry fixes reads and writes back byte for byte in- /// value, and the line shows (and exports) the fixed words while `src` stays what was heard.public static void KeepsTheMacsFixes(){const string mac = """@@ -361,7 +356,6 @@ static class Testspublic static void ExportMarksTalkKeyLinesAsInterpreted(){- // TranscriptExport.speakerName on the Mac: a "me" line was said with the talk key (同传).var s = new Session { Title = "会议 1月1日 10:00", StartedAt = DateTimeOffset.Now, Lines =[new TranscriptLine { Id = "h1-1", T = 1, Src = "Can we ship?", Dst = "能发布吗?", SrcLang = "en", DstLang = "zh-CN" },new TranscriptLine { Id = "m1", T = 5, Speaker = "me", Src = "可以", Dst = "Yes", SrcLang = "zh-CN", DstLang = "en" }] };@@ -372,7 +366,6 @@ static class Testspublic static void KeepsTheMacsImportAndRoomFields(){- // A Mac record of an imported room recording (a line by the room mic), plus a key no version knows yet.const string mac = """{"endedAt":"2026-01-01T02:10:00Z","futureKey":{"a":[1,2]},"hasAudio":true,"id":"20260101-100000","importing":false,"lines":[{"dstLang":"en","id":"h1-1","speaker":"them","src":"你好","srcLang":"zh-CN","t":2.5,"via":"room"}],"room":true,"sourceFile":"周会.m4a","sourcePath":"/Users/x/周会.m4a","startedAt":"2026-01-01T02:00:00Z","title":"会议 1月1日 10:00"}""";@@ -385,7 +378,6 @@ static class Tests// MARK: 保存会议录音- /// Records what it is given; the "file" is a list of samples, and Rewrap copies the partial file.sealed class FakeAudio : IAudioFiles{public readonly List<short> Samples = [];@@ -400,7 +392,6 @@ static class Tests}}- /// Loopback as it really is: sound while something plays, nothing at all in between.sealed class GappySource(params (double seconds, bool sound)[] parts) : IAudioSource{public event Action<short[]>? Samples;@@ -424,19 +415,18 @@ static class Testsreturn m;}- /// 电脑和会议室: the room mic goes into the meeting's one recording at its place on the clock (#19).public static void TheRoomIsMixedIntoTheRecordingWhereItWasHeard(){var audio = new FakeAudio();var mix = new RoomMix(audio.Open(Path.Combine(Path.GetTempPath(), $"mix-{Guid.NewGuid()}.aac"))!);- for (int i = 0; i < 30; i++) // 3 s of the PC at 1000; the room at 500 from 1 s to 2 s, half a second late+ for (int i = 0; i < 30; i++){mix.Write(Enumerable.Repeat((short)1000, 1600).ToArray());if (i >= 15 && i < 25) mix.Room(Enumerable.Repeat((short)500, 1600).ToArray(), (i - 5) * 1600);}mix.Write(Enumerable.Repeat((short)30000, 1600).ToArray());mix.Room(Enumerable.Repeat((short)30000, 1600).ToArray(), 3 * 16000);- mix.Room(Enumerable.Repeat((short)30000, 1600).ToArray(), 4 * 16000); // after the PC's last sample+ mix.Room(Enumerable.Repeat((short)30000, 1600).ToArray(), 4 * 16000);mix.Close();Check(audio.Closed, "closed");Equal(4 * 16000 + 1600, audio.Samples.Count, "the PC's 3.1 s, then silence up to the room's last words");@@ -457,7 +447,7 @@ static class Testsvar main = new ListenEngine(ling, new Translator(ling), store, new NotesEngine(ling, store), settings);var room = new ListenEngine(ling, new Translator(ling), store, new NotesEngine(ling, store), settings, roomSide: true);var pc = new GappySource((0.5, true), (2.5, false));- var mic = new GappySource((2.0, true)); // a mic sends all the time, quiet or not+ var mic = new GappySource((2.0, true));var ended = new TaskCompletionSource();pc.Ended += _ => ended.TrySetResult();main.Start(pc);@@ -479,7 +469,6 @@ static class Testspublic static async Task TheRecordingKeepsTheMeetingsClock(){- // 0.5 s of sound, 2.5 s of nothing (loopback while the PC is silent), 0.5 s of sound.var fake = new Fake(_ => Reply("{}"));var ling = Client(fake);var store = new SessionStore { Audio = new FakeAudio() };@@ -521,7 +510,6 @@ static class TestsEqual(600.0, audio.Rewraps[0].until, "a meeting that ended by itself is cut where it ended");Equal(m4a, Recording.Playable(store.Get(s.Id)!), "it plays");- // A meeting the app didn't get to close: finished at the next launch.var t = store.Begin(DateTimeOffset.Parse("2026-02-02T02:00:00Z"));store.Append(t.Id, new TranscriptLine { Id = "h1-1", Src = "hi", SrcLang = "en", DstLang = "zh-CN" });store.Flush();@@ -535,7 +523,6 @@ static class Testspublic static void AdtsFramesAreSplitAndACutOneDropped(){- // Two AAC-LC 16 kHz mono frames of 10 and 12 bytes (7-byte headers), then half a third.static byte[] Frame(int payload){int length = 7 + payload;@@ -572,7 +559,6 @@ static class Tests{var gate = new VoiceGate();Equal(0.004, gate.Threshold, "before the room is known");- // Half a minute of a fan at 0.003 with a voice at 0.02 now and then.for (int i = 0; i < 30 * 33; i++) gate.Voiced(i % 10 == 0 ? 0.02 : 0.003, 0.03);Check(Math.Abs(gate.Threshold - 0.006) < 1e-9, $"twice the room's noise, got {gate.Threshold}");Check(gate.Voiced(0.008, 0.03), "a quiet voice across the table");@@ -584,7 +570,6 @@ static class Testspublic static void ARoomMicHearsQuietSpeechTheFixedLineMisses(){- // A voice at -48 dBFS (0.004 RMS) over a quieter floor: under the fixed 0.01 line.var rng = new Random(1);short[] Noise(double seconds, double rms) => Enumerable.Range(0, (int)(seconds * Segmenter.Rate)).Select(_ => (short)((rng.NextDouble() * 2 - 1) * rms * 1.7 * 32768)).ToArray();short[] Voice(double seconds, double rms) => Enumerable.Range(0, (int)(seconds * Segmenter.Rate)).Select(i => (short)(Math.Sin(i * 0.05) * Math.Sin(i * 0.0007) * rms * 2 * 32768)).ToArray();@@ -651,7 +636,6 @@ static class TestsEqual("ja", Translator.ParseHeard("lang: ja-JP\noriginal: はい\ntranslation: 是", "zh-CN", null)!.Lang, "labels in any case");}- // Same cases as the Android and Linux ports' noise tests.public static void DropsNoise(){foreach (var o in new[] { "嗯。", "Mm.", "uh, um", "呃呃呃呃呃", "嗯,嗯,嗯,嗯,嗯,嗯,嗯,嗯,嗯,嗯,嗯,嗯。", string.Concat(Enumerable.Repeat("滴答", 50)),@@ -697,8 +681,6 @@ static class TestsEqual("Done.", Translator.CleanTranslation("<think>x</think>Done.", "en"), "leaked reasoning");}- /// While the check says the service is unreachable, a sentence doesn't wait on its timeout- /// every time: one in 15 s still tries it, the rest go straight to Google.public static async Task AnUnreachableServiceIsTriedOnceIn15Seconds(){var fake = new Fake(_ => Reply("你好"));@@ -729,14 +711,11 @@ static class Tests// MARK: Segmenter- /// A 300 Hz tone that swells and fades four times a second like syllables; steady when not, or- /// rising and falling by `wobble` twice a second like a fan.static short[] Tone(double seconds, double amp = 0.3, bool syllables = true, double wobble = 0) =>Enumerable.Range(0, (int)(seconds * 16000)).Select(i => (short)(Math.Sin(2 * Math.PI * 300 * i / 16000)* (syllables ? 0.55 + 0.45 * Math.Sin(2 * Math.PI * 4 * i / 16000) : 1 + wobble * Math.Sin(2 * Math.PI * 0.5 * i / 16000))* amp * 32767)).ToArray();static short[] Silence(double seconds) => new short[(int)(seconds * 16000)];- /// Typing: a key click every 0.2 s, 6 ms of decaying crackle peaking near -12 dBFS (scripts/vad-clips.py).static short[] Keys(double seconds){var x = Silence(seconds);@@ -744,18 +723,15 @@ static class Testsfor (int k = 0; k < 96; k++) x[at + k] = (short)(0.25 * Math.Exp(-k / 24.0) * (k % 2 == 1 ? 1 : -1) * 32767);return x;}- /// A sine at `freq` that swells and fades four times a second like syllables.static short[] Hz(double freq, double seconds, double amp) =>Enumerable.Range(0, (int)(seconds * 16000)).Select(i => (short)(Math.Sin(2 * Math.PI * freq * i / 16000)* (0.55 + 0.45 * Math.Sin(2 * Math.PI * 4 * i / 16000)) * amp * 32767)).ToArray();- /// One word on its own ("Thanks."): a 300 Hz tone that swells from nothing and fades back.static short[] Word(double seconds, double amp){int n = (int)(seconds * 16000);return Enumerable.Range(0, n).Select(i => (short)(Math.Sin(2 * Math.PI * 300 * i / 16000) * Math.Pow(Math.Sin(Math.PI * i / n), 2) * amp * 32767)).ToArray();}- /// A 7 kHz tone faded in and out over 0.3 s: crosses zero like a hiss, swells like a word.static short[] Hiss(double seconds, double amp){int n = (int)(seconds * 16000);@@ -783,7 +759,6 @@ static class Testspublic static void CutsLongSpeechAtItsQuietestMoment(){- // 7 s of speech, a 0.3 s dip (shorter than a pause), 4 s more: one cut, at the dip.var list = Cut(Tone(7), Tone(0.3, 0.004), Tone(4), Silence(1));Equal(2, list.Count, "split in two");Check(list[0].Seconds is > 6.9 and < 7.4, $"cut inside the dip, got {list[0].Seconds}");@@ -812,8 +787,6 @@ static class TestsEqual(1, Cut(Silence(1), Word(1.2, 0.022), Silence(1)).Count, "one smooth run of voice on its own, no dips inside");Equal(1, Cut(Silence(1), Tone(0.5, 0.022, syllables: false), Tone(0.15, 0.0025, syllables: false), Silence(1)).Count,"a quiet word whose fade (an \"s\", a breath) falls under gate / 4 still swells: a meeting's quiet opening line");- // Wherever the 30 ms frames fall (a few ms more lead-in), a quiet phrase with brief dips between- // its words stays a word, and a hum or a faded hiss in silence stays out.short[] Flat(double s, double a) => Tone(s, a, syllables: false);short[] phrase = [.. Flat(0.35, 0.022), .. Flat(0.04, 0.0055), .. Flat(0.4, 0.022), .. Flat(0.04, 0.0055), .. Flat(0.35, 0.022), .. Flat(0.06, 0.0025)];for (int ms = 0; ms < 30; ms += 2)@@ -831,13 +804,10 @@ static class Testspublic static void LateLoopbackPacketsDontSplitASentence(){- // A VM held packets back for 0.3-0.7 s: silence went in front of them and lines split- // mid-phrase. The tap now waits a second before it calls a stall silence.Equal(0, LoopbackGap.Silence(0.3, 0.3), "a 300 ms stall is no silence");Equal(0, LoopbackGap.Silence(0.9, 0.9), "nor is a 900 ms one");Equal(16000, LoopbackGap.Silence(1.0, 1.0), "a second of nothing is: all of it goes in");Equal(1600, LoopbackGap.Silence(1.1, 0.1), "then what has passed since");- // The segmenter fed like the tap: speech, a 0.3 s break between words, a 0.5 s stall.var whole = Cut(Tone(2), Silence(0.3), Tone(2), Silence(1));Equal(1, whole.Count, "one sentence");var stalled = Cut(Tone(2), Silence(0.3), new short[LoopbackGap.Silence(0.5, 0.5)], Tone(2), Silence(1));@@ -904,8 +874,6 @@ static class TestsEqual(2.0, next.Todos[0].T, "to-dos too");}- /// A heard form only a fix wrote ("platform" for 平台) isn't one: it would teach the translator- /// and the next fix the same mistake.public static void NotesTermsKeepOnlyFormsTheRecognizerWrote(){var l = new TranscriptLine { Id = "a", Speaker = "them", Src = "我们 twoty 平台", SrcLang = "zh-CN", DstLang = "en", Fixes = [new LineFix("平台", "platform")] };@@ -915,7 +883,6 @@ static class Testspublic static void NotesAndExportNameSpeakersLikeTheMac(){- // Two voices, five substantive lines each: 说话人 1 (voice 7) and 说话人 2 (voice 9).var lines = Enumerable.Range(0, 10).Select(i => new TranscriptLine { Id = $"h{i}-1", T = i * 10, Src = $"we will ship line {i}", Voice = i % 2 == 0 ? 7 : 9, SrcLang = "en", DstLang = "zh-CN" }).ToList();var s = new Session { Title = "会议 1月1日 10:00", StartedAt = DateTimeOffset.Now, Lines = lines,VoiceNames = new() { ["7"] = "George" }, VoiceGuesses = new() { ["9"] = new VoiceGuess { Name = "Anna" } } };@@ -964,10 +931,8 @@ static class Testspublic static void LiveNotesKeepFrozenTopicsAndTakeTheReplysTail(){var old = Enumerable.Range(0, 5).Select(i => Topic(i * 100, $"t{i}")).ToList();- // The model echoed everything, renamed the current topic and added one.var reply = new List<NoteTopic> { Topic(0, "t0"), Topic(100, "t1 改"), Topic(300, "t3"), Topic(400, "t4 改"), Topic(500, "t5") };Equal("t0,t1,t2,t3,t4 改,t5", Titles(NotesEngine.Merge(old, 3, reply)), "frozen kept, the reply's tail after them");- // The first update over many lines: nothing to echo, so every topic is the model's own.var own = Enumerable.Range(0, 5).Select(i => Topic(i * 100, $"t{i}")).ToList();Equal(Titles(own), Titles(NotesEngine.Merge([], 0, own)), "nothing frozen keeps every topic");Equal(Titles(own), Titles(NotesEngine.Merge([Topic(0, "t0")], 0, own)), "nothing frozen, with old topics");@@ -981,8 +946,6 @@ static class Testspublic static void FullLiveNotesJoinTheShortestSettledPair(){- // Twelve topics, t3 and t4 the shortest neighbours (t3 to t5 is 100 s): a new topic- // still starts, and those two become one.double[] starts = [0, 100, 200, 300, 330, 400, 600, 700, 800, 900, 1000, 1100];var old = starts.Select((s, i) => Topic(s, $"t{i}", [$"a{i}", $"b{i}", $"c{i}"])).ToList();var merged = NotesEngine.Merge(old, 10, [Topic(1000, "t10"), Topic(1100, "t11"), Topic(1200, "t12")]);@@ -1014,7 +977,6 @@ static class Testspublic static void LongMeetingsSplitByTime(){- // A line every 10 s: 90 min stays whole, 4 h becomes four parts of an hour.var whole = NotesEngine.Parts(TenSecondLines(540));Check(whole.Count == 1 && whole[0].Equals(0..540), "90 minutes stays whole");var four = NotesEngine.Parts(TenSecondLines(1440));@@ -1029,8 +991,6 @@ static class TestsCheck(ten.All(t => kept.Any(k => k.Title.Split(" / ").Contains(t.Title))), "every topic joined, none dropped");Equal("0", string.Join(",", NotesEngine.Thinned(ten, 1, 3000).Select(t => t.Start)), "one");Equal(3, NotesEngine.Thinned(ten.Take(3).ToList(), 4, 3000).Count, "fewer than asked stay");- // A 2.5-hour meeting's last part, asked for 2 topics, came back with 3: the budget topic's- // end as its own. Kept first and last, the budget topic at 125 min was lost.var part = new List<NoteTopic> { Topic(6000, "营销发布安排", ["a"]), Topic(7500, "预算评审", ["b"]), Topic(8982, "预算评审(续)", ["c"]) };var two = NotesEngine.Thinned(part, 2, 8990);Equal("营销发布安排,预算评审", Titles(two), "the topic kept over its continuation");@@ -1049,7 +1009,6 @@ static class TestsCheck(p.Contains("part 2 of 3"), "which part");Check(p.Contains("[L241 40:00 对方] line 240") && !p.Contains("[L238 "), "the transcript's own line numbers");Check(p.Contains("This part ran 39:50"), "the part's length");- // Each of three parts gets two of the eight topics.Check(p.Contains("use at most 2 topics"), "the part's share of the topics");var merge = NotesEngine.MergePrompt(["{\"summary\":\"a\"}", "{\"summary\":\"b\"}"], all, "English", voices: false);Check(merge.Contains("Part 2 of 2:\n{\"summary\":\"b\"}"), "the parts' notes");@@ -1070,7 +1029,6 @@ static class Tests// MARK: Strings- /// The notes store a to-do's owner as the transcript's Chinese label; it shows and exports in the UI language.public static void TodoOwnersShowInTheUILanguage(){var res = Path.Combine(AppContext.BaseDirectory, "Resources");@@ -1164,7 +1122,6 @@ static class Testsreturn new LingClient(key, fake, clock: clock);}- /// The start gate's time, moved on by each wait instead of waiting (one request at a time).sealed class FakeClock : GateClock{public DateTime Now = new(2026, 11, 5, 12, 0, 0, DateTimeKind.Utc);@@ -1207,8 +1164,6 @@ static class Testspublic static async Task LingHeardAudioRidesOutARunOf429s(){- // Ling's 429s come in runs (two in a row lost a line with one retry): heard audio backs off- // 1, 2, 4 s and gets through; text translation fails at once so the caller can fall back.int calls = 0;var clock = new FakeClock();var fake = new Fake(_ => Interlocked.Increment(ref calls) <= 3 ? Busy() : Reply("LANG: en\nORIGINAL: Hi.\nTRANSLATION: 嗨。"));@@ -1242,7 +1197,6 @@ static class Testsvar fake = new Fake(_ => Interlocked.Increment(ref calls) == 1 ? Busy("5") : Reply("ok"));Equal("ok", await Client(fake, clock).Chat("c", "i", Priority.Notes), "answered after the wait");Check(clock.Waits[0] is >= 5 and <= 5.5, $"waited as asked, got {clock.Waits[0]}");- // Asked to wait minutes: an outage, so the line goes now rather than after it.var outage = new Fake(_ => Busy("120"));try { await Client(outage, new FakeClock()).Chat("c", "i", Priority.Translate, model: LingClient.AudioModel, audio: [1]); throw new Exception("waited"); }catch (LingException e) { Equal(LingException.Kind.RateLimited, e.Failure, "given up"); }@@ -1260,11 +1214,9 @@ static class Testsvar fake = new Fake(_ => Interlocked.Increment(ref calls) == 1 ? Busy() : Reply("notes"));var ling = Client(fake, clock);try { await ling.Chat("first", "i", Priority.Translate); } catch (LingException) { }- // A translation that wouldn't retry fails at once, without spending a request on the limit…try { await ling.Chat("second", "i", Priority.Translate); throw new Exception("sent during the pause"); }catch (LingException e) { Equal(LingException.Kind.RateLimited, e.Failure, "busy"); }Equal(1, fake.Calls.Count, "nothing sent");- // …and one that would waits at the gate until the pause is over, then goes.Equal("notes", await ling.Chat("notes", "i", Priority.Notes), "notes after the pause");Check(clock.Waits.Sum() is >= 1 and <= 1.5, $"held for the pause, got {string.Join(",", clock.Waits)}");}@@ -1306,7 +1258,6 @@ static class Testsvar ling = Client(fake);var first = ling.Chat("first", "i", Priority.Notes);await Task.Delay(20);- // Queued while the gate is closed: the translation goes before the earlier notes call.var notes = ling.Chat("notes", "i", Priority.Notes);await Task.Delay(20);var translate = ling.Chat("translate", "i", Priority.Translate);@@ -1373,7 +1324,6 @@ static class Testspublic static void TheRoomsCopyOfARemoteSentenceIsAnEcho(){- // EchoMatchTests on the Mac, case for case.List<EchoMatch.Heard> online = [H("Revenue grew by 12%, mostly from the new region.", 10, 14)];Check(EchoMatch.IsEcho(H("revenue grew by 12% mostly from new region", 10.3, 14.2), online), "heard worse, a word lost");Check(!EchoMatch.IsEcho(H("I think we should check the numbers for Europe first", 11, 15), online), "room speech is kept");@@ -1412,7 +1362,6 @@ static class Tests{double now = 0;var g = new EchoGate(() => now);- // Music: loud, and no words for EchoGate.Music seconds.for (; now < EchoGate.Music - 1; now += 0.1) g.Hold();Check(g.Closed && !g.PlayingMusic, "no words yet: still taken for speech");for (; now < EchoGate.Music + 1; now += 0.1) g.Hold();@@ -1422,7 +1371,6 @@ static class Testsg.HeardWords(); g.Hold(); now += 0.1;Check(g.Closed, "words close it again");- // Headphones: the room mic stays at its floor while the computer plays.now = 1000;var h = new EchoGate(() => now);Check(h.Echo, "echo until measured");@@ -1431,7 +1379,6 @@ static class TestsCheck(!h.Echo, "no echo measured with headphones");h.Hold(); now += 0.1;Check(!h.Closed, "the room stays open with headphones");- // Speakers: the mic hears the computer.now += 100;for (var t = 0; t < 60; t++) { h.Hold(); now += 0.05; h.RoomLevel(0.03, 0.1); now += 0.05; }for (var t = 0; t < 60; t++) { now += 0.1; h.RoomLevel(0.001, 0.1); }@@ -1460,8 +1407,6 @@ static class Testspublic static async Task TheRoomSideDropsTheSpeakersAndKeepsTheTable(){- // The computer plays one sentence; the room mic hears it again from the speakers, then- // someone at the table says something else.const string remote = "LANG: en\nORIGINAL: Revenue grew by 12%, mostly from the new region.\nTRANSLATION: 收入增长了 12%,主要来自新区域。";const string table = "LANG: en\nORIGINAL: I think we should check the numbers for Europe first\nTRANSLATION: 我觉得应该先看欧洲的数字";var fake = new Fake(body =>@@ -1512,7 +1457,6 @@ static class Testspublic static async Task NeverJoinsTwoVoices(){- // Two halves of one "sentence" (no full stop, 0.4 s apart) in two different voices.var fake = new Fake(body =>{if (!body.Contains("Ming-3.0-audio-flash")) return Reply("{}");@@ -1526,7 +1470,6 @@ static class Testsvar store = new SessionStore();var engine = new ListenEngine(ling, new Translator(ling), store, new NotesEngine(ling, store), new AppSettings { Target = "zh-CN" }){- // Told apart by length: the first stretch is 2.5 s, the second 3 s.Voiceprint = new FakePrint(s => s.Length < 50_000 ? Unit(1, 0, 0) : Unit(0, 1, 0)),};var path = Path.Combine(Path.GetTempPath(), $"cicada-voices-{Environment.ProcessId}.wav");@@ -1612,7 +1555,6 @@ static class TestsLingClient.Spacing = 0.01;try{- // Ming hears and translates; Ming's voice streams two chunks.var spoken = new List<string>();var fake = new Fake(body =>{@@ -1633,7 +1575,6 @@ static class TestsCheck(sink.Rate == 24000 && sink.Chunks.Count == 2, "Ming's 24 kHz stream reaches the virtual mic");Equal("ming", engine.LastVoice, "voiced by Ming");- // No translation (Ming echoes the original, Ling and Google fail): nothing reaches the room.var echo = new Fake(body => body.Contains(LingClient.AudioModel)? Reply("LANG: zh-CN\nORIGINAL: 我们周三能测完吗?\nTRANSLATION: 我们周三能测完吗?"): new HttpResponseMessage(HttpStatusCode.InternalServerError));@@ -1643,7 +1584,6 @@ static class TestsCheck(await e2.Speak(Wav.Bytes(Tone(1)), quiet) is null, "no translation, nothing said");Check(quiet.Chunks.Count == 0 && voice2.Calls == 0 && e2.State == SpeakEngine.Phase.Failed, "and no voice at all");- // The virtual mic went away during the press: nothing is played anywhere (never the speakers).var gone = new Sink { Ready = false };var voice3 = new NoVoice();var e3 = Speaker(Client(fake), voice3, new AppSettings { SpeakFrom = "zh-CN" });@@ -1668,12 +1608,9 @@ static class Testsreturn new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("data:{\"type\":\"speech.audio.done\"}\n\n") };});var engine = Speaker(Client(fake), new NoVoice(), new AppSettings { SpeakFrom = "zh-CN" });- // A press nobody spoke in: not even sent to the service.Check(await engine.Speak(Wav.Bytes(new short[16000 * 3]), new Sink()) is null && asked == 0, "a silent press sends nothing");Check(engine.State == SpeakEngine.Phase.Idle && engine.Problem is null, "and says nothing about it");- // Ming heard only 嗯: nothing goes out.Check(await engine.Speak(Wav.Bytes(Tone(1)), new Sink()) is null && asked == 1, "a filler alone isn't sent");- // The computer played through the press: its echo, not me.double now = 0;var log = new LoudnessLog(() => now);engine.Echo = log;@@ -1681,13 +1618,11 @@ static class Testsfor (var i = 0; i < 30; i++) { log.Add(true); now += 0.1; }Check(await engine.Speak(Wav.Bytes(Tone(1)), new Sink()) is null && asked == 1, "pressed while the meeting played: not sent");Equal(Strings.L("对方在说话时说的,没有说出去"), engine.Problem, "and the bar says why");- // The same press through Windows' echo cancellation: the meeting is taken out, I am sent.reply = "LANG: zh-CN\nORIGINAL: 我们周三能测完吗?\nTRANSLATION: Can we finish testing by Wednesday?";engine.BeginRecording();for (var i = 0; i < 30; i++) { log.Add(true); now += 0.1; }Equal("Can we finish testing by Wednesday?", await engine.Speak(Wav.Bytes(Tone(1)), new Sink(), echoCancelled: true), "pressed while the meeting played, echo cancelled: sent");Check(asked == 2 && engine.Problem is null, "and heard by the service");- // Echo cancellation doesn't let a silent press through.engine.BeginRecording();for (var i = 0; i < 30; i++) { log.Add(true); now += 0.1; }Check(await engine.Speak(Wav.Bytes(new short[16000 * 3]), new Sink(), echoCancelled: true) is null && asked == 2, "a silent press still sends nothing");@@ -1739,14 +1674,12 @@ static class Testspublic static async Task ListenEngineEndToEndWithAFakeMing(){- // Two stretches of "speech", told apart by length (1 s, then 1.6 s); the fake Ming- // answers the first one slower, and lines still come out in order.var fake = new Fake(body =>{if (body.Contains("Ming-3.0-audio-flash")){var url = JsonNode.Parse(body)!["messages"]![1]!["content"]![0]!["audio_url"]!["url"]!.GetValue<string>();- bool first = url.Length < 60_000; // base64 of ~1.3 s at 32 kB/s, with lead-in and tail+ bool first = url.Length < 60_000;if (first) Thread.Sleep(400);return Reply(first ? "LANG: en\nORIGINAL: First one.\nTRANSLATION: 第一句。" : "LANG: en\nORIGINAL: Second one.\nTRANSLATION: 第二句。");}@@ -1802,7 +1735,6 @@ static class TestsEqual(null, UpdateChecker.ChecksumFor("ff00 Cicada-1.1.0-Windows-ARM64.exe", "Cicada-1.1.0-Windows-x64.exe"), "other file");}- /// The in-app download: the installer is kept only when it matches checksums.txt.public static async Task UpdateDownloadChecksTheInstaller(){var dir = Directory.CreateTempSubdirectory("cicada-upd-").FullName;@@ -1824,7 +1756,6 @@ static class TestsCheck(!File.Exists(got), "left-over installer removed");}- /// A release served over HTTP: checksums.txt, then the installer through `body`.sealed class Release(byte[] installer, Func<byte[], Stream> body) : HttpMessageHandler{protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancel)@@ -1838,7 +1769,6 @@ static class Tests}}- /// Sends `data` in `chunk`-sized pieces, then (when `stallAt` is reached) nothing at all.sealed class Trickle(byte[] data, int chunk, long stallAt = long.MaxValue) : Stream{long at;@@ -1860,8 +1790,6 @@ static class Testspublic override void Write(byte[] b, int o, int c) => throw new NotSupportedException();}- /// A slow download keeps going and reports progress up to 100 %; one that stops sending fails- /// after the stall limit, not after a fixed total time.public static async Task UpdateDownloadFailsOnAStallNotOnSlowness(){var installer = new byte[300_000];@@ -1883,8 +1811,6 @@ static class TestsCheck((DateTime.UtcNow - t).TotalSeconds < 5, "fails soon after the stall");}- /// The system proxy watch: polled from the first unreachable result; a change made while a- /// check runs is still acted on once that check ends unreachable; a reachable result stops it.public static void ProxyWatchKeepsAChangeMadeDuringACheck(){var w = new ProxyWatch();@@ -1923,7 +1849,6 @@ static class TestsEqual(1, UpdateChecker.Decode(Rel("v1.5.0"))!.Count, "a single release");Equal(null, UpdateChecker.Decode("{\"message\":\"Not Found\"}"), "GitHub's 404");Equal(null, UpdateChecker.Decode("<html>"), "not JSON");- // A release with the installer: it's what to download, on each architecture.var withSetup = UpdateChecker.Decode("""[{"tag_name":"v1.6.0","html_url":"https://example.com/r","assets":[{"name":"Cicada-1.6.0-Windows-x64.zip","browser_download_url":"https://example.com/z","size":5},@@ -1938,7 +1863,6 @@ static class Testsvar older = UpdateChecker.NewestWindows(withSetup.Take(1), "ARM64")!;Equal("https://example.com/setup-arm", older.Download, "ARM's installer");Equal(8L, older.Size, "its size");- // 1.1.0's installer names still count, so a release carrying only those is found too.var legacy = UpdateChecker.Decode("""[{"tag_name":"v1.1.0","html_url":"https://example.com/r","assets":[{"name":"Cicada-Setup.exe","browser_download_url":"https://example.com/old","size":3},@@ -1979,11 +1903,9 @@ static class Tests// 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 = [];- /// The key each request carried ("Bearer …"), in the order of Sent.public readonly List<string?> Auth = [];protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancel){@@ -2070,7 +1992,6 @@ static class TestsEqual(null, s.AIConfig().HearBase, "http off the local network is no address");Equal("https://zenmux.ai/api/v1/", new AppSettings { AiProvider = "zenmux" }.AIConfig().HearBase, "other services: theirs");Equal("https://api.ant-ling.com/v1/", new AppSettings().AIConfig().HearBase, "Ling");- // Not reaching a hear server of its own says nothing about the text address.Equal((AICheck.StepId.Hear, AICheck.Reason.Unreachable, (int?)null), AICheck.Classify(LingException.Kind.Network, 0, AICheck.StepId.Hear, hearElsewhere: true), "hear elsewhere");Equal((AICheck.StepId.Reach, AICheck.Reason.Unreachable, (int?)null), AICheck.Classify(LingException.Kind.Timeout, 0, AICheck.StepId.Hear), "same address");}@@ -2108,7 +2029,6 @@ static class Testsvar old = LingClient.Spacing; LingClient.Spacing = 0;try{- // A strict gateway refuses chat_template_kwargs; the model thinks, its answer in reasoning_content.var fake = new Service((url, body) =>body.Contains("chat_template_kwargs") ? Status(400): url.EndsWith("/models") ? Status(404)@@ -2136,7 +2056,7 @@ static class TestsEqual(AICheck.Kind.Ok, ling.Health[AICheck.StepId.Hear].Kind, "hears");ling.KeyChanged();fake.Sent.Clear();- try { await ling.Chat("x", "Translate.", Priority.Translate); } catch (LingException) { } // its answer is all reasoning+ try { await ling.Chat("x", "Translate.", Priority.Translate); } catch (LingException) { }Check(fake.Sent[0].body.Contains("chat_template_kwargs"), "settings changed: tried again");}finally { LingClient.Spacing = old; }@@ -2147,8 +2067,6 @@ static class Testsvar old = LingClient.Spacing; LingClient.Spacing = 0;try{- // No JSON mode on this server (OpenRouter's Novita for Ling 3.1 Flash): 400 with or- // without the kwargs. Asked again without JSON mode.var fake = new Service((url, body) => body.Contains("response_format") ? Status(400) : Reply("好"));var (ling, _) = Using(fake, "custom", key: null, new AppSettings { AiCustomBase = "http://192.168.1.20:8000/v1", AiModels = { ["custom"] = "m" } });Equal("好", await ling.Chat("x", "Notes.", Priority.Translate, json: true), "answered without JSON mode");@@ -2171,7 +2089,6 @@ static class Testsvar (ling, _) = Using(fake, "custom", key: null, s);await ling.Check();Check(ling.Health[AICheck.StepId.Text].Kind == AICheck.Kind.Ok && ling.Health.Failure?.Why != AICheck.Reason.NoJSON, ling.Health.Summary);- // One that can't answer JSON at all still fails.var plain = new Service((url, body) => url.EndsWith("/models") ? Status(404) : body.Contains("response_format") ? Status(400) : Reply("ok"));var (other, _) = Using(plain, "custom", key: null, s);await other.Check();@@ -2195,8 +2112,6 @@ static class TestsCheck(n is not null, "fenced notes parse");}- // 语音和文字只发给你的服务 (issue #15; the Mac's GoogleOffTests): Google is never asked.-public static void CustomOnlyActsWithTheCustomServiceAlone(){var s = new AppSettings { AiProvider = "custom", AiCustomOnly = true };@@ -2239,7 +2154,6 @@ static class TestsCheck(!t.SentencesUntranslated && changes == 2, "and the notice goes");Equal(0, google.Sent.Count, "still no Google");- // Off again: Google stands in as before.t.GoogleOff = false;up = false;Equal("谷歌的译文", await t.Translate("We ship on Friday.", "en", "zh-CN", Translator.Kind.Sentence), "Google once more");@@ -2285,7 +2199,6 @@ static class Tests// MARK: Notes apart (LingTests.swift › Notes apart)- /// A custom service whose notes use "big"; with `own`, at notes.example with 另一个服务.static (LingClient ling, AppSettings settings, Service fake) NotesClient(bool own, Func<string, string, HttpResponseMessage> respond, string? notesKey = null, GateClock? clock = null){var s = new AppSettings@@ -2312,7 +2225,6 @@ static class TestsEqual("big,mt", string.Join(",", fake.Sent.Select(x => JsonNode.Parse(x.body)!["model"]!.GetValue<string>())), "models");Equal("https://notes.example/v1/chat/completions,https://main.example/v1/chat/completions", string.Join(",", fake.Sent.Select(x => x.url)), "servers");Equal("Bearer sk-notes-222222222,Bearer sk-main-1111111111", string.Join(",", fake.Auth), "keys");- // A live line's corrections ride at Notes priority but are translation's.await ling.Chat("z", "JSON only.", Priority.Notes, notes: false);Check(fake.Sent[^1].url.StartsWith("https://main.example/") && fake.Auth[^1] == "Bearer sk-main-1111111111", "corrections stay with translation");}@@ -2328,13 +2240,11 @@ static class Testsawait ling.Chat("x", "Notes.", Priority.Notes);Equal("Bearer sk-main-1111111111", fake.Auth[0], "不填就用上面的 key");Check(!ling.NotesHasOwnKey, "no key of their own");- // The same service, another model: same address and key, even with a notes key file left over.var (same, _, f2) = NotesClient(false, (_, _) => Reply("{}"), notesKey: "sk-notes-222222222");await same.Chat("x", "Notes.", Priority.Notes);Check(f2.Sent[0].url.StartsWith("https://main.example/") && f2.Auth[0] == "Bearer sk-main-1111111111", "same service: its key");Equal("big", JsonNode.Parse(f2.Sent[0].body)!["model"]!.GetValue<string>(), "the notes model");Check(!same.NotesHasOwnKey, "同一个服务 has no key of its own");- // 另一个服务 at an http address on the internet: notes aren't sent anywhere else instead.var (bad, s3, f3) = NotesClient(true, (_, _) => Reply("{}"), notesKey: "sk-notes-222222222");s3.AiCustomNotesBase = "http://notes.example/v1";try { await bad.Chat("x", "Notes.", Priority.Notes); Check(false, "not sent"); } catch (LingException) { }@@ -2370,7 +2280,6 @@ static class Teststry { await ling.Chat("x", "Notes.", Priority.Notes); Check(false, "busy"); }catch (LingException e) { Equal(LingException.Kind.RateLimited, e.Failure, "notes gave up"); }Check(clock.Now > clock.Start, "notes waited at their own gate");- // A translation fails at once while its server cools down; this one isn't.Equal("好", await ling.Chat("y", "Translate.", Priority.Translate), "translation's gate isn't paused");Check(ling.Health.Failure is null && !ling.Health.NotesFailed, "busy is no failure: " + ling.Health.Summary);}@@ -2384,11 +2293,8 @@ static class TestsCheck(!plain.NotesApart && plain.ForNotes == plain, "nothing set: translation's");var model = new AIConfig(AIProvider.Custom, b, "mt", "", NotesModel: "big");Check(model.NotesApart && model.ForNotes.TextModel == "big" && model.ForNotes.Base == b, "another model, same address");- // Only the custom service splits.var ling = new AIConfig(AIProvider.Ling, AIProvider.Ling.Base, "x", "", NotesModel: "big");Check(!ling.NotesApart && ling.ForNotes.TextModel == "x", "Ling doesn't");- // From settings: the translation model named again is no model of its own; 另一个服务 off keeps- // the address but doesn't use it; an http address on the internet can't be used.var s = new AppSettings { AiProvider = "custom", AiCustomBase = "https://main.example/v1", AiModels = { ["custom"] = "mt", ["custom.notes"] = "mt" } };Check(!s.AIConfig().NotesApart, "same model: not apart");s.AiCustomNotesBase = "https://notes.example/v1";@@ -2407,7 +2313,6 @@ static class Testsvar old = LingClient.Spacing; LingClient.Spacing = 0;try{- // The notes model is gone from the notes server; translation's model, typed by hand, isn't listed but answers.var (ling, _, fake) = NotesClient(true, (url, body) =>url == "https://main.example/v1/models" ? Status(200, "{\"data\":[{\"id\":\"other\"}]}"): url == "https://notes.example/v1/models" ? Status(200, "{\"data\":[{\"id\":\"n1\"},{\"id\":\"n2\"}]}")@@ -2435,7 +2340,7 @@ static class Testsvar (ling, s) = Using(fake, "custom", key: null, new AppSettings { AiCustomBase = "http://localhost:8000/v1", AiModels = { ["custom"] = "m" } });var slow = Task.Run(ling.Check);while (fake.Sent.Count == 0) await Task.Delay(5);- s.AiCustomBase = "https://api.example.com/v1"; // remote now, and no key+ s.AiCustomBase = "https://api.example.com/v1";await ling.Check();gate.SetResult();await slow;@@ -2530,7 +2435,6 @@ static class Tests{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");@@ -2600,7 +2504,6 @@ static class Testsvar old = LingClient.Spacing; LingClient.Spacing = 0;try{- // ZenMux lists modalities at the top level: the text model is gone, and the hear model doesn't take audio.var (ling, _) = Using(new Service((url, _) => url.EndsWith("models")? Status(200, "{\"data\":[{\"id\":\"qwen/qwen3.8-flash\",\"input_modalities\":[\"text\"]},{\"id\":\"qwen/qwen3.8-omni-flash\",\"input_modalities\":[\"text\"]},{\"id\":\"a/ears\",\"input_modalities\":[\"audio\",\"text\"]}]}"): Reply("OK")));@@ -2708,7 +2611,6 @@ static class Testsvar m = new AICheck();m.Fail(AICheck.StepId.Key, AICheck.Reason.MgmtKey, reached: false);Equal(AICheck.Kind.Untested, m[AICheck.StepId.Reach].Kind, "nothing sent");- // Hearing doesn't need the text model, nor the other way round.var t = new AICheck();t.Fail(AICheck.StepId.Text, AICheck.Reason.NoModel, 404);Equal("reach=ok key=ok text=fail(noModel 404) hear=untested", t.Summary, "text");@@ -2778,7 +2680,6 @@ static class TestsEqual("inclusionai/ling-3.0-flash,qwen/qwen3.8-flash", string.Join(",", ids!.Order()), "ids");Equal(null, AICheck.ListedModels("{}"), "no data");Equal(null, AICheck.ListedModels("{\"data\":[]}"), "empty");- // OpenRouter says modalities under architecture; a list that says nothing proves nothing about hearing.var hearing = AICheck.ListedHearing("{\"data\":[{\"id\":\"a\",\"architecture\":{\"input_modalities\":[\"text\",\"audio\"]}},{\"id\":\"b\",\"architecture\":{\"input_modalities\":[\"text\"]}}]}");Equal("a", string.Join(",", hearing!), "hearing");Equal(null, AICheck.ListedHearing("{\"data\":[{\"id\":\"a\"}]}"), "nothing said");@@ -2826,7 +2727,6 @@ static class Testsvar 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"),@@ -2837,15 +2737,12 @@ static class TestsEqual("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" });@@ -2883,7 +2780,6 @@ static class Testsvar 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");- // #22: Windows' voice saved for a language this PC has no voice for.var system = new AppSettings { SpeakVoices = { ["en"] = "system" } };var ling = new AppSettings().AIConfig();Equal("system", VoiceCatalog.Chosen(system, "en", ling, true, windowsHasIt: true), "kept where Windows has it");@@ -2967,7 +2863,6 @@ static class Testsvar reference = new VoiceReference(new PlainProtector(), folder);var voice = new NoVoice();var engine = new SpeakEngine(ling, new Translator(ling), new SessionStore(), s, () => "ja", () => null, voice);- // Not recorded: Ming's default voice for Japanese.Check(await engine.Voice("こんにちは", "ja", new Sink()), "spoken");Equal("ming", engine.LastVoice, "Ming's own voice before the recording");engine.Reference = reference;@@ -2978,7 +2873,6 @@ static class Testsvar body = JsonNode.Parse(sse.Sent[^1].body)!;Check(body["references"] is JsonArray { Count: 1 } && body["voice"] is null, "the recording went with it");Equal("ja", body["language_id"]!.GetValue<string>(), "with Ming's language");- // Ling failing: Windows speaks the translation instead (never the original).var down = new Service((_, _) => new HttpResponseMessage(HttpStatusCode.InternalServerError));var (ling2, s2) = Using(down, "ling");s2.SpeakVoices["ja"] = "clone";@@ -2991,7 +2885,6 @@ static class Testspublic static void TellsASlowRecordingApart(){- // 21 characters read over 4 s of sound (a second of silence each side): an ordinary pace.var samples = new float[16000 * 6];for (var i = 16000; i < 16000 * 5; i++) samples[i] = (float)Math.Sin(i * 0.05) * 0.3f;var text = "大家好我是这次会议的主持人今天我们讨论计划";@@ -3020,7 +2913,6 @@ static class Testsvar (ok, text, kept) = await VoiceCloneCheck.Check(Spoken(12), _ => Task.FromResult<string?>(" " + passage + " "));Equal((VoiceCloneCheck.Outcome.Ready, passage), (ok, text), "an ordinary reading is kept with its words");Equal(11.4, Math.Round((kept.Length - 44) / 32000.0, 2), "and without its quiet ends (11 s read, 0.2 s kept each side)");- // 9.5 s read and a 3 s pause before 读完了: 12.5 s recorded, but under 10 s of reading.var paused = Spoken(10.5).Concat(new byte[16000 * 3 * 2]).ToArray();BitConverter.GetBytes(paused.Length - 44).CopyTo(paused, 40);Equal(VoiceCloneCheck.Outcome.TooShort, (await VoiceCloneCheck.Check(paused, _ => Task.FromResult<string?>(passage))).outcome, "the minimum is of the reading");@@ -3028,7 +2920,6 @@ static class Testspublic static void TrimsTheQuietEndsOfTheRecording(){- // 1 s quiet, 3 s of reading, 1 s quiet (the pause before 读完了 made Ming's clone silent).var pcm = new short[16000 * 5];for (var i = 16000; i < 16000 * 4; i++) pcm[i] = (short)(Math.Sin(i * 0.05) * 9000);var trimmed = VoicePace.Trim(Wav.Bytes(pcm));@@ -3065,18 +2956,14 @@ static class Tests{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").Body.Contains("ZenMux"), "named");- // One status line: subtitles and notes both wait, since the service hears the meeting here.Equal((null, "字幕和纪要等 Ling 恢复 · 连上后自动继续", false), ListenEngine.Words(LingException.Kind.Timeout, 0, "Ling"), "unreachable is one line");Check(!ListenEngine.Words(LingException.Kind.Http, 400, "Ling").Settings, "Ling's 400 is the network bar");- // A gateway's 502 in front of the server: the service erring, not the network, nothing in settings.Equal((null, "ZenMux 暂时出错(HTTP 502),稍后再试。", false), ListenEngine.Words(LingException.Kind.Http, 502, "ZenMux"), "a 5xx is the service's trouble");Equal("Ling 暂时出错(HTTP 503),稍后再试。", ListenEngine.Words(LingException.Kind.Http, 503, "Ling").Body, "Ling's too");}public static async Task ServerErrorsInARowAreSaidAndClearOnTheNextLine(){- // Every stretch answered 502 by a gateway: no subtitles, so from the third in a row the bar- // says the service is erring; the next stretch heard clears it. Two blips say nothing.var calls = 0;var seen = new List<(LingException.Kind? kind, int status, int calls)>();var fake = new Fake(body =>@@ -3095,7 +2982,6 @@ static class Testsvar path = Path.Combine(Path.GetTempPath(), $"cicada-502-{Environment.ProcessId}.wav");short[] stretches = [.. Tone(1), .. Silence(3), .. Tone(1), .. Silence(3), .. Tone(1), .. Silence(3), .. Tone(1), .. Silence(3)];File.WriteAllBytes(path, Wav.Bytes(stretches));- // Four times real time: each reply is back before the next stretch goes, as in a meeting.var src = new FileAudioSource(path, speed: 4);var ended = new TaskCompletionSource();src.Ended += _ => ended.TrySetResult();@@ -3131,7 +3017,6 @@ static class Tests}// MARK: 改正听错的词 (the Mac's CorrectionTests, VocabularyTests and LiveFixesTests, case for case;- // cases from a 21-minute meeting recording, a DeFi team's weekly)static Correction.Verdict Verdict(string from, string to, double c, (string, string)[]? known = null, (string, string)[]? rejected = null) =>Correction.Decide(new Correction.Edit(from, to, c), (a, b) => (known ?? []).Contains((a, b)), (a, b) => (rejected ?? []).Contains((a, b)));@@ -3143,7 +3028,6 @@ static class TestsEqual(Correction.Verdict.Apply, Verdict("两个代笔", "两个代币", 0.9), "代笔");Equal(Correction.Verdict.Apply, Verdict("管理房", "管理方", 0.9), "管理房");Equal(Correction.Verdict.Apply, Verdict("追压", "质押", 0.85), "追压");- // Only the changed part is compared: 花/概 share nothing, though the phrase around them does.Equal(Correction.Verdict.Drop, Verdict("花了大花", "花了大概", 0.85), "花/概");Equal(Correction.Verdict.Apply, Verdict("FFT制押", "FFT质押", 0.9), "FFT制押");}@@ -3172,7 +3056,6 @@ static class TestsEqual(Correction.Verdict.Drop, Verdict("莫纳", "Morpho", 0.7), "莫纳");}- /// A learned "S平 → X平" never reaches into "iOS平台"; on its own it still applies.public static void FixLearnedWordsStayWhole(){Check(Correction.WordIn("S平", "iOS平台很好") < 0, "inside iOS");@@ -3183,7 +3066,6 @@ static class TestsEqual("iOS平台和X平台", Correction.Apply([new("S平", "X平")], "iOS平台和S平台").Text, "applied to the whole one");}- /// A translation isn't a misheard name: one 对 to "X平台 → X platform" taught 平台 → platform.public static void FixTranslationsAreNotAsked(){Equal(Correction.Verdict.Drop, Verdict("X平台", "X platform", 0.9), "X平台");@@ -3212,7 +3094,6 @@ static class TestsEqual(("Un450P三", "Uniswap V3"), Correction.Core("Un450P三", "Uniswap V3"), "a Latin word stays whole");Equal(("莫拉", "Morpho"), Correction.Core("解释这个莫拉的", "解释这个Morpho的"), "name");Equal(("cransfer", "transfer"), Correction.Core("找了cransfer记录", "找了transfer记录"), "spelling");- // A Chinese change next to a Latin word leaves the word out.Equal(("制押", "质押"), Correction.Core("FFT制押", "FFT质押"), "beside a Latin word");}@@ -3232,7 +3113,6 @@ static class Testsvar (t2, m2) = Correction.Apply([new("质压", "质押"), new("莫拉", "Morpho")], "莫拉说质压");Equal("Morpho说质押", t2, "later fix shifts");Equal("Morpho|质押", string.Join("|", m2.Select(m => t2.Substring(m.Start, m.Length))), "earlier marks kept");- // The words went away (the line was heard again differently): nothing breaks.Equal("解释这个摩托的", Correction.Apply([new("莫拉", "Morpho")], "解释这个摩托的").Text, "skipped");}@@ -3274,26 +3154,21 @@ static class Testspublic static void FixAddedWordStaysOnItsLineAndNeverMatchesPunctuation(){- // "now" added before the full stop: the fix is the last word, unique in the line, not ".".const string line = "Great, let's lock that in.";var e = Correction.UserEdit(line, "Great, let's lock that in now.", line, []);Equal("in", e?.Fix.From, "from");Equal("in now", e?.Fix.To, "to");Equal(false, e?.Swap, "added, not swapped");Equal("Great, let's lock that in now.", Correction.Apply([e!.Value.Fix], line).Text, "applied");- // A word added at the start.var s = Correction.UserEdit(line, "OK Great, let's lock that in.", line, []);Equal("Great", s?.Fix.From, "start from");Equal("OK Great", s?.Fix.To, "start to");Equal(false, s?.Swap, "start swap");- // A word that appears twice: grown until the span is unique.var t = Correction.UserEdit("in the room in the hall", "in the room inside the hall", "in the room in the hall", []);Equal("in the room inside the hall", Correction.Apply([t!.Value.Fix], "in the room in the hall").Text, "unique span");- // Chinese: an inserted word takes its neighbour.var c = Correction.UserEdit("好的我来看一下", "好的OK我来看一下", "好的我来看一下", []);Equal("好的OK我来看一下", c is { } cc ? Correction.Apply([cc.Fix], "好的我来看一下").Text : null, "Chinese insert");Equal(false, c?.Swap, "Chinese swap");- // A real swap is still a swap.Equal(true, Correction.UserEdit("我木娜找了", "我Monad找了", "我木娜找了", [])?.Swap, "swap");}@@ -3483,7 +3358,6 @@ static class TestsCheck(FixLine(store, id, "l0").Shown.Contains("跑跑的"), "sound-alike applied");fx.Answer(fx.Pending(id)[0].Fix, true, id);Equal("最近那个Curve提了,这个是跑跑的测试", FixLine(store, id, "l0").Shown, "yes");- // The second pass, with the lines after it in view, proposes nothing.fx.Received(id, "l0", []);Equal("最近那个Curve提了,这个是跑好的测试", FixLine(store, id, "l0").Shown, "guess taken back, yes kept");}@@ -3506,7 +3380,6 @@ static class TestsEqual("Monad那边也有", FixLine(store, id, "l1").Shown, "everywhere");Check(fx.Vocabulary.Knows("木娜", "Monad"), "taught");Check(fx.Toast?.Text.Contains("Monad") == true, "toast");- // A later pass can't override what the user wrote.fx.Received(id, "l1", [new("木娜", "Mona", 0.95)]);Equal("Monad那边也有", FixLine(store, id, "l1").Shown, "user wins");fx.Undo();@@ -3562,8 +3435,6 @@ static class TestsEqual(null, FixLine(store, id, "l0").Fixes, "nothing fixed");}- /// A finished line goes to the AI service again with fixes asked for, in one request with the- /// Mac's prompt and no JSON mode; its translation (of the sentence as fixed) replaces Ming's.public static async Task FixesRideOnTheSentencesTranslation(){var fake = new Fake(body =>@@ -3729,7 +3600,6 @@ static class Testsstatic byte[] UnB64Url(string s) => Convert.FromBase64String(s.Replace('-', '+').Replace('_', '/').PadRight((s.Length + 3) / 4 * 4, '='));- /// Answers the share service's routes and checks each signed request as server/src/auth.js does.sealed class ShareServer(Func<HttpRequestMessage, string, HttpResponseMessage> respond) : HttpMessageHandler{public readonly List<string> Seen = [];@@ -3769,7 +3639,6 @@ static class Testsif (path == "/api/v1/devices") return Status(201, "{\"device\":\"0123456789abcdef0123456789abcdef\"}");if (path == "/api/v1/shares" && r.Method == HttpMethod.Post){- // The first signed call finds the device forgotten: the client registers again once.if (forgotten) { forgotten = false; return Status(401, "{\"code\":\"unknown_device\"}"); }var j = JsonNode.Parse(body)!;Check(r.Headers.GetValues("Idempotency-Key").First().StartsWith("20261106-140000-"), "idempotency key");@@ -3842,7 +3711,6 @@ static class Tests}}- /// The name: the user's title, else the notes', else the imported file's, never the display title.public static void FolderExportNamePrecedence(){var s = FolderSession();@@ -3892,7 +3760,6 @@ static class Testsvar index = Path.Combine(dir, "FolderExport.json");var ex = new FolderExporter(store, settings, index) { Delay = TimeSpan.FromMilliseconds(20) };var stem = FolderExportFormat.Stem(store.Get(s.Id)!);- // A file Cicada didn't write is never overwritten.Directory.CreateDirectory(folder);File.WriteAllText(Path.Combine(folder, stem + ".md"), "mine");ex.Choose(folder);@@ -3907,7 +3774,6 @@ static class TestsCheck(text.StartsWith("---\ncicada: 1\n") && text.Contains("title: \"周会\""), "frontmatter, then the body");Check(!Directory.GetFiles(folder, ".cicada*").Any(), "no temporary or check file left");Check(Json.Read<FolderExporter.Index>(File.ReadAllText(index))!.Files.ContainsKey(s.Id), "the index keeps it");- // A new name moves the file.store.Rename(s.Id, "周会改");store.Flush();ex.Saved(s.Id);@@ -3916,17 +3782,14 @@ static class Testsvar moved = ex.FileFor(s.Id)!;Check(Path.GetFileName(moved).EndsWith("周会改.md"), "renamed: " + Path.GetFileName(moved));Check(!File.Exists(Path.Combine(folder, stem + " 2.md")), "the old file went");- // Unchanged content isn't written again.var at = File.GetLastWriteTimeUtc(moved);ex.Saved(s.Id);await Task.Delay(200);await ex.Idle();Equal(at, File.GetLastWriteTimeUtc(moved), "unchanged");- // Deleting the record leaves its file.ex.Deleted(s.Id);Check(File.Exists(moved), "the file stays");store.Delete(s.Id);- // A folder whose parent is gone isn't made.ex.Choose(Path.Combine(dir, "gone", "Cicada"));await ex.Idle();Equal(FolderExporter.Kind.Missing, ex.Trouble?.Kind, "missing");@@ -3963,7 +3826,6 @@ static class Tests{var notes = new List<NoteTerm> { new() { Name = "江充", Heard = ["江松"] }, new() { Name = "Ling" } };Equal("江充,江松", string.Join(",", TranscriptSearch.Terms("江充", notes)), "the name and how it was heard");- // Searching the misheard form finds the right one too; an unrelated term stays out.Equal("江松,江充", string.Join(",", TranscriptSearch.Terms(" 江松 ", notes)), "the misheard form finds the name");Equal(0, TranscriptSearch.Terms(" ", notes).Count, "a blank query finds nothing");}@@ -3976,7 +3838,6 @@ static class TestsEqual("b", string.Join(",", TranscriptSearch.Matches(lines, ["BUDGET"])), "the translation, any case");Equal("a,b", string.Join(",", TranscriptSearch.Matches(lines, ["预算", "budget"])), "every term, in line order");Equal(0, TranscriptSearch.Matches(lines, []).Count, "no terms, no matches");- // A fixed word is searched as shown, not as heard.var fixedLine = new TranscriptLine { Id = "f", Src = "莫拉的方案", Fixes = [new LineFix("莫拉", "Morpho")] };Equal("f", string.Join(",", TranscriptSearch.Matches([fixedLine], ["morpho"])), "the shown text");}diff --git a/windows/vm/deploy.sh b/windows/vm/deploy.shindex 26a2224..68d7453 100755--- a/windows/vm/deploy.sh+++ b/windows/vm/deploy.sh@@ -1,5 +1,4 @@#!/bin/bash-# Quits Cicada in the test VM and copies in fresh builds (run scripts/build.sh first).set -euo pipefailhere="$(cd "$(dirname "$0")" && pwd)""$here/vmctl.sh" ssh 'Get-Process Cicada -ErrorAction SilentlyContinue | Stop-Process -Force; Start-Sleep 1; Remove-Item C:\cicada-test\Cicada-win-arm64, C:\cicada-test\Cicada-win-x64 -Recurse -Force -ErrorAction SilentlyContinue; exit 0'diff --git a/windows/vm/firstlogon.ps1 b/windows/vm/firstlogon.ps1index a82f0a2..b7d0b8d 100644--- a/windows/vm/firstlogon.ps1+++ b/windows/vm/firstlogon.ps1@@ -1,4 +1,3 @@-# First logon: OpenSSH server (PowerShell shell, key auth for the host), no sleep or lock, then a marker.$ErrorActionPreference = 'Continue'Start-Transcript C:\firstlogon.log$src = Split-Path $MyInvocation.MyCommand.Path@@ -6,7 +5,6 @@ powercfg /change monitor-timeout-ac 0; powercfg /change standby-timeout-ac 0reg add "HKLM\SOFTWARE\Policies\Microsoft\Windows\Personalization" /v NoLockScreen /t REG_DWORD /d 1 /freg add "HKCU\Control Panel\Desktop" /v ScreenSaveActive /t REG_SZ /d 0 /fSet-NetConnectionProfile -NetworkCategory Private -ErrorAction SilentlyContinue-# OpenSSH: the built-in capability first, else the zip on this disc.if (-not (Get-Service sshd -ErrorAction SilentlyContinue)) { Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0 }if (-not (Get-Service sshd -ErrorAction SilentlyContinue) -and (Test-Path "$src\OpenSSH-ARM64.zip")) {Expand-Archive "$src\OpenSSH-ARM64.zip" 'C:\Program Files' -Forcediff --git a/windows/vm/guest.ps1 b/windows/vm/guest.ps1index 2766003..d1d79bf 100644--- a/windows/vm/guest.ps1+++ b/windows/vm/guest.ps1@@ -1,16 +1,3 @@-# Guest-side helpers, run over SSH. SSH sessions have no desktop, so anything that needs one-# (launching Cicada, playing sound, screenshots, clicks, the foreground window) runs as a one-off-# scheduled task in tester's logged-on session and writes its result to a file we read back.-# guest.ps1 desk '<powershell>' # run in the desktop session, wait, print its output-# guest.ps1 launch <exe> [args] # start a program on the desktop without waiting-# guest.ps1 shot <out.png> # screenshot taken inside Windows (what screen sharing sees)-# guest.ps1 click <x> <y> # left click at physical pixel x,y-# guest.ps1 move <x> <y> # pointer to physical pixel x,y (hover)-# guest.ps1 wheel <x> <y> <notches> # mouse wheel at x,y; negative notches scroll down-# guest.ps1 key <keys> # SendKeys to the foreground window, e.g. "hello{ENTER}"-# guest.ps1 front # title and process of the foreground window-# guest.ps1 windows # visible top-level windows with their bounds-# guest.ps1 play <wav> # play a WAV from another process (as a meeting app would)param([Parameter(Position = 0)][string]$Verb, [Parameter(ValueFromRemainingArguments = $true)][string[]]$Rest)$ErrorActionPreference = 'Stop'$dir = 'C:\cicada-test\guest'; New-Item -ItemType Directory $dir -Force | Out-Null@@ -38,8 +25,6 @@ public static class W {function Desk([string]$script, [int]$timeout = 60, [switch]$NoWait) {$id = [guid]::NewGuid().ToString('N').Substring(0, 8)$ps1 = "$dir\$id.ps1"; $out = "$dir\$id.out"; $done = "$dir\$id.done"- # The script redirects its own output, so the task line needs no quotes; conhost --headless keeps- # a console window from flashing up and taking the foreground.@"`$ErrorActionPreference='Continue'& {@@ -88,7 +73,6 @@ Add-Type -AssemblyName System.Windows.Forms, System.DrawingDesk "[W]::SetCursorPos($($Rest[0]), $($Rest[1])) | Out-Null; 'moved'"}'wheel' {- # One notch is 120; negative scrolls down. mouse_event takes it as a uint.$notches = [int]$Rest[2]$delta = if ($notches -lt 0) { 4294967296 - 120 } else { 120 }Desk "[W]::SetCursorPos($($Rest[0]), $($Rest[1])) | Out-Null; Start-Sleep -Milliseconds 100; for (`$i = 0; `$i -lt $([Math]::Abs($notches)); `$i++) { [W]::mouse_event(0x0800,0,0,$delta,[UIntPtr]::Zero); Start-Sleep -Milliseconds 40 }; 'wheeled'"diff --git a/windows/vm/run.sh b/windows/vm/run.shindex 04d49ed..ac0d218 100755--- a/windows/vm/run.sh+++ b/windows/vm/run.sh@@ -1,7 +1,4 @@#!/bin/bash-# Runs the Windows 11 ARM64 test VM under QEMU (HVF), headless: VNC on :1, the QEMU monitor on-# $VM/monitor.sock, SSH on localhost:2222. First run (no disk yet) installs Windows unattended.-# VM=~/VMs/cicada-win11 windows/vm/run.sh # needs win11.iso, virtio-win.iso, vm_key in $VMset -euo pipefailhere="$(cd "$(dirname "$0")" && pwd)"VM="${VM:-$HOME/VMs/cicada-win11}"@@ -9,14 +6,11 @@ cd "$VM"share=/opt/homebrew/share/qemuinstall=()-# The virtio drivers are only needed while installing: a VM without the ISO still boots.virtio=()[ -f virtio-win.iso ] && virtio=(-drive file=virtio-win.iso,media=cdrom,if=none,id=cd2,readonly=on -device usb-storage,drive=cd2)if [ ! -f disk.qcow2 ]; thenqemu-img create -f qcow2 disk.qcow2 64G >/dev/nullcp "$share/edk2-arm-vars.fd" vars.fd- # The answer file and first-logon script on their own disc, with the host's SSH key and the- # OpenSSH zip in case the built-in capability can't be downloaded.rm -rf seed && mkdir seedcp "$here/autounattend.xml" "$here/firstlogon.ps1" seed/cp vm_key.pub seed/authorized_keys@@ -26,7 +20,6 @@ if [ ! -f disk.qcow2 ]; then-drive file=seed.iso,media=cdrom,if=none,id=cd1,readonly=on -device usb-storage,drive=cd1)fi-# No TPM: HVF refuses tpm-tis-device (HV_BAD_ARGUMENT); the answer file bypasses Windows 11's check.qemu-system-aarch64 \-name cicada-win11 -machine virt,highmem=on -accel hvf -cpu host -smp 4 -m 8G -device qemu-xhci \-drive if=pflash,format=raw,readonly=on,file="$share/edk2-aarch64-code.fd" \diff --git a/windows/vm/vmctl.sh b/windows/vm/vmctl.shindex fc7f8d5..b75c8ac 100755--- a/windows/vm/vmctl.sh+++ b/windows/vm/vmctl.sh@@ -1,12 +1,4 @@#!/bin/bash-# Host-side helpers for the test VM.-# vmctl.sh shot <out.png> # screenshot of the VM's screen (what a viewer of the display sees)-# vmctl.sh mon <command…> # one QEMU monitor command (sendkey ret, mouse_move…, system_powerdown)-# vmctl.sh ssh <powershell…> # run PowerShell in the VM over SSH-# vmctl.sh put <local> <remote> # copy into the VM-# vmctl.sh run <local.ps1> # run a script in the VM's desktop session and print its output-# vmctl.sh g <verb> <args…> # guest.ps1 in the VM (desk, launch, shot, click, move, wheel, key, front, windows, play)-# vmctl.sh stop # shut Windows down and wait for QEMU to exit (frees its 8 GB)set -euo pipefailVM="${VM:-$HOME/VMs/cicada-win11}"common=(-i "$VM/vm_key" -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR -o ConnectTimeout=5)@@ -18,8 +10,8 @@ case "$1" insleep 0.3; sips -s format png "$tmp" --out "$2" >/dev/null ;;mon) shift; mon "$*" ;;ssh) shift; ssh "${common[@]}" -p 2222 [email protected] "[Console]::OutputEncoding = [Text.Encoding]::UTF8; $*" ;;- g) shift; "$0" ssh "& C:\\cicada-test\\guest.ps1 $*" ;; # a guest.ps1 verb, e.g. g front- run) # a local .ps1 in the VM's desktop session: no quoting through ssh and schtasks+ g) shift; "$0" ssh "& C:\\cicada-test\\guest.ps1 $*" ;;+ run)"$0" put "$2" C:/cicada-test/run.ps1 && "$0" g desk "'& C:\\cicada-test\\run.ps1'" ;;put) scp -r "${common[@]}" -P 2222 "$2" "[email protected]:$3" ;;stop)