知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
feat: Diagnostics shows each AI request by service, model and use, with time to first audio for the translated voice
wquguru16d70e686fc7
diff --git a/AGENTS.md b/AGENTS.mdindex f88c945..75382c8 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,6 +1,6 @@# AGENTS.md-Cicada (知了, formerly Live Subs) turns what a computer plays into live translated subtitles and meeting notes, keeps each meeting as a bilingual record, and speaks what you say back into the room in their language. The Mac app (menu bar) is the main one; `windows/`, `android/` and `linux/` are ports that only listen, each with its own AGENTS.md. This file covers the whole repo and the Mac app.+Cicada (知了, formerly Live Subs) turns what a computer plays into live translated subtitles and meeting notes, keeps each meeting as a bilingual record, and speaks what you say back into the room in their language. The Mac app (menu bar) is the main one; `windows/`, `android/` and `linux/` are ports with their own AGENTS.md. This file covers the whole repo and the Mac app.## Scope@@ -13,6 +13,7 @@ Cicada (知了, formerly Live Subs) turns what a computer plays into live transl- AI keys live only in 0600 files (`AIKey`): never UserDefaults, logs or exports.- Every AI call goes through `LingClient` (rate gate, priorities, `thinking: disabled`, content in the system message). Partial text is translated by Google, never Ling.- Never speak untranslated text into the room. Never bundle the GPL BlackHole driver; download it and check its pinned SHA-256.+- Only the Mac app recognizes on the device: don't claim 声音不出本机 for the ports (Ming, Ling key required).- The notes window is a non-activating panel with `sharingType = .none`: it must never take focus, and stays out of screen captures unless the user turns on 共享屏幕时让对方看到 (then it shows a badge).- Mac: UI and engine state are `@MainActor`; audio callbacks hand buffers to `AudioRouter`'s queue.- Don't change the release bundle id `com.wquguru.cicada` or the ad-hoc designated requirement: permissions are tied to them.@@ -53,6 +54,7 @@ scripts/deploy-site.sh # build and deploy the site (cicada.indal- Match the existing naming and comment density; comments say why.- Commits are English Conventional Commits (`feat:` `fix:` `docs:` `build:` `refactor:` `test:` `chore:`). `feat:` and `fix:` subjects are the release notes (`scripts/changelog.py`), one line each linked to the commit: say what the user gets in one plain sentence, one change per commit. The scope picks the platform: `(windows)` `(android)` `(linux)` `(site)`, anything else is Mac.+- Release notes have no Chinese but the brand: name UI in English (Listen to › Room).- Every user-visible change also gets a Chinese item in `site/changelog.json`, the website's changelog; keep `README.md` (Chinese, the default) and `README.en.md` in step.- One semver version for every platform, in `VERSION`; every build reads it. Patch for fixes only, minor for features, major only when users of any platform must grant permissions again. A release ships only the platforms with a feat or fix.- This file stays under 6 KB with these sections; `scripts/check-agents.py` enforces it in `scripts/test.sh`, CI and the pre-commit hook. Implementation detail belongs in code comments, not here.diff --git a/Resources/en.lproj/Localizable.strings b/Resources/en.lproj/Localizable.stringsindex c6f761a..17b1cb0 100644--- a/Resources/en.lproj/Localizable.strings+++ b/Resources/en.lproj/Localizable.strings@@ -11,7 +11,6 @@"自定义服务" = "Custom service";/* AISettings */-"其他(兼容 OpenAI)" = "Other (OpenAI-compatible)";"现在能用的" = "What works now";"用 %@" = "Uses %@";"实时纪要" = "Live notes";@@ -72,6 +71,7 @@"声音" = "Voice";"例如 af_heart" = "e.g. af_heart";"跟上面一样" = "Same as above";+"其他(兼容 OpenAI)" = "Other (OpenAI-compatible)";"(推荐)" = "(Recommended)";"模型名" = "Model name";"好" = "OK";@@ -165,23 +165,20 @@/* Diagnostics */"%@ %@ 诊断 %@" = "%1$@ %2$@ diagnostics %3$@";-"模型 %@" = "Model %@";"本场 %.0f 分钟" = "This meeting %.0f min";"说完到出字幕 " = "Speech end → subtitle ";"识别定稿 " = "Final transcript ";"翻译 " = "Translation ";-"同声传译(松开到译好)" = "Interpreting (release → translated) ";-"单轮纪要耗时 " = "Notes round ";+"同声传译(松开到对方听到)" = "Interpreting (release → heard) ";"翻译来源 " = "Translated by ";"换后备 " = "Fallbacks ";"无" = "none";-"Ling 请求 %d 次 · 排队最久 %.2fs · token %d/%d" = "Ling requests: %d · longest queue %.2fs · tokens %d/%d";+"AI 请求 %d 次 · 排队最久 %.2fs · token %d/%d" = "AI requests: %d · longest queue %.2fs · tokens %d/%d";"有人说话后,这里会显示每句话的耗时明细" = "Each sentence's timing shows here once someone speaks";"这场会议 · %lld 分钟 · %lld 句 · 同声传译 %lld 次" = "This meeting · %lld min · sentences: %lld · interpreted: %lld";"开始聆听后,这里会显示每句话的耗时明细" = "Once listening starts, the timing of every sentence shows here";-"说完到上屏" = "Speech end → on screen";-"识别定稿" = "Final transcript";-"纪要一轮" = "Notes round";+"对方说完 → 你看到字幕" = "They finish → you see subtitles";+"你说完 → 对方听到" = "You finish → they hear you";"只记时间和次数,不存字幕原文" = "Only timings and counts are recorded, never the words";"已复制" = "Copied";"复制诊断信息" = "Copy Diagnostics";@@ -190,32 +187,51 @@"暂无数据" = "No data yet";"一句话的路" = "A sentence's path";"还没有句子" = "No sentences yet";+"识别定稿" = "Final transcript";"听清这句话" = "Hearing it";"译成目标语言" = "Translating it";+"说完到上屏" = "Speech end → on screen";"你感到的延迟" = "The delay you feel";+"纪要一轮" = "Notes round";"更新一次纪要" = "One notes update";-"翻译通道" = "Translation";-"Ling 用量" = "Ling usage";+"AI 服务" = "AI Service";"账号上限约每秒 2 次" = "The account allows about 2 per second";-"Ming 语音" = "Ming voice";-"没译出" = "Not translated";+"本场用量" = "This meeting's usage";"本场还没调用" = "Not used yet";"最近的句子" = "Recent sentences";"示例 · 对方" = "Example · them";"识别" = "Recognize";"排队" = "Queue";+"Ming 语音" = "Ming voice";+"没译出" = "Not translated";"被搜索劫持" = "Search hijack";"限流" = "Rate limited";"超时" = "Timeout";"回复格式不对" = "Bad reply format";"网络错误" = "Network error";"未安装语言包" = "Language not installed";-"翻译通道分布" = "Translation providers";-"共 %lld 句" = "Total: %lld";+"整句翻译" = "Sentence translation";+"听懂你说的" = "Hearing you";+"认出说话人" = "Naming speakers";+"跟着 AI 服务走 · %@" = "Depends on the AI service · %@";+"不受换服务影响" = "Same with any service";+"%lld 次" = "requests: %lld";+"%lld 字" = "characters: %lld";+"%lld 句退回 %@" = "%lld fell back to %@";+"失败 %lld" = "failed: %lld";+"没有失败" = "no failures";+"到开始出声" = "to first sound";+"识别对方" = "Recognizing them";+"本机识别" = "On this Mac";+"%lld 句" = "%lld lines";+"识别你说的" = "Recognizing you";+"半句翻译" = "Partial translation";"Ling 请求速度" = "Ling request rate";"排队最久" = "Longest queue";-"本场用量" = "This meeting's usage";+"请求太密时,纪要让翻译先走" = "When requests pile up, notes let translation go first";+"服务返回的数,以服务的账单为准" = "As reported by the service; its bill is final";"%.1f / 2 次每秒" = "%.1f / 2 per second";+"%lld 次 · %lld token · %lld 字语音" = "requests: %lld · tokens: %lld · voice characters: %lld";"%lld 次 · %lld token" = "requests: %lld · tokens: %lld";"还没有" = "None yet";"你" = "You";@@ -234,6 +250,9 @@"文字记录已转到 %@ / %@" = "Transcribed to %@ of %@";"还有 %lld 句在翻译" = "%lld lines still translating";"纪要等文字记录转完再整理;正在听的会议优先" = "Notes come once it's transcribed; a live meeting goes first";+"这场会议只留下了录音" = "Only the recording was kept";+"当时没听出是哪种语言。选一下,就按它转成文字" = "The language wasn't recognized at the time. Pick it to turn the recording into text";+"其他语言…" = "Other…";"找不到原文件,没法播放" = "Can't find the original file to play";"暂停" = "Pause";"播放" = "Play";@@ -377,7 +396,6 @@"收成小卡" = "Collapse to card";"正在听 · " = "Listening · ";"正在记录 · " = "Recording · ";-"%lld 句" = "%lld lines";"刚刚更新" = "Updated just now";"%lld 秒前更新" = "Updated %lld s ago";"%lld 分钟前更新" = "Updated %lld min ago";@@ -567,7 +585,6 @@/* SettingsWindow */"语言" = "Language";"通用" = "General";-"AI 服务" = "AI Service";"诊断" = "Diagnostics";"有人说话时" = "While someone talks";"始终显示" = "Always";@@ -885,6 +902,7 @@"本周" = "This Week";"收起更早的会议" = "Hide earlier meetings";"更早的会议" = "Earlier meetings";+"只有录音" = "Recording only";"未命名会议" = "Untitled meeting";"转写中 %lld%%" = "%lld%%";"翻译中" = "Translating";@@ -906,6 +924,7 @@"葡语" = "Portuguese";"正在听,说话的内容会出现在这里" = "Listening; what's said will appear here";"转出的文字会陆续出现在这里" = "The transcript will appear here as it's made";+"还没有文字记录" = "No transcript yet";"这场会议没有记录到内容" = "Nothing was recorded in this meeting";"还没有会议" = "No meetings yet";"打开会议或视频,开始听后,每一场都会存在这里。" = "Open a meeting or a video and start listening: each one is kept here.";@@ -979,6 +998,7 @@"录制" = "Record";"录 15 秒原声,对方听到你的音色,晚约 3 秒" = "Record 15 s so they hear your own voice, about 3 s later";"已录 %lld 秒 · %@" = "Recorded %lld s · %@";+"读得偏慢" = "Read slowly";"重录" = "Re-record";"最像你" = "sounds most like you";"会带你的口音" = "keeps your accent";@@ -998,7 +1018,6 @@"用你的声音说%@" = "Your voice speaking %@";"对方会听到这个" = "They'll hear this";"用这个声音" = "Use This Voice";-"读得偏慢" = "Read slowly";/* Voices */"美式" = "American";@@ -1020,5 +1039,5 @@"麦克风没收到声音,请检查麦克风权限" = "The microphone got no sound; check microphone permission";"无法打开麦克风:%@" = "Can't open the microphone: %@";"录音太短了,请至少朗读 %lld 秒" = "Too short; read for at least %lld seconds";-"没听清录音内容,请换个安静的地方再录一次" = "Couldn't make out the recording; try again somewhere quiet";"读得有点慢,克隆的声音也会这么慢。请用平时说话的语速再录一次" = "Read a bit slowly: your cloned voice would be just as slow. Record again at your usual pace";+"没听清录音内容,请换个安静的地方再录一次" = "Couldn't make out the recording; try again somewhere quiet";diff --git a/Resources/ja.lproj/Localizable.strings b/Resources/ja.lproj/Localizable.stringsindex 4142291..4492bf0 100644--- a/Resources/ja.lproj/Localizable.strings+++ b/Resources/ja.lproj/Localizable.strings@@ -11,7 +11,6 @@"自定义服务" = "カスタムサービス";/* AISettings */-"其他(兼容 OpenAI)" = "その他(OpenAI 互換)";"现在能用的" = "現在使える機能";"用 %@" = "%@ を使用";"实时纪要" = "ライブ議事メモ";@@ -72,6 +71,7 @@"声音" = "声";"例如 af_heart" = "例: af_heart";"跟上面一样" = "上と同じ";+"其他(兼容 OpenAI)" = "その他(OpenAI 互換)";"(推荐)" = "(推奨)";"模型名" = "モデル名";"好" = "OK";@@ -165,23 +165,20 @@/* Diagnostics */"%@ %@ 诊断 %@" = "%1$@ %2$@ 診断 %3$@";-"模型 %@" = "モデル %@";"本场 %.0f 分钟" = "今回 %.0f分";"说完到出字幕 " = "発話終了→字幕表示 ";"识别定稿 " = "認識確定 ";"翻译 " = "翻訳 ";-"同声传译(松开到译好)" = "同時通訳(離してから翻訳完了まで) ";-"单轮纪要耗时 " = "議事メモ1回の所要時間 ";+"同声传译(松开到对方听到)" = "同時通訳(離してから相手に聞こえるまで) ";"翻译来源 " = "翻訳元 ";"换后备 " = "代替に切替 ";"无" = "なし";-"Ling 请求 %d 次 · 排队最久 %.2fs · token %d/%d" = "Ling リクエスト %d回 · 最長待ち %.2fs · トークン %d/%d";+"AI 请求 %d 次 · 排队最久 %.2fs · token %d/%d" = "AI リクエスト %d回 · 最長待ち %.2fs · トークン %d/%d";"有人说话后,这里会显示每句话的耗时明细" = "誰かが話すと、ここに一文ごとの所要時間が表示されます";"这场会议 · %lld 分钟 · %lld 句 · 同声传译 %lld 次" = "今回の会議 · %lld分 · %lld文 · 同時通訳 %lld回";"开始聆听后,这里会显示每句话的耗时明细" = "聞き取りを開始すると、各文の所要時間がここに表示されます";-"说完到上屏" = "発話終了→画面表示";-"识别定稿" = "認識確定";-"纪要一轮" = "議事メモ1回";+"对方说完 → 你看到字幕" = "相手が話し終える → 字幕が出る";+"你说完 → 对方听到" = "話し終える → 相手に聞こえる";"只记时间和次数,不存字幕原文" = "記録するのは時間と回数だけで、字幕の本文は保存しません";"已复制" = "コピーしました";"复制诊断信息" = "診断情報をコピー";@@ -190,32 +187,51 @@"暂无数据" = "データなし";"一句话的路" = "一文の流れ";"还没有句子" = "まだ文がありません";+"识别定稿" = "認識確定";"听清这句话" = "文を聞き取る";"译成目标语言" = "訳す";+"说完到上屏" = "発話終了→画面表示";"你感到的延迟" = "体感の遅れ";+"纪要一轮" = "議事メモ1回";"更新一次纪要" = "メモを一回更新";-"翻译通道" = "翻訳経路";-"Ling 用量" = "Ling の使用量";+"AI 服务" = "AI サービス";"账号上限约每秒 2 次" = "アカウントの上限は毎秒約2回";-"Ming 语音" = "Ming の音声";-"没译出" = "翻訳なし";+"本场用量" = "この会議の使用量";"本场还没调用" = "まだ使っていません";"最近的句子" = "最近の文";"示例 · 对方" = "例 · 相手";"识别" = "認識";"排队" = "待ち";+"Ming 语音" = "Ming の音声";+"没译出" = "翻訳なし";"被搜索劫持" = "検索に誘導された";"限流" = "レート制限";"超时" = "タイムアウト";"回复格式不对" = "応答形式が不正";"网络错误" = "ネットワークエラー";"未安装语言包" = "言語パック未インストール";-"翻译通道分布" = "翻訳経路の内訳";-"共 %lld 句" = "計%lld文";+"整句翻译" = "文ごとの翻訳";+"听懂你说的" = "あなたの発言の聞き取り";+"认出说话人" = "話者の特定";+"跟着 AI 服务走 · %@" = "AI サービスで変わる · %@";+"不受换服务影响" = "サービスを変えても同じ";+"%lld 次" = "%lld回";+"%lld 字" = "%lld文字";+"%lld 句退回 %@" = "%lld文が %@ に切り替え";+"失败 %lld" = "失敗 %lld";+"没有失败" = "失敗なし";+"到开始出声" = "音が出るまで";+"识别对方" = "相手の音声認識";+"本机识别" = "この Mac で認識";+"%lld 句" = "%lld文";+"识别你说的" = "あなたの音声認識";+"半句翻译" = "途中の翻訳";"Ling 请求速度" = "Ling リクエスト速度";"排队最久" = "最長待ち";-"本场用量" = "この会議の使用量";+"请求太密时,纪要让翻译先走" = "リクエストが混むと、議事メモは翻訳を先に通します";+"服务返回的数,以服务的账单为准" = "サービスが返した値。請求はサービス側が正です";"%.1f / 2 次每秒" = "%.1f / 毎秒2回";+"%lld 次 · %lld token · %lld 字语音" = "%lld回 · %lld トークン · 音声 %lld文字";"%lld 次 · %lld token" = "%lld回 · %lld トークン";"还没有" = "まだありません";"你" = "自分";@@ -234,6 +250,9 @@"文字记录已转到 %@ / %@" = "%@ / %@ まで文字起こし済み";"还有 %lld 句在翻译" = "あと %lld 文を翻訳中";"纪要等文字记录转完再整理;正在听的会议优先" = "メモは文字起こしの後に作成。進行中の会議を優先します";+"这场会议只留下了录音" = "この会議は録音だけが残っています";+"当时没听出是哪种语言。选一下,就按它转成文字" = "その時は言語を判別できませんでした。選ぶとその言語で文字起こしします";+"其他语言…" = "その他…";"找不到原文件,没法播放" = "元のファイルが見つからず再生できません";"暂停" = "一時停止";"播放" = "再生";@@ -377,7 +396,6 @@"收成小卡" = "カードに折りたたむ";"正在听 · " = "聞き取り中 · ";"正在记录 · " = "記録中 · ";-"%lld 句" = "%lld文";"刚刚更新" = "たった今更新";"%lld 秒前更新" = "%lld秒前に更新";"%lld 分钟前更新" = "%lld分前に更新";@@ -567,7 +585,6 @@/* SettingsWindow */"语言" = "言語";"通用" = "一般";-"AI 服务" = "AI サービス";"诊断" = "診断";"有人说话时" = "誰かが話しているとき";"始终显示" = "常に表示";@@ -885,6 +902,7 @@"本周" = "今週";"收起更早的会议" = "以前の会議を隠す";"更早的会议" = "以前の会議";+"只有录音" = "録音のみ";"未命名会议" = "無題の会議";"转写中 %lld%%" = "文字起こし中 %lld%%";"翻译中" = "翻訳中";@@ -906,6 +924,7 @@"葡语" = "ポルトガル語";"正在听,说话的内容会出现在这里" = "聞き取り中。発言内容がここに表示されます";"转出的文字会陆续出现在这里" = "文字起こしが順にここに表示されます";+"还没有文字记录" = "まだ文字起こしがありません";"这场会议没有记录到内容" = "この会議では何も記録されませんでした";"还没有会议" = "まだ会議はありません";"打开会议或视频,开始听后,每一场都会存在这里。" = "会議や動画を開いて聞き取りを始めると、毎回ここに保存されます。";@@ -979,6 +998,7 @@"录制" = "録音";"录 15 秒原声,对方听到你的音色,晚约 3 秒" = "15 秒録音すると相手にあなたの声で届きます(約 3 秒遅れ)";"已录 %lld 秒 · %@" = "%lld 秒録音済み · %@";+"读得偏慢" = "読むのが遅め";"重录" = "録り直す";"最像你" = "いちばん自分らしい";"会带你的口音" = "あなたの訛りが残ります";@@ -998,7 +1018,6 @@"用你的声音说%@" = "あなたの声で%@を話す";"对方会听到这个" = "相手にはこう聞こえます";"用这个声音" = "この声を使う";-"读得偏慢" = "読むのが遅め";/* Voices */"美式" = "アメリカ英語";@@ -1020,5 +1039,5 @@"麦克风没收到声音,请检查麦克风权限" = "マイクに音声が届いていません。マイクの権限を確認してください";"无法打开麦克风:%@" = "マイクを開けません: %@";"录音太短了,请至少朗读 %lld 秒" = "録音が短すぎます。%lld秒以上読み上げてください";-"没听清录音内容,请换个安静的地方再录一次" = "録音を聞き取れませんでした。静かな場所でもう一度録音してください";"读得有点慢,克隆的声音也会这么慢。请用平时说话的语速再录一次" = "読むのが少し遅いため、クローンの声も同じく遅くなります。普段の話す速さでもう一度録音してください";+"没听清录音内容,请换个安静的地方再录一次" = "録音を聞き取れませんでした。静かな場所でもう一度録音してください";diff --git a/Resources/ko.lproj/Localizable.strings b/Resources/ko.lproj/Localizable.stringsindex a9028f8..77cc868 100644--- a/Resources/ko.lproj/Localizable.strings+++ b/Resources/ko.lproj/Localizable.strings@@ -11,7 +11,6 @@"自定义服务" = "사용자 지정 서비스";/* AISettings */-"其他(兼容 OpenAI)" = "기타 (OpenAI 호환)";"现在能用的" = "지금 사용 가능";"用 %@" = "%@ 사용";"实时纪要" = "실시간 회의록";@@ -72,6 +71,7 @@"声音" = "목소리";"例如 af_heart" = "예: af_heart";"跟上面一样" = "위와 동일";+"其他(兼容 OpenAI)" = "기타 (OpenAI 호환)";"(推荐)" = "(추천)";"模型名" = "모델 이름";"好" = "확인";@@ -165,23 +165,20 @@/* Diagnostics */"%@ %@ 诊断 %@" = "%1$@ %2$@ 진단 %3$@";-"模型 %@" = "모델 %@";"本场 %.0f 分钟" = "이번 회의 %.0f분";"说完到出字幕 " = "발화 종료 → 자막 표시 ";"识别定稿 " = "인식 확정 ";"翻译 " = "번역 ";-"同声传译(松开到译好)" = "동시통역(손 뗌 → 번역 완료) ";-"单轮纪要耗时 " = "회의록 1회 소요 ";+"同声传译(松开到对方听到)" = "동시통역(손 뗌 → 상대가 들음) ";"翻译来源 " = "번역 경로 ";"换后备 " = "대체 전환 ";"无" = "없음";-"Ling 请求 %d 次 · 排队最久 %.2fs · token %d/%d" = "Ling 요청 %d회 · 최장 대기 %.2fs · token %d/%d";+"AI 请求 %d 次 · 排队最久 %.2fs · token %d/%d" = "AI 요청 %d회 · 최장 대기 %.2fs · token %d/%d";"有人说话后,这里会显示每句话的耗时明细" = "누군가 말하면 문장별 소요 시간이 여기에 표시돼요";"这场会议 · %lld 分钟 · %lld 句 · 同声传译 %lld 次" = "이번 회의 · %lld분 · %lld문장 · 동시통역 %lld회";"开始聆听后,这里会显示每句话的耗时明细" = "듣기를 시작하면 문장별 소요 시간이 여기에 표시됩니다";-"说完到上屏" = "발화 종료 → 화면 표시";-"识别定稿" = "인식 확정";-"纪要一轮" = "회의록 1회";+"对方说完 → 你看到字幕" = "상대가 말을 마침 → 자막 표시";+"你说完 → 对方听到" = "내가 말을 마침 → 상대가 들음";"只记时间和次数,不存字幕原文" = "시간과 횟수만 기록하며 자막 원문은 저장하지 않습니다";"已复制" = "복사됨";"复制诊断信息" = "진단 정보 복사하기";@@ -190,32 +187,51 @@"暂无数据" = "데이터 없음";"一句话的路" = "한 문장의 흐름";"还没有句子" = "아직 문장이 없어요";+"识别定稿" = "인식 확정";"听清这句话" = "문장 알아듣기";"译成目标语言" = "번역하기";+"说完到上屏" = "발화 종료 → 화면 표시";"你感到的延迟" = "체감 지연";+"纪要一轮" = "회의록 1회";"更新一次纪要" = "메모 한 번 갱신";-"翻译通道" = "번역 경로";-"Ling 用量" = "Ling 사용량";+"AI 服务" = "AI 서비스";"账号上限约每秒 2 次" = "계정 한도는 초당 약 2회";-"Ming 语音" = "Ming 음성";-"没译出" = "번역 안 됨";+"本场用量" = "이번 회의 사용량";"本场还没调用" = "아직 사용 안 함";"最近的句子" = "최근 문장";"示例 · 对方" = "예시 · 상대";"识别" = "인식";"排队" = "대기";+"Ming 语音" = "Ming 음성";+"没译出" = "번역 안 됨";"被搜索劫持" = "검색 응답으로 변질";"限流" = "요청 제한";"超时" = "시간 초과";"回复格式不对" = "응답 형식 오류";"网络错误" = "네트워크 오류";"未安装语言包" = "언어 팩 미설치";-"翻译通道分布" = "번역 경로 분포";-"共 %lld 句" = "총 %lld문장";+"整句翻译" = "문장 번역";+"听懂你说的" = "내 말 알아듣기";+"认出说话人" = "화자 인식";+"跟着 AI 服务走 · %@" = "AI 서비스에 따라 달라짐 · %@";+"不受换服务影响" = "서비스를 바꿔도 그대로";+"%lld 次" = "%lld회";+"%lld 字" = "%lld자";+"%lld 句退回 %@" = "%lld문장 %@(으)로 대체";+"失败 %lld" = "실패 %lld";+"没有失败" = "실패 없음";+"到开始出声" = "소리가 날 때까지";+"识别对方" = "상대 음성 인식";+"本机识别" = "이 Mac에서 인식";+"%lld 句" = "%lld문장";+"识别你说的" = "내 음성 인식";+"半句翻译" = "부분 번역";"Ling 请求速度" = "Ling 요청 속도";"排队最久" = "최장 대기";-"本场用量" = "이번 회의 사용량";+"请求太密时,纪要让翻译先走" = "요청이 몰리면 회의록이 번역에 순서를 양보합니다";+"服务返回的数,以服务的账单为准" = "서비스가 알려준 값이며, 청구액은 서비스 기준입니다";"%.1f / 2 次每秒" = "%.1f / 초당 2회";+"%lld 次 · %lld token · %lld 字语音" = "%lld회 · %lld token · 음성 %lld자";"%lld 次 · %lld token" = "%lld회 · %lld token";"还没有" = "아직 없음";"你" = "나";@@ -234,6 +250,9 @@"文字记录已转到 %@ / %@" = "%@ / %@까지 받아씀";"还有 %lld 句在翻译" = "%lld문장 번역 중";"纪要等文字记录转完再整理;正在听的会议优先" = "노트는 받아쓰기 후 작성. 진행 중인 회의가 우선";+"这场会议只留下了录音" = "이 회의는 녹음만 남았습니다";+"当时没听出是哪种语言。选一下,就按它转成文字" = "당시 언어를 알아듣지 못했습니다. 선택하면 그 언어로 텍스트로 변환합니다";+"其他语言…" = "기타…";"找不到原文件,没法播放" = "원본 파일이 없어 재생할 수 없음";"暂停" = "일시정지";"播放" = "재생";@@ -377,7 +396,6 @@"收成小卡" = "카드로 접기";"正在听 · " = "듣는 중 · ";"正在记录 · " = "기록 중 · ";-"%lld 句" = "%lld문장";"刚刚更新" = "방금 업데이트됨";"%lld 秒前更新" = "%lld초 전 업데이트됨";"%lld 分钟前更新" = "%lld분 전 업데이트됨";@@ -567,7 +585,6 @@/* SettingsWindow */"语言" = "언어";"通用" = "일반";-"AI 服务" = "AI 서비스";"诊断" = "진단";"有人说话时" = "누군가 말할 때";"始终显示" = "항상 표시";@@ -885,6 +902,7 @@"本周" = "이번 주";"收起更早的会议" = "이전 회의 숨기기";"更早的会议" = "이전 회의";+"只有录音" = "녹음만 있음";"未命名会议" = "제목 없는 회의";"转写中 %lld%%" = "받아쓰는 중 %lld%%";"翻译中" = "번역 중";@@ -906,6 +924,7 @@"葡语" = "포르투갈어";"正在听,说话的内容会出现在这里" = "듣는 중입니다. 말한 내용이 여기에 표시됩니다";"转出的文字会陆续出现在这里" = "받아쓴 내용이 여기에 차례로 나타납니다";+"还没有文字记录" = "아직 텍스트 기록이 없습니다";"这场会议没有记录到内容" = "이 회의에는 기록된 내용이 없습니다";"还没有会议" = "아직 회의가 없습니다";"打开会议或视频,开始听后,每一场都会存在这里。" = "회의나 동영상을 열고 듣기를 시작하면 모두 여기에 저장됩니다.";@@ -979,6 +998,7 @@"录制" = "녹음";"录 15 秒原声,对方听到你的音色,晚约 3 秒" = "15초 녹음하면 상대가 내 음색으로 듣습니다(약 3초 지연)";"已录 %lld 秒 · %@" = "%lld초 녹음됨 · %@";+"读得偏慢" = "느리게 읽음";"重录" = "다시 녹음";"最像你" = "가장 나다운 소리";"会带你的口音" = "내 억양이 남습니다";@@ -998,7 +1018,6 @@"用你的声音说%@" = "내 목소리로 %@ 말하기";"对方会听到这个" = "상대에게 이렇게 들립니다";"用这个声音" = "이 음성 사용";-"读得偏慢" = "느리게 읽음";/* Voices */"美式" = "미국식";@@ -1020,5 +1039,5 @@"麦克风没收到声音,请检查麦克风权限" = "마이크에 소리가 입력되지 않았습니다. 마이크 권한을 확인하세요";"无法打开麦克风:%@" = "마이크를 열 수 없습니다: %@";"录音太短了,请至少朗读 %lld 秒" = "녹음이 너무 짧습니다. 최소 %lld초 이상 읽어 주세요";-"没听清录音内容,请换个安静的地方再录一次" = "녹음 내용을 알아듣지 못했습니다. 조용한 곳에서 다시 녹음하세요";"读得有点慢,克隆的声音也会这么慢。请用平时说话的语速再录一次" = "조금 느리게 읽어서 복제한 목소리도 똑같이 느려집니다. 평소 말하는 속도로 다시 녹음하세요";+"没听清录音内容,请换个安静的地方再录一次" = "녹음 내용을 알아듣지 못했습니다. 조용한 곳에서 다시 녹음하세요";diff --git a/Resources/zh-Hans.lproj/Localizable.strings b/Resources/zh-Hans.lproj/Localizable.stringsindex 866700e..c5b3478 100644--- a/Resources/zh-Hans.lproj/Localizable.strings+++ b/Resources/zh-Hans.lproj/Localizable.strings@@ -11,7 +11,6 @@"自定义服务" = "自定义服务";/* AISettings */-"其他(兼容 OpenAI)" = "其他(兼容 OpenAI)";"现在能用的" = "现在能用的";"用 %@" = "用 %@";"实时纪要" = "实时纪要";@@ -72,6 +71,7 @@"声音" = "声音";"例如 af_heart" = "例如 af_heart";"跟上面一样" = "跟上面一样";+"其他(兼容 OpenAI)" = "其他(兼容 OpenAI)";"(推荐)" = "(推荐)";"模型名" = "模型名";"好" = "好";@@ -165,23 +165,20 @@/* Diagnostics */"%@ %@ 诊断 %@" = "%@ %@ 诊断 %@";-"模型 %@" = "模型 %@";"本场 %.0f 分钟" = "本场 %.0f 分钟";"说完到出字幕 " = "说完到出字幕 ";"识别定稿 " = "识别定稿 ";"翻译 " = "翻译 ";-"同声传译(松开到译好)" = "同声传译(松开到译好)";-"单轮纪要耗时 " = "单轮纪要耗时 ";+"同声传译(松开到对方听到)" = "同声传译(松开到对方听到)";"翻译来源 " = "翻译来源 ";"换后备 " = "换后备 ";"无" = "无";-"Ling 请求 %d 次 · 排队最久 %.2fs · token %d/%d" = "Ling 请求 %d 次 · 排队最久 %.2fs · token %d/%d";+"AI 请求 %d 次 · 排队最久 %.2fs · token %d/%d" = "AI 请求 %d 次 · 排队最久 %.2fs · token %d/%d";"有人说话后,这里会显示每句话的耗时明细" = "有人说话后,这里会显示每句话的耗时明细";"这场会议 · %lld 分钟 · %lld 句 · 同声传译 %lld 次" = "这场会议 · %lld 分钟 · %lld 句 · 同声传译 %lld 次";"开始聆听后,这里会显示每句话的耗时明细" = "开始聆听后,这里会显示每句话的耗时明细";-"说完到上屏" = "说完到上屏";-"识别定稿" = "识别定稿";-"纪要一轮" = "纪要一轮";+"对方说完 → 你看到字幕" = "对方说完 → 你看到字幕";+"你说完 → 对方听到" = "你说完 → 对方听到";"只记时间和次数,不存字幕原文" = "只记时间和次数,不存字幕原文";"已复制" = "已复制";"复制诊断信息" = "复制诊断信息";@@ -190,32 +187,51 @@"暂无数据" = "暂无数据";"一句话的路" = "一句话的路";"还没有句子" = "还没有句子";+"识别定稿" = "识别定稿";"听清这句话" = "听清这句话";"译成目标语言" = "译成目标语言";+"说完到上屏" = "说完到上屏";"你感到的延迟" = "你感到的延迟";+"纪要一轮" = "纪要一轮";"更新一次纪要" = "更新一次纪要";-"翻译通道" = "翻译通道";-"Ling 用量" = "Ling 用量";+"AI 服务" = "AI 服务";"账号上限约每秒 2 次" = "账号上限约每秒 2 次";-"Ming 语音" = "Ming 语音";-"没译出" = "没译出";+"本场用量" = "本场用量";"本场还没调用" = "本场还没调用";"最近的句子" = "最近的句子";"示例 · 对方" = "示例 · 对方";"识别" = "识别";"排队" = "排队";+"Ming 语音" = "Ming 语音";+"没译出" = "没译出";"被搜索劫持" = "被搜索劫持";"限流" = "限流";"超时" = "超时";"回复格式不对" = "回复格式不对";"网络错误" = "网络错误";"未安装语言包" = "未安装语言包";-"翻译通道分布" = "翻译通道分布";-"共 %lld 句" = "共 %lld 句";+"整句翻译" = "整句翻译";+"听懂你说的" = "听懂你说的";+"认出说话人" = "认出说话人";+"跟着 AI 服务走 · %@" = "跟着 AI 服务走 · %@";+"不受换服务影响" = "不受换服务影响";+"%lld 次" = "%lld 次";+"%lld 字" = "%lld 字";+"%lld 句退回 %@" = "%lld 句退回 %@";+"失败 %lld" = "失败 %lld";+"没有失败" = "没有失败";+"到开始出声" = "到开始出声";+"识别对方" = "识别对方";+"本机识别" = "本机识别";+"%lld 句" = "%lld 句";+"识别你说的" = "识别你说的";+"半句翻译" = "半句翻译";"Ling 请求速度" = "Ling 请求速度";"排队最久" = "排队最久";-"本场用量" = "本场用量";+"请求太密时,纪要让翻译先走" = "请求太密时,纪要让翻译先走";+"服务返回的数,以服务的账单为准" = "服务返回的数,以服务的账单为准";"%.1f / 2 次每秒" = "%.1f / 2 次每秒";+"%lld 次 · %lld token · %lld 字语音" = "%lld 次 · %lld token · %lld 字语音";"%lld 次 · %lld token" = "%lld 次 · %lld token";"还没有" = "还没有";"你" = "你";@@ -234,6 +250,9 @@"文字记录已转到 %@ / %@" = "文字记录已转到 %@ / %@";"还有 %lld 句在翻译" = "还有 %lld 句在翻译";"纪要等文字记录转完再整理;正在听的会议优先" = "纪要等文字记录转完再整理;正在听的会议优先";+"这场会议只留下了录音" = "这场会议只留下了录音";+"当时没听出是哪种语言。选一下,就按它转成文字" = "当时没听出是哪种语言。选一下,就按它转成文字";+"其他语言…" = "其他语言…";"找不到原文件,没法播放" = "找不到原文件,没法播放";"暂停" = "暂停";"播放" = "播放";@@ -377,7 +396,6 @@"收成小卡" = "收成小卡";"正在听 · " = "正在听 · ";"正在记录 · " = "正在记录 · ";-"%lld 句" = "%lld 句";"刚刚更新" = "刚刚更新";"%lld 秒前更新" = "%lld 秒前更新";"%lld 分钟前更新" = "%lld 分钟前更新";@@ -567,7 +585,6 @@/* SettingsWindow */"语言" = "语言";"通用" = "通用";-"AI 服务" = "AI 服务";"诊断" = "诊断";"有人说话时" = "有人说话时";"始终显示" = "始终显示";@@ -885,6 +902,7 @@"本周" = "本周";"收起更早的会议" = "收起更早的会议";"更早的会议" = "更早的会议";+"只有录音" = "只有录音";"未命名会议" = "未命名会议";"转写中 %lld%%" = "转写中 %lld%%";"翻译中" = "翻译中";@@ -906,6 +924,7 @@"葡语" = "葡语";"正在听,说话的内容会出现在这里" = "正在听,说话的内容会出现在这里";"转出的文字会陆续出现在这里" = "转出的文字会陆续出现在这里";+"还没有文字记录" = "还没有文字记录";"这场会议没有记录到内容" = "这场会议没有记录到内容";"还没有会议" = "还没有会议";"打开会议或视频,开始听后,每一场都会存在这里。" = "打开会议或视频,开始听后,每一场都会存在这里。";@@ -979,6 +998,7 @@"录制" = "录制";"录 15 秒原声,对方听到你的音色,晚约 3 秒" = "录 15 秒原声,对方听到你的音色,晚约 3 秒";"已录 %lld 秒 · %@" = "已录 %lld 秒 · %@";+"读得偏慢" = "读得偏慢";"重录" = "重录";"最像你" = "最像你";"会带你的口音" = "会带你的口音";@@ -998,7 +1018,6 @@"用你的声音说%@" = "用你的声音说%@";"对方会听到这个" = "对方会听到这个";"用这个声音" = "用这个声音";-"读得偏慢" = "读得偏慢";/* Voices */"美式" = "美式";@@ -1020,5 +1039,5 @@"麦克风没收到声音,请检查麦克风权限" = "麦克风没收到声音,请检查麦克风权限";"无法打开麦克风:%@" = "无法打开麦克风:%@";"录音太短了,请至少朗读 %lld 秒" = "录音太短了,请至少朗读 %lld 秒";-"没听清录音内容,请换个安静的地方再录一次" = "没听清录音内容,请换个安静的地方再录一次";"读得有点慢,克隆的声音也会这么慢。请用平时说话的语速再录一次" = "读得有点慢,克隆的声音也会这么慢。请用平时说话的语速再录一次";+"没听清录音内容,请换个安静的地方再录一次" = "没听清录音内容,请换个安静的地方再录一次";diff --git a/Sources/LiveSubs/AppModel.swift b/Sources/LiveSubs/AppModel.swiftindex 907f4c4..aad34a6 100644--- a/Sources/LiveSubs/AppModel.swift+++ b/Sources/LiveSubs/AppModel.swift@@ -183,6 +183,7 @@ final class AppModel: ObservableObject {await self?.listen.translate(text, source: from, target: to, kind: .speak, trace: TranslateTrace())}ling.onCall = { [weak self] in self?.diagnostics.record($0) }+ translator.onDraft = { [weak self] in self?.diagnostics.recordDraft(seconds: $0, ok: $1) }ling.config = { [weak self] in self?.settings.aiConfig ?? AIConfig(provider: .ling, base: AIProvider.ling.base, textModel: "Ling-3.1-flash") }listen.translator = translator@@ -1340,7 +1341,7 @@ final class AppModel: ObservableObject {setDiagnostics(arg != "off")debugLog("diagnostics \(settings.diagnostics ? "on" : "off")")case "diagReport":- debugLog("diag report:\n" + diagnostics.report(version: "", model: settings.textModel))+ debugLog("diag report:\n" + diagnostics.report(version: "", service: settings.aiConfig))case "micTest": installer.runTest()case "micNext": installer.next()case "sysMic":diff --git a/Sources/LiveSubs/Diagnostics.swift b/Sources/LiveSubs/Diagnostics.swiftindex 1f0bc96..aa56e2d 100644--- a/Sources/LiveSubs/Diagnostics.swift+++ b/Sources/LiveSubs/Diagnostics.swift@@ -5,12 +5,12 @@ import SwiftUI/// One provider tried for one translation, and why it fell through.struct TranslateAttempt: Codable {- let provider: String // ling / google / apple+ let provider: String // the AI service (ling, zenmux…) / ming / google / applelet seconds: Doublelet failure: String? // nil = this one answered}-/// Filled in by `TranslationService` as it walks Ling → Google → Apple.+/// Filled in by `TranslationService` as it walks the AI service → Google → Apple.@MainActorfinal class TranslateTrace {var attempts: [TranslateAttempt] = []@@ -38,18 +38,30 @@ struct SentenceTiming: Codable, Identifiable {let failed: Doublelet via: Stringlet fallbacks: [String]+ /// me: translation → the first sound in the room (what the other side waits for).+ var firstAudio: Double? = nilvar total: Double { (recognize ?? 0) + translate }}-/// One Ling request.-struct LingCall: Codable {+/// One request to the AI service (any provider, any model), written as `"type":"call"`.+struct AICall: Codable {let at: Date+ /// `AIProvider.ID` raw value: ling / openrouter / zenmux / openai / custom.+ let provider: String+ let model: String+ /// What it was for: translate / notes / voice / heard-me / speakers / test.+ let role: String+ /// The gate's lane (speak / translate / notes), not the use: speak-back translation is "translate".let priority: Stringlet queue: Doublelet seconds: Doublelet outcome: String // ok / rateLimited / hijacked / timeout / …let promptTokens: Intlet completionTokens: Int+ /// voice: characters spoken.+ var chars = 0+ /// voice: request start → first audio chunk.+ var firstAudio: Double?}// MARK: - Recorder@@ -59,7 +71,9 @@ struct LingCall: Codable {@MainActorfinal class Diagnostics: ObservableObject {@Published private(set) var sentences: [SentenceTiming] = []- @Published private(set) var calls: [LingCall] = []+ @Published private(set) var calls: [AICall] = []+ /// Partial translations, refreshed about every second while someone talks: counted, not listed.+ @Published private(set) var drafts = Drafts()@Published private(set) var startedAt: Date?/// When the meeting stopped: the header stops counting minutes.@Published private(set) var endedAt: Date?@@ -71,6 +85,7 @@ final class Diagnostics: ObservableObject {func begin() {sentences = []calls = []+ drafts = Drafts()startedAt = Date()endedAt = nil}@@ -87,11 +102,29 @@ final class Diagnostics: ObservableObject {s.fallbacks.isEmpty ? "" : " fallbacks=" + s.fallbacks.joined(separator: ",")))}- func record(_ c: LingCall) {+ func record(_ c: AICall) {guard enabled() else { return }calls.append(c)if calls.count > 1000 { calls.removeFirst(calls.count - 1000) }- write("ling", c)+ write("call", c)+ }++ struct Drafts: Equatable {+ var n = 0+ var failed = 0+ var seconds: [Double] = []+ }++ /// Memory only: a line per refresh would bury the sentences in metrics.jsonl.+ func recordDraft(seconds: Double, ok: Bool) {+ guard enabled() else { return }+ drafts.n += 1+ if ok {+ drafts.seconds.append(seconds)+ if drafts.seconds.count > 2000 { drafts.seconds.removeFirst(drafts.seconds.count - 2000) }+ } else {+ drafts.failed += 1+ }}private func write<T: Encodable>(_ type: String, _ value: T) {@@ -130,7 +163,60 @@ final class Diagnostics: ObservableObject {var recognize: Stat? { Self.stat(heard.compactMap(\.recognize)) }var translate: Stat? { Self.stat(heard.map(\.translate)) }var speakBack: Stat? { Self.stat(said.map { ($0.recognize ?? 0) + $0.translate }) }- var notesRounds: Stat? { Self.stat(calls.filter { $0.priority == "notes" && $0.outcome == "ok" }.map(\.seconds)) }+ var notesRounds: Stat? { Self.stat(calls.filter { $0.role == "notes" && $0.outcome == "ok" }.map(\.seconds)) }+ /// Key released → the first sound in the room.+ var toRoom: Stat? { Self.stat(said.compactMap { s in s.firstAudio.map { (s.recognize ?? 0) + s.translate + $0 } }) }+ /// What I said, recognized on this Mac (Ming hears it on the service instead: that's a call).+ var recognizeMine: Stat? { Self.stat(said.filter { $0.via != "ming" }.compactMap(\.recognize)) }+ var draftStat: Stat? { Self.stat(drafts.seconds) }++ /// One row of the diagnostics list: a use with the service and model it went to.+ struct Use: Identifiable {+ let role: String+ let provider: String+ let model: String+ var id: String { "\(role)|\(provider)|\(model)" }+ let n: Int+ let failed: Int+ /// ok requests; voice: to the first audio, not the whole clip.+ let latency: Stat?+ let tokens: Int+ let chars: Int+ /// Why the failed ones failed, most first.+ let reasons: [(String, Int)]+ }++ /// The uses shown, in this order; test scores and file imports only count in the totals.+ static let roles = ["translate", "heard-me", "voice", "notes", "speakers"]++ var uses: [Use] {+ Dictionary(grouping: calls.filter { Self.roles.contains($0.role) }) { "\($0.role)|\($0.provider)|\($0.model)" }+ .values.compactMap { xs -> Use? in+ guard let c = xs.first else { return nil }+ let ok = xs.filter { $0.outcome == "ok" }+ // A voice cut short on purpose (stop, a new press) isn't a failure.+ let failed = xs.filter { $0.outcome != "ok" && $0.outcome != "cancelled" }+ var reasons: [String: Int] = [:]+ for f in failed { reasons[f.outcome, default: 0] += 1 }+ return Use(role: c.role, provider: c.provider, model: c.model, n: xs.count, failed: failed.count,+ latency: Self.stat(c.role == "voice" ? ok.compactMap(\.firstAudio) : ok.map(\.seconds)),+ tokens: xs.reduce(0) { $0 + $1.promptTokens + $1.completionTokens },+ chars: xs.reduce(0) { $0 + $1.chars },+ reasons: reasons.sorted { $0.value > $1.value }.map { ($0.key, $0.value) })+ }+ .sorted { a, b in+ let (i, j) = (Self.roles.firstIndex(of: a.role) ?? 99, Self.roles.firstIndex(of: b.role) ?? 99)+ return i != j ? i < j : a.n > b.n+ }+ }++ /// Sentences the AI service gave up on, by who answered instead (google / apple / none), most first.+ var retreats: [(String, Int)] {+ let services = Set(AIProvider.all.map(\.id.rawValue))+ let xs = sentences.filter { s in s.fallbacks.contains { services.contains(String($0.split(separator: ":").first ?? "")) } }+ return Dictionary(grouping: xs, by: \.via).map { ($0.key, $0.value.count) }.sorted { $0.1 > $1.1 }+ }+ var voiceChars: Int { calls.filter { $0.role == "voice" }.reduce(0) { $0 + $1.chars } }/// How many sentences each provider answered, most first.var viaCounts: [(String, Int, Double)] {@@ -139,15 +225,15 @@ final class Diagnostics: ObservableObject {}.sorted { $0.1 > $1.1 }}- /// Why Ling (or Google) was passed over: hijacked, rateLimited, timeout…+ /// Why the AI service (or Google) was passed over: hijacked, rateLimited, timeout…var fallbackCounts: [(String, Int)] {var counts: [String: Int] = [:]for s in sentences { for f in s.fallbacks { counts[f, default: 0] += 1 } }- for c in calls where c.outcome == "rateLimited" && c.priority == "notes" { counts["notes:rateLimited", default: 0] += 1 }+ for c in calls where c.outcome == "rateLimited" && c.role == "notes" { counts["notes:rateLimited", default: 0] += 1 }return counts.sorted { $0.value > $1.value }.map { ($0.key, $0.value) }}- /// Ling requests started in the last 10 s, per second (the account allows about 2).+ /// Requests started in the last 10 s, per second (a Ling account allows about 2).var lingRate: Double {let since = Date().addingTimeInterval(-10)return Double(calls.filter { $0.at > since }.count) / 10@@ -155,20 +241,29 @@ final class Diagnostics: ObservableObject {var maxQueue: Double { calls.map(\.queue).max() ?? 0 }var tokens: (Int, Int) { calls.reduce((0, 0)) { ($0.0 + $1.promptTokens, $0.1 + $1.completionTokens) } }- /// Plain text for "复制诊断信息": numbers only, safe to paste anywhere.- func report(version: String, model: String) -> String {+ /// Plain text for "复制诊断信息": numbers only, safe to paste anywhere. Full model names live+ /// here, the page shortens them.+ func report(version: String, service: AIConfig) -> String {func f(_ s: Stat?) -> String { s.map { String(format: "p50 %.2fs p95 %.2fs n=%d", $0.p50, $0.p95, $0.n) } ?? "-" }- var lines = [L("\(appDisplayName) \(version) 诊断 \(Date())"), L("模型 \(model)")]+ var lines = [L("\(appDisplayName) \(version) 诊断 \(Date())"),+ "AI: \(service.provider.id.rawValue) · \(service.textModel)" + (service.voiceModel.map { " · " + $0 } ?? "")]if let startedAt { lines.append(String(format: L("本场 %.0f 分钟"), (endedAt ?? Date()).timeIntervalSince(startedAt) / 60)) }lines.append(L("说完到出字幕 ") + f(endToEnd))lines.append(L("识别定稿 ") + f(recognize))lines.append(L("翻译 ") + f(translate))- lines.append(L("同声传译(松开到译好)") + f(speakBack))- lines.append(L("单轮纪要耗时 ") + f(notesRounds))+ lines.append(L("同声传译(松开到对方听到)") + f(toRoom))+ for u in uses {+ var line = "\(u.role) \(u.provider) \(u.model) \(f(u.latency)) calls=\(u.n) failed=\(u.failed)"+ if !u.reasons.isEmpty { line += " (" + u.reasons.map { "\($0.0) \($0.1)" }.joined(separator: ", ") + ")" }+ if u.tokens > 0 { line += " tokens=\(u.tokens)" }+ if u.chars > 0 { line += " chars=\(u.chars)" }+ lines.append(line)+ }+ if drafts.n > 0 { lines.append("draft google \(f(draftStat)) calls=\(drafts.n) failed=\(drafts.failed)") }lines.append(L("翻译来源 ") + viaCounts.map { String(format: "%@ %d (p50 %.2fs)", $0.0, $0.1, $0.2) }.joined(separator: " · "))lines.append(L("换后备 ") + (fallbackCounts.isEmpty ? L("无") : fallbackCounts.map { "\($0.0) \($0.1)" }.joined(separator: " · ")))let t = tokens- lines.append(String(format: L("Ling 请求 %d 次 · 排队最久 %.2fs · token %d/%d"), calls.count, maxQueue, t.0, t.1))+ lines.append(String(format: L("AI 请求 %d 次 · 排队最久 %.2fs · token %d/%d"), calls.count, maxQueue, t.0, t.1))return lines.joined(separator: "\n")}}@@ -177,7 +272,8 @@ final class Diagnostics: ObservableObject {struct DiagnosticsView: View {@ObservedObject var diagnostics: Diagnostics- var model: String = ""+ /// The service in settings: names the group, and the empty page before any request.+ var service: AIConfig@State private var copied = false@State private var tick = Date()private let timer = Timer.publish(every: 2, on: .main, in: .common).autoconnect()@@ -192,14 +288,13 @@ struct DiagnosticsView: View {emptyChannelsemptyRecent} else {+ // What people feel; each step's time is in the list below.HStack(spacing: 8) {- tile(L("说完到上屏"), diagnostics.endToEnd, dark: true)- tile(L("识别定稿"), diagnostics.recognize)- tile(L("翻译"), diagnostics.translate)- tile(L("纪要一轮"), diagnostics.notesRounds)+ tile(L("对方说完 → 你看到字幕"), diagnostics.endToEnd, dark: true)+ tile(L("你说完 → 对方听到"), diagnostics.toRoom)}- providers- lingCard+ uses+ totalsrecent}HStack(spacing: 8) {@@ -283,17 +378,11 @@ struct DiagnosticsView: View {private var emptyChannels: some View {SettingsCard {- SettingsRow(title: L("翻译通道")) {- HStack(spacing: 12) {- ForEach(["ling", "google", "apple"], id: \.self) { v in- HStack(spacing: 5) {- RoundedRectangle(cornerRadius: 2).fill(Self.color(v)).frame(width: 8, height: 8)- Text(Self.name(v)).font(.system(size: 12)).foregroundStyle(Palette.secondary)- }- }- }+ SettingsRow(title: L("AI 服务"), detail: service.provider.id == .ling ? L("账号上限约每秒 2 次") : nil) {+ Text("\(service.provider.name) · \(Self.short(service.textModel))").font(.system(size: 12))+ .foregroundStyle(Palette.secondary).lineLimit(1)}- SettingsRow(title: L("Ling 用量"), detail: L("账号上限约每秒 2 次"), divider: false) {+ SettingsRow(title: L("本场用量"), divider: false) {Text("本场还没调用").font(.system(size: 12)).foregroundStyle(Palette.tertiary)}}@@ -333,28 +422,29 @@ struct DiagnosticsView: View {}}+ /// The service's own ids (ling, zenmux…), as recorded in `via` and the fallbacks.+ private static func serviceName(_ id: String) -> String? { AIProvider.all.first { $0.id.rawValue == id }?.name }+private static func color(_ via: String) -> Color {switch via {- case "ling": Palette.inkcase "google": Palette.accentcase "ming": Palette.accentInk- default: Color(red: 0.72, green: 0.74, blue: 0.78)+ default: serviceName(via) != nil ? Palette.ink : Color(red: 0.72, green: 0.74, blue: 0.78)}}private static func name(_ via: String) -> String {switch via {- case "ling": "Ling"case "google": "Google"case "apple": L("本机")case "ming": L("Ming 语音")- default: L("没译出")+ default: serviceName(via) ?? L("没译出")}}private static func reason(_ key: String) -> String {let parts = key.split(separator: ":").map(String.init)- let who = parts.first.map { $0 == "ling" ? "Ling" : $0 == "google" ? "Google" : $0 == "notes" ? L("纪要") : $0 == "ming" ? L("Ming 语音") : L("本机") } ?? ""+ let who = parts.count < 2 ? "" : parts.first.map { $0 == "google" ? "Google" : $0 == "notes" ? L("纪要") : $0 == "ming" ? L("Ming 语音") : serviceName($0) ?? L("本机") } ?? ""let why: Stringswitch parts.last ?? "" {case "hijacked": why = L("被搜索劫持")@@ -365,67 +455,137 @@ struct DiagnosticsView: View {case "unavailable": why = L("未安装语言包")default: why = parts.last ?? ""}- return "\(who) \(why)"+ return who.isEmpty ? why : "\(who) \(why)"}- private var providers: some View {- let counts = diagnostics.viaCounts- let total = max(1, counts.reduce(0) { $0 + $1.1 })- return VStack(alignment: .leading, spacing: 10) {- HStack {- Text("翻译通道分布").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)- Spacer()- Text("共 \(diagnostics.sentences.count) 句").font(.system(size: 12)).foregroundStyle(Palette.tertiary)+ /// "inclusionai/ling-3.0-flash" → "ling-3.0-flash": the vendor is in the group name already.+ static func short(_ model: String) -> String { model.split(separator: "/").last.map(String.init) ?? model }++ private static func seconds(_ x: Double) -> String { String(format: "%.1fs", x) }++ private static func count(_ n: Int) -> String { n >= 1000 ? String(format: "%.1fk", Double(n) / 1000) : "\(n)" }++ private static func title(_ role: String) -> String {+ switch role {+ case "translate": L("整句翻译")+ case "heard-me": L("听懂你说的")+ case "voice": L("同传声音")+ case "notes": L("实时纪要")+ case "speakers": L("认出说话人")+ default: role+ }+ }++ /// 1A: one row per use, a single big number (p50) with p95 under it. Uses that follow the AI+ /// service come first; the ones fixed on this Mac or Google come after, so switching service+ /// visibly changes only the first group.+ private var uses: some View {+ let uses = diagnostics.uses+ let retreats = diagnostics.retreats+ let current = service.provider.id.rawValue+ return VStack(alignment: .leading, spacing: 0) {+ group(L("跟着 AI 服务走 · \(service.provider.name)"))+ if uses.isEmpty {+ Text("本场还没调用").font(.system(size: 12)).foregroundStyle(Palette.tertiary).padding(.vertical, 9)}- GeometryReader { geo in- HStack(spacing: 2) {- ForEach(counts, id: \.0) { c in- Rectangle().fill(Self.color(c.0)).frame(width: max(2, geo.size.width * CGFloat(c.1) / CGFloat(total) - 2))- }- if counts.isEmpty { Rectangle().fill(Palette.fill) }+ ForEach(Array(uses.enumerated()), id: \.element.id) { i, u in+ let model = (u.provider == current ? "" : (Self.serviceName(u.provider) ?? u.provider) + " · ") + Self.short(u.model)+ var foot = [L("\(u.n) 次")]+ if u.tokens > 0 { foot.append("\(Self.count(u.tokens)) token") }+ if u.chars > 0 { foot.append(L("\(u.chars) 字")) }+ var pill: String?+ let why = u.reasons.prefix(2).map { "\(Self.reason($0.0)) \($0.1)" }.joined(separator: "、")+ if u.role == "translate", let top = retreats.first {+ let n = retreats.reduce(0) { $0 + $1.1 }+ pill = L("\(n) 句退回 \(Self.name(top.0))") + (why.isEmpty ? "" : " · " + why)+ } else if u.failed > 0 {+ pill = L("失败 \(u.failed)") + (why.isEmpty ? "" : " · " + why)+ } else {+ foot.append(L("没有失败"))}- .clipShape(RoundedRectangle(cornerRadius: 5))+ return useRow(Self.title(u.role), u.role == "voice" ? model + " · " + L("到开始出声") : model,+ u.latency, foot: foot, pill: pill, divider: i > 0)}- .frame(height: 10)- HStack(spacing: 14) {- ForEach(counts, id: \.0) { c in- HStack(spacing: 6) {- RoundedRectangle(cornerRadius: 2).fill(Self.color(c.0)).frame(width: 8, height: 8)- Text(String(format: "%@ %d · %.1fs", Self.name(c.0), c.1, c.2)).font(.system(size: 12).monospacedDigit())- .foregroundStyle(Palette.secondary)- }+ let fixed = fixedRows+ if !fixed.isEmpty {+ group(L("不受换服务影响")).padding(.top, 12)+ ForEach(Array(fixed.enumerated()), id: \.offset) { i, r in+ useRow(r.title, r.detail, r.stat, foot: r.foot, dim: true, divider: i > 0)}}- if !diagnostics.fallbackCounts.isEmpty {+ }+ .padding(14)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(RoundedRectangle(cornerRadius: 12).fill(Color.white))+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(Palette.line, lineWidth: 1))+ }++ private var fixedRows: [(title: String, detail: String, stat: Diagnostics.Stat?, foot: [String])] {+ var rows: [(title: String, detail: String, stat: Diagnostics.Stat?, foot: [String])] = []+ if let r = diagnostics.recognize { rows.append((L("识别对方"), L("本机识别"), r, [L("\(r.n) 句")])) }+ if let r = diagnostics.recognizeMine { rows.append((L("识别你说的"), L("本机识别"), r, [L("\(r.n) 句")])) }+ let d = diagnostics.drafts+ if d.n > 0 {+ rows.append((L("半句翻译"), "Google", diagnostics.draftStat,+ [L("\(d.n) 次"), d.failed > 0 ? L("失败 \(d.failed)") : L("没有失败")]))+ }+ return rows+ }++ private func group(_ title: String) -> some View {+ Text(title).font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.tertiary).padding(.bottom, 2)+ }++ private func useRow(_ title: String, _ detail: String, _ s: Diagnostics.Stat?, foot: [String] = [], pill: String? = nil,+ dim: Bool = false, divider: Bool) -> some View {+ VStack(alignment: .leading, spacing: 4) {+ HStack(alignment: .top, spacing: 12) {+ VStack(alignment: .leading, spacing: 2) {+ Text(title).font(.system(size: 13, weight: dim ? .medium : .semibold)).foregroundStyle(Palette.ink)+ Text(detail).font(.system(size: 11)).foregroundStyle(Palette.secondary).lineLimit(1).truncationMode(.middle)+ }+ Spacer(minLength: 0)+ VStack(alignment: .trailing, spacing: 1) {+ Text(s.map { Self.seconds($0.p50) } ?? "—")+ .font(.system(size: dim ? 15 : 18, weight: .bold).monospacedDigit()).foregroundStyle(Palette.ink)+ if let s { Text("p95 " + Self.seconds(s.p95)).font(.system(size: 10).monospacedDigit()).foregroundStyle(Palette.tertiary) }+ }+ }+ if pill != nil || !foot.isEmpty {HStack(spacing: 6) {- ForEach(diagnostics.fallbackCounts.prefix(4), id: \.0) { f in- Text("\(Self.reason(f.0)) \(f.1)").font(.system(size: 12))- .foregroundStyle(f.0.hasSuffix("hijacked") ? Palette.accentInk : Palette.secondary)- .padding(.horizontal, 8).padding(.vertical, 3)- .background(RoundedRectangle(cornerRadius: 6).fill(f.0.hasSuffix("hijacked") ? Palette.accentPale : Palette.fill))+ if let pill {+ Text(pill).font(.system(size: 10.5, weight: .semibold)).foregroundStyle(Palette.accentInk).lineLimit(1)+ .padding(.horizontal, 7).padding(.vertical, 1.5)+ .background(Capsule().fill(Palette.accentPale))}+ Text(foot.joined(separator: " · ")).font(.system(size: 11).monospacedDigit()).foregroundStyle(Palette.tertiary)+ .lineLimit(1)}}}- .padding(14)- .background(RoundedRectangle(cornerRadius: 12).fill(Color.white))- .overlay(RoundedRectangle(cornerRadius: 12).stroke(Palette.line, lineWidth: 1))+ .padding(.vertical, 9)+ .frame(maxWidth: .infinity, alignment: .leading)+ .overlay(alignment: .top) { if divider { Rectangle().fill(Palette.line).frame(height: 1) } }}- private var lingCard: some View {+ private var totals: some View {let _ = ticklet t = diagnostics.tokens+ let n = diagnostics.calls.count+ let chars = diagnostics.voiceCharsreturn SettingsCard {- SettingsRow(title: L("Ling 请求速度"), detail: L("账号上限约每秒 2 次")) {- Text(String(format: L("%.1f / 2 次每秒"), diagnostics.lingRate)).font(.system(size: 12).monospacedDigit())- .foregroundStyle(Palette.secondary)+ if service.provider.id == .ling {+ SettingsRow(title: L("Ling 请求速度"), detail: L("账号上限约每秒 2 次")) {+ Text(String(format: L("%.1f / 2 次每秒"), diagnostics.lingRate)).font(.system(size: 12).monospacedDigit())+ .foregroundStyle(Palette.secondary)+ }}- SettingsRow(title: L("排队最久")) {+ SettingsRow(title: L("排队最久"), detail: L("请求太密时,纪要让翻译先走")) {Text(String(format: "%.1fs", diagnostics.maxQueue)).font(.system(size: 12).monospacedDigit()).foregroundStyle(Palette.secondary)}- SettingsRow(title: L("本场用量"), divider: false) {- Text("\(diagnostics.calls.count) 次 · \(t.0 + t.1) token").font(.system(size: 12).monospacedDigit())- .foregroundStyle(Palette.secondary)+ SettingsRow(title: L("本场用量"), detail: L("服务返回的数,以服务的账单为准"), divider: false) {+ Text(chars > 0 ? L("\(n) 次 · \(t.0 + t.1) token · \(chars) 字语音") : L("\(n) 次 · \(t.0 + t.1) token"))+ .font(.system(size: 12).monospacedDigit()).foregroundStyle(Palette.secondary)}}}@@ -448,7 +608,7 @@ struct DiagnosticsView: View {.frame(width: 150, alignment: .leading)bar(s)Spacer(minLength: 0)- Text(String(format: "%.1fs", s.total + (s.voice ?? 0))).font(.system(size: 12, weight: .semibold).monospacedDigit())+ Text(String(format: "%.1fs", s.total + (s.firstAudio ?? s.voice ?? 0))).font(.system(size: 12, weight: .semibold).monospacedDigit())}.frame(height: 34)}@@ -466,7 +626,8 @@ struct DiagnosticsView: View {if s.queue > 0.05 { seg(s.queue, Color(red: 0.96, green: 0.78, blue: 0.71), scale) }if fallback > 0.05 { seg(fallback, Palette.accent, scale) }seg(max(0.02, s.translate - s.queue - fallback), Palette.ink, scale)- if let v = s.voice { seg(v, Color(red: 0.60, green: 0.63, blue: 0.67), scale) }+ // Speak-back counts to the first sound, not the whole clip: that's what the other side waits for.+ if let v = s.firstAudio ?? s.voice { seg(v, Color(red: 0.60, green: 0.63, blue: 0.67), scale) }}.frame(width: 200, alignment: .leading).clipped()}@@ -483,7 +644,7 @@ struct DiagnosticsView: View {private func copy() {let text = diagnostics.report(version: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "",- model: model)+ service: service)NSPasteboard.general.clearContents()NSPasteboard.general.setString(text, forType: .string)copied = truediff --git a/Sources/LiveSubs/Ling.swift b/Sources/LiveSubs/Ling.swiftindex ad1aed0..6b19fea 100644--- a/Sources/LiveSubs/Ling.swift+++ b/Sources/LiveSubs/Ling.swift@@ -279,7 +279,7 @@ final class LingClient: ObservableObject {/// instruction, for Ming's audio model (Ling only: `hearsAudio`).func chat(content: String, instruction: String, priority: Priority, json: Bool = false,maxTokens: Int = 1024, timeout: TimeInterval = 30, model: String? = nil, audio: Data? = nil,- onQueued: ((Double) -> Void)? = nil) async throws -> String {+ role: String? = nil, onQueued: ((Double) -> Void)? = nil) async throws -> String {guard let key else { throw Failure.noKey }guard keyState != .invalid else { throw Failure.invalidKey }if let simulate {@@ -287,8 +287,10 @@ final class LingClient: ObservableObject {throw simulate}let c = config()+ let call = CallLabel(provider: c.provider.id.rawValue, model: model ?? c.textModel,+ role: role ?? (priority == .notes ? "notes" : "translate"))var body: [String: Any] = [- "model": model ?? c.textModel,+ "model": call.model,"messages": [["role": "system", "content": content],["role": "user", "content": audio.map { wav -> Any in@@ -322,12 +324,12 @@ final class LingClient: ObservableObject {let ms = Int(Date().timeIntervalSince(started) * 1000)let usage = root["usage"] as? [String: Any]debugLog("ling: \(priority) ok \(ms) ms tokens=\(usage?["prompt_tokens"] ?? "?")/\(usage?["completion_tokens"] ?? "?")")- report(priority, at: started, queued: queued, outcome: "ok",+ report(call, priority, at: started, queued: queued, outcome: "ok",tokens: (usage?["prompt_tokens"] as? Int ?? 0, usage?["completion_tokens"] as? Int ?? 0))if rateLimitedAt != nil { rateLimitedAt = nil }return trimmed} catch let failure as Failure {- report(priority, at: started, queued: queued, outcome: Self.name(failure))+ report(call, priority, at: started, queued: queued, outcome: Self.name(failure))guard failure == .rateLimited else { throw failure }guard attempt < attempts else {rateLimitedAt = Date()@@ -343,11 +345,16 @@ final class LingClient: ObservableObject {}/// Every request, for diagnostics (timings and token counts only).- var onCall: ((LingCall) -> Void)?+ var onCall: ((AICall) -> Void)?- private func report(_ priority: Priority, at started: Date, queued: Double, outcome: String, tokens: (Int, Int) = (0, 0)) {- onCall?(LingCall(at: started, priority: "\(priority)", queue: queued, seconds: Date().timeIntervalSince(started),- outcome: outcome, promptTokens: tokens.0, completionTokens: tokens.1))+ /// Which service, model and use a request is for: the diagnostics page groups by these.+ struct CallLabel { let provider, model, role: String }++ private func report(_ call: CallLabel, _ priority: Priority, at started: Date, queued: Double, outcome: String,+ tokens: (Int, Int) = (0, 0), chars: Int = 0, firstAudio: Double? = nil) {+ onCall?(AICall(at: started, provider: call.provider, model: call.model, role: call.role, priority: "\(priority)",+ queue: queued, seconds: Date().timeIntervalSince(started), outcome: outcome,+ promptTokens: tokens.0, completionTokens: tokens.1, chars: chars, firstAudio: firstAudio))}static func name(_ failure: Failure) -> String {@@ -373,7 +380,16 @@ final class LingClient: ObservableObject {guard let self, let key = self.key else { cont.finish(throwing: Failure.noKey); return }let c = self.config()guard let base = c.voiceBase, let voiceModel = c.voiceModel else { cont.finish(throwing: Failure.noKey); return }+ let asked = Date()await self.acquire(.speak)+ let queued = Date().timeIntervalSince(asked)+ let started = Date()+ var firstAudio: Double?+ let call = CallLabel(provider: c.provider.id.rawValue, model: voiceModel, role: "voice")+ func yield(_ pcm: Data) {+ if firstAudio == nil { firstAudio = Date().timeIntervalSince(started) }+ cont.yield(pcm)+ }var req = URLRequest(url: base.appendingPathComponent("audio/speech"))req.httpMethod = "POST"req.timeoutInterval = 20@@ -415,26 +431,30 @@ final class LingClient: ObservableObject {let obj = try? JSONSerialization.jsonObject(with: Data(line.dropFirst(5).utf8)) as? [String: Any]else { continue }if obj["type"] as? String == "speech.audio.done" { break }- if let b64 = obj["audio"] as? String, let pcm = Data(base64Encoded: b64) { cont.yield(pcm) }+ if let b64 = obj["audio"] as? String, let pcm = Data(base64Encoded: b64) { yield(pcm) }}} else if type.contains("json") {var data = Data()for try await b in bytes { data.append(b) }guard let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any],let b64 = obj["audio"] as? String, let wav = Data(base64Encoded: b64) else { throw Failure.parse }- cont.yield(Self.pcm(fromWAV: wav))+ yield(Self.pcm(fromWAV: wav))} else {// Raw PCM: hand it on in 0.1 s pieces so playback starts early.var chunk = Data()chunk.reserveCapacity(4800)for try await b in bytes {chunk.append(b)- if chunk.count >= 4800 { cont.yield(chunk); chunk.removeAll(keepingCapacity: true) }+ if chunk.count >= 4800 { yield(chunk); chunk.removeAll(keepingCapacity: true) }}- if !chunk.isEmpty { cont.yield(chunk) }+ if !chunk.isEmpty { yield(chunk) }}+ self.report(call, .speak, at: started, queued: queued, outcome: "ok", chars: text.count, firstAudio: firstAudio)cont.finish()} catch {+ // Cancelled: the voice was cut short on purpose (stop, a new press), not a failure.+ let outcome = Task.isCancelled ? "cancelled" : (error as? Failure).map(Self.name) ?? "network"+ self.report(call, .speak, at: started, queued: queued, outcome: outcome, chars: text.count, firstAudio: firstAudio)cont.finish(throwing: error)}}diff --git a/Sources/LiveSubs/SettingsWindow.swift b/Sources/LiveSubs/SettingsWindow.swiftindex 3f3b2c7..be49f0a 100644--- a/Sources/LiveSubs/SettingsWindow.swift+++ b/Sources/LiveSubs/SettingsWindow.swift@@ -442,7 +442,7 @@ struct SettingsView: View {case .language: LanguageSettings(model: model, settings: settings)case .records: recordscase .ai: AISettingsView(model: model, ling: model.ling, settings: settings)- case .diagnostics: DiagnosticsView(diagnostics: model.diagnostics, model: settings.textModel)+ case .diagnostics: DiagnosticsView(diagnostics: model.diagnostics, service: settings.aiConfig)}}.padding(.leading, 12).padding(.trailing, 28).padding(.top, 40).padding(.bottom, 28)diff --git a/Sources/LiveSubs/SpeakEngine.swift b/Sources/LiveSubs/SpeakEngine.swiftindex c7bb54c..69c5096 100644--- a/Sources/LiveSubs/SpeakEngine.swift+++ b/Sources/LiveSubs/SpeakEngine.swift@@ -431,10 +431,11 @@ final class SpeakEngine {probe?.via = result == nil ? "none" : trace.viaprobe?.from = fromprobe?.to = to- @MainActor func timing(voice: Double?) -> SentenceTiming {+ @MainActor func timing(voice: Double?, firstAudio: Double? = nil) -> SentenceTiming {SentenceTiming(at: textAt, side: "me", chars: text.count, recognize: textAt.timeIntervalSince(released),queue: trace.lingQueue, translate: translatedAt.timeIntervalSince(textAt), voice: voice,- failed: trace.failedSeconds, via: result == nil ? "none" : trace.via, fallbacks: trace.fallbacks)+ failed: trace.failedSeconds, via: result == nil ? "none" : trace.via, fallbacks: trace.fallbacks,+ firstAudio: firstAudio)}guard let translated = result else {debugLog("speak: translation failed, nothing sent")@@ -456,7 +457,8 @@ final class SpeakEngine {probe.device = lastDeviceprobe.finish()} else {- onTiming?(timing(voice: Date().timeIntervalSince(translatedAt)))+ onTiming?(timing(voice: Date().timeIntervalSince(translatedAt),+ firstAudio: firstAudioAt.map { $0.timeIntervalSince(translatedAt) }))if let first = firstAudioAt { onLatency?(first.timeIntervalSince(released)) }}if phase == .speaking { phase = .idle }diff --git a/Sources/LiveSubs/SpeakTest.swift b/Sources/LiveSubs/SpeakTest.swiftindex 57e8e47..126e70f 100644--- a/Sources/LiveSubs/SpeakTest.swift+++ b/Sources/LiveSubs/SpeakTest.swift@@ -456,7 +456,7 @@ final class SpeakTester: ObservableObject {let instruction = "Score from 0 to 100 how faithfully what the listener heard conveys the original's meaning. "+ "Reply as JSON: {\"score\": <0-100>, \"issue\": \"<the main problem in at most 12 words of \(TranslationService.englishName(from)), or empty>\"}"if let reply = try? await ling.chat(content: content, instruction: instruction, priority: .translate, json: true,- maxTokens: 120, timeout: 10),+ maxTokens: 120, timeout: 10, role: "test"),let v = SpeakScore.parseJudge(reply) {return .score(v.score, v.issue)}diff --git a/Sources/LiveSubs/SpeakerID.swift b/Sources/LiveSubs/SpeakerID.swiftindex 2c3c86e..d886ba2 100644--- a/Sources/LiveSubs/SpeakerID.swift+++ b/Sources/LiveSubs/SpeakerID.swift@@ -445,7 +445,7 @@ final class SpeakerNamer: ObservableObject {defer { busy.remove(id) }do {let reply = try await ling.chat(content: content, instruction: SpeakerNameGuess.instruction,- priority: .notes, json: true, maxTokens: 300)+ priority: .notes, json: true, maxTokens: 300, role: "speakers")let (found, read) = SpeakerNameGuess.read(reply, s)var refuted = readfor (key, g) in s.voiceGuesses ?? [:] {diff --git a/Sources/LiveSubs/Translator.swift b/Sources/LiveSubs/Translator.swiftindex adb86ac..7587345 100644--- a/Sources/LiveSubs/Translator.swift+++ b/Sources/LiveSubs/Translator.swift@@ -69,19 +69,34 @@ final class TranslationService {/// Debug (`translateFail:<n>`): the next n sentences fail on every provider, to test the retry.var failNext = 0+ /// Partial text (`.draft`) has no trace: each one reports here instead (seconds, answered), so+ /// diagnostics can count them without a line per refresh.+ var onDraft: ((Double, Bool) -> Void)?+func translate(_ text: String, source: String, target: String, kind: Kind, trace: TranslateTrace? = nil) async -> String? {if source == target { return text }+ if kind == .draft, let onDraft {+ let started = Date()+ let out = await chain(text, source: source, target: target, kind: kind, trace: trace)+ onDraft(Date().timeIntervalSince(started), out != nil)+ return out+ }+ return await chain(text, source: source, target: target, kind: kind, trace: trace)+ }++ private func chain(_ text: String, source: String, target: String, kind: Kind, trace: TranslateTrace?) async -> String? {if kind == .sentence, failNext > 0 {failNext -= 1- trace?.attempts.append(.init(provider: "ling", seconds: 0, failure: "simulated"))+ trace?.attempts.append(.init(provider: ling.provider.id.rawValue, seconds: 0, failure: "simulated"))return nil}if kind != .draft, ling.usable {let started = Date()let (out, failure) = await viaLing(text, source: source, target: target, kind: kind, trace: trace)- trace?.attempts.append(.init(provider: "ling", seconds: Date().timeIntervalSince(started), failure: out == nil ? failure : nil))+ trace?.attempts.append(.init(provider: ling.provider.id.rawValue, seconds: Date().timeIntervalSince(started),+ failure: out == nil ? failure : nil))if let out {- debugLog("translate via=ling kind=\(kind)")+ debugLog("translate via=\(ling.provider.id.rawValue) kind=\(kind)")return out}}@@ -127,6 +142,7 @@ final class TranslationService {let priority: LingClient.Priority = kind == .speak ? .speak : kind == .file ? .notes : .translatelet out = try await ling.chat(content: prompt, instruction: "Translate.", priority: priority,maxTokens: 400, timeout: kind == .speak ? 10 : kind == .file ? 20 : 6,+ role: kind == .file ? "file" : "translate",onQueued: { [weak trace] in trace?.lingQueue += $0 })if out.isEmpty { return (nil, "empty") }guard let clean = Self.cleanTranslation(out, target: target) else {@@ -160,7 +176,7 @@ final class TranslationService {do {// A 30 s press is ~1 MB of audio: a little more time than a text translation (10 s).let reply = try await ling.chat(content: prompt, instruction: instruction, priority: .speak, maxTokens: 800,- timeout: 12, model: "Ming-3.0-audio-flash", audio: wav,+ timeout: 12, model: "Ming-3.0-audio-flash", audio: wav, role: "heard-me",onQueued: { [weak trace] in trace?.lingQueue += $0 })if let parsed = Self.parseInterpretation(reply, target: target) {trace.attempts.append(.init(provider: "ming", seconds: Date().timeIntervalSince(started), failure: nil))diff --git a/Tests/LiveSubsTests/DiagnosticsTests.swift b/Tests/LiveSubsTests/DiagnosticsTests.swiftnew file mode 100644index 0000000..7fab10a--- /dev/null+++ b/Tests/LiveSubsTests/DiagnosticsTests.swift@@ -0,0 +1,111 @@+import Foundation+import Testing+@testable import LiveSubs++/// The diagnostics list: requests grouped by use, service and model; speak-back to the first sound;+/// partial translations counted in memory.+@MainActor struct DiagnosticsTests {+ private func diag() -> Diagnostics {+ let d = Diagnostics()+ d.enabled = { true }+ d.begin()+ return d+ }++ private func call(_ role: String, _ seconds: Double, outcome: String = "ok", provider: String = "zenmux",+ model: String = "inclusionai/ling-3.0-flash", tokens: Int = 10, chars: Int = 0,+ firstAudio: Double? = nil) -> AICall {+ AICall(at: Date(), provider: provider, model: model, role: role, priority: "translate", queue: 0, seconds: seconds,+ outcome: outcome, promptTokens: tokens, completionTokens: 0, chars: chars, firstAudio: firstAudio)+ }++ private func sentence(_ side: String, via: String, fallbacks: [String] = [], recognize: Double = 0.5,+ translate: Double = 1, firstAudio: Double? = nil) -> SentenceTiming {+ SentenceTiming(at: Date(), side: side, chars: 10, recognize: recognize, queue: 0, translate: translate, voice: nil,+ failed: 0, via: via, fallbacks: fallbacks, firstAudio: firstAudio)+ }++ @Test func usesGroupByRoleAndModelInOrder() {+ let d = diag()+ d.record(call("notes", 5))+ d.record(call("translate", 1))+ d.record(call("translate", 3))+ d.record(call("translate", 0.1, outcome: "rateLimited"))+ d.record(call("voice", 4, model: "google/gemini-3.8-flash-tts", tokens: 0, chars: 12, firstAudio: 0.9))+ d.record(call("voice", 2, outcome: "cancelled", model: "google/gemini-3.8-flash-tts", tokens: 0, chars: 5))+ d.record(call("test", 1))+ let uses = d.uses+ #expect(uses.map(\.role) == ["translate", "voice", "notes"]) // test scores aren't a use+ let t = uses[0]+ #expect(t.n == 3 && t.failed == 1 && t.tokens == 30)+ #expect(t.reasons.first?.0 == "rateLimited")+ #expect(t.latency?.n == 2) // only answered requests time the use+ let v = uses[1]+ #expect(v.failed == 0) // cut short on purpose isn't a failure+ #expect(v.latency?.p50 == 0.9) // to the first audio, not the whole clip+ #expect(v.chars == 17)+ }++ @Test func aModelSwitchMidMeetingIsItsOwnRow() {+ let d = diag()+ d.record(call("translate", 1, model: "a"))+ d.record(call("translate", 1, model: "b"))+ d.record(call("translate", 1, model: "b"))+ #expect(d.uses.map(\.model) == ["b", "a"])+ }++ @Test func retreatsCountSentencesTheServiceGaveUpOn() {+ let d = diag()+ d.record(sentence("them", via: "zenmux"))+ d.record(sentence("them", via: "google", fallbacks: ["zenmux:rateLimited"]))+ d.record(sentence("them", via: "google", fallbacks: ["zenmux:timeout"]))+ d.record(sentence("them", via: "apple", fallbacks: ["google:rateLimited"])) // Google's fallback, not the service's+ #expect(d.retreats.map(\.0) == ["google"])+ #expect(d.retreats.first?.1 == 2)+ }++ @Test func speakBackCountsToTheFirstSound() {+ let d = diag()+ d.record(sentence("me", via: "zenmux", recognize: 0.5, translate: 1, firstAudio: 0.9))+ d.record(sentence("me", via: "ming", recognize: 2, translate: 0, firstAudio: 1))+ #expect(d.toRoom?.n == 2)+ // recognize + translate + first sound: 0.5 + 1 + 0.9 and 2 + 0 + 1.+ #expect(abs((d.toRoom?.p95 ?? 0) - 3) < 0.001)+ // Ming hears it on the service: not recognized on this Mac.+ #expect(d.recognizeMine?.n == 1)+ }++ @Test func draftsAreCountedNotTimedWhenTheyFail() {+ let d = diag()+ d.recordDraft(seconds: 0.3, ok: true)+ d.recordDraft(seconds: 0.5, ok: true)+ d.recordDraft(seconds: 8, ok: false)+ #expect(d.drafts.n == 3 && d.drafts.failed == 1)+ #expect(d.draftStat?.n == 2)+ d.begin()+ #expect(d.drafts.n == 0)+ }++ @Test func nothingIsKeptWhileOff() {+ let d = Diagnostics()+ d.recordDraft(seconds: 1, ok: true)+ d.record(call("translate", 1))+ #expect(d.drafts.n == 0 && d.calls.isEmpty)+ }++ @Test func reportNamesTheServiceAndFullModel() {+ let d = diag()+ d.record(call("translate", 1.2))+ d.recordDraft(seconds: 0.3, ok: true)+ let config = AIConfig(provider: .zenmux, base: AIProvider.zenmux.base, textModel: "inclusionai/ling-3.0-flash")+ let text = d.report(version: "9.9.9", service: config)+ #expect(text.contains("AI: zenmux · inclusionai/ling-3.0-flash"))+ #expect(text.contains("translate zenmux inclusionai/ling-3.0-flash p50 1.20s"))+ #expect(text.contains("draft google"))+ }++ @Test func pageShortensTheModel() {+ #expect(DiagnosticsView.short("inclusionai/ling-3.0-flash") == "ling-3.0-flash")+ #expect(DiagnosticsView.short("Ling-3.1-flash") == "Ling-3.1-flash")+ }+}diff --git a/Tests/LiveSubsTests/LingTests.swift b/Tests/LiveSubsTests/LingTests.swiftindex 0f7a2a8..429ce0c 100644--- a/Tests/LiveSubsTests/LingTests.swift+++ b/Tests/LiveSubsTests/LingTests.swift@@ -127,6 +127,33 @@ final class LingStub: URLProtocol, @unchecked Sendable {#expect(messages[1]["content"] as? String == "Translate the system message.")}+ @Test func eachRequestIsReportedWithServiceModelAndUse() async throws {+ let ling = client()+ var calls: [AICall] = []+ ling.onCall = { calls.append($0) }+ LingStub.reset(200, LingStub.chatReply("ok"))+ _ = try await ling.chat(content: "x", instruction: "y", priority: .translate)+ _ = try await ling.chat(content: "x", instruction: "y", priority: .notes)+ _ = try await ling.chat(content: "x", instruction: "y", priority: .notes, model: "Ling-3.0-tiny", role: "speakers")+ #expect(calls.map(\.provider) == ["ling", "ling", "ling"])+ #expect(calls.map(\.role) == ["translate", "notes", "speakers"])+ #expect(calls.map(\.model) == ["Ling-3.1-flash", "Ling-3.1-flash", "Ling-3.0-tiny"])+ #expect(calls.allSatisfy { $0.outcome == "ok" })+ }++ @Test func voiceRequestsAreReportedWithFirstAudio() async throws {+ let ling = client()+ var calls: [AICall] = []+ ling.onCall = { calls.append($0) }+ LingStub.reset(200, "0123456789") // no Content-Type: raw PCM, one chunk+ var chunks = 0+ for try await _ in ling.speech("你好世界") { chunks += 1 }+ #expect(chunks == 1)+ let c = try #require(calls.first)+ #expect(c.role == "voice" && c.provider == "ling" && c.model == "Ming-3.0-tts-0.5B")+ #expect(c.outcome == "ok" && c.chars == 4 && c.firstAudio != nil && c.promptTokens == 0)+ }+@Test func rejectedKeyIsMarkedInvalid() async {let ling = client()LingStub.reset(401, "{}")