知了 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: update in place, open at login, About links and unit tests
wquguruf4f62268f8b5
diff --git a/AGENTS.md b/AGENTS.mdindex de11f5d..207af9e 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -4,7 +4,7 @@ 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: 显示 / 语言 (`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).+- Few surfaces, nothing more: the **menu bar panel** (on/off, heard language, translate-to language, "同声传译", display mode, an update strip when a newer release is out, 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) / 同声传译 / 通用 (meeting audio, records folder, 登录时打开, version + 检查更新, onboarding; `SettingsSection.records`) / 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.@@ -13,7 +13,8 @@ Cicada (知了, formerly Live Subs) is a macOS menu bar app that turns whatever- 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 (a meeting name — shown as "<date> <name>" via `Session.displayTitle` unless the user renamed it —, 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), 窗口, 帮助.+- 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 (关于 with links to the site, GitHub and issues — `AboutPanel`; 检查更新…, which becomes 安装 x.y.z once one is found), 纪要, 显示 (display mode, ⌘1–⌘3 sizes, 始终置顶), 编辑 (standard responder-chain actions, so ⌘V works in fields; ⌘F search), 窗口, 帮助 (新手引导, 知了网站, 反馈问题… → GitHub `issues/new`).+- Updates (`UpdateChecker`, `Updater`, `Updates`, `UpdateViews`; ported from cameo): once a day (release builds; a dev build only with a test feed) `api.github.com/repos/wquguru/cicada/releases/latest`; a newer tag puts an orange dot on the menu bar glyph (`BrandImage.menuBar(badge:)`, no longer a template image then) and a strip in the panel. Installing asks first when a meeting with lines is live and ends it (`Updates.install`; quitting then doesn't ask again, `Updates.installing`, or the swap script would wait for a quit the user cancelled), downloads `Cicada-*-macOS-AppleSilicon.zip`, checks it against `checksums.txt`, the bundle id, the version and `codesign --verify`, and a shell script swaps the bundle after the app quits and reopens it. Ad-hoc signing with the bundle id as designated requirement keeps the TCC permissions across the swap. Not in place (DMG, App Translocation, unwritable folder) or any failure: the reason in the panel and the release page opens. Silent while the repository is private (the API answers 404). `CICADA_UPDATE_FEED=<url>` or the `updateFeed:` debug command points it at a fake release JSON (`file://` assets work). 登录时打开 is `SMAppService.mainApp` (`LoginItem`), state read from the system, never stored.- Meeting records: one folder per meeting, `session.json` + `system.m4a` (+ `mic.m4a`; recorded as ADTS `system.aac` / `mic.aac`, which survive a crash, and rewrapped to .m4a without re-encoding at the end or at the next launch, `AudioFileWriter.finish`); sentences heard before auto-detection confirms the language are held and recorded once it does (dropped on a switch, which replays them); 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.@@ -28,7 +29,7 @@ Cicada (知了, formerly Live Subs) is a macOS menu bar app that turns whatever## Layout- `Package.swift`: SwiftPM, macOS 26+, Swift 5 language mode, no dependencies.-- `Sources/LiveSubs`: the app. Engine files are UI-free: `SystemAudioTap`, `AudioRouter` (resample, feed, ring buffer, recording), `LanguageDetector`, `ListenEngine`, `SpeakEngine`, `Shortcuts` (Carbon `HotKey`, right-⌥ `RightOptionKey`), `Ling` (Keychain key + client), `Notes` (model + engine), `Translator`, `VirtualMic`, `SessionStore` (+ exports). UI: `Overlay` (subtitle bar), `Views` (panel, main window), `SettingsWindow` (settings + the virtual mic checklist), `AISettings`, `NotesWindow` + `NotesViews` (live notes window; notes and transcript views shared with the main window), `Onboarding` (+ sample player, brand mark), `AppMenu` (the menus top left), `AppModel` (wiring, status item, windows, activation policy, debug control, `@main`). `DMGBackground` draws the installer background; `DevBuild` tells dev from release.+- `Sources/LiveSubs`: the app. Engine files are UI-free: `SystemAudioTap`, `AudioRouter` (resample, feed, ring buffer, recording), `LanguageDetector`, `ListenEngine`, `SpeakEngine`, `Shortcuts` (Carbon `HotKey`, right-⌥ `RightOptionKey`), `Ling` (Keychain key + client), `Notes` (model + engine), `Translator`, `VirtualMic`, `SessionStore` (+ exports). UI: `Overlay` (subtitle bar), `Views` (panel, main window), `SettingsWindow` (settings + the virtual mic checklist), `AISettings`, `NotesWindow` + `NotesViews` (live notes window; notes and transcript views shared with the main window), `Onboarding` (+ sample player, brand mark), `AppMenu` (the menus top left), `AboutPanel`, `UpdateViews` (panel strip, 通用 rows), `AppModel` (wiring, status item, windows, activation policy, debug control, `@main`). `DMGBackground` draws the installer background; `DevBuild` tells dev from release.- `Sources/LiveSubsIcon`: CLI that renders the icon set (`--dev` adds the DEV band).- `Resources/`: `Info.plist`, `sample/` (the 7 s onboarding clip, made by `scripts/make-sample.sh`), `dmg/DS_Store` (installer window layout).- `scripts/build.sh`: builds `build/Cicada.app` (executable `Cicada`; the SwiftPM product and the source folder are still `LiveSubs`). Shown as 知了 on Chinese systems and Cicada elsewhere (`Resources/*.lproj/InfoPlist.strings`). Without `RELEASE=1` it is a **dev build**: "知了 Dev" / "Cicada Dev", bundle id `com.wquguru.cicada.dev`, `LiveSubsDev` = `branch @ commit[+]` in Info.plist; "DEV" beside the menu bar glyph, a DEV badge and the stamp in the panel, a DEV band on the icon, its own settings, permissions, `~/Library/Application Support/LiveSubs Dev` and log `/tmp/livesubs-dev-debug.log`. Both builds are signed ad hoc with a fixed designated requirement (the bundle id) so rebuilding keeps the system-audio and microphone permissions. Don't change the release bundle id `com.wquguru.cicada`: permissions are tied to it.@@ -40,6 +41,7 @@ Cicada (知了, formerly Live Subs) is a macOS menu bar app that turns whatever```bashswift build # debug build+scripts/test.sh # unit tests (Swift Testing; adds the CLT framework paths)scripts/build.sh && open build/Cicada.app # dev build (知了 Dev)RELEASE=1 scripts/build.sh # release build (com.wquguru.cicada)scripts/package.sh # DMG + zip + checksums in build/@@ -49,7 +51,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>`, `subtitles:<both|translation|original>`, `meetingSubtitles:<…>`, `notesLang:<mine|source>`, `meetingNotesLang:<…>`, `notesRegenerate:<id>=<mine|source>`, `settings:language`, `notesWindow[:x,y,w,h]`, `notesClose` (its close button), `closeWindow:<main|settings|onboarding>`, `notesFrame`, `notesNow`, `notesState`, `notesShow:<id>`, `notesReplay:<id>`, `notesRender:<png>`, `notesCapturable`, `windowsRender:<dir>` (every visible window as drawn), `settingsRender:<section>=<png>` (one settings page in full), `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]`, `notesClose` (its close button), `closeWindow:<main|settings|onboarding>`, `notesFrame`, `notesNow`, `notesState`, `notesShow:<id>`, `notesReplay:<id>`, `notesRender:<png>`, `notesCapturable`, `windowsRender:<dir>` (every visible window as drawn), `settingsRender:<section>=<png>` (one settings page in full), `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>`, `updateFeed:<url>`, `updateCheck`, `updateInstall`, `updateState`, `loginItem[:on|off]`, `about` …).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.@@ -59,7 +61,7 @@ Only Command Line Tools are required (no Xcode project). Do not add an `.xcodeprRun the app and check the behaviour, not just the build. For the English UI: `defaults write com.wquguru.cicada.dev AppleLanguages -array en`, relaunch, and `defaults delete com.wquguru.cicada.dev AppleLanguages` afterwards. The pattern used so far: dev build, `tools/lsctl` to drive it, `afplay Resources/sample/sample.m4a` (or `say -o` clips) as the "someone talking" input, read `/tmp/livesubs-dev-debug.log`, screenshot windows with `screencapture -l <id>` (`tools/winall`). Synthetic mouse/key events (`tools/mouse`, `tools/key`, `tools/toggle-key`) need the terminal to have Accessibility access. The notes window is excluded from screen capture: send `notesCapturable` before `screencapture -l`, or `notesRender:<png>` for the whole notes column. Ling tests need a key: `aiKeyFile:` a 0600 file in the scratchpad, deleted right after. Synthetic keys reach every app: another app's launcher may take ⌥ Space. The real microphone, the BlackHole install (password), granting Input Monitoring and a Mac without permissions need a person.-TODO: unit tests for the pure parts (language-code mapping, detection scoring, SRT/Markdown export). Swift Testing under Command Line Tools needs extra framework search paths (see cameo's `scripts/test.sh`).+Unit tests (`Tests/LiveSubsTests`, `@testable import LiveSubs`, run with `scripts/test.sh`) cover the pure parts: version compare and checksum lookup, language-code mapping, detection scoring, SRT/Markdown export. Add a test when changing one of those. To try an update end to end: build with a bumped `CFBundleShortVersionString`, `ditto -c -k --keepParent build/Cicada.app Cicada-<v>-macOS-AppleSilicon.zip`, `shasum -a 256` it into `checksums.txt`, write a release JSON with `file://` asset URLs, run a copy of the older dev build from the scratchpad (not `build/`), then `updateFeed:file://…` and `updateInstall`.## Conventionsdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex c9a97b2..2c45d37 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,10 @@ the release workflow publishes it as the release notes.## Unreleased+- New: in-app updates. Once a day the app checks GitHub Releases; when a newer version is out, an orange dot appears on the menu bar icon and the panel offers to install it. Installing downloads the release zip, checks it against `checksums.txt`, the bundle id, the version and its signature, then replaces the app and reopens it, keeping the system-audio and microphone permissions. A meeting being recorded is ended first, after asking. If the app can't replace itself (still in the DMG, or a folder it can't write to), it says why and opens the release page. Also in the app menu (检查更新…) and Settings › 通用.+- New: 登录时打开 in Settings › 通用: after you log in the app waits in the menu bar without opening any window.+- New: the About window links to the website, GitHub and the issue tracker; Help has 知了网站 and 反馈问题….+- Changed: the 会议记录 settings page is now 通用 (meeting audio, records folder, open at login, version, onboarding).- Fixed: with the heard language on 自动识别, the first sentences of a meeting (everything said before the language was confirmed, usually the first 2–5 s) were shown but never saved to the meeting record or the notes. They are now recorded, with their translation and the time they were said, as soon as the language is confirmed.- Fixed: if the app was force-quit or crashed during a meeting, its recording (`system.m4a`, `mic.m4a`) could not be opened. Meetings are now recorded in a format that survives that, and turned into .m4a when the meeting ends or, after a crash, the next time the app starts.- Fixed: changing the notes language while the notes were being updated kept the notes in the old language. The rewrite now runs right after, and the reply in the old language is dropped.diff --git a/Package.swift b/Package.swiftindex d09de8f..a5ab42d 100644--- a/Package.swift+++ b/Package.swift@@ -7,6 +7,7 @@ let package = Package(targets: [.executableTarget(name: "LiveSubs", path: "Sources/LiveSubs"),.executableTarget(name: "LiveSubsIcon", path: "Sources/LiveSubsIcon"),+ .testTarget(name: "LiveSubsTests", dependencies: ["LiveSubs"], path: "Tests/LiveSubsTests"),],swiftLanguageModes: [.v5])diff --git a/README.md b/README.mdindex 76a0a7b..e169e6d 100644--- a/README.md+++ b/README.md@@ -65,7 +65,7 @@ Cicada (知了, formerly Live Subs) is a macOS menu bar app that listens to what## Cost & Privacy-Audio capture, language detection, speech recognition (Apple SpeechAnalyzer) and meeting recordings all stay on your Mac. The only data that leaves your device is the recognized text sent for translation and meeting notes, plus the short audio clips you speak while holding the talk key when using a Ling API key.+Audio capture, language detection, speech recognition (Apple SpeechAnalyzer) and meeting recordings all stay on your Mac. The only data that leaves your device is the recognized text sent for translation and meeting notes, plus the short audio clips you speak while holding the talk key when using a Ling API key. Once a day the app also asks GitHub for the latest release (a plain request with nothing about you or your meetings in it).Subtitles, translation, meeting records and push-to-talk interpreting work out of the box without any API key (translation uses Google and falls back to Apple on-device translation).@@ -103,6 +103,8 @@ Requires **macOS 26 or later** on **Apple silicon**.2. Open the DMG and drag **Cicada** into **Applications**.3. Because the app is ad-hoc signed and not notarized, macOS will block the first launch. Open **System Settings › Privacy & Security** and click **Open Anyway**.+Updates come from inside the app: when a new version is out, an orange dot appears on the menu bar icon; one click downloads it, checks it against the published SHA-256, replaces the app and reopens it, keeping its permissions. To have Cicada waiting in the menu bar after you log in, turn on **Settings › General › Open at Login**.+On first launch, a three-step guide helps you grant system audio capture permission (and optionally microphone access), play a built-in sample video to see live subtitles right away, and optionally install the BlackHole 2ch virtual microphone with one click (requires your Mac administrator password once) with an automatic sound check.## Usagediff --git a/README.zh-CN.md b/README.zh-CN.mdindex 3680c9f..3e3e69e 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -65,7 +65,7 @@## 费用与隐私-声音采集、语言识别、语音识别(Apple SpeechAnalyzer)和会议录音全部在本机完成,录音文件只存在你自己的硬盘里。会离开电脑的数据只有识别出来的文字(发去做翻译和生成纪要),以及填了 Ling API key 并按住说话键用同声传译时,你按住按键说的那几句语音。+声音采集、语言识别、语音识别(Apple SpeechAnalyzer)和会议录音全部在本机完成,录音文件只存在你自己的硬盘里。会离开电脑的数据只有识别出来的文字(发去做翻译和生成纪要),以及填了 Ling API key 并按住说话键用同声传译时,你按住按键说的那几句语音。另外,知了每天会向 GitHub 查一次最新版本,请求里不带任何关于你或会议的内容。不填 API key 的情况下,实时字幕、翻译、会议记录和同声传译都能正常用,此时翻译默认走 Google,连不上时退回 Apple 本机翻译。@@ -102,6 +102,8 @@2. 打开 DMG,把知了拖进“应用程序”文件夹。3. 因为应用采用本地签名(ad-hoc),没有走苹果公证,第一次打开会被系统拦下。请打开系统的“系统设置 › 隐私与安全性”,滑到底部点“仍要打开”。+以后的新版本在应用里就能更新:有新版本时菜单栏图标上会出现一个橙点,点一下即可下载、按 SHA-256 校验、替换并重新打开,权限不丢。想开机后让知了在菜单栏待命,打开“设置 › 通用 › 登录时打开”。+首次打开时有简单的三步引导,先开启“听电脑里的声音”权限(麦克风权限可选),接着播放内置示例视频马上看到实时字幕跳出来,最后如果想让对方听到翻译,点一下就能安装虚拟麦克风(需要输一次电脑的管理员密码)并自动试音。## 使用方法diff --git a/Resources/en.lproj/Localizable.strings b/Resources/en.lproj/Localizable.stringsindex ca5ec06..394e715 100644--- a/Resources/en.lproj/Localizable.strings+++ b/Resources/en.lproj/Localizable.strings@@ -549,3 +549,45 @@"无法打开麦克风:%@" = "Can't open the microphone: %@";"录音太短了,请至少朗读 %lld 秒" = "Too short; read for at least %lld seconds";"没听清录音内容,请换个安静的地方再录一次" = "Couldn't make out the recording; try again somewhere quiet";++/* Updates, login item, About */+"把 Mac 正在播放的声音变成实时双语字幕和会议纪要" = "Live bilingual subtitles and meeting notes from whatever your Mac is playing";+"网站" = "Website";+"反馈问题" = "Report an Issue";+"检查更新…" = "Check for Updates…";+"%@ 网站" = "%@ Website";+"反馈问题…" = "Report an Issue…";+"安装 %@ 并重新打开" = "Install %@ and Reopen";+"有新版本 %@" = "Version %@ is available";+"当前版本 %@。安装后会自动重新打开。" = "You have %@. The app reopens after installing.";+"安装并重新打开" = "Install and Reopen";+"更新说明" = "Release Notes";+"稍后" = "Later";+"已是最新版本" = "You’re up to date";+"当前版本 %@。" = "You have %@.";+"暂时无法检查更新" = "Couldn’t check for updates";+"连不上 GitHub,请稍后再试。" = "GitHub can’t be reached. Try again later.";+"%@(有新版本)" = "%@ (update available)";+"通用" = "General";+"下载进度" = "Download progress";+"新版本 %@" = "Version %@";+"正在下载 %lld%%,完成后自动重新打开" = "Downloading %lld%%, reopens when done";+"没能自动更新:%@。已打开下载页" = "Couldn’t update automatically: %@. Opened the download page";+"安装后自动重新打开" = "Reopens after installing";+"登录时打开" = "Open at Login";+"版本 %@" = "Version %@";+"请在“系统设置 › 通用 › 登录项”中允许" = "Allow it in System Settings › General › Login Items";+"开机后在菜单栏待命,不弹窗口" = "Waits in the menu bar, no windows";+"正在下载 %@:%lld%%" = "Downloading %@: %lld%%";+"没能自动更新:%@" = "Couldn’t update automatically: %@";+"连不上 GitHub,请稍后再试" = "GitHub can’t be reached; try again later";+"检查更新" = "Check for Updates";+"下载的不是预期的版本" = "The download isn’t the expected version";+"下载的文件校验不通过" = "The download didn’t match its checksum";+"请先把应用拖进“应用程序”文件夹" = "Move the app to Applications first";+"这个版本没有可安装的文件" = "This release has nothing to install";+"下载失败(HTTP %lld)" = "The download failed (HTTP %lld)";+"下载失败" = "The download failed";+"更新包无效" = "The update package is invalid";+"安装更新会结束这场记录,已记下的内容会保存。" = "Installing the update ends this recording. What has been recorded is kept.";+"结束并更新" = "End and Update";diff --git a/Resources/ja.lproj/Localizable.strings b/Resources/ja.lproj/Localizable.stringsindex c2b7e90..ac466cb 100644--- a/Resources/ja.lproj/Localizable.strings+++ b/Resources/ja.lproj/Localizable.strings@@ -549,3 +549,45 @@"无法打开麦克风:%@" = "マイクを開けません: %@";"录音太短了,请至少朗读 %lld 秒" = "録音が短すぎます。%lld秒以上読み上げてください";"没听清录音内容,请换个安静的地方再录一次" = "録音を聞き取れませんでした。静かな場所でもう一度録音してください";++/* Updates, login item, About */+"把 Mac 正在播放的声音变成实时双语字幕和会议纪要" = "Mac で再生中の音声を、リアルタイムの対訳字幕と議事録に";+"网站" = "Web サイト";+"反馈问题" = "問題を報告";+"检查更新…" = "アップデートを確認…";+"%@ 网站" = "%@ Web サイト";+"反馈问题…" = "問題を報告…";+"安装 %@ 并重新打开" = "%@ をインストールして再起動";+"有新版本 %@" = "新しいバージョン %@ があります";+"当前版本 %@。安装后会自动重新打开。" = "現在のバージョンは %@ です。インストール後に自動で再起動します。";+"安装并重新打开" = "インストールして再起動";+"更新说明" = "リリースノート";+"稍后" = "後で";+"已是最新版本" = "最新バージョンです";+"当前版本 %@。" = "現在のバージョンは %@ です。";+"暂时无法检查更新" = "アップデートを確認できません";+"连不上 GitHub,请稍后再试。" = "GitHub に接続できません。しばらくしてからお試しください。";+"%@(有新版本)" = "%@(アップデートあり)";+"通用" = "一般";+"下载进度" = "ダウンロードの進行状況";+"新版本 %@" = "バージョン %@";+"正在下载 %lld%%,完成后自动重新打开" = "ダウンロード中 %lld%%、完了後に再起動";+"没能自动更新:%@。已打开下载页" = "自動アップデートできませんでした:%@。ダウンロードページを開きました";+"安装后自动重新打开" = "インストール後に自動で再起動";+"登录时打开" = "ログイン時に開く";+"版本 %@" = "バージョン %@";+"请在“系统设置 › 通用 › 登录项”中允许" = "「システム設定 › 一般 › ログイン項目」で許可してください";+"开机后在菜单栏待命,不弹窗口" = "メニューバーで待機し、ウインドウは開きません";+"正在下载 %@:%lld%%" = "%@ をダウンロード中:%lld%%";+"没能自动更新:%@" = "自動アップデートできませんでした:%@";+"连不上 GitHub,请稍后再试" = "GitHub に接続できません。後でお試しください";+"检查更新" = "アップデートを確認";+"下载的不是预期的版本" = "ダウンロードしたものが想定のバージョンではありません";+"下载的文件校验不通过" = "ダウンロードしたファイルのチェックサムが一致しません";+"请先把应用拖进“应用程序”文件夹" = "先にアプリを「アプリケーション」フォルダに移動してください";+"这个版本没有可安装的文件" = "このリリースにはインストールできるファイルがありません";+"下载失败(HTTP %lld)" = "ダウンロードに失敗しました(HTTP %lld)";+"下载失败" = "ダウンロードに失敗しました";+"更新包无效" = "アップデートパッケージが無効です";+"安装更新会结束这场记录,已记下的内容会保存。" = "アップデートするとこの記録は終了します。記録済みの内容は保存されます。";+"结束并更新" = "終了してアップデート";diff --git a/Resources/ko.lproj/Localizable.strings b/Resources/ko.lproj/Localizable.stringsindex dd00f11..29edc56 100644--- a/Resources/ko.lproj/Localizable.strings+++ b/Resources/ko.lproj/Localizable.strings@@ -549,3 +549,45 @@"无法打开麦克风:%@" = "마이크를 열 수 없습니다: %@";"录音太短了,请至少朗读 %lld 秒" = "녹음이 너무 짧습니다. 최소 %lld초 이상 읽어 주세요";"没听清录音内容,请换个安静的地方再录一次" = "녹음 내용을 알아듣지 못했습니다. 조용한 곳에서 다시 녹음하세요";++/* Updates, login item, About */+"把 Mac 正在播放的声音变成实时双语字幕和会议纪要" = "Mac에서 재생 중인 소리를 실시간 이중 언어 자막과 회의록으로";+"网站" = "웹사이트";+"反馈问题" = "문제 신고";+"检查更新…" = "업데이트 확인…";+"%@ 网站" = "%@ 웹사이트";+"反馈问题…" = "문제 신고…";+"安装 %@ 并重新打开" = "%@ 설치 후 다시 열기";+"有新版本 %@" = "새 버전 %@ 사용 가능";+"当前版本 %@。安装后会自动重新打开。" = "현재 버전은 %@입니다. 설치 후 자동으로 다시 열립니다.";+"安装并重新打开" = "설치 후 다시 열기";+"更新说明" = "릴리스 노트";+"稍后" = "나중에";+"已是最新版本" = "최신 버전입니다";+"当前版本 %@。" = "현재 버전은 %@입니다.";+"暂时无法检查更新" = "업데이트를 확인할 수 없습니다";+"连不上 GitHub,请稍后再试。" = "GitHub에 연결할 수 없습니다. 잠시 후 다시 시도하세요.";+"%@(有新版本)" = "%@ (업데이트 있음)";+"通用" = "일반";+"下载进度" = "다운로드 진행률";+"新版本 %@" = "버전 %@";+"正在下载 %lld%%,完成后自动重新打开" = "다운로드 중 %lld%%, 완료되면 다시 열림";+"没能自动更新:%@。已打开下载页" = "자동 업데이트 실패: %@. 다운로드 페이지를 열었습니다";+"安装后自动重新打开" = "설치 후 자동으로 다시 열림";+"登录时打开" = "로그인 시 열기";+"版本 %@" = "버전 %@";+"请在“系统设置 › 通用 › 登录项”中允许" = "‘시스템 설정 › 일반 › 로그인 항목’에서 허용하세요";+"开机后在菜单栏待命,不弹窗口" = "메뉴 막대에서 대기하며 창을 띄우지 않음";+"正在下载 %@:%lld%%" = "%@ 다운로드 중: %lld%%";+"没能自动更新:%@" = "자동 업데이트 실패: %@";+"连不上 GitHub,请稍后再试" = "GitHub에 연결할 수 없습니다. 나중에 다시 시도하세요";+"检查更新" = "업데이트 확인";+"下载的不是预期的版本" = "다운로드한 파일이 예상한 버전이 아닙니다";+"下载的文件校验不通过" = "다운로드한 파일의 체크섬이 일치하지 않습니다";+"请先把应用拖进“应用程序”文件夹" = "먼저 앱을 ‘응용 프로그램’ 폴더로 옮기세요";+"这个版本没有可安装的文件" = "이 릴리스에는 설치할 파일이 없습니다";+"下载失败(HTTP %lld)" = "다운로드 실패 (HTTP %lld)";+"下载失败" = "다운로드 실패";+"更新包无效" = "업데이트 패키지가 올바르지 않습니다";+"安装更新会结束这场记录,已记下的内容会保存。" = "업데이트를 설치하면 이 기록이 끝납니다. 기록된 내용은 저장됩니다.";+"结束并更新" = "종료 후 업데이트";diff --git a/Resources/zh-Hans.lproj/Localizable.strings b/Resources/zh-Hans.lproj/Localizable.stringsindex 76eafc5..2204033 100644--- a/Resources/zh-Hans.lproj/Localizable.strings+++ b/Resources/zh-Hans.lproj/Localizable.strings@@ -549,3 +549,45 @@"无法打开麦克风:%@" = "无法打开麦克风:%@";"录音太短了,请至少朗读 %lld 秒" = "录音太短了,请至少朗读 %lld 秒";"没听清录音内容,请换个安静的地方再录一次" = "没听清录音内容,请换个安静的地方再录一次";++/* Updates, login item, About */+"把 Mac 正在播放的声音变成实时双语字幕和会议纪要" = "把 Mac 正在播放的声音变成实时双语字幕和会议纪要";+"网站" = "网站";+"反馈问题" = "反馈问题";+"检查更新…" = "检查更新…";+"%@ 网站" = "%@ 网站";+"反馈问题…" = "反馈问题…";+"安装 %@ 并重新打开" = "安装 %@ 并重新打开";+"有新版本 %@" = "有新版本 %@";+"当前版本 %@。安装后会自动重新打开。" = "当前版本 %@。安装后会自动重新打开。";+"安装并重新打开" = "安装并重新打开";+"更新说明" = "更新说明";+"稍后" = "稍后";+"已是最新版本" = "已是最新版本";+"当前版本 %@。" = "当前版本 %@。";+"暂时无法检查更新" = "暂时无法检查更新";+"连不上 GitHub,请稍后再试。" = "连不上 GitHub,请稍后再试。";+"%@(有新版本)" = "%@(有新版本)";+"通用" = "通用";+"下载进度" = "下载进度";+"新版本 %@" = "新版本 %@";+"正在下载 %lld%%,完成后自动重新打开" = "正在下载 %lld%%,完成后自动重新打开";+"没能自动更新:%@。已打开下载页" = "没能自动更新:%@。已打开下载页";+"安装后自动重新打开" = "安装后自动重新打开";+"登录时打开" = "登录时打开";+"版本 %@" = "版本 %@";+"请在“系统设置 › 通用 › 登录项”中允许" = "请在“系统设置 › 通用 › 登录项”中允许";+"开机后在菜单栏待命,不弹窗口" = "开机后在菜单栏待命,不弹窗口";+"正在下载 %@:%lld%%" = "正在下载 %@:%lld%%";+"没能自动更新:%@" = "没能自动更新:%@";+"连不上 GitHub,请稍后再试" = "连不上 GitHub,请稍后再试";+"检查更新" = "检查更新";+"下载的不是预期的版本" = "下载的不是预期的版本";+"下载的文件校验不通过" = "下载的文件校验不通过";+"请先把应用拖进“应用程序”文件夹" = "请先把应用拖进“应用程序”文件夹";+"这个版本没有可安装的文件" = "这个版本没有可安装的文件";+"下载失败(HTTP %lld)" = "下载失败(HTTP %lld)";+"下载失败" = "下载失败";+"更新包无效" = "更新包无效";+"安装更新会结束这场记录,已记下的内容会保存。" = "安装更新会结束这场记录,已记下的内容会保存。";+"结束并更新" = "结束并更新";diff --git a/Sources/LiveSubs/AboutPanel.swift b/Sources/LiveSubs/AboutPanel.swiftnew file mode 100644index 0000000..321e4a2--- /dev/null+++ b/Sources/LiveSubs/AboutPanel.swift@@ -0,0 +1,37 @@+import AppKit++/// "关于知了": the standard About panel (icon, name, version and copyright come from Info.plist)+/// with a line about the app and links to the website, the project and its issues.+@MainActor+enum AboutPanel {+ static let website = URL(string: "https://cicada.indaloop.app/")!+ static let issues = UpdateChecker.repository.appendingPathComponent("issues/new")++ static func show() {+ NSApp.activate()+ NSApp.orderFrontStandardAboutPanel(options: [.credits: credits])+ }++ private static var credits: NSAttributedString {+ let centered = NSMutableParagraphStyle()+ centered.alignment = .center+ centered.paragraphSpacing = 6+ let plain: [NSAttributedString.Key: Any] = [+ .font: NSFont.systemFont(ofSize: 11), .foregroundColor: NSColor.labelColor, .paragraphStyle: centered,+ ]+ let text = NSMutableAttributedString(string: L("把 Mac 正在播放的声音变成实时双语字幕和会议纪要") + "\n", attributes: plain)+ let links = [(L("网站"), website), ("GitHub", UpdateChecker.repository), (L("反馈问题"), issues)]+ for (i, (title, url)) in links.enumerated() {+ if i > 0 { text.append(NSAttributedString(string: " · ", attributes: plain)) }+ var linked = plain+ linked[.link] = url+ text.append(NSAttributedString(string: title, attributes: linked))+ }+ if let dev = DevBuild.label {+ var secondary = plain+ secondary[.foregroundColor] = NSColor.secondaryLabelColor+ text.append(NSAttributedString(string: "\nDEV · \(dev)", attributes: secondary))+ }+ return text+ }+}diff --git a/Sources/LiveSubs/AppMenu.swift b/Sources/LiveSubs/AppMenu.swiftindex 306c19e..664e34d 100644--- a/Sources/LiveSubs/AppMenu.swift+++ b/Sources/LiveSubs/AppMenu.swift@@ -20,6 +20,7 @@ final class AppMenu: NSObject, NSMenuItemValidation {let app = NSMenu(title: name)app.addItem(item(L("关于 \(name)"), #selector(about)))+ app.addItem(item(L("检查更新…"), #selector(checkUpdates)))app.addItem(.separator())app.addItem(item(L("设置…"), #selector(openSettings), ","))app.addItem(item(L("AI 服务…"), #selector(openAI)))@@ -83,6 +84,9 @@ final class AppMenu: NSObject, NSMenuItemValidation {let help = NSMenu(title: L("帮助"))help.addItem(item(L("新手引导"), #selector(onboarding)))+ help.addItem(.separator())+ help.addItem(item(L("\(name) 网站"), #selector(openWebsite)))+ help.addItem(item(L("反馈问题…"), #selector(reportIssue)))add(help, to: main)NSApp.mainMenu = main@@ -135,6 +139,14 @@ final class AppMenu: NSObject, NSMenuItemValidation {return truecase #selector(search):return notesWindow.isVisible+ case #selector(checkUpdates):+ // Becomes the update itself once one is found; greyed while downloading.+ if let u = model.updates.update {+ item.title = L("安装 \(u.version) 并重新打开")+ return model.updates.progress == nil+ }+ item.title = L("检查更新…")+ return model.updates.check != .checkingdefault:return true}@@ -142,11 +154,42 @@ final class AppMenu: NSObject, NSMenuItemValidation {// MARK: Actions- @objc private func about() {- NSApp.activate()- NSApp.orderFrontStandardAboutPanel(nil)+ @objc private func about() { AboutPanel.show() }++ @objc private func checkUpdates() {+ guard let model else { return }+ if model.updates.update != nil { model.updates.install(model: model); return }+ Task {+ model.updates.checkNow()+ // A manual check from the menu answers in an alert: the panel isn't open to show it.+ while model.updates.check == .checking { try? await Task.sleep(for: .milliseconds(100)) }+ let alert = NSAlert()+ if let u = model.updates.update {+ alert.messageText = L("有新版本 \(u.version)")+ alert.informativeText = L("当前版本 \(Updates.current)。安装后会自动重新打开。")+ alert.addButton(withTitle: L("安装并重新打开"))+ alert.addButton(withTitle: L("更新说明"))+ alert.addButton(withTitle: L("稍后"))+ switch alert.runModal() {+ case .alertFirstButtonReturn: model.updates.install(model: model)+ case .alertSecondButtonReturn: NSWorkspace.shared.open(u.url)+ default: break+ }+ } else if model.updates.check == .upToDate {+ alert.messageText = L("已是最新版本")+ alert.informativeText = L("当前版本 \(Updates.current)。")+ alert.runModal()+ } else {+ alert.messageText = L("暂时无法检查更新")+ alert.informativeText = L("连不上 GitHub,请稍后再试。")+ alert.runModal()+ }+ }}+ @objc private func openWebsite() { NSWorkspace.shared.open(AboutPanel.website) }+ @objc private func reportIssue() { NSWorkspace.shared.open(AboutPanel.issues) }+@objc private func openSettings() { model?.openSettings() }@objc private func openAI() { model?.openSettings(.ai) }@objc private func openRecords() { showMainWindow() }diff --git a/Sources/LiveSubs/AppModel.swift b/Sources/LiveSubs/AppModel.swiftindex f69605e..6aa0e54 100644--- a/Sources/LiveSubs/AppModel.swift+++ b/Sources/LiveSubs/AppModel.swift@@ -43,6 +43,8 @@ final class AppModel: ObservableObject {let ling = LingClient()lazy var translator = TranslationService(ling: ling)let diagnostics = Diagnostics()+ let updates = Updates()+ let loginItem = LoginItem()lazy var notes = NotesEngine(ling: ling, store: store)lazy var notesWindow = NotesWindowController(model: self)let sample = SamplePlayer()@@ -722,6 +724,18 @@ final class AppModel: ObservableObject {let kv = arg.split(separator: "=", maxSplits: 1).map(String.init)if kv.count == 2 { previewVoice(kv[1], language: kv[0]) }case "notesNow": notes.updateNow()+ case "updateFeed":+ // updateFeed:<release json url>: check a fake release (file:// works), even in a dev build.+ if let url = URL(string: arg) { updates.checker.feed = url }+ updates.checkNow()+ case "updateCheck": updates.checkNow()+ case "updateInstall": updates.install(model: self)+ case "updateState": debugLog("update current=\(Updates.current) found=\(updates.update?.version ?? "-") check=\(updates.check) progress=\(updates.progress.map { String($0) } ?? "-") failure=\(updates.failure ?? "-")")+ case "loginItem":+ if !arg.isEmpty { loginItem.set(arg == "on") }+ loginItem.refresh()+ debugLog("login item enabled=\(loginItem.enabled) needsApproval=\(loginItem.needsApproval)")+ case "about": AboutPanel.show()case "display": setDisplayMode(arg)case "notesWindow":let v = arg.split(separator: ",").compactMap { Double($0) }@@ -852,8 +866,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {model.openSettingsWindow = { [weak self] in self?.showSettingsWindow() }model.showPanel = { [weak self] in self?.togglePopover() }model.openOnboarding = { [weak self] in self?.showOnboarding() }- runningObserver = model.$running.sink { [weak self] live in- self?.statusItem.button?.image = BrandImage.menuBar(live: live)+ runningObserver = model.$running.combineLatest(model.updates.$update).sink { [weak self] live, update in+ self?.statusItem.button?.image = BrandImage.menuBar(live: live, badge: update != nil)}let poll = Timer(timeInterval: 1.0, repeats: true) { [weak self] _ inMainActor.assumeIsolated { self?.model.refreshPermissions() }@@ -871,6 +885,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {model.installDebugControl()installDeviceListener()Task { await model.launch() }+ model.updates.start()}/// Started by the system at login: stay in the menu bar.@@ -893,7 +908,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {/// Quitting ends the meeting being recorded: ask first.func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {- guard model.running, let id = model.store.liveID, !(model.store.session(id)?.lines.isEmpty ?? true) else { return .terminateNow }+ guard !model.updates.installing, model.running, let id = model.store.liveID, !(model.store.session(id)?.lines.isEmpty ?? true) else { return .terminateNow }NSApp.activate()let alert = NSAlert()alert.messageText = L("正在记录会议")diff --git a/Sources/LiveSubs/LanguageDetector.swift b/Sources/LiveSubs/LanguageDetector.swiftindex e670beb..db880cc 100644--- a/Sources/LiveSubs/LanguageDetector.swift+++ b/Sources/LiveSubs/LanguageDetector.swift@@ -71,7 +71,7 @@ enum LanguageDetector {}}- private static func score(conf: Double, chars: Int, text: String, lang: Lang) -> Double {+ static func score(conf: Double, chars: Int, text: String, lang: Lang) -> Double {guard chars > 0 else { return 0 }// Very short output means the model mostly heard noise.let lengthFactor = min(1.0, Double(chars) / 6.0)diff --git a/Sources/LiveSubs/LoginItem.swift b/Sources/LiveSubs/LoginItem.swiftnew file mode 100644index 0000000..50c7ed4--- /dev/null+++ b/Sources/LiveSubs/LoginItem.swift@@ -0,0 +1,32 @@+import ServiceManagement++/// "登录时打开": the app as a login item (`SMAppService.mainApp`). Started that way it stays in+/// the menu bar (`AppDelegate.launchedAsLoginItem`). The state lives with the system, not in+/// UserDefaults, so it is read again whenever settings show it.+@MainActor+final class LoginItem: ObservableObject {+ @Published private(set) var enabled = false+ /// Turned on, but the user switched it off in System Settings › General › Login Items.+ @Published private(set) var needsApproval = false+ @Published private(set) var error: String?++ init() { refresh() }++ func refresh() {+ let status = SMAppService.mainApp.status+ enabled = status == .enabled+ needsApproval = status == .requiresApproval+ }++ func set(_ on: Bool) {+ error = nil+ do {+ if on { try SMAppService.mainApp.register() } else { try SMAppService.mainApp.unregister() }+ } catch {+ self.error = error.localizedDescription+ debugLog("login item \(on ? "register" : "unregister") failed: \(error.localizedDescription)")+ }+ refresh()+ if on && needsApproval { SMAppService.openSystemSettingsLoginItems() }+ }+}diff --git a/Sources/LiveSubs/Onboarding.swift b/Sources/LiveSubs/Onboarding.swiftindex ca8bfd4..ebf52fd 100644--- a/Sources/LiveSubs/Onboarding.swift+++ b/Sources/LiveSubs/Onboarding.swift@@ -132,7 +132,7 @@ enum BrandImage {}()/// Menu bar template glyph: the logo in one colour. Paused draws it at 40%.- static func menuBar(live: Bool) -> NSImage {+ static func menuBar(live: Bool, badge: Bool = false) -> NSImage {let img = NSImage(size: NSSize(width: 18, height: 16), flipped: true) { _ inguard let c = NSGraphicsContext.current?.cgContext else { return false }// Design units 8…92 across and 16…94 down fill the 16 pt height.@@ -142,7 +142,22 @@ enum BrandImage {}img.isTemplate = trueimg.accessibilityDescription = appDisplayName- return img+ return badge ? withBadge(img) : img+ }++ /// The glyph with an orange dot top right, while an update is available. A coloured dot+ /// can't be part of a template image, so the glyph is filled with the label colour instead.+ private static func withBadge(_ glyph: NSImage) -> NSImage {+ let image = NSImage(size: glyph.size, flipped: false) { rect in+ glyph.draw(in: rect, from: .zero, operation: .sourceOver, fraction: 1)+ NSColor.labelColor.setFill()+ rect.fill(using: .sourceIn)+ NSColor(red: 0xE8 / 255, green: 0x55 / 255, blue: 0x2B / 255, alpha: 1).setFill()+ NSBezierPath(ovalIn: NSRect(x: rect.maxX - 6, y: rect.maxY - 6, width: 5.5, height: 5.5)).fill()+ return true+ }+ image.accessibilityDescription = L("\(appDisplayName)(有新版本)")+ return image}}diff --git a/Sources/LiveSubs/SettingsWindow.swift b/Sources/LiveSubs/SettingsWindow.swiftindex c36e164..c2e2679 100644--- a/Sources/LiveSubs/SettingsWindow.swift+++ b/Sources/LiveSubs/SettingsWindow.swift@@ -10,7 +10,7 @@ enum SettingsSection: String, CaseIterable, Identifiable {case .overlay: L("显示")case .language: L("语言")case .speak: L("同声传译")- case .records: L("会议记录")+ case .records: L("通用")case .ai: L("AI 服务")case .diagnostics: L("诊断")}@@ -20,7 +20,7 @@ enum SettingsSection: String, CaseIterable, Identifiable {case .overlay: "captions.bubble"case .language: "globe"case .speak: "mic"- case .records: "doc.text"+ case .records: "gearshape"case .ai: "key"case .diagnostics: "waveform.path.ecg"}@@ -526,17 +526,17 @@ struct SettingsView: View {}private var records: some View {- SettingsCard {- SettingsRow(title: L("保存会议录音"), detail: L("只存在这台 Mac 上")) {- Toggle("保存会议录音", isOn: $settings.recordAudio)- .toggleStyle(.switch).labelsHidden().controlSize(.small).tint(Palette.ink)- }- SettingsRow(title: L("记录文件夹")) {- SoftButton(L("打开")) { NSWorkspace.shared.open(model.store.root) }- }- SettingsRow(title: L("首次引导"), divider: false) {- SoftButton(L("重新看")) { model.onboardingStep = 1; model.openOnboarding?() }+ VStack(alignment: .leading, spacing: 14) {+ SettingsCard {+ SettingsRow(title: L("保存会议录音"), detail: L("只存在这台 Mac 上")) {+ Toggle("保存会议录音", isOn: $settings.recordAudio)+ .toggleStyle(.switch).labelsHidden().controlSize(.small).tint(Palette.ink)+ }+ SettingsRow(title: L("记录文件夹"), divider: false) {+ SoftButton(L("打开")) { NSWorkspace.shared.open(model.store.root) }+ }}+ AppRows(updates: model.updates, loginItem: model.loginItem, model: model)}}}diff --git a/Sources/LiveSubs/UpdateChecker.swift b/Sources/LiveSubs/UpdateChecker.swiftnew file mode 100644index 0000000..313a0d9--- /dev/null+++ b/Sources/LiveSubs/UpdateChecker.swift@@ -0,0 +1,81 @@+import Foundation++/// Checks GitHub Releases once a day for a version newer than the running one.+/// Failures (offline, rate-limited, or the repository not public: the API answers 404) are silent.+@MainActor+final class UpdateChecker {+ struct Update: Equatable {+ let version: String+ /// The release page, the fallback when the update can't be installed in place.+ let url: URL+ /// The app zip and its checksums, when the release has them.+ let zip: URL?+ let checksums: URL?+ /// The zip's size in bytes, 0 when unknown.+ let size: Int+ }++ static let repository = URL(string: "https://github.com/wquguru/cicada")!++ /// `CICADA_UPDATE_FEED` (or the `updateFeed:` debug command) points at another release JSON;+ /// a file:// URL works, for testing.+ var feed = ProcessInfo.processInfo.environment["CICADA_UPDATE_FEED"].flatMap(URL.init(string:))+ ?? URL(string: "https://api.github.com/repos/wquguru/cicada/releases/latest")!+ private let onUpdate: (Update?) -> Void+ private var timer: Timer?++ init(onUpdate: @escaping (Update?) -> Void) {+ self.onUpdate = onUpdate+ }++ func start() {+ Task { await check() }+ timer = Timer.scheduledTimer(withTimeInterval: 24 * 60 * 60, repeats: true) { [weak self] _ in+ Task { await self?.check() }+ }+ }++ /// Returns false when the feed couldn't be reached or answered with something unexpected.+ @discardableResult+ func check() async -> Bool {+ var request = URLRequest(url: feed)+ request.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept")+ guard let (data, response) = try? await URLSession.shared.data(for: request),+ (response as? HTTPURLResponse)?.statusCode ?? 200 == 200,+ let release = try? JSONDecoder().decode(Release.self, from: data),+ let url = URL(string: release.html_url) else { return false }+ let latest = release.tag_name.trimmingCharacters(in: CharacterSet(charactersIn: "v"))+ let current = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0"+ let zip = release.assets.first { $0.name.hasPrefix("Cicada-") && $0.name.hasSuffix("-macOS-AppleSilicon.zip") }+ let checksums = release.assets.first { $0.name == "checksums.txt" }+ let update = Update(version: latest, url: url,+ zip: zip.flatMap { URL(string: $0.browser_download_url) },+ checksums: checksums.flatMap { URL(string: $0.browser_download_url) },+ size: zip?.size ?? 0)+ onUpdate(Self.isNewer(latest, than: current) ? update : nil)+ return true+ }++ /// Compares dotted numeric versions: "2.10.0" is newer than "2.9.1".+ nonisolated static func isNewer(_ a: String, than b: String) -> Bool {+ let x = a.split(separator: ".").map { Int($0) ?? 0 }+ let y = b.split(separator: ".").map { Int($0) ?? 0 }+ for i in 0..<max(x.count, y.count) {+ let l = i < x.count ? x[i] : 0, r = i < y.count ? y[i] : 0+ if l != r { return l > r }+ }+ return false+ }++ private struct Release: Decodable {+ let tag_name: String+ let html_url: String+ let assets: [Asset]+ }++ private struct Asset: Decodable {+ let name: String+ let browser_download_url: String+ let size: Int?+ }+}diff --git a/Sources/LiveSubs/UpdateViews.swift b/Sources/LiveSubs/UpdateViews.swiftnew file mode 100644index 0000000..c97e6de--- /dev/null+++ b/Sources/LiveSubs/UpdateViews.swift@@ -0,0 +1,88 @@+import SwiftUI++/// The panel's update strip, shown only while there is a newer release: install it, watch it+/// download, or read why installing in place failed (the release page was opened instead).+struct UpdateBanner: View {+ @ObservedObject var updates: Updates+ let model: AppModel++ var body: some View {+ if let update = updates.update {+ VStack(alignment: .leading, spacing: 6) {+ HStack(spacing: 8) {+ Circle().fill(Palette.accent).frame(width: 7, height: 7)+ VStack(alignment: .leading, spacing: 2) {+ Text("新版本 \(update.version)").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)+ Text(detail(update)).font(.system(size: 11)).foregroundStyle(Palette.secondary)+ .fixedSize(horizontal: false, vertical: true)+ }+ Spacer()+ if updates.progress == nil {+ SoftButton(updates.failure == nil ? L("安装") : L("重试")) { updates.install(model: model) }+ }+ }+ if let p = updates.progress {+ ProgressView(value: p).controlSize(.small).tint(Palette.accent).accessibilityLabel(L("下载进度"))+ }+ }+ .padding(10).frame(maxWidth: .infinity, alignment: .leading)+ .background(RoundedRectangle(cornerRadius: 9).fill(Palette.accentPale))+ .contextMenu { Button("更新说明") { NSWorkspace.shared.open(update.url) } }+ }+ }++ private func detail(_ update: UpdateChecker.Update) -> String {+ if let p = updates.progress { return L("正在下载 \(Int(p * 100))%,完成后自动重新打开") }+ if let f = updates.failure { return L("没能自动更新:\(f)。已打开下载页") }+ let size = update.size > 0 ? ByteCountFormatter.string(fromByteCount: Int64(update.size), countStyle: .file) + " · " : ""+ return size + L("安装后自动重新打开")+ }+}++/// Settings › 会议记录, the app-wide rows: open at login and the version with a check button.+struct AppRows: View {+ @ObservedObject var updates: Updates+ @ObservedObject var loginItem: LoginItem+ let model: AppModel++ var body: some View {+ SettingsCard {+ SettingsRow(title: L("登录时打开"), detail: loginDetail) {+ Toggle("登录时打开", isOn: Binding(get: { loginItem.enabled }, set: { loginItem.set($0) }))+ .toggleStyle(.switch).labelsHidden().controlSize(.small).tint(Palette.ink)+ }+ SettingsRow(title: L("版本 \(Updates.current)"), detail: checkDetail) {+ if updates.update != nil {+ SoftButton(L("安装并重新打开"), dark: true) { updates.install(model: model) }+ .disabled(updates.progress != nil)+ } else {+ SoftButton(L("检查更新")) { updates.checkNow() }.disabled(updates.check == .checking)+ }+ }+ SettingsRow(title: L("首次引导"), divider: false) {+ SoftButton(L("重新看")) { model.onboardingStep = 1; model.openOnboarding?() }+ }+ }+ .onAppear { loginItem.refresh() }+ }++ private var loginDetail: String {+ if let e = loginItem.error { return e }+ if loginItem.needsApproval { return L("请在“系统设置 › 通用 › 登录项”中允许") }+ return L("开机后在菜单栏待命,不弹窗口")+ }++ private var checkDetail: String? {+ if let u = updates.update {+ if let p = updates.progress { return L("正在下载 \(u.version):\(Int(p * 100))%") }+ if let f = updates.failure { return L("没能自动更新:\(f)") }+ return L("有新版本 \(u.version)")+ }+ switch updates.check {+ case .checking: return L("正在检查…")+ case .upToDate: return L("已是最新版本")+ case .failed: return L("连不上 GitHub,请稍后再试")+ case .idle: return nil+ }+ }+}diff --git a/Sources/LiveSubs/Updater.swift b/Sources/LiveSubs/Updater.swiftnew file mode 100644index 0000000..bfa23f9--- /dev/null+++ b/Sources/LiveSubs/Updater.swift@@ -0,0 +1,125 @@+import AppKit+import CryptoKit++/// Installs an update in place: downloads the release zip, checks it against checksums.txt,+/// unpacks it, then hands off to a small shell script that swaps the app bundle once the app+/// has quit and relaunches it. URLSession downloads carry no quarantine, so the new (ad-hoc+/// signed) app opens without a Gatekeeper prompt; its designated requirement is the bundle id,+/// so the system-audio and microphone permissions carry over.+@MainActor+enum Updater {+ struct Failure: LocalizedError {+ let errorDescription: String?+ init(_ message: String) { errorDescription = message }+ }++ /// Reports download progress (0...1) on the way; returns only if installing failed.+ /// The caller has already ended the meeting: quitting must not stop to ask.+ static func install(_ update: UpdateChecker.Update, progress: @escaping (Double) -> Void) async throws {+ guard let zipURL = update.zip, let checksumsURL = update.checksums else {+ throw Failure(L("这个版本没有可安装的文件"))+ }+ let app = Bundle.main.bundleURL+ let folder = app.deletingLastPathComponent()+ guard !app.path.contains("/AppTranslocation/"), !app.path.hasPrefix("/Volumes/"),+ FileManager.default.isWritableFile(atPath: folder.path) else {+ throw Failure(L("请先把应用拖进“应用程序”文件夹"))+ }++ let work = FileManager.default.temporaryDirectory.appendingPathComponent("CicadaUpdate-\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)+ do {+ let zip = work.appendingPathComponent(zipURL.lastPathComponent)+ try await download(zipURL, to: zip, progress: progress)+ let (checksums, _) = try await URLSession.shared.data(from: checksumsURL)+ guard let expected = expectedHash(of: zip.lastPathComponent, in: checksums),+ try await sha256(of: zip) == expected else {+ throw Failure(L("下载的文件校验不通过"))+ }++ let unpacked = work.appendingPathComponent("unpacked")+ try await run("/usr/bin/ditto", "-x", "-k", zip.path, unpacked.path)+ let newApp = unpacked.appendingPathComponent("Cicada.app")+ let info = Bundle(url: newApp)?.infoDictionary+ guard info?["CFBundleIdentifier"] as? String == Bundle.main.bundleIdentifier,+ info?["CFBundleShortVersionString"] as? String == update.version else {+ throw Failure(L("下载的不是预期的版本"))+ }+ try await run("/usr/bin/codesign", "--verify", "--deep", "--strict", newApp.path)++ let script = work.appendingPathComponent("swap.sh")+ try swapScript.write(to: script, atomically: true, encoding: .utf8)+ let swap = Process()+ swap.executableURL = URL(fileURLWithPath: "/bin/sh")+ swap.arguments = [script.path, String(getpid()), app.path, newApp.path, work.path]+ try swap.run()+ } catch {+ try? FileManager.default.removeItem(at: work)+ throw error+ }+ NSApp.terminate(nil)+ }++ /// Waits for the app to quit, moves the old bundle aside (restoring it if the new one can't be+ /// moved in), relaunches, and cleans up. Arguments: pid, app path, new app path, work folder.+ private static let swapScript = """+ while kill -0 "$1" 2>/dev/null; do sleep 0.2; done+ if mv "$2" "$4/old.app"; then+ if mv "$3" "$2"; then rm -rf "$4/old.app"; else mv "$4/old.app" "$2"; fi+ fi+ open "$2"+ rm -rf "$4"+ """++ /// The hash listed for `name` in a `shasum -a 256` file.+ nonisolated static func expectedHash(of name: String, in checksums: Data) -> String? {+ String(decoding: checksums, as: UTF8.self)+ .split(separator: "\n")+ .map { $0.split(separator: " ", omittingEmptySubsequences: true) }+ .first { $0.count == 2 && $0[1].trimmingCharacters(in: CharacterSet(charactersIn: "*")) == name }+ .map { $0[0].lowercased() }+ }++ private static func download(_ url: URL, to destination: URL, progress: @escaping (Double) -> Void) async throws {+ var observation: NSKeyValueObservation?+ defer { observation?.invalidate() }+ try await withCheckedThrowingContinuation { (done: CheckedContinuation<Void, Error>) in+ let task = URLSession.shared.downloadTask(with: url) { file, response, error in+ if let status = (response as? HTTPURLResponse)?.statusCode, status != 200 {+ return done.resume(throwing: Failure(L("下载失败(HTTP \(status))")))+ }+ guard let file else { return done.resume(throwing: error ?? Failure(L("下载失败"))) }+ // The temporary file is deleted when this handler returns, so move it now.+ do { try FileManager.default.moveItem(at: file, to: destination); done.resume() }+ catch { done.resume(throwing: error) }+ }+ observation = task.progress.observe(\.fractionCompleted) { p, _ in+ let fraction = p.fractionCompleted+ Task { @MainActor in progress(fraction) }+ }+ task.resume()+ }+ }++ private static func sha256(of file: URL) async throws -> String {+ try await Task.detached {+ let handle = try FileHandle(forReadingFrom: file)+ defer { try? handle.close() }+ var hasher = SHA256()+ while let chunk = try handle.read(upToCount: 1 << 20), !chunk.isEmpty { hasher.update(data: chunk) }+ return hasher.finalize().map { String(format: "%02x", $0) }.joined()+ }.value+ }++ private static func run(_ tool: String, _ arguments: String...) async throws {+ let process = Process()+ process.executableURL = URL(fileURLWithPath: tool)+ process.arguments = arguments+ try await withCheckedThrowingContinuation { (done: CheckedContinuation<Void, Error>) in+ process.terminationHandler = { p in+ p.terminationStatus == 0 ? done.resume() : done.resume(throwing: Failure(L("更新包无效")))+ }+ do { try process.run() } catch { done.resume(throwing: error) }+ }+ }+}diff --git a/Sources/LiveSubs/Updates.swift b/Sources/LiveSubs/Updates.swiftnew file mode 100644index 0000000..901f85b--- /dev/null+++ b/Sources/LiveSubs/Updates.swift@@ -0,0 +1,70 @@+import AppKit++/// What the panel, the app menu and settings show about updates: a newer release, a manual+/// check's result, download progress, and why installing in place failed.+@MainActor+final class Updates: ObservableObject {+ enum Check { case idle, checking, upToDate, failed }++ @Published private(set) var update: UpdateChecker.Update?+ @Published private(set) var check = Check.idle+ /// Download progress (0...1) while an update installs; the app quits and reopens when done.+ @Published private(set) var progress: Double?+ /// Why the last in-place update failed (the release page was opened instead).+ @Published var failure: String?+ /// Set once installing has started: quitting then must not stop to ask about the meeting,+ /// or the swap script would wait for a quit that the user cancelled.+ private(set) var installing = false++ private(set) lazy var checker = UpdateChecker { [weak self] in self?.update = $0 }++ static let current = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? ""++ /// Daily checks. A dev build has its own bundle id, so a release can't replace it: it checks+ /// only when pointed at a test feed.+ func start() {+ guard !DevBuild.isDev || ProcessInfo.processInfo.environment["CICADA_UPDATE_FEED"] != nil else { return }+ checker.start()+ }++ func checkNow() {+ guard check != .checking else { return }+ check = .checking+ Task {+ let reached = await checker.check()+ check = update != nil ? .idle : reached ? .upToDate : .failed+ try? await Task.sleep(for: .seconds(4))+ if check != .checking { check = .idle }+ }+ }++ /// Installs in place; a meeting being recorded is ended first, after asking.+ /// If installing can't be done, says why and opens the release page.+ func install(model: AppModel) {+ guard let update, progress == nil else { return }+ if model.running, let id = model.store.liveID, !(model.store.session(id)?.lines.isEmpty ?? true) {+ NSApp.activate()+ let alert = NSAlert()+ alert.messageText = L("正在记录会议")+ alert.informativeText = L("安装更新会结束这场记录,已记下的内容会保存。")+ alert.addButton(withTitle: L("结束并更新"))+ alert.addButton(withTitle: L("取消"))+ guard alert.runModal() == .alertFirstButtonReturn else { return }+ model.stop()+ }+ progress = 0+ failure = nil+ installing = true+ Task {+ do {+ try await Updater.install(update) { [weak self] in self?.progress = $0 }+ } catch {+ debugLog("update install failed: \(error.localizedDescription)")+ installing = false+ progress = nil+ failure = error.localizedDescription+ NSWorkspace.shared.open(update.url)+ }+ }+ }+}diff --git a/Sources/LiveSubs/Views.swift b/Sources/LiveSubs/Views.swiftindex 3917ea1..9893af9 100644--- a/Sources/LiveSubs/Views.swift+++ b/Sources/LiveSubs/Views.swift@@ -233,6 +233,8 @@ struct MenuPanelView: View {.font(.system(size: 12))}+ UpdateBanner(updates: model.updates, model: model)+Divider()HStack {diff --git a/Tests/LiveSubsTests/ExportTests.swift b/Tests/LiveSubsTests/ExportTests.swiftnew file mode 100644index 0000000..8e610f9--- /dev/null+++ b/Tests/LiveSubsTests/ExportTests.swift@@ -0,0 +1,44 @@+import Foundation+import Testing+@testable import LiveSubs++@Suite struct ExportTests {+ private func line(_ id: String, _ t: Double, _ speaker: String, _ src: String, _ dst: String?) -> TranscriptLine {+ TranscriptLine(id: id, t: t, speaker: speaker, src: src, dst: dst, srcLang: "en", dstLang: "zh-CN")+ }++ private var session: Session {+ Session(id: "s", title: "Weekly", startedAt: Date(timeIntervalSince1970: 0), endedAt: Date(timeIntervalSince1970: 600),+ lines: [line("1", 1.5, "them", "Hello.", "你好。"),+ line("2", 3.25, "me", "Same", "Same"),+ line("3", 20, "them", "Bye.", nil)],+ hasAudio: false, notes: nil, renamed: true)+ }++ @Test func clockFormats() {+ #expect(TranscriptExport.clock(0) == "00:00")+ #expect(TranscriptExport.clock(-5) == "00:00")+ #expect(TranscriptExport.clock(125.9) == "02:05")+ #expect(TranscriptExport.clock(3725) == "1:02:05")+ }++ @Test func srtTimesAndTranslations() {+ let srt = TranscriptExport.srt(session)+ let cues = srt.components(separatedBy: "\n\n").filter { !$0.isEmpty }+ #expect(cues.count == 3)+ // Ends at the next line, at least 1 s and at most 8 s after it starts.+ #expect(cues[0] == "1\n00:00:01,500 --> 00:00:03,250\nHello.\n你好。")+ // A translation identical to the source isn't repeated.+ #expect(cues[1] == "2\n00:00:03,250 --> 00:00:11,250\nSame")+ // The last line gets 4 s.+ #expect(cues[2] == "3\n00:00:20,000 --> 00:00:24,000\nBye.")+ }++ @Test func markdownHasTitleLinesAndQuotes() {+ let md = TranscriptExport.markdown(session)+ #expect(md.hasPrefix("# Weekly\n\n"))+ #expect(md.contains("**[00:01] 对方** \nHello.\n> 你好。\n"))+ #expect(md.contains("**[00:03] 你** \nSame\n\n"))+ #expect(!md.contains("> Same"))+ }+}diff --git a/Tests/LiveSubsTests/LanguageTests.swift b/Tests/LiveSubsTests/LanguageTests.swiftnew file mode 100644index 0000000..23b7a7c--- /dev/null+++ b/Tests/LiveSubsTests/LanguageTests.swift@@ -0,0 +1,39 @@+import Testing+@testable import LiveSubs++@Suite struct LanguageTests {+ @Test(arguments: [+ ("zh-Hans-CN", "zh-CN"), ("zh-Hans-CA", "zh-CN"), ("zh-Hant-TW", "zh-TW"),+ ("zh-TW", "zh-TW"), ("zh-HK", "zh-TW"), ("zh-CN", "zh-CN"),+ ("en-CA", "en"), ("ja-JP", "ja"), ("pt-BR", "pt"),+ ])+ func systemLanguageMapsToTranslationCode(id: String, code: String) {+ #expect(translationCode(forSystemLanguage: id) == code)+ }++ @Test func cjkJoinsWithoutSpaces() {+ #expect(joiner(for: "zh-CN") == "")+ #expect(joiner(for: "ja") == "")+ #expect(joiner(for: "en") == " ")+ }++ private let english = sourceLanguages.first { $0.code == "en" }!+ private let japanese = sourceLanguages.first { $0.code == "ja" }!++ @Test func detectionScoreFollowsConfidence() {+ let text = "hello there everyone"+ #expect(LanguageDetector.score(conf: 0.9, chars: text.count, text: text, lang: english) == 0.9)+ #expect(LanguageDetector.score(conf: 0.9, chars: 0, text: "", lang: english) == 0)+ }++ @Test func shortOutputCountsAsNoise() {+ #expect(LanguageDetector.score(conf: 0.9, chars: 3, text: "abc", lang: english) == 0.45)+ }++ @Test func cjkModelWritingLatinIsPenalised() {+ let latin = "hello there everyone"+ let native = "こんにちは皆さん"+ #expect(LanguageDetector.score(conf: 0.8, chars: latin.count, text: latin, lang: japanese) == 0.8 * 0.75)+ #expect(LanguageDetector.score(conf: 0.8, chars: native.count, text: native, lang: japanese) == 0.8)+ }+}diff --git a/Tests/LiveSubsTests/UpdateTests.swift b/Tests/LiveSubsTests/UpdateTests.swiftnew file mode 100644index 0000000..a5d4596--- /dev/null+++ b/Tests/LiveSubsTests/UpdateTests.swift@@ -0,0 +1,23 @@+import Foundation+import Testing+@testable import LiveSubs++@Suite struct UpdateTests {+ @Test func versionsCompareNumerically() {+ #expect(UpdateChecker.isNewer("2.10.0", than: "2.9.1"))+ #expect(UpdateChecker.isNewer("2.0.1", than: "2.0"))+ #expect(!UpdateChecker.isNewer("2.0", than: "2.0.0"))+ #expect(!UpdateChecker.isNewer("1.9.9", than: "2.0.0"))+ #expect(!UpdateChecker.isNewer("2.0.0", than: "2.0.0"))+ }++ @Test func checksumIsFoundByName() {+ let file = Data("""+ AAA111 Cicada-2.1.0-macOS-AppleSilicon.dmg+ BBB222 *Cicada-2.1.0-macOS-AppleSilicon.zip+ """.utf8)+ #expect(Updater.expectedHash(of: "Cicada-2.1.0-macOS-AppleSilicon.zip", in: file) == "bbb222")+ #expect(Updater.expectedHash(of: "Cicada-2.1.0-macOS-AppleSilicon.dmg", in: file) == "aaa111")+ #expect(Updater.expectedHash(of: "Cicada-2.0.0-macOS-AppleSilicon.zip", in: file) == nil)+ }+}diff --git a/scripts/test.sh b/scripts/test.shnew file mode 100755index 0000000..85b98f7--- /dev/null+++ b/scripts/test.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Runs the unit tests. With only the Command Line Tools, Swift Testing lives outside the default search paths.+set -euo pipefail+cd "$(dirname "$0")/.."+F=$(xcode-select -p)/Library/Developer/Frameworks+L=$(xcode-select -p)/Library/Developer/usr/lib+exec swift test -Xswiftc -F -Xswiftc "$F" -Xlinker -F -Xlinker "$F" -Xlinker -rpath -Xlinker "$F" -Xlinker -rpath -Xlinker "$L" "$@"diff --git a/site/changelog.json b/site/changelog.jsonindex c4d58fd..4c5243c 100644--- a/site/changelog.json+++ b/site/changelog.json@@ -6,6 +6,21 @@"summary": "这一版让知了从“实时字幕”变成完整的会议助手:边开会边写纪要,同声传译可以用更自然的声音说出去,虚拟麦克风装完能当场试音。","image": null,"items": [+ {+ "kind": "new",+ "title": "应用内更新。",+ "text": "知了每天检查一次新版本,有新版时菜单栏图标上出现一个橙点,面板里点「安装」即可:下载后按 SHA-256 校验、核对版本和签名,替换并自动重新打开,听电脑声音和麦克风的权限都不丢。正在记录的会议会先问你,再结束保存。装在 DMG 里或没有写入权限时,会说明原因并打开下载页。菜单「检查更新…」和设置 › 通用里也能手动检查。"+ },+ {+ "kind": "new",+ "title": "登录时打开。",+ "text": "设置 › 通用 里打开后,开机登录就在菜单栏待命,不弹窗口。"+ },+ {+ "kind": "new",+ "title": "关于窗口和帮助菜单。",+ "text": "关于窗口加上了官网、GitHub 和反馈问题的链接;帮助菜单里也能直接打开官网和反馈问题。"+ },{"kind": "new","title": "英文、日文、韩文界面。",