知了 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
docs: cut AGENTS.md from 27 KB to 4 KB and gate its size
wqugurua7683233ba5d
diff --git a/.githooks/pre-commit b/.githooks/pre-commitnew file mode 100755index 0000000..76b77d0--- /dev/null+++ b/.githooks/pre-commit@@ -0,0 +1,5 @@+#!/bin/bash+# Enabled with `git config core.hooksPath .githooks`.+if git diff --cached --name-only | grep -qx 'AGENTS.md'; then+ exec python3 "$(git rev-parse --show-toplevel)/scripts/check-agents.py"+fidiff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex be64615..09da952 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -11,6 +11,7 @@ jobs:runs-on: macos-26steps:- uses: actions/checkout@v4+ - run: python3 scripts/check-agents.py- run: swift build- run: scripts/package.sh- uses: actions/upload-artifact@v4diff --git a/AGENTS.md b/AGENTS.mdindex 69af9d1..753fb21 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,74 +1,53 @@# AGENTS.md-Cicada (知了, formerly Live Subs) is a macOS menu bar app that turns whatever the Mac is playing (streams, videos, meetings, voice rooms) into live translated subtitles, keeps every meeting as a bilingual transcript, and can translate what you say back into the room as speech.+Cicada (知了, formerly Live Subs): a macOS menu bar app that turns what the Mac plays into live translated subtitles and meeting notes, keeps each meeting as a bilingual record, and speaks what you say back into the room in their language.-## Scope (deliberately small)+## Scope-- 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.-- 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 (which shows it only until the device is loaded, then one line). We never bundle the GPL driver.-- Settings › 同声传译 is three steps in one card (virtual mic, talk key, "对方听到": the room language's voice as a chip opening the list, `AppModel.voicePickerOpen`), 声音输出到 under 高级, and a top line with the last measured press (`lastSpeakLatency`; else ~3 s for Ming's voices, ~1 s for the Mac's). **试一句** (`SpeakTester` in `SpeakTest.swift`, sheet `SpeakTestView`): one real press (the user's, or a sample sentence in their language synthesized by the Mac and fed in real time through `SpeakEngine.speakBuffers`) armed with a `SpeakProbe`, so it reports every stage and stays out of the meeting record and diagnostics. Meanwhile `LoopbackRecorder` records the virtual mic's input side. Scored (`SpeakScore`, pure, unit-tested): onset in 10 ms windows (the device is digital, silence is zeros) gives release → room hears; peak and clipping; the recording transcribed again in the room's language and compared word by word (CJK by character) with the translation sent; with a Ling key one JSON call scores the meaning 0–100, else the heard text is translated back for the user. Where it broke = the first stage with nothing out (mic peak < −50 dB, no text, no translation, no audio, silence on the virtual mic — then the output device is named). Measured on an M-series Mac: Ming interpret 1.4–2.8 s + Ming voice first audio 1.1–1.4 s + ~0.2 s ≈ 3–3.5 s; no Ling (on-device + Google + Mac voice) 0.4–0.5 s warm; cloned voice ≈ 5–5.7 s.-- 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 (关于 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.+- Surfaces: menu bar panel, live notes window (default) or subtitle bar while listening, main window (meeting records), settings, three-step onboarding. A request that fits none of them gets pushed back before any UI is added.+- Nothing the user does needs the Terminal.+- Listening: Core Audio process tap → on-device language detection and `SpeechAnalyzer` → translation. Speaking: hold right ⌥ or a shortcut → mic → Ming (with a Ling key) or on-device + translation → voice → BlackHole 2ch virtual mic.++## Hard rules++- The Ling key lives only in the 0600 `ling-api-key` file (`AIKey`): never UserDefaults, logs or exports.+- Every Ling call goes through `LingClient` (rate gate, priorities, `thinking: disabled`, content in the system message). Partial text is translated by Google, never Ling.+- Never speak untranslated text into the room. Never bundle the GPL BlackHole driver; download it and check its pinned SHA-256.+- The notes window is a non-activating panel with `sharingType = .none`: it must never take focus or show in screen captures.+- UI and engine state are `@MainActor`; audio callbacks hand buffers to `AudioRouter`'s queue.+- Don't change the release bundle id `com.wquguru.cicada` or the ad-hoc designated requirement: permissions are tied to them.+- No third-party dependencies, no `.xcodeproj`; Command Line Tools only.## Design-- Source of truth: the Design canvases in claude.ai (logo directions, onboarding, auto show/hide) and the app itself.-- Look: light grey ground `#F3F4F6`/`#F6F7F9`, white cards, ink `#15171C`, one accent orange `#E8552B` for "live" (dots, the speaking line, the icon). Text greys `#5A5F6B` / `#6B7080` (they pass 4.5:1 on white).-- Logo B (design: claude.ai/artifact/96R6Md276c3jAS4Mk4Ustn): a cicada's dark eyes and white wings peeking over a white subtitle card that leans 5° and bleeds off the bottom right, on an orange gradient squircle. The geometry (100-unit design space) is in three places kept in step: `CicadaLogo` in `Onboarding.swift` (the in-app `BrandMark` and the one-colour menu bar glyph `BrandImage.menuBar` with a whole card, 40% when paused), its copy in `Sources/LiveSubsIcon` (the app icon) and `site/icon.svg`. After changing it: `scripts/site-images.sh` (site `icon.png`, `og.png`) and `docs/icon.png` (the README's, the app icon's 256 px render).-- Copy is Chinese, short: one line of grey helper text at most. The UI also ships in English (`Localization.swift`): the Chinese source text is the key and `Resources/{en,ja,ko}.lproj/Localizable.strings` hold English, Japanese and Korean (English plurals in `en.lproj/Localizable.stringsdict`). SwiftUI literals (`Text`, `Button`, `.help` …) localize by themselves; every other UI string goes through `L("…")` (menus, alerts, status text, `String` parameters such as `SoftButton`/`SettingsRow`). Never `L()` prompts, `debugLog` lines or anything stored (session titles, speaker ids). Dates use `dateText(_, template)`. After changing UI text run `python3 scripts/strings.py` (lists keys missing in any language and values whose format specifiers differ from the key; `--write` adds them as TODO and regenerates the `zh-Hans` identity table, needed because the development region is English). English runs wider: check the panel, sidebars and segmented pickers in both languages.+- Ground `#F3F4F6`, white cards, ink `#15171C`, one accent `#E8552B` for "live", greys `#5A5F6B` / `#6B7080`. Design canvases on claude.ai and the app itself are the source of truth.+- Copy is Chinese and short, at most one grey helper line. Chinese text is the localization key; `Resources/{en,ja,ko}.lproj` translate it. SwiftUI literals localize themselves; other UI strings use `L("…")`; never `L()` prompts, logs or stored values. After changing UI text run `python3 scripts/strings.py` (`--write` adds TODOs), and check the English UI, which runs wider.+- The logo geometry is kept in step in `CicadaLogo` (`Onboarding.swift`), `Sources/LiveSubsIcon` and `site/icon.svg`; then rerun `scripts/site-images.sh`.## 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), `AboutPanel`, `UpdateViews` (panel strip, 通用 rows), `AppModel` (wiring, status item, windows, activation policy, debug control, `@main`). `SpeakTest` + `SpeakTestView` (试一句), `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.-- `scripts/package.sh`: `RELEASE=1` build (refuses any other bundle id) → `Cicada-<version>-macOS-AppleSilicon.dmg` / `.zip` + `checksums.txt`. The DMG background is drawn by the app (`LiveSubs --render-dmg-background out.png <scale>`); the window layout is `Resources/dmg/DS_Store`, made by Finder via `scripts/dmg-template.sh` — rerun it after changing the window, icon positions or background, and keep `DMGBackground.swift` in step.-- `site/`: the website (GitHub Pages, Chinese first): `index.html` and `changelog.html` are templates sharing `header.html` / `footer.html` and `style.css`; `changelog.json` is the Chinese changelog the site shows (newest first, `"date": null` = not released yet; keep it in step with `CHANGELOG.md`). `scripts/site.py` builds `build/site/` (pages, `feed.xml`, `sitemap.xml`, `robots.txt`; `SITE_URL` sets the address); `.github/workflows/pages.yml` deploys it (skipped while the repo is private). `og.png` and `icon.png` are rendered by `scripts/site-images.sh` (Chrome) from `scripts/site-og.html` and `site/icon.svg`, and committed. Phones get no download: a "发到我的 Mac" button shares or copies the link.-- `tools/`: test helpers (remote control, synthetic mouse/keys, window capture, transcription check); see `tools/README.md`.+- `Sources/LiveSubs`: the app, one concern per file. Engines are UI-free (`ListenEngine`, `SpeakEngine`, `SpeakTest`, `Notes`, `Translator`, `Ling`, `VirtualMic`, `SessionStore`, `Updates`…); `AppModel` wires them and holds the debug commands. Settings keys: `AppSettings` in `Settings.swift`.+- `Sources/LiveSubsIcon`: renders the icon set. `site/`: the website, built by `scripts/site.py`. `tools/`: test helpers. `Tests/LiveSubsTests`: unit tests for the pure parts.## Commands```bash-swift 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/-scripts/make-sample.sh # regenerate the onboarding sample clip-python3 scripts/site.py && python3 -m http.server -d build/site # website preview+scripts/test.sh # AGENTS.md check + unit tests+scripts/build.sh && open build/Cicada.app # dev build: own bundle id, settings, log+RELEASE=1 scripts/build.sh # release build+scripts/package.sh # DMG + zip + checksums+scripts/release.sh <x.y.z> # needs a dated CHANGELOG section; CI publishes the tag```-Diagnostics (`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` (with `CICADA_DEBUG_CHANNEL=x` set both for `open -n --env CICADA_DEBUG_CHANNEL=x build/Cicada.app` and for `lsctl`, that copy alone listens and logs to `/tmp/livesubs-dev-debug-x.log`, so two dev builds can run side by side; `start`, `stop`, `open`, `panel`, `onboarding:<step>`, `samplePlay`, `speakFile:<audio>` (fed in real time), `speakTest:<sample|voice>` (opens settings and the 试一句 sheet and runs it; result in the log as `speak test:`), `speakTestBegin` / `speakTestEnd` (the hold button in voice mode), `speakTestState`, `speakTestRender:<png>`, `speakTestClose`, `speakOutput:<part of a device name>` (empty = virtual mic), `voicePicker:<on|off>`, `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.--Only Command Line Tools are required (no Xcode project). Do not add an `.xcodeproj`.--## Verifying changes--Run 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.+## Verifying-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`.+- Run the app and check the behaviour, not just the build; check the English UI too.+- Drive the dev build with `tools/lsctl` (commands and testing tips in `tools/README.md`; the source of truth is `AppModel.debugCommand`). Use `afplay Resources/sample/sample.m4a` or `say -o` clips as input and read `/tmp/livesubs-dev-debug.log`.+- A real voice, the BlackHole install, Input Monitoring and a Mac without permissions need a person.## Conventions-- 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`, `subtitles` (both/translation/original: "original" translates nothing), `notesLanguage` (mine = `AppSettings.myLanguage`, source = the meeting's most heard language), `aiModel`, `speakVoices`, `notesOnTop`, `diagnostics`, `settingsSection`, `lastSpeakLatency`) 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. Messages are English only (UI terms by their English UI names, never the Chinese ones) and follow Conventional Commits: `feat:`, `fix:`, `docs:`, `build:`, `refactor:`, `test:`, `chore:`, then a short lowercase imperative subject.+- Match the existing naming and comment density; comments say why.+- Every user-visible change gets a `CHANGELOG.md` line and a matching `site/changelog.json` item; keep `README.md` and `README.zh-CN.md` in step.+- Commit messages are English only and follow Conventional Commits (`feat:`, `fix:`, `docs:`, `build:`, `refactor:`, `test:`, `chore:`).+- This file stays under 6 KB with these sections; `scripts/check-agents.py` enforces it in `scripts/test.sh`, CI and the pre-commit hook. Implementation detail belongs in code comments, not here.diff --git a/scripts/check-agents.py b/scripts/check-agents.pynew file mode 100755index 0000000..572e7ce--- /dev/null+++ b/scripts/check-agents.py@@ -0,0 +1,27 @@+#!/usr/bin/env python3+"""Keeps AGENTS.md (read by every agent session) small and in shape. Run by scripts/test.sh,+CI and the pre-commit hook. Budgets sit below where the file had grown to (27 KB), on purpose."""+import re, sys+from pathlib import Path++MAX_BYTES = 6 * 1024+MAX_LINE = 400 # long lines are how it grew last time while the line count stood still+SECTIONS = ["Scope", "Hard rules", "Design", "Layout", "Commands", "Verifying", "Conventions"]++path = Path(__file__).resolve().parent.parent / "AGENTS.md"+text = path.read_text(encoding="utf-8")+errors = []+size = len(text.encode("utf-8"))+if size > MAX_BYTES:+ errors.append(f"{size} bytes, budget {MAX_BYTES}: move detail to code comments or tools/README.md")+for n, line in enumerate(text.splitlines(), 1):+ if len(line) > MAX_LINE:+ errors.append(f"line {n} is {len(line)} chars (max {MAX_LINE})")+found = re.findall(r"^## (.+)$", text, re.M)+if found != SECTIONS:+ errors.append(f"sections {found}, expected {SECTIONS} in that order")+if "```" not in text:+ errors.append("no fenced block: keep the commands block (prevents flat-list regression)")+for e in errors:+ print(f"AGENTS.md: {e}", file=sys.stderr)+sys.exit(1 if errors else 0)diff --git a/scripts/test.sh b/scripts/test.shindex 85b98f7..a793b1d 100755--- a/scripts/test.sh+++ b/scripts/test.sh@@ -2,6 +2,7 @@# Runs the unit tests. With only the Command Line Tools, Swift Testing lives outside the default search paths.set -euo pipefailcd "$(dirname "$0")/.."+python3 scripts/check-agents.pyF=$(xcode-select -p)/Library/Developer/FrameworksL=$(xcode-select -p)/Library/Developer/usr/libexec swift test -Xswiftc -F -Xswiftc "$F" -Xlinker -F -Xlinker "$F" -Xlinker -rpath -Xlinker "$F" -Xlinker -rpath -Xlinker "$L" "$@"diff --git a/tools/README.md b/tools/README.mdindex a551438..a7f2344 100644--- a/tools/README.md+++ b/tools/README.md@@ -15,6 +15,23 @@- 试一句:`speakTest:sample`(Mac 读一句示例)或 `speakTest:voice`(再发 `speakTestBegin` / `speakTestEnd` 当作按住、松开),结果以 `speak test:` 写进日志;`speakTestState`、`speakTestRender:<png>`、`speakTestClose`- 多开:两边都设 `CICADA_DEBUG_CHANNEL=x`(`open -n --env CICADA_DEBUG_CHANNEL=x build/Cicada.app`),命令只发给这一份,日志在 `/tmp/livesubs-dev-debug-x.log`- 导出:`export:<目录>`+ - 新手引导与窗口:`onboarding:<步骤>`、`samplePlay`、`closeWindow:<main|settings|onboarding>`、`settings:<overlay|language|speak|records|ai|diagnostics>`、`about`+ - 显示与字幕:`display:<notes|bar|none>`、`subtitles:<both|translation|original>`、`meetingSubtitles:<…>`、`overlayState`、`overlayToggle`、`overlayAuto[:off]`、`hideAfter:<秒>`+ - 纪要:`notesLang:<mine|source>`、`meetingNotesLang:<…>`、`notesRegenerate:<id>=<mine|source>`、`notesWindow[:x,y,w,h]`、`notesClose`、`notesFrame`、`notesNow`、`notesState`、`notesShow:<id>`、`notesReplay:<id>`、`notesCapturable[:off]`+ - 渲染(不需要录屏权限):`windowsRender:<目录>`、`settingsRender:<栏目>=<png>`、`notesRender:<png>`、`mainShow:<id>[,transcript]`、`mainRender:<png>`、`speakTestRender:<png>`+ - AI:`aiKeyFile:<路径>`(从 0600 文件读 key,不经过日志;测完就删掉文件)、`aiCheck`、`aiRemove`、`aiState`、`lingSimulate:<429|hijack|timeout|off>`+ - 声音:`voice:<语言>[=<id>]`、`voicePreview:<语言>=<id>`、`voiceCloneFile:<wav>`、`voicePicker:<on|off>`+ - 诊断:`diagnostics:<on|off>`、`diagReport`+ - 更新与登录项:`updateFeed:<url>`、`updateCheck`、`updateInstall`、`updateState`、`loginItem[:on|off]`+ - 完整、最新的清单以 `AppModel.debugCommand` 里的 `switch` 为准。++## 测试技巧++- 英文界面:`defaults write com.wquguru.cicada.dev AppleLanguages -array en` 后重启,测完 `defaults delete com.wquguru.cicada.dev AppleLanguages`;或启动时加 `--args -AppleLanguages "(en)"`。+- 纪要窗口不出现在截屏里:先发 `notesCapturable` 再 `screencapture -l`,或直接 `notesRender:`。+- 合成的按键会发给所有 App:别的 App 的启动器可能抢走 ⌥ Space。模拟鼠标和按键需要终端有“辅助功能”权限。+- 试一句可以测整条同传链路和延迟:`speakTest:sample` 连发几次,读日志里的 `speak test:` 行。+- 端到端测更新:把 `CFBundleShortVersionString` 调高再构建,`ditto -c -k --keepParent build/Cicada.app Cicada-<v>-macOS-AppleSilicon.zip`,`shasum -a 256` 写进 `checksums.txt`,写一个资源地址用 `file://` 的 release JSON,从 scratchpad 运行旧版开发版(不要用 `build/` 里的),再 `updateFeed:file://…` 和 `updateInstall`。- `mouse move|drag|dclick|click|scroll ...`:模拟鼠标移动、拖动、双击、单击、滚轮(`scroll x y 行数`,正数往上翻),坐标原点在主屏左下角。- `key`:模拟按住说话键。`key right [秒]` 单按右 ⌥;`key <keyCode> <Carbon 修饰键> [秒]` 按组合键(如 `key 122 0` 是 F1);不带参数是 ⌥ Space。- `toggle-key`:模拟按一下 ⌃⌥S。