知了 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: put every language choice in one place, add an end-meeting flow, fix notes window bugs
wquguru218bd376fc24
diff --git a/AGENTS.md b/AGENTS.mdindex fec8f73..ba04b21 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -4,16 +4,16 @@ Cicada (知了, formerly Live Subs) is a macOS menu bar app that turns whatever## Scope (deliberately small)-- Few surfaces, nothing more: the **menu bar panel** (on/off, heard language, translate-to language, "同声传译", display mode, meeting records, quit), what shows while listening — the **live notes window** (default) or the **subtitle bar** or nothing (`displayMode`) —, the **main window** (meeting records) and a **settings window** (sidebar: 显示 (heard language and translate-to on top) / 同声传译 / 会议记录 / AI 服务, plus 诊断 when the bottom-left switch is on). First launch shows a three-step **onboarding** window (permissions, try the sample video, speaking).+- Few surfaces, nothing more: the **menu bar panel** (on/off, heard language, translate-to language, "同声传译", display mode, meeting records, quit), what shows while listening — the **live notes window** (default) or the **subtitle bar** or nothing (`displayMode`) —, the **main window** (meeting records) and a **settings window** (sidebar: 显示 / 语言 (`LanguageSettings`: heard language, 字幕 both/translation/original, translate-to, notes language mine/source, speak-back pair, under a route line) / 同声传译 / 会议记录 / AI 服务, plus 诊断 when the bottom-left switch is on). First launch shows a three-step **onboarding** window (permissions, try the sample video, speaking).- Listening: system audio (Core Audio process tap, our own process excluded) → spoken-language detection across installed on-device models → on-device transcription (`SpeechAnalyzer` / `SpeechTranscriber`) → translation → notes window caption or subtitle bar. Every confirmed sentence goes into the live meeting record. Translation (`TranslationService`): finished sentences and speak-back go to Ling when a key is set (glossary from the notes' terms), else or on any failure Google, then Apple's on-device `TranslationSession(installedSource:)`; partial text refreshed every second always goes to Google (it would use up Ling's rate limit).- Language detection compares confidence: the same 3–6 s clip after a pause is transcribed by every installed model; a winner needs confidence ≥ 0.6 and a 0.08 lead; the first detection or a 0.30 lead switches at once, otherwise two agreeing detections. After a switch the last 8 s are replayed into the new model.- "Follow system" translates into the first system language that differs from the source language.- Subtitle bar: shows only while someone talks (auto) or always; tucks into a dot after 2/4/8 s of quiet; fades to 15% and stays click-through while the pointer passes over it; editable after the pointer rests 0.6 s (drag to move, drag the corner to scale, double-click resets); ⌃⌥S (changeable) cycles the display mode (notes → bar → none). Position, width and size are remembered per display.- Speaking: hold the right ⌥ key alone (a listen-only event tap, needs Input Monitoring; any other key while held cancels the press as a chord) or a user-chosen combination (Carbon hotkey, no permission) → microphone → with a usable Ling key the press (16 kHz WAV, ≤ 60 s) goes to `Ming-3.0-audio-flash` in one `.speak` request that returns `ORIGINAL:` / `TRANSLATION:` lines (`TranslationService.interpret`; anything else is dropped, since the model sometimes answers a question instead of interpreting it; ~2 s, names right). One `SpeechAnalyzer` per press always runs too, finished with `finalizeAndFinishThroughEndOfInput`: it shows the words while held and is the fallback transcript, translated into the room's language by the usual chain → voice → the chosen output device (a virtual microphone). The virtual microphone is BlackHole 2ch, installed from the app: download the official notarized package, check its pinned SHA-256, run `installer` and restart `coreaudiod` in one standard administrator prompt (the package only copies the driver and asks for a reboot; Core Audio loads a new HAL plug-in only when it restarts). Then a loopback sound test: speak a fixed English phrase into the device, record its input side, transcribe it (`LoopbackTest`). The checklist UI (`MicSetupCard`) is shared by onboarding step 3 and settings. We never bundle the GPL driver.- AI (Ling, ant-ling.com, OpenAI-compatible): one user key for the whole app, for now in a 0600 file `ling-api-key` in the app's Application Support folder, excluded from backups (`AIKey`; never in UserDefaults, logs or exports; ad-hoc signing makes the Keychain ask for the password after every rebuild or update, so it moves back to the Keychain once builds have a Developer ID; a key in the old Keychain item, service = bundle id + `.ai`, is moved over once), checked with a one-token `Ling-3.0-tiny` call. `LingClient` is the single gate for every call: request *starts* ≥ 0.6 s apart (the account allows ~2 requests/s across all models), waiting requests ordered speak-back > translation > notes; notes retry 429 with 1/2/4/8 s backoff, translation and speak-back fail fast to the next translator; 401 marks the key invalid. Every call sends `thinking: disabled`, puts the content in the **system** message and a fixed instruction in the user message (otherwise question-like text gets a search-grounded essay instead), and drops replies with no `finish_reason` or starting 根据现有检索证据.-- Live notes (`NotesEngine`, UI-free): about every 45 s with new lines, one JSON call sends the current notes + new lines (`[L12 02:03 对方] …`) and gets the whole notes back (summary, ≤ 8 topics with points and an optional fishbone, conclusions/to-dos with evidence line ids → support counts, terms with misrecognised forms); a bad reply never replaces good notes. A final pass over the whole transcript runs when the meeting ends ("完整版"). Notes are written in Chinese when Chinese is among the system languages. Stored as `notes` in `session.json`; finished meetings without notes can generate them from the main window. Speak-back voices (`Voices.swift`, settings UI `VoicePicker.swift` on the 同声传译 page): one choice per room language (`speakVoices`, "en" → `ming:US_Emma` / `system:<AVSpeechSynthesisVoice id>` / `clone`). Offered: hand-picked Ming voices (English Emma/George/Charlotte; Chinese 小雅/小棠/小锋/卓然; ja/ko/de/fr/es via Emma/George with `language_id`) and the Mac's best female and male voice; default is Ming's first with a key, else the Mac's. `clone` is the user's own voice: a 8–30 s recording read from a passage in their language (16 kHz WAV + its on-device transcript in `voice/` under Application Support, 0600, out of backups), sent to Ming as `references` with every sentence (~600 KB, first audio ~3 s, ~8 s on a cold call; a foreign language keeps the speaker's accent). Ming's voices fall back to the Mac's voice without a usable key or when the stream fails; previews play on the default output, not the room.0-tts-0.5B`, SSE PCM 24 kHz) through the same key, falling back to the system voice.-- Live notes window (`NotesWindow`): a floating `NSPanel`, `sharingType = .none` (invisible to screen sharing and screenshots), on all Spaces, frame autosaved; < 360 px a card that offers what the notes added since it was collapsed ("收起后新增 …", only when there is something), tabs 纪要 / 文字记录 in between, both side by side from 760 px; banners for no key (inline key entry) / invalid key / rate limited. While writing: sound bars before anyone speaks, a spinner with "已听到 N 句" and shimmering placeholders for the first version, an "正在更新" pill and a warm shimmer under the current topic for later updates (`TimelineView`, since the window redraws every second). Transcript: oldest first, follows the newest line plus the sentence still being spoken; scrolling up pauses following and gathers new lines into a "↓ N 句新内容" button; search highlights in place (query plus the notes' misheard forms of a name). Notes carry times: points and conclusions get the time of their first evidence line (`pointTimes`, `NoteItem.t`; carried over when the model echoes a point without evidence), topics show ranges.-- App menu (`AppMenu`): the app is a regular app (name and menus top left, Dock, ⌘Tab) while the main, settings or onboarding window is visible, and an accessory otherwise (`AppDelegate.updateActivationPolicy`). The notes window doesn't count: it is a non-activating panel, so clicking it never takes focus from the meeting app or brings our other windows forward; it becomes key only for its text fields. The Dock icon brings back whichever windows are open (the main window only when none is); quitting while a meeting with lines is being recorded asks first; exports are a sheet on the window they were asked from. The settings window remembers its frame and last tab (`settingsSection`). Menus: app, 纪要, 显示 (display mode, ⌘1–⌘3 sizes, 始终置顶), 编辑 (standard responder-chain actions, so ⌘V works in fields; ⌘F search), 窗口, 帮助.+- Live notes (`NotesEngine`, UI-free): about every 45 s with new lines, one JSON call sends the current notes + new lines (`[L12 02:03 对方] …`) and gets the whole notes back (summary, ≤ 8 topics with points and an optional fishbone, conclusions/to-dos with evidence line ids → support counts, terms with misrecognised forms); a bad reply never replaces good notes. A final pass over the whole transcript runs when the meeting ends ("完整版"). Notes are written in the 纪要语言 (`AppModel.notesLanguageCode`): the reader's language by default (the translate-to choice, or Chinese when Chinese is among the system languages), or the meeting's own; one meeting can differ (`notesLanguageFor`, the notes window's "EN → 中" chip, an inline card since a popover closes at once in the non-activating panel; changing it mid-meeting rewrites the notes from scratch, `NotesEngine.rewrite`). The language is stated again at the end of the prompt and in the user message, and a reply not in it (`NotesEngine.written`, CJK share) is retried once on the final pass, otherwise dropped: the final pass has no Chinese notes to follow, and a long English transcript pulls it into English. Stored as `notes` in `session.json`; finished meetings without notes can generate them from the main window. Speak-back voices (`Voices.swift`, settings UI `VoicePicker.swift` on the 同声传译 page): one choice per room language (`speakVoices`, "en" → `ming:US_Emma` / `system:<AVSpeechSynthesisVoice id>` / `clone`). Offered: hand-picked Ming voices (English Emma/George/Charlotte; Chinese 小雅/小棠/小锋/卓然; ja/ko/de/fr/es via Emma/George with `language_id`) and the Mac's best female and male voice; default is Ming's first with a key, else the Mac's. `clone` is the user's own voice: a 8–30 s recording read from a passage in their language (16 kHz WAV + its on-device transcript in `voice/` under Application Support, 0600, out of backups), sent to Ming as `references` with every sentence (~600 KB, first audio ~3 s, ~8 s on a cold call; a foreign language keeps the speaker's accent). Ming's voices fall back to the Mac's voice without a usable key or when the stream fails; previews play on the default output, not the room.0-tts-0.5B`, SSE PCM 24 kHz) through the same key, falling back to the system voice.+- Live notes window (`NotesWindow`): opens at the first words of a meeting (system audio or a talk press; `AppModel.heardSpeech`), or at once when the user picks it; a floating `NSPanel`, `sharingType = .none` (invisible to screen sharing and screenshots), on all Spaces, frame autosaved; < 360 px a card that offers what the notes added since it was collapsed ("收起后新增 …", only when there is something), tabs 纪要 / 文字记录 in between, both side by side from 760 px; a 结束 button while live (asks in an inline strip once there are lines; `AppModel.requestStop` asks with an alert for ⌘R and the panel switch, 继续记录 the default), then an ended strip (final-pass state, 在会议记录中查看, 开始新会议); `FirstClickHostingView` so a click works without focusing the panel first; banners for no key (inline key entry) / invalid key / rate limited. While writing: sound bars before anyone speaks, a spinner with "已听到 N 句" and shimmering placeholders for the first version, an "正在更新" pill and a warm shimmer under the current topic for later updates (`TimelineView`, since the window redraws every second). Transcript: oldest first, follows the newest line plus the sentence still being spoken; following survives content and window height changes, and only a real scroll-wheel/trackpad event (`UserScroll`) followed by scrolling up pauses it and gathers new lines into a "↓ N 句新内容" button; search highlights in place (query plus the notes' misheard forms of a name). Notes carry times: points and conclusions get the time of their first evidence line (`pointTimes`, `NoteItem.t`; carried over when the model echoes a point without evidence), topics show ranges.+- App menu (`AppMenu`): the app is a regular app (name and menus top left, Dock, ⌘Tab) while the main, settings or onboarding window is visible, and an accessory otherwise (`AppDelegate.updateActivationPolicy`). The notes window doesn't count: it is a non-activating panel, so clicking it never takes focus from the meeting app or brings our other windows forward; it becomes key only for its text fields. Opening the app by hand shows the main window (not when started as a login item); the Dock icon brings back whichever windows are open (the main window only when none is); quitting while a meeting with lines is being recorded asks first; exports are a sheet on the window they were asked from. The settings window remembers its frame and last tab (`settingsSection`). Menus: app, 纪要, 显示 (display mode, ⌘1–⌘3 sizes, 始终置顶), 编辑 (standard responder-chain actions, so ⌘V works in fields; ⌘F search), 窗口, 帮助.- Meeting records: one folder per meeting, `session.json` + `system.m4a` (+ `mic.m4a`); empty meetings are dropped; export to Markdown, Word (`.docx` via `NSAttributedString`, both starting with the notes) and SRT. Speaker labels are only "对方" (system audio) and "你" (microphone): no diarization yet.- Shortcuts (`Shortcuts.swift`): talk and subtitle-bar toggle are recorded in settings (`ShortcutField`). A combination must include ⌃ or ⌘ (⌥/⇧ alone types characters; bare F keys are brightness/volume), must not be a system shortcut (`CopySymbolicHotKeys`) or held by another app (Carbon refuses to register it).- Nothing the user does needs the Terminal. When a feature request fits none of the above, push back before adding UI.@@ -49,7 +49,7 @@ python3 scripts/site.py && python3 -m http.server -d build/site # website prevDiagnostics (`Diagnostics.swift`, design: claude.ai/artifact/GHGzgN1sCodGfa17ZXLCa7): a "诊断" switch at the bottom left of the settings sidebar, beside the version (`diagnostics`, off by default; on in dev builds); switching it on adds a "诊断" tab below the others. It records only timings and counts, never transcript text: per heard sentence last new words → final transcript ("识别定稿") and final → translation, with Ling queue time, the provider that answered and why earlier ones fell through (`TranslateTrace`); per speak-back press release → transcript → translation → voice done; every Ling request (priority, queue, duration, outcome, tokens). Lines go to `metrics.jsonl` in the meeting folder (`type` = `sentence` / `ling`). The tab shows p50/p95, the provider split, fallback reasons, Ling rate and the last sentences as bars, and copies a plain-text report. It is separate from `debug`: the switch never enables transcript logging or the debug notification. Not done yet: the latency line under the subtitle bar and the health line in the panel.-Debug control: dev builds always accept commands on the distributed notification `com.wquguru.cicada.debug` (release builds only with `defaults write com.wquguru.cicada debug -bool true`, which also logs transcript text). Send them with `tools/lsctl` (`start`, `stop`, `open`, `panel`, `onboarding:<step>`, `samplePlay`, `speakFile:<audio>`, `settings:<overlay|speak|records|ai|diagnostics>`, `diagnostics:<on|off>`, `diagReport`, `micTest`, `micNext`, `talkKey:<right|keyCode:mods>`, `toggleKey:<keyCode:mods>`, `shortcuts`, `aiKeyFile:<path>` (key from a 0600 file, never through the log), `aiCheck`, `aiRemove`, `aiState`, `lingSimulate:<429|hijack|timeout|off>`, `voice:<lang>[=<id>]`, `voicePreview:<lang>=<id>`, `voiceCloneFile:<wav>`, `display:<notes|bar|none>`, `notesWindow[:x,y,w,h]`, `notesFrame`, `notesNow`, `notesState`, `notesShow:<id>`, `notesReplay:<id>`, `notesRender:<png>`, `notesCapturable`, `mainShow:<id>[,transcript]`, `mainRender:<png>` (the main window, plus the shown meeting's whole notes page as `<png>.notes.png`), `place:x,y,w,font`, `frame`, `overlayState`, `export:<dir>` …).+Debug control: dev builds always accept commands on the distributed notification `com.wquguru.cicada.debug` (release builds only with `defaults write com.wquguru.cicada debug -bool true`, which also logs transcript text). Send them with `tools/lsctl` (`start`, `stop`, `open`, `panel`, `onboarding:<step>`, `samplePlay`, `speakFile:<audio>`, `settings:<overlay|speak|records|ai|diagnostics>`, `diagnostics:<on|off>`, `diagReport`, `micTest`, `micNext`, `talkKey:<right|keyCode:mods>`, `toggleKey:<keyCode:mods>`, `shortcuts`, `aiKeyFile:<path>` (key from a 0600 file, never through the log), `aiCheck`, `aiRemove`, `aiState`, `lingSimulate:<429|hijack|timeout|off>`, `voice:<lang>[=<id>]`, `voicePreview:<lang>=<id>`, `voiceCloneFile:<wav>`, `display:<notes|bar|none>`, `subtitles:<both|translation|original>`, `meetingSubtitles:<…>`, `notesLang:<mine|source>`, `meetingNotesLang:<…>`, `notesRegenerate:<id>=<mine|source>`, `settings:language`, `notesWindow[:x,y,w,h]`, `notesFrame`, `notesNow`, `notesState`, `notesShow:<id>`, `notesReplay:<id>`, `notesRender:<png>`, `notesCapturable`, `mainShow:<id>[,transcript]`, `mainRender:<png>` (the main window, plus the shown meeting's whole notes page as `<png>.notes.png`), `place:x,y,w,font`, `frame`, `overlayState`, `export:<dir>` …).Release: `scripts/release.sh <x.y.z>` (clean `main`, a `## x.y.z — <today>` section in `CHANGELOG.md`) bumps `Resources/Info.plist`, commits, tags `v<x.y.z>` and pushes; `.github/workflows/release.yml` (runner `macos-26`) builds the tag, checks it matches Info.plist and publishes the DMG, zip and checksums with notes from `scripts/release_notes.sh`. `build.yml` runs on pull requests and on demand only: macOS minutes are expensive for a private repo.@@ -66,6 +66,6 @@ TODO: unit tests for the pure parts (language-code mapping, detection scoring, S- Keep files small and single-purpose; match the existing naming and comment density (comments say why).- UI and engine state are `@MainActor`; audio callbacks never touch app state directly (they hand buffers to `AudioRouter`'s queue).- No third-party dependencies; system frameworks only.-- User data: `~/Library/Application Support/LiveSubs/Sessions` and `UserDefaults` (`sourceMode`, `target`, `speakEnabled`, `speakFrom`, `speakTo`, `speakOutput`, `recordAudio`, `overlayAuto`, `overlayHideAfter`, `overlay.<screen>`, `lastDetected`, `onboarded`, `talkKey`, `toggleKey` as `keyCode:carbonModifiers`, `displayMode`, `aiModel`, `speakVoices`, `notesOnTop`, `diagnostics`, `settingsSection`) and the Ling key file (`ling-api-key`).+- User data: `~/Library/Application Support/LiveSubs/Sessions` and `UserDefaults` (`sourceMode`, `target`, `speakEnabled`, `speakFrom`, `speakTo`, `speakOutput`, `recordAudio`, `overlayAuto`, `overlayHideAfter`, `overlay.<screen>`, `lastDetected`, `onboarded`, `talkKey`, `toggleKey` as `keyCode:carbonModifiers`, `displayMode`, `subtitles` (both/translation/original: "original" translates nothing), `notesLanguage` (mine = `AppSettings.myLanguage`, source = the meeting's most heard language), `aiModel`, `speakVoices`, `notesOnTop`, `diagnostics`, `settingsSection`) and the Ling key file (`ling-api-key`).- Add a line to `CHANGELOG.md` with every user-visible change. Keep `README.md` and `README.zh-CN.md` in step.- Commit in coherent batches with a short imperative subject.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bcdffc4..5735de1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,14 @@ the release workflow publishes it as the release notes.## Unreleased+- New: Settings › 语言 puts every language choice in one place, under a line that reads the whole route ("对方说 English → 字幕 简体中文 · 纪要 简体中文 / 你说 中文 → 对方听到 English"): what the other side speaks, what the subtitles show (原文 + 译文 / 只看译文 / 只看原文 — the last translates nothing and uses no Ling quota; also in the menu bar panel), what to translate into, the notes language (你的语言 or the meeting's own), and the speak-back pair. 显示 and 同声传译 no longer hold these.+- New: an "EN → 中" chip in the live notes window changes the subtitles and notes language for this meeting only; a new notes language rewrites the notes right away. After a meeting, "改用 English 重新整理" writes its notes again in the other language.+- Fixed: the full notes written when a long meeting in another language ended came out in that language (English) instead of yours, while the live notes were right. The notes language is now stated where the model reads it last, and a reply in the wrong language is retried once, then dropped in favour of the live notes.+- New: a 结束 button in the notes window. With anything recorded it asks first, in a strip below the header (继续记录 / 结束会议), so a double click can't end the meeting; ⌘R and the panel switch ask too, with 继续记录 as the default. After the meeting the window says so, shows when the full notes are ready, and offers 在会议记录中查看 and 开始新会议.+- Fixed: the transcript sometimes stopped following the newest line on its own (after a window resize, a late translation or a notes update). It now pauses only when you scroll up yourself.+- Fixed: buttons in the notes window needed two clicks while another app was in front.+- Changed: the notes window waits until someone speaks (in the meeting or you, holding the talk key) before it opens, instead of opening as soon as the app starts listening. Choosing 实时纪要 as the display, or opening it from the menu, still shows it at once.+- Changed: opening the app from Finder, Launchpad or Spotlight shows the meeting records window, instead of only the notes window (it still starts listening right away). Started at login, it stays in the menu bar.- Changed: with a Ling key, what you say while holding the talk key is heard and translated in one step by Ming's audio model, which gets names right far more often than the on-device recognizer (江充 instead of 将冲) and needs one request instead of two. The translation is ready about 2 s after you let go (about 1 s before); if Ming is slow, busy or replies oddly, it falls back to on-device recognition and the usual translation. 诊断 shows which one answered.- Changed: the meeting records window reads like a document: meetings grouped by 今天 / 昨天 / 本周 / month, a card at the bottom showing whether it's listening (with the switch and settings), and each meeting opens as a page: date, a large editable title, its length, sentence count and languages, the summary as the opening paragraph, then topics with their times, conclusions and to-dos. ⌘F jumps to search.- Changed: Live Subs is now 知了 (Cicada in English): new name, new logo, new app id (`com.wquguru.cicada`). macOS treats it as a new app, so it asks again for system audio, microphone and Input Monitoring, and settings and the AI key start fresh; meeting records are kept. Delete the old Live Subs from Applications.diff --git a/Sources/LiveSubs/AppModel.swift b/Sources/LiveSubs/AppModel.swiftindex 658b13b..58500b9 100644--- a/Sources/LiveSubs/AppModel.swift+++ b/Sources/LiveSubs/AppModel.swift@@ -59,9 +59,11 @@ final class AppModel: ObservableObject {listen.onSubtitle = { [weak self] src, dst inself?.liveSource = srcself?.liveTranslation = dst- guard self?.settings.displayMode == "bar" else { return }- self?.overlay.clearStatus()- self?.overlay.setSubtitle(source: src, translation: dst)+ if !src.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { self?.heardSpeech() }+ guard let self, self.settings.displayMode == "bar" else { return }+ self.overlay.clearStatus()+ let shown = self.displayed(src, dst)+ self.overlay.setSubtitle(source: shown.source, translation: shown.translation)}listen.onStatus = { [weak self] text inself?.status = text@@ -86,12 +88,10 @@ final class AppModel: ObservableObject {ling.model = { [weak self] in self?.settings.aiModel ?? "Ling-3.1-flash" }listen.translator = translatortranslator.glossary = { [weak self] in self?.notes.glossary ?? [] }- notes.language = {- // The app speaks Chinese, so notes do too when Chinese is among the system languages.- let prefs = Locale.preferredLanguages- let pick = prefs.first(where: { $0.hasPrefix("zh") }) ?? prefs.first ?? "zh-Hans"- return TranslationService.englishName(translationCode(forSystemLanguage: pick))+ notes.language = { [weak self] id in+ TranslationService.englishName(self?.notesLanguageCode(id) ?? "zh-CN")}+ listen.translationOff = { [weak self] in self?.subtitles == "original" }if ling.hasKey { Task { await ling.check() } }installer.speakThrough = { [weak self] text, lang, device in@@ -102,15 +102,16 @@ final class AppModel: ObservableObject {speak.translate = { [weak self] text, from, to, trace inawait self?.listen.translate(text, source: from, target: to, kind: .speak, trace: trace)}- speak.roomLanguage = { [weak self] in self?.listen.activeLang?.code }- applyVoice()speak.interpret = { [weak self] wav, from, to, trace inawait self?.translator.interpret(wav: wav, source: from, target: to, trace: trace)}+ speak.roomLanguage = { [weak self] in self?.listen.activeLang?.code }+ applyVoice()speak.onStatus = { [weak self] text in self?.status = text }speak.onLive = { [weak self] phase, src, dst inguard let self else { return }self.speakPhase = phase+ if phase == .listening && !src.isEmpty { self.heardSpeech() }guard self.settings.displayMode == "bar" else {// The notes window's caption line shows what you are saying.if phase != .idle || !src.isEmpty {@@ -245,6 +246,8 @@ final class AppModel: ObservableObject {let session = store.begin()diagnostics.begin()lineForSegment = [:]+ speechHeard = false+ meetingSubtitles = nilif settings.recordAudio {listen.router.setRecording(store.systemAudioURL(session.id))speak.setRecording(store.micAudioURL(session.id))@@ -269,7 +272,23 @@ final class AppModel: ObservableObject {refresh()}- func setRunning(_ on: Bool) { on ? start() : stop() }+ func setRunning(_ on: Bool) { on ? start() : requestStop() }++ /// The menu (⌘R) and the panel switch: a meeting with lines is ended only after asking, with+ /// "继续记录" as the default so a stray Return keeps it going. An empty one just stops.+ func requestStop() {+ guard listen.isRunning, let id = store.liveID, let s = store.session(id), !s.lines.isEmpty else { stop(); return }+ NSApp.activate()+ let alert = NSAlert()+ alert.messageText = "结束这场会议?"+ alert.informativeText = "已记录 \(NotesEngine.clock(Date().timeIntervalSince(s.startedAt))) · \(s.lines.count) 句。结束后停止收听,并整理一份完整版纪要。"+ let end = alert.addButton(withTitle: "结束会议")+ let keep = alert.addButton(withTitle: "继续记录")+ end.hasDestructiveAction = true+ end.keyEquivalent = ""+ keep.keyEquivalent = "\r"+ if alert.runModal() == .alertFirstButtonReturn { stop() }+ }/// The bottom-left 诊断 switch in settings: shows or hides the 诊断 tab.func setDiagnostics(_ on: Bool) {@@ -278,12 +297,68 @@ final class AppModel: ObservableObject {objectWillChange.send()}+ // MARK: Languages++ /// This meeting's 字幕 choice from the notes window's language chip (nil: the settings').+ @Published var meetingSubtitles: String?+ /// Notes language chosen for one meeting (the chip during it, 重新整理 after it).+ @Published private(set) var notesLanguageFor: [String: String] = [:]++ var subtitles: String { meetingSubtitles ?? settings.subtitles }++ func notesChoice(_ id: String) -> String { notesLanguageFor[id] ?? settings.notesLanguage }++ /// The language the other side spoke most in a meeting (the detected one while nothing is recorded yet).+ func meetingLanguage(_ id: String?) -> String? {+ let heard = id.flatMap { store.session($0) }?.lines.filter { $0.speaker != "me" }.map(\.srcLang) ?? []+ let counts = Dictionary(heard.map { ($0, 1) }, uniquingKeysWith: +)+ return counts.max { $0.value < $1.value }?.key ?? (id == store.liveID ? listen.activeLang?.code : nil)+ }++ func notesLanguageCode(_ id: String) -> String {+ notesChoice(id) == "source" ? (meetingLanguage(id) ?? settings.myLanguage) : settings.myLanguage+ }++ /// The subtitle as the 字幕 choice shows it: both lines, the translation alone, or the+ /// original alone as the main line.+ func displayed(_ src: String, _ dst: String) -> (source: String, translation: String) {+ switch subtitles {+ case "original": return ("", src)+ case "translation": return dst.isEmpty ? (src, "") : ("", dst)+ default: return (src, dst)+ }+ }++ func setSubtitles(_ mode: String, meetingOnly: Bool = false) {+ let wasOff = subtitles == "original"+ if meetingOnly { meetingSubtitles = mode } else { settings.subtitles = mode; meetingSubtitles = nil }+ if wasOff && subtitles != "original" { listen.translationResumed() }+ debugLog("subtitles=\(subtitles) meetingOnly=\(meetingOnly)")+ objectWillChange.send()+ }++ /// A different notes language during a meeting rewrites the notes in it right away.+ func setNotesLanguage(_ choice: String, meetingOnly: Bool = false) {+ let live = store.liveID+ let before = live.map(notesLanguageCode)+ if meetingOnly, let live { notesLanguageFor[live] = choice } else { settings.notesLanguage = choice }+ if let live, notesLanguageCode(live) != before { notes.rewrite() }+ debugLog("notesLanguage=\(live.map(notesLanguageCode) ?? settings.notesLanguage) meetingOnly=\(meetingOnly)")+ objectWillChange.send()+ }++ /// After a meeting: write its notes again in the other language.+ func regenerateNotes(_ id: String, choice: String) {+ notesLanguageFor[id] = choice+ notes.generate(for: id)+ }+// MARK: Display (live notes / subtitle bar / nothing)func setDisplayMode(_ mode: String) {settings.displayMode = modeobjectWillChange.send()- showDisplay()+ showDisplay(force: true)}/// ⌃⌥S: notes → subtitle bar → nothing → notes.@@ -293,7 +368,17 @@ final class AppModel: ObservableObject {setDisplayMode(order[(i + 1) % order.count])}- private func showDisplay() {+ /// Set at the first words of a meeting: until then listening stays out of sight.+ private var speechHeard = false++ private func heardSpeech() {+ guard !speechHeard, listen.isRunning else { return }+ speechHeard = true+ if settings.displayMode == "notes" { notesWindow.show() }+ }++ /// `force`: the user asked for this mode, show it even before anyone speaks.+ private func showDisplay(force: Bool = false) {switch settings.displayMode {case "bar":notesWindow.hide()@@ -303,7 +388,9 @@ final class AppModel: ObservableObject {overlay.hide()default:overlay.hide()- if listen.isRunning { notesWindow.show() }+ // The notes window waits for someone to speak, so launching or a silent tab+ // doesn't put an empty window on screen.+ if listen.isRunning && (speechHeard || force) { notesWindow.show() }}}@@ -662,6 +749,13 @@ final class AppModel: ObservableObject {debugLog("ling simulate=\(String(describing: ling.simulate))")case "aiRemove": ling.removeKey()case "aiState": debugLog("ai state=\(ling.keyState) hasKey=\(ling.hasKey) model=\(settings.aiModel)")+ case "subtitles": setSubtitles(arg)+ case "meetingSubtitles": setSubtitles(arg, meetingOnly: true)+ case "notesLang": setNotesLanguage(arg)+ case "meetingNotesLang": setNotesLanguage(arg, meetingOnly: true)+ case "notesRegenerate":+ let p = arg.split(separator: "=").map(String.init)+ if p.count == 2 { regenerateNotes(p[0], choice: p[1]) }case "speakOn": enableSpeaking(true)case "speakOff": enableSpeaking(false)case "speakOut": speak.debugOutputURL = arg.isEmpty ? nil : URL(fileURLWithPath: arg)@@ -725,12 +819,22 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { [weak self] inMainActor.assumeIsolated { self?.showOnboarding() }}+ } else if !Self.launchedAsLoginItem {+ // Opened by hand (Finder, Launchpad, Spotlight): show something, like the Dock icon does.+ showMainWindow()}model.installDebugControl()installDeviceListener()Task { await model.launch() }}+ /// Started by the system at login: stay in the menu bar.+ private static var launchedAsLoginItem: Bool {+ guard let event = NSAppleEventManager.shared().currentAppleEvent else { return false }+ return event.eventID == kAEOpenApplication+ && event.paramDescriptor(forKeyword: keyAEPropData)?.enumCodeValue == keyAELaunchedAsLogInItem+ }+func applicationWillTerminate(_ notification: Notification) {model.stop()}diff --git a/Sources/LiveSubs/LanguageSettings.swift b/Sources/LiveSubs/LanguageSettings.swiftnew file mode 100644index 0000000..7ee5e9b--- /dev/null+++ b/Sources/LiveSubs/LanguageSettings.swift@@ -0,0 +1,136 @@+import SwiftUI++/// Settings › 语言: every language choice in one place — what the other side speaks, whether and+/// into what it is translated, what the notes are written in, and the speak-back pair — under a+/// line that reads the whole route.+struct LanguageSettings: View {+ @ObservedObject var model: AppModel+ @ObservedObject var settings: AppSettings++ var body: some View {+ VStack(alignment: .leading, spacing: 14) {+ route+ group("听对方") {+ SettingsRow(title: "对方说的语言", detail: heardDetail) {+ PillMenu(value: heardValue, options: [("auto", "自动识别")] + sourceLanguages.map { ($0.locale, $0.name) }) {+ model.sourceSelection = $0+ }+ }+ SettingsRow(title: "字幕", detail: "只看原文时不翻译,也不用 Ling 额度") {+ Segments(options: subtitleOptions, value: settings.subtitles) { model.setSubtitles($0) }+ }+ SettingsRow(title: "翻译成", detail: targetDetail, divider: false) {+ PillMenu(value: settings.target == "system" ? "跟随系统(\(targetName(model.listen.resolvedTarget)))"+ : targetName(settings.target),+ options: [("system", "跟随系统")] + targetLanguages.map { ($0.code, $0.name) }) {+ model.targetSelection = $0+ }+ }+ }+ group("纪要") {+ SettingsRow(title: "纪要语言", detail: "实时纪要和完整版同一种语言", divider: false) {+ Segments(options: [("mine", "我的语言 · \(targetName(settings.myLanguage))"), ("source", sourceTitle)],+ value: settings.notesLanguage) { model.setNotesLanguage($0) }+ }+ }+ group("同声传译") {+ SettingsRow(title: "我说", detail: settings.speakEnabled ? nil : "同声传译还没打开") {+ PillMenu(value: settings.speakFromLang.name, options: sourceLanguages.map { ($0.locale, $0.name) }) {+ settings.speakFrom = $0+ model.speakFromChanged()+ }+ }+ SettingsRow(title: "对方听到", detail: "跟随对方时,对方说什么语言就翻成什么", divider: false) {+ PillMenu(value: settings.speakTo == "room" ? "跟随对方(\(targetName(model.speak.targetCode)))" : targetName(settings.speakTo),+ options: [("room", "跟随对方")] + targetLanguages.map { ($0.code, $0.name) }) {+ settings.speakTo = $0+ model.objectWillChange.send()+ }+ }+ }+ }+ }++ // MARK: The route++ /// 对方说 English → 字幕 简体中文 · 纪要 简体中文 / 你说 中文 → 对方听到 English+ private var route: some View {+ VStack(alignment: .leading, spacing: 10) {+ HStack(spacing: 8) {+ label("对方说")+ chip(heardNow, accent: false)+ arrow+ Text("字幕").font(.system(size: 13)).foregroundStyle(.white)+ chip(settings.subtitles == "original" ? "原文" : targetName(model.listen.resolvedTarget), accent: true)+ Text("·").foregroundStyle(Color(white: 0.55))+ Text("纪要").font(.system(size: 13)).foregroundStyle(.white)+ chip(notesNow, accent: true)+ }+ HStack(spacing: 8) {+ label("你说")+ chip(settings.speakFromLang.name, accent: false)+ arrow+ Text("对方听到").font(.system(size: 13)).foregroundStyle(.white)+ chip(targetName(model.speak.targetCode), accent: false)+ if !settings.speakEnabled {+ Text("(同声传译未开)").font(.system(size: 12)).foregroundStyle(Color(white: 0.62))+ }+ }+ }+ .padding(.horizontal, 18).padding(.vertical, 16)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(RoundedRectangle(cornerRadius: 12).fill(Palette.ink))+ .accessibilityElement(children: .combine)+ }++ private func label(_ t: String) -> some View {+ Text(t).font(.system(size: 13)).foregroundStyle(Color(white: 0.72)).frame(width: 46, alignment: .leading)+ }++ private func chip(_ t: String, accent: Bool) -> some View {+ Text(t).font(.system(size: 13, weight: .semibold)).foregroundStyle(.white).lineLimit(1)+ .padding(.horizontal, 10).frame(height: 24)+ .background(Capsule().fill(accent ? Palette.accent : Color.white.opacity(0.14)))+ }++ private var arrow: some View {+ Image(systemName: "arrow.right").font(.system(size: 11, weight: .bold)).foregroundStyle(Palette.accent)+ }++ private func group<Content: View>(_ title: String, @ViewBuilder _ content: () -> Content) -> some View {+ VStack(alignment: .leading, spacing: 8) {+ Text(title).font(.system(size: 12, weight: .semibold)).foregroundStyle(Palette.secondary).padding(.leading, 4)+ SettingsCard { content() }+ }+ }++ // MARK: Words++ private var heardValue: String {+ if case .fixed(let l) = settings.sourceMode { return l.name }+ return "自动识别"+ }++ private var heardNow: String {+ if case .fixed(let l) = settings.sourceMode { return l.name }+ return model.listen.activeLang?.name ?? "自动识别"+ }++ private var heardDetail: String {+ if case .fixed = settings.sourceMode { return "只按这种语言识别" }+ return model.listen.activeLang.map { "现在听出是 \($0.name)" } ?? "从已安装的语音模型里挑最有把握的"+ }++ private var targetDetail: String {+ settings.target == "system" ? "对方说的正是系统语言时,翻成系统里的另一种" : "对方说的就是这种语言时不翻译"+ }++ private var sourceTitle: String {+ model.listen.activeLang.map { "会议原文 · \($0.name)" } ?? "会议原文"+ }++ private var notesNow: String {+ if settings.notesLanguage == "source" { return model.listen.activeLang?.name ?? "会议原文" }+ return targetName(settings.myLanguage)+ }+}diff --git a/Sources/LiveSubs/ListenEngine.swift b/Sources/LiveSubs/ListenEngine.swiftindex 9c536e1..930fda3 100644--- a/Sources/LiveSubs/ListenEngine.swift+++ b/Sources/LiveSubs/ListenEngine.swift@@ -433,6 +433,8 @@ final class ListenEngine {/// Set by the app: the shared translation chain.var translator: TranslationService?+ /// Subtitles set to the original only: nothing is translated.+ var translationOff: () -> Bool = { false }func translate(_ text: String, source: String, target: String? = nil,kind: TranslationService.Kind = .sentence, trace: TranslateTrace? = nil) async -> String? {@@ -446,7 +448,7 @@ final class ListenEngine {}private func translateSegment(id: Int) {- guard let seg = segments.first(where: { $0.id == id }) else { return }+ guard !translationOff(), let seg = segments.first(where: { $0.id == id }) else { return }let trace = TranslateTrace()let asked = Date()Task { [weak self] in@@ -470,7 +472,7 @@ final class ListenEngine {}private func translateVolatile() {- guard isRunning, !volatileInFlight, volatileText.count >= 2, volatileText != lastVolatileSent else { return }+ guard isRunning, !translationOff(), !volatileInFlight, volatileText.count >= 2, volatileText != lastVolatileSent else { return }let text = volatileTextlet epoch = volatileEpochlet source = activeLang?.code ?? "auto"@@ -493,6 +495,9 @@ final class ListenEngine {lastVolatileSent = ""}+ /// Translation switched back on: translate what is on screen now.+ func translationResumed() { if isRunning { retranslateVisible() } }+private func retranslateVisible() {volatileTranslation = ""lastVolatileSent = ""diff --git a/Sources/LiveSubs/Notes.swift b/Sources/LiveSubs/Notes.swiftindex 741ea46..216953f 100644--- a/Sources/LiveSubs/Notes.swift+++ b/Sources/LiveSubs/Notes.swift@@ -89,8 +89,9 @@ final class NotesEngine: ObservableObject {let ling: LingClientlet store: SessionStore- /// The language the reader wants notes in (their own system language).- var language: () -> String = { "Simplified Chinese" }+ /// The language a meeting's notes are written in (English name), set by the app from the+ /// 纪要语言 choice.+ var language: (_ sessionID: String) -> String = { _ in "Simplified Chinese" }private var sessionID: String?/// The session whose notes `notes` shows (stays set after the meeting ends).@@ -139,6 +140,12 @@ final class NotesEngine: ObservableObject {Task { await update(id, final: true) }}+ /// The notes language changed during the meeting: rewrite the whole notes in it now.+ func rewrite() {+ guard let id = sessionID else { return }+ Task { await update(id, final: false, fresh: true) }+ }+func updateNow() {guard let id = sessionID else { return }Task { await update(id, final: false) }@@ -181,7 +188,8 @@ final class NotesEngine: ObservableObject {if due { Task { await update(id, final: false) } }}- private func update(_ id: String, final: Bool, upto: Int? = nil) async {+ /// `fresh`: start from nothing (a new notes language); the final pass always does.+ private func update(_ id: String, final: Bool, upto: Int? = nil, fresh: Bool = false) async {if inFlight {// Never drop the end-of-meeting pass or a "生成纪要" request: queue it.if final { pendingFinal = id; generatingID = id }@@ -203,15 +211,25 @@ final class NotesEngine: ObservableObject {}let lines = Array(session.lines.prefix(upto ?? session.lines.count))- let base = final ? MeetingNotes() : (id == shownID ? notes : session.notes ?? MeetingNotes())+ let base = final || fresh ? MeetingNotes() : (id == shownID ? notes : session.notes ?? MeetingNotes())let from = final ? 0 : min(base.covered, lines.count)- let prompt = Self.prompt(notes: base, lines: lines, from: from, language: language(), final: final)+ let lang = language(id)+ let prompt = Self.prompt(notes: base, lines: lines, from: from, language: lang, final: final)let started = Date()do {- let raw = try await ling.chat(content: prompt, instruction: "Update the notes.", priority: .notes,- json: true, maxTokens: 6000, timeout: 90)- guard var next = Self.parse(raw, times: lines.map(\.t), startedAt: session.lines.first?.t ?? 0) else {- debugLog("notes: reply was not usable JSON, kept the previous notes")+ // The final pass sends only the transcript, with no notes in the reader's language to+ // follow: given a long English meeting the model drifts into English. Say the language+ // again where it is read last, and try once more if the reply still isn't in it.+ var next: MeetingNotes?+ for attempt in 1...(final || fresh ? 2 : 1) {+ let raw = try await ling.chat(content: prompt, instruction: "Update the notes. Write them in \(lang).",+ priority: .notes, json: true, maxTokens: 6000, timeout: 90)+ guard let parsed = Self.parse(raw, times: lines.map(\.t), startedAt: session.lines.first?.t ?? 0) else { break }+ if Self.written(parsed, in: lang) { next = parsed; break }+ debugLog("notes: \(final ? "final" : "live") reply not in \(lang) (attempt \(attempt)), dropped")+ }+ guard var next else {+ debugLog("notes: no usable reply, kept the previous notes")state = .failedreturn}@@ -312,12 +330,24 @@ final class NotesEngine: ObservableObject {- Add a fishbone only to a topic that discusses causes, reasons or factors (3-5 branches); otherwise null.- Every topic, point, branch, conclusion and to-do needs evidence: the ids of the lines that say it. Never state anything the transcript does not say.- terms: at most 10 people, places or jargon words that matter. name is the correct spelling in the transcript's language (no translation in brackets); heard lists only the wrong forms the transcript used; note is a few words.+ - Write every summary, title, point, branch, conclusion and to-do in \(language), even when the transcript is in another language. Only term names keep the transcript's spelling.- Write about what was said, never about the transcript or recognition quality.- Use empty arrays when there is nothing. No markdown, no text outside the JSON."""return p}+ /// Whether the notes' own words (summary, titles) are in `language`: Chinese, Japanese and+ /// Korean need a fair share of CJK (names and numbers stay Latin), other languages must not be mostly CJK.+ static func written(_ notes: MeetingNotes, in language: String) -> Bool {+ let text = ([notes.summary] + notes.topics.map(\.title)).joined()+ let letters = text.unicodeScalars.filter { $0.properties.isAlphabetic }+ guard !letters.isEmpty else { return true }+ let cjk = letters.filter { (0x3040...0x9FFF).contains($0.value) || (0xAC00...0xD7AF).contains($0.value) }.count+ let wantsCJK = ["Chinese", "Japanese", "Korean"].contains { language.contains($0) }+ return wantsCJK ? cjk * 5 >= letters.count : cjk * 2 < letters.count+ }+/// The current notes as sent back to the model (no bookkeeping fields).private struct Compact: Encodable {let summary: Stringdiff --git a/Sources/LiveSubs/NotesViews.swift b/Sources/LiveSubs/NotesViews.swiftindex 26a2a16..e3bb47c 100644--- a/Sources/LiveSubs/NotesViews.swift+++ b/Sources/LiveSubs/NotesViews.swift@@ -282,6 +282,25 @@ struct FishboneView: View {// MARK: - Transcript+/// When the user last turned a scroll wheel or swiped the trackpad in this app. SwiftUI also moves+/// a scroll view by itself (rows measured late, text rewrapping after a resize), so only a recent+/// real scroll may pause following.+@MainActor+enum UserScroll {+ private static var last = Date.distantPast+ private static var monitor: Any?++ static func install() {+ guard monitor == nil else { return }+ monitor = NSEvent.addLocalMonitorForEvents(matching: .scrollWheel) { event in+ last = Date()+ return event+ }+ }++ static var recent: Bool { Date().timeIntervalSince(last) < 0.6 }+}+/// The transcript grouped under the notes' topics, oldest first. While live it follows the/// newest line; scrolling up pauses that and collects new lines into a "↓ N 句新内容" button./// A search highlights matches in place instead of hiding the lines around them.@@ -325,6 +344,7 @@ struct TranscriptListView: View {private struct Edge: Equatable {var distance: CGFloatvar height: CGFloat+ var container: CGFloat}var body: some View {@@ -362,12 +382,18 @@ struct TranscriptListView: View {.padding(.bottom, 12)}.onScrollGeometryChange(for: Edge.self) { g in- Edge(distance: g.contentSize.height - g.contentOffset.y - g.containerSize.height, height: g.contentSize.height)+ Edge(distance: g.contentSize.height - g.contentOffset.y - g.containerSize.height,+ height: g.contentSize.height, container: g.containerSize.height)} action: { old, new in- if new.distance < 40 {+ if new.height != old.height || new.container != old.container {+ // Not only new lines move the bottom: a translation arriving under its line,+ // topic headers from a notes update, rows the lazy stack only now measured,+ // the window resizing. Following means staying on the newest line through all of them.+ if new.distance > 1 { follow(proxy) }+ } else if new.distance < 40 {if !following { following = true }- } else if following, new.distance > 60, new.height == old.height {- // The reader scrolled up (content growing never pauses following).+ } else if following, new.distance > 60, UserScroll.recent {+ // The reader scrolled up (content growing or reflowing never pauses following).following = falseseenCount = lines.count}@@ -385,6 +411,7 @@ struct TranscriptListView: View {reveal(target, anchor: .top, proxy)}.onAppear {+ UserScroll.install()seenCount = lines.countif let t = jumpTo, let target = lines.first(where: { $0.t >= t - 1 }) {following = falsediff --git a/Sources/LiveSubs/NotesWindow.swift b/Sources/LiveSubs/NotesWindow.swiftindex 1fcfb15..4636ad0 100644--- a/Sources/LiveSubs/NotesWindow.swift+++ b/Sources/LiveSubs/NotesWindow.swift@@ -63,7 +63,7 @@ final class NotesWindowController: NSObject, NSWindowDelegate {p.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]p.minSize = NSSize(width: 300, height: 180)p.backgroundColor = .white- p.contentView = NSHostingView(rootView: NotesWindowView(+ p.contentView = FirstClickHostingView(rootView: NotesWindowView(model: model, engine: model.notes, store: model.store, settings: model.settings,commands: commands.eraseToAnyPublisher(),setWidth: { [weak self] w, h in self?.resize(width: w, height: h) }))@@ -126,6 +126,9 @@ struct NotesWindowView: View {@State private var matchIndex = 0@State private var now = Date()@State private var width: CGFloat = 460+ /// "结束" was clicked during a meeting with lines: the confirmation strip is showing.+ @State private var confirmEnd = false+ @State private var languageOpen = false@FocusState private var searchFocused: Boolprivate var session: Session? { store.session(store.liveID ?? engine.shownID) }@@ -141,6 +144,7 @@ struct NotesWindowView: View {} else {VStack(alignment: .leading, spacing: 0) {header(wide: geo.size.width >= 760)+ meetingBar.padding(.horizontal, 24).padding(.bottom, 4)banner.padding(.horizontal, 24).padding(.bottom, 4)if geo.size.width >= 760 {HStack(alignment: .top, spacing: 0) {@@ -217,7 +221,7 @@ struct NotesWindowView: View {VStack(alignment: .leading, spacing: 16) {HStack(alignment: .top, spacing: 4) {VStack(alignment: .leading, spacing: 6) {- Text("实时纪要").font(.system(size: 24, weight: .bold))+ Text(live || session == nil ? "实时纪要" : "会议纪要").font(.system(size: 24, weight: .bold))HStack(spacing: 6) {if live { LiveDot() }Text(statusLine).font(.system(size: 12)).foregroundStyle(Palette.tertiary).lineLimit(1)@@ -227,6 +231,16 @@ struct NotesWindowView: View {if engine.state == .updating, !engine.notes.isEmpty {UpdatingPill().padding(.top, 4).padding(.trailing, 4)}+ if live {+ languageChip.padding(.trailing, 2)+ Button(action: askToEnd) {+ Text("结束").font(.system(size: 12, weight: .semibold)).foregroundStyle(Palette.ink)+ .padding(.horizontal, 12).frame(height: 28)+ .overlay(RoundedRectangle(cornerRadius: 7).stroke(Palette.line, lineWidth: 1))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain).help("结束这场会议").padding(.trailing, 4)+ }iconButton(wide ? "rectangle.split.2x1.fill" : "rectangle.split.2x1", help: wide ? "收窄" : "纪要和原话并排") {setWidth(wide ? 460 : 820, nil)}@@ -325,12 +339,159 @@ struct NotesWindowView: View {if !engine.notes.isEmpty, lastCovered > 0 { parts.append("纪要已更新至 \(NotesEngine.clock(lastCovered))") }return parts.joined(separator: " · ")}- let clock = session.map { TranscriptExport.header($0) } ?? "没有进行中的会议"+ let clock = session.map { "已结束 · " + TranscriptExport.header($0) } ?? "没有在记录"guard let at = engine.notes.updatedAt, engine.state != .updating else { return clock }let ago = Int(now.timeIntervalSince(at))return clock + " · " + (ago < 10 ? "刚刚更新" : ago < 60 ? "\(ago) 秒前更新" : "\(ago / 60) 分钟前更新")}+ // MARK: This meeting's languages++ /// "EN → 中": what the meeting speaks → what the notes are written in. Opens this meeting's+ /// choices below the header (not a popover: the panel never activates the app, and a popover in+ /// an inactive app closes as soon as it opens); the defaults live in 设置 › 语言.+ private var languageChip: some View {+ let id = session?.id ?? ""+ let from = model.meetingLanguage(store.liveID).map(Self.short) ?? "自动"+ return Button { languageOpen.toggle() } label: {+ HStack(spacing: 4) {+ Text(from)+ Image(systemName: "arrow.right").font(.system(size: 9, weight: .bold))+ Text(Self.short(model.notesLanguageCode(id)))+ }+ .font(.system(size: 12, weight: .semibold)).foregroundStyle(Palette.accentInk)+ .padding(.horizontal, 9).frame(height: 28)+ .background(RoundedRectangle(cornerRadius: 7).fill(Palette.accentPale))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain).help("这场会议的语言").accessibilityLabel("这场会议的语言")+ }++ private func languageCard(_ id: String) -> some View {+ let source = model.meetingLanguage(store.liveID)+ let mine = settings.myLanguage+ return VStack(alignment: .leading, spacing: 14) {+ HStack(alignment: .top) {+ VStack(alignment: .leading, spacing: 3) {+ Text("这场会议").font(.system(size: 14, weight: .bold))+ Text("只改这一场,默认值在 设置 › 语言").font(.system(size: 12)).foregroundStyle(Palette.tertiary)+ }+ Spacer()+ iconButton("xmark", help: "收起") { languageOpen = false }+ }+ VStack(alignment: .leading, spacing: 6) {+ Text("对方说").font(.system(size: 12, weight: .semibold)).foregroundStyle(Palette.secondary)+ Text(source.map(targetName) ?? "还没听出来").font(.system(size: 13))+ }+ VStack(alignment: .leading, spacing: 6) {+ Text("字幕").font(.system(size: 12, weight: .semibold)).foregroundStyle(Palette.secondary)+ Segments(options: [("both", "双语"), ("translation", "只看译文"), ("original", "只看原文")],+ value: model.subtitles, fill: true) { model.setSubtitles($0, meetingOnly: true) }+ }+ VStack(alignment: .leading, spacing: 6) {+ Text("纪要").font(.system(size: 12, weight: .semibold)).foregroundStyle(Palette.secondary)+ Segments(options: [("mine", targetName(mine)), ("source", source.map { "\(targetName($0))(原文)" } ?? "会议原文")],+ value: model.notesChoice(id), fill: true) { model.setNotesLanguage($0, meetingOnly: true) }+ Text("换了以后会马上用新语言重写纪要").font(.system(size: 12)).foregroundStyle(Palette.tertiary)+ }+ Button("打开语言设置") {+ languageOpen = false+ model.openSettings(.language)+ }+ .buttonStyle(.plain).font(.system(size: 12)).foregroundStyle(Palette.accentInk)+ }+ .padding(14)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(RoundedRectangle(cornerRadius: 12).fill(Palette.fill))+ .foregroundStyle(Palette.ink)+ }++ static func short(_ code: String) -> String {+ switch code {+ case "zh-CN": "中"+ case "zh-TW": "繁"+ case "ja": "日"+ case "ko": "韩"+ default: code.prefix(2).uppercased()+ }+ }++ // MARK: Ending a meeting++ /// Nothing heard yet: there is nothing to lose, stop at once. Otherwise ask first, below the+ /// header (away from the button, so a double click can't confirm it).+ private func askToEnd() {+ if heard == 0 { model.stop() } else { confirmEnd = true }+ }++ /// While live: the confirmation, when asked. After the meeting: what happens to it and what next.+ @ViewBuilder+ private var meetingBar: some View {+ if live {+ if languageOpen && !confirmEnd { languageCard(session?.id ?? "") }+ if confirmEnd {+ VStack(alignment: .leading, spacing: 10) {+ Text("结束这场会议?").font(.system(size: 14, weight: .bold))+ Text("已记录 \(NotesEngine.clock(elapsed)) · \(heard) 句。结束后停止收听,并整理一份完整版纪要。")+ .font(.system(size: 12)).foregroundStyle(Palette.secondary).lineSpacing(2)+ .fixedSize(horizontal: false, vertical: true)+ HStack(spacing: 8) {+ SoftButton("继续记录") { confirmEnd = false }+ SoftButton("结束会议", dark: true) {+ confirmEnd = false+ model.stop()+ }+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(14)+ .background(RoundedRectangle(cornerRadius: 12).fill(Palette.accentPale))+ // No timeout: a strip that vanished under the pointer would let the click land on the notes.+ }+ } else {+ VStack(alignment: .leading, spacing: 10) {+ HStack(spacing: 8) {+ if session != nil && engine.state == .updating {+ ProgressView().controlSize(.small)+ } else if session != nil {+ Image(systemName: "checkmark.circle.fill").foregroundStyle(Palette.accent)+ }+ Text(endedText).font(.system(size: 13, weight: .semibold)).lineLimit(2)+ }+ HStack(spacing: 8) {+ if let id = session?.id, let other = otherNotesLanguage(id) {+ SoftButton("改用\(targetName(other.code))重新整理") { model.regenerateNotes(id, choice: other.choice) }+ .disabled(engine.state == .updating)+ }+ if let id = session?.id {+ SoftButton("在会议记录中查看") {+ model.mainShow = nil+ model.mainShow = "\(id),notes"+ model.openMainWindow?()+ }+ }+ SoftButton(session == nil ? "开始记录" : "开始新会议", dark: true) { model.start() }+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(14)+ .background(RoundedRectangle(cornerRadius: 12).fill(Palette.fill))+ }+ }++ /// The notes language this meeting's notes are not in, when the meeting's language differs from mine.+ private func otherNotesLanguage(_ id: String) -> (choice: String, code: String)? {+ guard let source = model.meetingLanguage(id), source != settings.myLanguage else { return nil }+ return model.notesChoice(id) == "source" ? ("mine", settings.myLanguage) : ("source", source)+ }++ private var endedText: String {+ guard session != nil else { return "现在没有在记录" }+ if engine.state == .updating { return "会议已结束,正在整理完整版纪要…" }+ if engine.state == .noKey || engine.notes.isEmpty { return "会议已结束,文字记录已保存" }+ return "会议已结束,完整版纪要已整理好 · " + targetName(model.notesLanguageCode(session?.id ?? ""))+ }+// MARK: Banners (key and service states)@ViewBuilder@@ -451,13 +612,14 @@ struct NotesWindowView: View {@ViewBuilderprivate var caption: some View {- if live, !model.liveSource.isEmpty || !model.liveTranslation.isEmpty {+ let shown = model.displayed(model.liveSource, model.liveTranslation)+ if live, !shown.source.isEmpty || !shown.translation.isEmpty {VStack(alignment: .leading, spacing: 3) {- if !model.liveSource.isEmpty {- Text(model.liveSource).font(.system(size: 12)).foregroundStyle(Color(white: 0.74)).lineLimit(2)+ if !shown.source.isEmpty {+ Text(shown.source).font(.system(size: 12)).foregroundStyle(Color(white: 0.74)).lineLimit(2)}- if !model.liveTranslation.isEmpty {- Text(model.liveTranslation).font(.system(size: 14, weight: .semibold)).foregroundStyle(.white).lineLimit(3)+ if !shown.translation.isEmpty {+ Text(shown.translation).font(.system(size: 14, weight: .semibold)).foregroundStyle(.white).lineLimit(3)}}.frame(maxWidth: .infinity, alignment: .leading)@@ -574,3 +736,9 @@ struct NotesWindowView: View {return s < 60 ? "\(s) 秒" : "\(s / 60) 分钟"}}++/// The panel never activates the app, so it is almost never the key window when clicked; a plain+/// hosting view would spend that click on focus and every button would need two.+final class FirstClickHostingView<Content: View>: NSHostingView<Content> {+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }+}diff --git a/Sources/LiveSubs/Settings.swift b/Sources/LiveSubs/Settings.swiftindex d6da83e..d71ef2e 100644--- a/Sources/LiveSubs/Settings.swift+++ b/Sources/LiveSubs/Settings.swift@@ -18,6 +18,16 @@ final class AppSettings: ObservableObject {@Published var target: String {didSet { save() }}+ /// What the subtitles show: "both" (original + translation), "translation", or "original"+ /// (nothing is translated, so no translator is called).+ @Published var subtitles: String {+ didSet { save() }+ }+ /// The language notes are written in: "mine" (the translate-to language, or the system's when+ /// that follows the system) or "source" (the meeting's own language).+ @Published var notesLanguage: String {+ didSet { save() }+ }@Published var speakEnabled: Bool {didSet { save() }}@@ -82,6 +92,8 @@ final class AppSettings: ObservableObject {sourceMode = .auto}target = defaults.string(forKey: "target") ?? "system"+ subtitles = defaults.string(forKey: "subtitles") ?? "both"+ notesLanguage = defaults.string(forKey: "notesLanguage") ?? "mine"speakEnabled = defaults.bool(forKey: "speakEnabled")let prefersChinese = Locale.preferredLanguages.contains { $0.hasPrefix("zh") }speakFrom = defaults.string(forKey: "speakFrom") ?? (prefersChinese ? "zh-CN" : "en-US")@@ -104,6 +116,8 @@ final class AppSettings: ObservableObject {case .fixed(let lang): defaults.set(lang.locale, forKey: "sourceMode")}defaults.set(target, forKey: "target")+ defaults.set(subtitles, forKey: "subtitles")+ defaults.set(notesLanguage, forKey: "notesLanguage")defaults.set(speakEnabled, forKey: "speakEnabled")defaults.set(speakFrom, forKey: "speakFrom")defaults.set(speakTo, forKey: "speakTo")@@ -128,6 +142,14 @@ final class AppSettings: ObservableObject {return prefs.first ?? "zh-CN"}+ /// The reader's own language: the translate-to choice, or with "follow system" the first+ /// system language (Chinese first when it is there: the app speaks Chinese).+ var myLanguage: String {+ if target != "system" { return target }+ let prefs = Locale.preferredLanguages+ return translationCode(forSystemLanguage: prefs.first(where: { $0.hasPrefix("zh") }) ?? prefs.first ?? "zh-Hans")+ }+func systemTargetDescription() -> String {let prefs = Locale.preferredLanguages.map(translationCode(forSystemLanguage:))var seen: [String] = []diff --git a/Sources/LiveSubs/SettingsWindow.swift b/Sources/LiveSubs/SettingsWindow.swiftindex 0acfb9d..072c626 100644--- a/Sources/LiveSubs/SettingsWindow.swift+++ b/Sources/LiveSubs/SettingsWindow.swift@@ -3,11 +3,12 @@ import Carbon.HIToolboximport SwiftUIenum SettingsSection: String, CaseIterable, Identifiable {- case overlay, speak, records, ai, diagnostics+ case overlay, language, speak, records, ai, diagnosticsvar id: String { rawValue }var title: String {switch self {case .overlay: "显示"+ case .language: "语言"case .speak: "同声传译"case .records: "会议记录"case .ai: "AI 服务"@@ -17,6 +18,7 @@ enum SettingsSection: String, CaseIterable, Identifiable {var icon: String {switch self {case .overlay: "captions.bubble"+ case .language: "globe"case .speak: "mic"case .records: "doc.text"case .ai: "key"@@ -61,6 +63,37 @@ struct SettingsRow<Trailing: View>: View {}}+/// A few mutually exclusive choices side by side, the chosen one raised.+struct Segments: View {+ let options: [(id: String, title: String)]+ let value: String+ var fill = false+ let onPick: (String) -> Void+ var body: some View {+ HStack(spacing: 2) {+ ForEach(options, id: \.id) { o in+ let on = o.id == value+ Button { onPick(o.id) } label: {+ Text(o.title).font(.system(size: 12, weight: on ? .semibold : .regular))+ .foregroundStyle(on ? Palette.ink : Palette.secondary).lineLimit(1)+ .padding(.horizontal, 10).frame(maxWidth: fill ? .infinity : nil).frame(height: 26)+ .background(RoundedRectangle(cornerRadius: 7).fill(on ? Color.white : .clear)+ .shadow(color: .black.opacity(on ? 0.08 : 0), radius: 1.5, y: 1))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .accessibilityAddTraits(on ? .isSelected : [])+ }+ }+ .padding(3)+ .background(RoundedRectangle(cornerRadius: 9).fill(Palette.fill))+ .fixedSize(horizontal: !fill, vertical: false)+ }+}++/// The 字幕 choices.+let subtitleOptions: [(id: String, title: String)] = [("both", "原文 + 译文"), ("translation", "只看译文"), ("original", "只看原文")]+/// A grey pill that opens a menu: the value and a small chevron.struct PillMenu: View {let value: String@@ -354,6 +387,7 @@ struct SettingsView: View {switch model.settingsSection {case .speak: speakcase .overlay: overlay+ 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.aiModel)@@ -410,29 +444,6 @@ struct SettingsView: View {// MARK: Sections- /// Who is heard and what they're translated into: the top of the 显示 page.- private var listen: some View {- SettingsCard {- SettingsRow(title: "听到") {- PillMenu(value: heardValue, options: [("auto", "自动识别")] + sourceLanguages.map { ($0.locale, $0.name) }) {- model.sourceSelection = $0- }- }- SettingsRow(title: "翻译成", divider: false) {- PillMenu(value: settings.target == "system" ? "跟随系统(\(targetName(model.listen.resolvedTarget)))"- : targetName(settings.target),- options: [("system", "跟随系统")] + targetLanguages.map { ($0.code, $0.name) }) {- model.targetSelection = $0- }- }- }- }-- private var heardValue: String {- if case .fixed(let l) = settings.sourceMode { return l.name }- return "自动识别"- }-private var speak: some View {VStack(alignment: .leading, spacing: 14) {Text("按住说话,松开后约 2 秒,对方听到译文").font(.system(size: 12)).foregroundStyle(Palette.secondary)@@ -448,17 +459,8 @@ struct SettingsView: View {ShortcutField(model: model, role: .talk)}if settings.speakEnabled && model.talkNeedsPermission { TalkKeyPermissionRow(model: model) }- SettingsRow(title: "我说的语言") {- PillMenu(value: settings.speakFromLang.name, options: sourceLanguages.map { ($0.locale, $0.name) }) {- settings.speakFrom = $0- model.speakFromChanged()- }- }- SettingsRow(title: "对方听到") {- PillMenu(value: settings.speakTo == "room" ? "跟随对方的语言" : targetName(settings.speakTo),- options: [("room", "跟随对方的语言")] + targetLanguages.map { ($0.code, $0.name) }) {- settings.speakTo = $0- }+ SettingsRow(title: "语言", detail: "说\(settings.speakFromLang.name),对方听到\(targetName(model.speak.targetCode))") {+ SoftButton("修改") { model.settingsSection = .language }}SettingsRow(title: "声音输出到", divider: false) {PillMenu(value: outputName,@@ -480,7 +482,6 @@ struct SettingsView: View {private var overlay: some View {VStack(alignment: .leading, spacing: 14) {- listenSettingsCard {SettingsRow(title: "听的时候显示", detail: "选择任意模式都会正常保存记录、生成纪要") {Picker("显示方式", selection: Binding(get: { settings.displayMode }, set: { model.setDisplayMode($0) })) {diff --git a/Sources/LiveSubs/Views.swift b/Sources/LiveSubs/Views.swiftindex cbbdefc..83be54a 100644--- a/Sources/LiveSubs/Views.swift+++ b/Sources/LiveSubs/Views.swift@@ -129,6 +129,10 @@ struct MenuPanelView: View {options: targetOptions) {model.targetSelection = $0}+ ChoiceRow(label: "字幕", value: subtitleOptions.first { $0.id == model.subtitles }?.title ?? "原文 + 译文",+ badge: model.meetingSubtitles != nil ? "仅本场" : nil, options: subtitleOptions) {+ model.setSubtitles($0)+ }}Divider()diff --git a/site/changelog.json b/site/changelog.jsonindex 5b43d83..1c7704f 100644--- a/site/changelog.json+++ b/site/changelog.json@@ -6,6 +6,16 @@"summary": "这一版让知了从“实时字幕”变成完整的会议助手:边开会边写纪要,同声传译可以用更自然的声音说出去,虚拟麦克风装完能当场试音。","image": null,"items": [+ {+ "kind": "new",+ "title": "语言集中设置。",+ "text": "设置 › 语言 把对方说的语言、字幕(双语 / 只看译文 / 只看原文)、翻译成、纪要语言和同声传译的语言放在一起,顶部一行看清整条路线;纪要窗口的「EN → 中」可以只改这一场,会后还能改用另一种语言重新整理纪要。"+ },+ {+ "kind": "fixed",+ "title": "会后完整版纪要变成英文。",+ "text": "长的英文会议结束后,完整版纪要会变成英文;现在始终用你选的纪要语言。"+ },{"kind": "new","title": "AI 实时会议纪要。",