知了 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
fix: Stop sticking on 正在识别语言 when only one speech model is installed
wquguru328e2502053b
diff --git a/Sources/LiveSubs/AppModel.swift b/Sources/LiveSubs/AppModel.swiftindex 5302694..9e4bbff 100644--- a/Sources/LiveSubs/AppModel.swift+++ b/Sources/LiveSubs/AppModel.swift@@ -52,6 +52,21 @@ final class AppModel: ObservableObject {@Published var summary = ""@Published var installed: Set<String> = []@Published var candidates: [Lang] = []+ /// 听不出: the languages offered while "auto" can't tell (empty when it can).+ @Published var languageAsk: [Lang] = []+ /// The second speech model coming in the background: its name and how far along.+ @Published var modelFetch: ModelFetch?+ @Published var identifyingLanguage = false+ /// 在会议室里开会? in the panel: the Mac has played nothing for a minute of listening.+ @Published var roomPrompt = false+ /// Answered (or 听哪里 changed) in this meeting: not asked again until the next one.+ var roomPromptDismissed = false+ /// Why the model 听不出 needed couldn't be had, when that is so.+ @Published var modelProblem: ModelProblem?+ /// That model was the one to start with and there is none to fall back on: nothing is listening.+ @Published var modelBlocked = false+ /// 听不出 because none of the installed models hear their language: it offers ones not installed.+ @Published var languageNotInstalled = false@Published var outputs: [OutputDevice] = []@Published var speakPhase: SpeakEngine.Phase = .idle@Published var settingsSection: SettingsSection =@@ -118,12 +133,14 @@ final class AppModel: ObservableObject {init() {listen.onSubtitle = { [weak self] src, dst in- self?.liveSource = src+ // Someone is speaking either way; only the wrong model's words aren't shown.+ let visible = self?.listen.hidesSource == true ? "" : src+ self?.liveSource = visibleself?.liveTranslation = dstif !src.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { self?.heardSpeech(); self?.heardWords() }guard let self, self.settings.displayMode == "bar" else { return }self.overlay.clearStatus()- let shown = self.displayed(src, dst)+ let shown = self.displayed(visible, dst)self.overlay.setSubtitle(source: shown.source, translation: shown.translation)}listen.onStatus = { [weak self] text in@@ -243,6 +260,15 @@ final class AppModel: ObservableObject {RunLoop.main.add(watch, forMode: .common)}+ func pickLanguage(_ lang: Lang) { listen.pickLanguage(lang) }+ func retryModel() { listen.retryModel() }+ func openDictationSettings() {+ if let url = URL(string: "x-apple.systempreferences:com.apple.Keyboard-Settings.extension") { NSWorkspace.shared.open(url) }+ }+ func openStorageSettings() {+ if let url = URL(string: "x-apple.systempreferences:com.apple.settings.Storage") { NSWorkspace.shared.open(url) }+ }+func setOverlayAuto(_ on: Bool) {settings.overlayAuto = onoverlay.modeChanged()@@ -263,6 +289,18 @@ final class AppModel: ObservableObject {summary = listen.languageSummary()candidates = listen.candidatesinstalled = listen.installedLocales+ let ask = listen.asksLanguage ? listen.askChoices : []+ if ask != languageAsk { languageAsk = ask }+ let fetch = listen.fetchingModel.map { ModelFetch(name: $0.lang.name, fraction: $0.progress.fractionCompleted) }+ if fetch != modelFetch { modelFetch = fetch }+ if listen.identifyingLanguage != identifyingLanguage { identifyingLanguage = listen.identifyingLanguage }+ let roomAsk = listen.isRunning && RoomPrompt.shows(silent: listen.macSilent, answered: roomPromptDismissed,+ inCall: listen.macSilent && !(fakeCalls ?? MicUsers.currentCalls()).isEmpty)+ if roomAsk != roomPrompt { roomPrompt = roomAsk }+ if listen.modelProblem != modelProblem { modelProblem = listen.modelProblem }+ if listen.blockedByModel != modelBlocked { modelBlocked = listen.blockedByModel }+ let notInstalled = !ask.isEmpty && listen.mismatch && ask.allSatisfy { !listen.candidates.contains($0) }+ if notInstalled != languageNotInstalled { languageNotInstalled = notInstalled }if running { status = listen.statusText }}@@ -454,7 +492,7 @@ final class AppModel: ObservableObject {}// Read the whole meeting for names once more (the id outlives store.end).let ended = store.liveID- store.end(at: endedAt)+ store.end(at: endedAt, heardSpeech: listen.heardSpeech)if settings.speakerVoices, let ended { speakerNamer.guess(ended, force: true) }notes.finish()overlay.hide()@@ -1034,6 +1072,41 @@ final class AppModel: ObservableObject {let arg = parts.count > 1 ? parts[1] : ""switch parts.first ?? "" {case "start": start()+ case "models":+ // models:<installed,…>/<system languages,…> pretends the Mac has only these speech models+ // and languages, to test the fetch of a second model and 听不出; models:off ends it.+ // models:none/zh-Hans-CN is a Mac with no model at all.+ let parts = arg.split(separator: "@", maxSplits: 1).map(String.init)+ listen.simulatedFetchDelay = parts.count > 1 ? Double(parts[1]) ?? 0 : 0+ let p = parts[0].split(separator: "/", omittingEmptySubsequences: false)+ .map { $0.split(separator: ",").map(String.init).filter { $0 != "none" } }+ listen.simulatedModels = arg == "off" ? nil : Set(p.first ?? [])+ listen.simulatedSystemLanguages = arg == "off" || p.count < 2 ? nil : p[1]+ Task { await listen.refreshInstalledLocales() }+ case "recognizer":+ // recognizer:legacy runs the macOS 14/15 recognizer (SFSpeechRecognizer) on 26; recognizer:auto ends it.+ // Takes effect from the next start.+ Recognition.forceLegacy = arg == "legacy"+ debugLog("recognizer: \(Recognition.name)")+ Task { await listen.refreshInstalledLocales() }+ case "releaseModel":+ // releaseModel:<locale> gives back a speech model this app reserved (macOS keeps five per app).+ guard #available(macOS 26, *) else { break }+ guard #available(macOS 26, *) else { break }+ Task {+ let ok = await AssetInventory.release(reservedLocale: Locale(identifier: arg.replacingOccurrences(of: "-", with: "_")))+ debugLog("releaseModel \(arg): \(ok) reserved now=\(await AssetInventory.reservedLocales.map { $0.identifier })")+ await listen.refreshInstalledLocales()+ }+ case "modelFail":+ // modelFail:<offline|disk|limit|other> makes every model download fail that way; modelFail:off ends it.+ listen.simulatedModelFailure = arg == "off" || arg.isEmpty ? nil : arg+ case "network":+ // network:<on|off> pretends the network came or went; network:real follows the real one.+ listen.simulatedOnline = arg == "on" ? true : arg == "off" ? false : nil+ case "modelRetry": listen.retryModel()+ case "pickLanguage":+ if let lang = sourceLanguages.first(where: { $0.locale == arg }) { listen.pickLanguage(lang) }case "stop": stop()case "open": openMainWindow?()case "panel": showPanel?()@@ -1606,3 +1679,8 @@ struct LiveSubsMain {}}}++struct ModelFetch: Equatable {+ let name: String+ let fraction: Double+}diff --git a/Sources/LiveSubs/AudioRouter.swift b/Sources/LiveSubs/AudioRouter.swiftindex ba2a512..c5f2215 100644--- a/Sources/LiveSubs/AudioRouter.swift+++ b/Sources/LiveSubs/AudioRouter.swift@@ -54,7 +54,12 @@ final class AudioRouter: @unchecked Sendable {private var sink: RecognitionStream?private var ring: [(buffer: AVAudioPCMBuffer, seconds: Double, voiced: Bool)] = []private var ringSeconds = 0.0- private let ringLimit = 10.0+ private var ringLimit = 10.0+ /// While the language is unknown the audio is kept longer: the right model, once it is known+ /// or fetched, hears it all again instead of the wrong model's guesses being kept.+ func holdAudio(_ seconds: Double) {+ queue.async { [self] in ringLimit = seconds }+ }private var voicedTotal = 0.0private var silenceRun = 0.0private var sinceGap = 0.0@@ -237,6 +242,21 @@ final class AudioRouter: @unchecked Sendable {}}+ /// The last `seconds` of speech with the silences left out: what was said, even when nobody is+ /// speaking now (a model that arrives after the talk stopped can still check it).+ func voicedSnapshot(seconds: Double) -> (buffers: [AVAudioPCMBuffer], seconds: Double) {+ queue.sync {+ var acc = 0.0+ var out: [AVAudioPCMBuffer] = []+ for item in ring.reversed() where item.voiced {+ if acc >= seconds { break }+ acc += item.seconds+ out.append(item.buffer)+ }+ return (out.reversed(), acc)+ }+ }+func snapshot(seconds: Double) -> [AVAudioPCMBuffer] {queue.sync {var acc = 0.0diff --git a/Sources/LiveSubs/Languages.swift b/Sources/LiveSubs/Languages.swiftindex a930c1e..3729f74 100644--- a/Sources/LiveSubs/Languages.swift+++ b/Sources/LiveSubs/Languages.swift@@ -66,6 +66,22 @@ func followSystemTarget(source: String?, systemLanguages prefs: [String]) -> Str?? (mine.hasPrefix("zh") ? "en" : "zh-CN")}+/// The languages "auto" most likely hears, most likely first: the last one detected, the Mac's+/// own languages, then English. Detection compares two or more models, so a Mac with fewer+/// fetches the first ones of these it lacks; and they are what 听不出 offers to pick from.+func likelySourceLanguages(last: String?, systemLanguages prefs: [String]) -> [Lang] {+ var out: [Lang] = []+ func add(_ lang: Lang?) { if let lang, !out.contains(lang) { out.append(lang) } }+ add(sourceLanguages.first { $0.locale == last })+ for id in prefs {+ let code = translationCode(forSystemLanguage: id)+ // The only Chinese model listed is Mandarin (zh-CN); it hears Taiwanese Mandarin as well.+ add(sourceLanguages.first { $0.code == (code.hasPrefix("zh") ? "zh-CN" : code) })+ }+ add(sourceLanguages.first { $0.code == "en" })+ return out+}+/// The speech locale to listen for when I speak my language (English when it isn't one we recognize).func speakLocale(forLanguage code: String) -> String {if code.hasPrefix("zh") { return "zh-CN" }diff --git a/Sources/LiveSubs/ListenEngine.swift b/Sources/LiveSubs/ListenEngine.swiftindex 10b6a4f..8a47c16 100644--- a/Sources/LiveSubs/ListenEngine.swift+++ b/Sources/LiveSubs/ListenEngine.swift@@ -1,7 +1,7 @@import AppKitimport AVFoundationimport CoreMedia-import Speech+import Networkstruct Segment {let id: Int@@ -40,9 +40,37 @@ final class ListenEngine {private(set) var detecting = falseprivate(set) var candidates: [Lang] = []private(set) var installedLocales: Set<String> = []+ /// The speech model fetched in the background so "auto" has two to compare.+ private(set) var fetchingModel: (lang: Lang, progress: Progress)?+ private var fetchFailed: Set<String> = []+ /// Debug (`models:`): treat only these as installed, plus what is fetched meanwhile, and these as the Mac's languages.+ var simulatedModels: Set<String>?+ var simulatedSystemLanguages: [String]?+ /// Debug (`models:…@<s>`): a background download takes at least this long, like a slow network.+ var simulatedFetchDelay: Double = 0+ /// Debug (`modelFail:`): every model download fails this way (offline, disk, limit, other).+ var simulatedModelFailure: String?+ /// Debug (`network:`): pretend to be on or offline; nil follows the real network.+ var simulatedOnline: Bool? { didSet { networkChanged() } }+ /// A model that couldn't be had while it was needed, shown in 听不出 with what to do.+ private(set) var modelProblem: ModelProblem?+ private let pathMonitor = NWPathMonitor()+ private var realOnline = true+ private var online: Bool { simulatedOnline ?? realOnline }+ private var systemLanguages: [String] { simulatedSystemLanguages ?? Locale.preferredLanguages }+ /// When words were first heard this run: 听不出 is offered once the language stays unknown long after.+ private var firstHeardAt: Date?+ private var askShown = false- private var audioTap: SystemAudioTap?- private var analyzer: SpeechAnalyzer?+ private var audioTap: AudioSource?+ /// 会议室: the microphone Cicada listens to the room with; nil leaves the input on its default.+ var roomDevice: (() -> OutputDevice?)?+ /// The Mac reading a translation aloud, or the talk key held: the room mic hears silence then.+ private var roomMuted = false+ private var startedAt = Date()+ /// Listening to the Mac, and it has played nothing since the start: maybe the meeting is in the room.+ private(set) var macSilent = false+ private var recognizer: RecognitionStream?private var resultsTask: Task<Void, Never>?private var generation = 0private var pendingSwitch: Lang?@@ -54,7 +82,28 @@ final class ListenEngine {/// Sentences finished before detection settled the language: recorded once it confirms the/// language they were heard in, dropped on a switch (the replay into the new model redoes them).private var unconfirmed: [(seg: Segment, at: Date, duration: Double)] = []- private var recordable: Bool { settings.sourceMode != .auto || languageConfirmed || ambiguousDetections >= 2 }+ private var recordable: Bool {+ settings.sourceMode != .auto || languageConfirmed || (ambiguousDetections >= 2 && !mismatch)+ }+ /// The only model there is checked the audio and it isn't its language: what it writes is+ /// noise, neither shown nor kept, until another model or a pick settles it.+ private(set) var mismatch = false+ private var unsureStreak = 0+ private var sureStreak = 0+ /// The model for the language it starts with couldn't be had, and there is none to fall back+ /// on: nothing is listening, so the problem shows without waiting for 听不出.+ var blockedByModel: Bool { isRunning && modelProblem?.picked == true && recognizer == nil && modelProblem?.lang == activeLang }+ var hidesSource: Bool { mismatch && !recordable }+ /// Someone has spoken and the language isn't settled yet: what 此刻 says instead of 等有人开口.+ var identifyingLanguage: Bool {+ isRunning && settings.sourceMode == .auto && !recordable && firstHeardAt != nil+ }+ /// How much audio a switch can replay: all of it since the start while the language is unknown.+ /// Three minutes (≈6 MB): a model download seen taking 106 s fits with room to spare.+ private static let holdUnknown = 180.0+ private func updateHold() {+ router.holdAudio(settings.sourceMode == .auto && !languageConfirmed ? Self.holdUnknown : 10)+ }private var failureStreak = 0private var segments: [Segment] = []@@ -82,6 +131,18 @@ final class ListenEngine {init(settings: AppSettings) {self.settings = settings+ // A download that failed for want of a network resumes when there is one again.+ pathMonitor.pathUpdateHandler = { [weak self] path in+ let up = path.status == .satisfied+ DispatchQueue.main.async {+ MainActor.assumeIsolated {+ guard let self, self.realOnline != up else { return }+ self.realOnline = up+ self.networkChanged()+ }+ }+ }+ pathMonitor.start(queue: DispatchQueue(label: "cicada.network"))}var resolvedTarget: String { settings.resolvedTarget(source: activeLang?.code) }@@ -112,6 +173,65 @@ final class ListenEngine {candidates = sourceLanguages.filter { installedLocales.contains($0.locale) }debugLog("installed speech models: \(installedLocales.sorted()) candidates=\(candidates.map(\.locale))")onStateChange?()+ // Also when not listening: at launch the Mac's language and English come in quietly, so+ // the first meeting already has two models to compare.+ fetchSecondModel()+ }++ /// Detection needs two models: a Mac with fewer fetches the likeliest missing ones in the+ /// background, one at a time (each one's end refreshes the list and asks for the next).+ private func fetchSecondModel(besides starting: Lang? = nil) {+ guard settings.sourceMode == .auto, fetchingModel == nil, candidates.count < 2 else { return }+ let last = UserDefaults.standard.string(forKey: "lastDetected")+ // The model being started is fetched by `ensureModel` already. At a start that is `starting`:+ // `activeLang` is still the last run's then, and may be a model since taken away.+ let busy = starting ?? (isRunning ? activeLang : nil)+ guard let lang = likelySourceLanguages(last: last, systemLanguages: systemLanguages).first(where: {+ !installedLocales.contains($0.locale) && !fetchFailed.contains($0.locale) && $0 != busy+ }) else { return }+ fetchingModel = (lang, Progress())+ Task { [weak self] in+ var ok = false+ do {+ if await Recognition.status(lang.locale) == .unsupported {+ debugLog("model fetch: \(lang.locale) unsupported")+ } else {+ try await Recognition.install(lang.locale) { progress in+ self?.fetchingModel = (lang, progress)+ self?.onStateChange?()+ debugLog("model fetch: downloading \(lang.locale)")+ }+ if let delay = self?.simulatedFetchDelay, delay > 0 { try await Task.sleep(for: .seconds(delay)) }+ if let fail = self?.simulatedModelFailure { throw ModelProblem.simulated(fail) }+ ok = true+ }+ } catch {+ debugLog("model fetch \(lang.locale) failed: \(error)")+ if let self, await self.modelFailed(lang, error, picked: false) {+ // A slot was given back: try again straight away.+ self.fetchingModel = nil+ self.fetchSecondModel()+ return+ }+ }+ guard let self else { return }+ debugLog("model fetch: \(lang.locale) \(ok ? "ready" : "gave up")")+ self.fetchingModel = nil+ // The new model gets its 20 s to settle the language before 听不出 is offered.+ if self.firstHeardAt != nil { self.firstHeardAt = Date() }+ if ok {+ self.mismatch = false+ self.unsureStreak = 0+ self.sureStreak = 0+ self.simulatedModels?.insert(lang.locale)+ if self.modelProblem?.lang == lang { self.modelProblem = nil }+ } else {+ self.fetchFailed.insert(lang.locale)+ }+ self.needsDetection = true+ await self.refreshInstalledLocales()+ if ok { self.detectHeld() }+ }}// MARK: Start / stop@@ -131,8 +251,18 @@ final class ListenEngine {needsDetection = truenextPeriodicDetection = 30ambiguousDetections = 0+ unsureStreak = 0+ sureStreak = 0unconfirmed = []lastDetectionAt = .distantPast+ firstHeardAt = nil+ askShown = false+ fetchFailed = []+ modelProblem = nil+ mismatch = false+ startedAt = Date()+ macSilent = false+ updateHold()debugLog("listen start mode=\(settings.sourceMode) target=\(resolvedTarget)")guard startTap() else { return }@@ -146,13 +276,25 @@ final class ListenEngine {initial = langcase .auto:let last = UserDefaults.standard.string(forKey: "lastDetected")- initial = candidates.first(where: { $0.locale == last }) ?? candidates.first ?? sourceLanguages[0]+ let likely = likelySourceLanguages(last: last, systemLanguages: systemLanguages)+ // No model at all: start with the likeliest; the second follows in the background.+ initial = candidates.first(where: { $0.locale == last }) ?? candidates.first ?? likely.first ?? sourceLanguages[0]}setStatus(L("正在听"))Task { await switchTranscriber(to: initial) }+ fetchSecondModel(besides: initial)}+ /// The last run heard speech (a few seconds of it), read when its meeting ends.+ private(set) var heardSpeech = false+func stop() {+ // Lines still waiting for the language are recorded rather than dropped: the meeting+ // ended before detection settled it. Not when the only model said the audio isn't its+ // language: those lines are noise, and the recording keeps what was said.+ if settings.sourceMode == .auto, !recordable, !mismatch { flushUnconfirmed() }+ unconfirmed = []+ heardSpeech = isRunning && (router.stats().voicedTotal >= 3 || firstHeardAt != nil)isRunning = falsegeneration += 1tickTimer?.invalidate()@@ -209,6 +351,8 @@ final class ListenEngine {func sourceModeChanged() {languageConfirmed = false+ mismatch = false+ updateHold()pendingSwitch = nilneedsDetection = trueif isRunning, case .fixed(let lang) = settings.sourceMode {@@ -216,6 +360,7 @@ final class ListenEngine {if lang == activeLang { flushUnconfirmed() }Task { await switchTranscriber(to: lang) }}+ fetchSecondModel()onStateChange?()}@@ -227,28 +372,35 @@ final class ListenEngine {func redetect() {guard isRunning, settings.sourceMode == .auto else { return }languageConfirmed = false+ updateHold()pendingSwitch = nilneedsDetection = trueambiguousDetections = 0+ unsureStreak = 0+ sureStreak = 0lastDetectionAt = .distantPastonStateChange?()}// MARK: Transcriber- private func ensureModel(for transcriber: SpeechTranscriber, lang: Lang) async throws {- let status = await AssetInventory.status(forModules: [transcriber])- if status == .installed { return }- debugLog("model status for \(lang.locale): \(status)")- guard status != .unsupported else {- throw NSError(domain: "LiveSubsSpeech", code: 1,- userInfo: [NSLocalizedDescriptionKey: L("本机不支持\(lang.name)识别")])- }- if let request = try await AssetInventory.assetInstallationRequest(supporting: [transcriber]) {+ private func ensureModel(for lang: Lang) async throws {+ // Already coming in the background (fetched at launch): wait for it rather than ask twice.+ while fetchingModel?.lang == lang {setStatus(L("正在下载 \(lang.name) 语音模型…"))- try await request.downloadAndInstall()- await refreshInstalledLocales()+ try await Task.sleep(for: .milliseconds(300))+ }+ let status = await Recognition.status(lang.locale)+ if status == .installed {+ if simulatedModels?.insert(lang.locale).inserted == true { await refreshInstalledLocales() }+ return}+ debugLog("model status for \(lang.locale): \(status)")+ guard status != .unsupported else { throw Recognition.unsupported(lang.locale) }+ if let fail = simulatedModelFailure { throw ModelProblem.simulated(fail) }+ try await Recognition.install(lang.locale) { _ in self.setStatus(L("正在下载 \(lang.name) 语音模型…")) }+ simulatedModels?.insert(lang.locale)+ await refreshInstalledLocales()}private func switchTranscriber(to lang: Lang, replaySeconds: Double = 0) async {@@ -263,9 +415,11 @@ final class ListenEngine {}guard isRunning, gen == generation else { return }+ let previous = activeLangif activeLang != lang {segments.removeAll()unconfirmed = []+ mismatch = false}activeLang = langvolatileText = ""@@ -278,7 +432,36 @@ final class ListenEngine {onStateChange?()do {- try await ensureModel(for: transcriber, lang: lang)+ do {+ try await ensureModel(for: lang)+ } catch where settings.sourceMode == .auto && previous != nil && previous != lang {+ // A model that can't be had (no network, or the Mac's five reserved languages taken):+ // retrying would fail the same way every 30 s. Go back to the one that works, unsure again.+ debugLog("model for \(lang.locale) unavailable, back to \(previous!.locale): \(error)")+ if await modelFailed(lang, error, picked: true) {+ guard isRunning, gen == generation else { return }+ Task { await switchTranscriber(to: lang, replaySeconds: replaySeconds) }+ return+ }+ fetchFailed.insert(lang.locale)+ languageConfirmed = false+ // macOS 14/15: a language is added in Dictation settings, which only the user can do.+ setStatus(Recognition.needsUser(error) ? error.localizedDescription : L("没能下载 \(lang.name) 语音模型"))+ guard isRunning, gen == generation else { return }+ Task { await switchTranscriber(to: previous!) }+ return+ } catch {+ // Nothing to fall back on (a language chosen in settings, or the first model on this+ // Mac): say why instead of retrying every 30 s; the network back or 再试一次 resumes.+ debugLog("model for \(lang.locale) unavailable, nothing to fall back on: \(error)")+ if await modelFailed(lang, error, picked: true) {+ guard isRunning, gen == generation else { return }+ Task { await switchTranscriber(to: lang, replaySeconds: replaySeconds) }+ return+ }+ setStatus(Recognition.needsUser(error) ? error.localizedDescription : L("没能下载 \(lang.name) 语音模型"))+ return+ }guard isRunning, gen == generation else { return }let stream = try await Recognition.start(lang.locale, drafts: true, confidence: true)guard isRunning, gen == generation else {@@ -309,8 +492,14 @@ final class ListenEngine {guard gen == generation, isRunning else { return }debugLog("recognition error: \(error)")failureStreak += 1- let delay = min(30.0, 2.0 * pow(2.0, Double(failureStreak - 1)))- setStatus(L("识别出错,\(Int(delay)) 秒后重试"))+ var delay = min(30.0, 2.0 * pow(2.0, Double(failureStreak - 1)))+ if Recognition.needsUser(error) {+ // Fixed in System Settings, not by waiting: say what to do, and try again soon after.+ delay = 3+ setStatus(error.localizedDescription)+ } else {+ setStatus(L("识别出错,\(Int(delay)) 秒后重试"))+ }guard let lang = activeLang else { return }DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] inMainActor.assumeIsolated {@@ -366,7 +555,9 @@ final class ListenEngine {// Only confirmed-language sentences go into the meeting record; earlier ones wait.let spoken = duration.isFinite ? duration : 0if recordable {- onFinal?(seg, spoken)+ // A replayed line was spoken longer ago than it lasted: the audio clock knows when.+ let since = router.fedSeconds() - seg.start+ onFinal?(seg, since.isFinite && since > spoken + 5 ? since : spoken)} else {unconfirmed.append((seg, Date(), spoken))// Held lines keep their audio only while recent: an undecided language must not pile up minutes of it.@@ -378,6 +569,7 @@ final class ListenEngine {}checkForeignLetters(text)} else {+ if firstHeardAt == nil, text.contains(where: \.isLetter) { firstHeardAt = Date() }if volatileText.isEmpty { volatileStartedAt = Date(); volatileStartClock = router.fedSeconds() }if text != volatileText { volatileChangedAt = Date() }volatileText = text@@ -391,8 +583,8 @@ final class ListenEngine {let srcJoin = joiner(for: activeLang?.code ?? "en")let source = [segments.last?.text ?? "", volatileText].filter { !$0.isEmpty }.joined(separator: srcJoin.isEmpty ? " " : srcJoin)- if settings.sourceMode == .auto, !languageConfirmed, ambiguousDetections < 2 {- onSubtitle?(source, L("正在识别语言…"))+ if settings.sourceMode == .auto, !recordable {+ onSubtitle?(source, asksLanguage ? L("听不出是哪种语言,到菜单栏里选一下") : L("正在识别语言…"))return}let tgtJoin = joiner(for: resolvedTarget)@@ -418,7 +610,9 @@ final class ListenEngine {}private func maybeDetectLanguage() {- guard isRunning, settings.sourceMode == .auto, !detecting, candidates.count >= 2 else { return }+ // One model can still tell whether the audio is its language, until the language is known.+ guard isRunning, settings.sourceMode == .auto, !detecting,+ candidates.count >= 2 || (!languageConfirmed && candidates.first == activeLang && activeLang != nil) else { return }var stats = router.stats(window: 6)if stats.silenceRun >= AudioRouter.gapSeconds { needsDetection = true }if stats.voicedTotal >= nextPeriodicDetection { needsDetection = true }@@ -428,12 +622,24 @@ final class ListenEngine {stats = router.stats(window: clipSeconds)guard stats.recentVoiced >= 2.5 else { return }+ nextPeriodicDetection = stats.voicedTotal + 20+ runDetection(router.snapshot(seconds: clipSeconds))+ }++ /// A model that just arrived checks the speech held back, without waiting for someone to talk again.+ private func detectHeld() {+ guard isRunning, settings.sourceMode == .auto, !languageConfirmed, !detecting, candidates.count >= 2 else { return }+ let held = router.voicedSnapshot(seconds: 6)+ guard held.seconds >= 2.5 else { return }+ debugLog(String(format: "detect: new model, checking %.1f s of held speech", held.seconds))+ runDetection(held.buffers)+ }++ private func runDetection(_ clip: [AVAudioPCMBuffer]) {needsDetection = falselastDetectionAt = Date()detecting = true- nextPeriodicDetection = stats.voicedTotal + 20onStateChange?()- let clip = router.snapshot(seconds: clipSeconds)let candidates = self.candidatesTask { [weak self] inlet started = Date()@@ -450,6 +656,45 @@ final class ListenEngine {private func applyDetection(_ ranked: [LanguageDetector.Candidate]) {guard let best = ranked.first else { return }+ if ranked.count == 1 {+ // The right model is ≥0.85 sure; English heard by a French model scored 0.12.+ guard best.lang == activeLang, best.confidence >= 0.6, best.score >= 0.6 else {+ // Asked again only by the usual triggers (a pause, 20 s more speech), or when a model arrives.+ if !mismatch { debugLog("detect: not \(best.lang.locale), holding lines for another model") }+ mismatch = true+ // Checked on speech: someone is talking even if the model wrote nothing down.+ if firstHeardAt == nil { firstHeardAt = Date() }+ renderSubtitles()+ return+ }+ mismatch = false+ }+ // Every model unsure: a language with no model here, not a close call. On their own language+ // English scored 0.95, Chinese 0.84, Korean 0.97; Japanese heard by the Chinese model 0.66,+ // German and Spanish heard by English or Chinese at most 0.48.+ // Twice in a row, so one noisy clip doesn't ask; nothing is kept meanwhile.+ if ranked.count >= 2, best.score < 0.72 {+ unsureStreak += 1+ sureStreak = 0+ if unsureStreak >= 2, !mismatch, !languageConfirmed {+ debugLog("detect: none of \(ranked.map(\.lang.locale).joined(separator: ",")), holding lines")+ mismatch = true+ if firstHeardAt == nil { firstHeardAt = Date() }+ }+ if !languageConfirmed { needsDetection = true }+ renderSubtitles()+ return+ }+ unsureStreak = 0+ // Said no once: Japanese heard by the Chinese model reached 0.73 now and then, so one sure+ // answer doesn't take it back; two in a row do.+ if mismatch, ranked.count >= 2 {+ sureStreak += 1+ if sureStreak < 2 {+ needsDetection = true+ return+ }+ }let runnerUp = ranked.dropFirst().first?.score ?? 0guard best.confidence >= 0.6, best.score - runnerUp >= 0.08 else {debugLog("detect: ambiguous, keeping \(activeLang?.locale ?? "-")")@@ -461,6 +706,8 @@ final class ListenEngine {}if best.lang == activeLang {languageConfirmed = true+ mismatch = false+ updateHold()flushUnconfirmed()pendingSwitch = nilUserDefaults.standard.set(best.lang.locale, forKey: "lastDetected")@@ -471,17 +718,133 @@ final class ListenEngine {let overwhelming = best.score - currentScore >= 0.30if !languageConfirmed || overwhelming || pendingSwitch == best.lang {debugLog("detect: switching \(activeLang?.locale ?? "-") → \(best.lang.locale)")+ // The first answer replays everything held back; a later switch, the last sentence or so.+ let replay = languageConfirmed ? 8 : Self.holdUnknownlanguageConfirmed = trueunconfirmed = []pendingSwitch = nilUserDefaults.standard.set(best.lang.locale, forKey: "lastDetected")- Task { await switchTranscriber(to: best.lang, replaySeconds: 8) }+ Task { await switchTranscriber(to: best.lang, replaySeconds: replay) }} else {pendingSwitch = best.langneedsDetection = true}}+ /// Why a model couldn't be had. At the five-model limit a model Cicada isn't using is given+ /// back first: true means one was, and the caller tries again; otherwise the problem is kept+ /// for 听不出 to show.+ private func modelFailed(_ lang: Lang, _ error: Error, picked: Bool) async -> Bool {+ let cause = ModelProblem.cause(of: error, online: online, freeBytes: ModelProblem.freeBytes())+ debugLog("model problem \(lang.locale): \(cause)")+ if cause == .limit, simulatedModelFailure == nil, await freeModelSlot(for: lang) { return true }+ modelProblem = ModelProblem(lang: lang, cause: cause, picked: picked)+ onStateChange?()+ return false+ }++ /// Gives back a reserved model that isn't in use and isn't a likely language, oldest guess first.+ private func freeModelSlot(for wanted: Lang) async -> Bool {+ let keep = Set(likelySourceLanguages(last: UserDefaults.standard.string(forKey: "lastDetected"),+ systemLanguages: systemLanguages).map(\.locale)+ + [wanted.locale, activeLang?.locale].compactMap { $0 })+ for locale in await Recognition.reservedLocales() where !keep.contains(locale) {+ if await Recognition.release(locale) {+ debugLog("model limit: gave back \(locale) for \(wanted.locale)")+ await refreshInstalledLocales()+ return true+ }+ }+ return false+ }++ /// 再试一次, or the network back for a download that needed it.+ func retryModel() {+ guard let p = modelProblem else { return }+ debugLog("model retry: \(p.lang.locale)")+ modelProblem = nil+ fetchFailed.remove(p.lang.locale)+ if p.picked, isRunning, p.lang == activeLang, recognizer == nil {+ // Nothing is listening: start the language again, with all the speech held since the start.+ Task { await switchTranscriber(to: p.lang, replaySeconds: languageConfirmed ? 0 : Self.holdUnknown) }+ } else if p.picked, isRunning {+ languageConfirmed = false+ pickLanguage(p.lang)+ } else {+ fetchSecondModel()+ }+ onStateChange?()+ }++ /// macOS 14/15: the language added in Dictation settings carries on by itself, as the network does.+ private func checkDictation() {+ guard isRunning, let p = modelProblem, case .dictation = p.cause, Recognition.dictationEnabled else { return }+ Task {+ guard await Recognition.status(p.lang.locale) == .installed, self.modelProblem == p else { return }+ self.retryModel()+ }+ }++ private func networkChanged() {+ debugLog("network \(online ? "up" : "down")")+ if online, modelProblem?.cause == .offline { retryModel() }+ }++ /// 听不出: the language is still unknown 20 s after the first words, with nothing under way that+ /// could settle it (no check running, no model coming). Too quiet for a check, two models that+ /// keep disagreeing, a model that couldn't be fetched: one click ends each.+ var asksLanguage: Bool {+ guard isRunning, settings.sourceMode == .auto, !languageConfirmed, fetchingModel == nil,+ let firstHeardAt else { return false }+ // Once offered it stays until answered: a check running meanwhile doesn't make it blink.+ if askShown { return true }+ // The one model said no and no other is coming: nothing is shown or kept, so ask now.+ if mismatch { return true }+ return !detecting && Date().timeIntervalSince(firstHeardAt) >= 20+ }++ /// What 听不出 offers first; the rest sit under 更多.+ var askChoices: [Lang] {+ // None of the installed ones: offer what isn't installed; they are a 其实是 aside.+ if mismatch {+ let others = (likelySourceLanguages(last: nil, systemLanguages: systemLanguages) + sourceLanguages)+ .filter { !candidates.contains($0) && !fetchFailed.contains($0.locale) }+ var out: [Lang] = []+ for lang in others where !out.contains(lang) { out.append(lang) }+ if !out.isEmpty { return Array(out.prefix(3)) }+ }+ var out = likelySourceLanguages(last: activeLang?.locale, systemLanguages: systemLanguages)+ for lang in candidates + sourceLanguages where !out.contains(lang) { out.append(lang) }+ return Array(out.filter { !fetchFailed.contains($0.locale) }.prefix(3))+ }++ /// The language picked from 听不出: confirmed for this run (settings stay on auto). A model+ /// not on the Mac yet is downloaded as when it is detected.+ func pickLanguage(_ lang: Lang) {+ guard isRunning, settings.sourceMode == .auto else { return }+ debugLog("language picked: \(lang.locale) (was \(activeLang?.locale ?? "-"))")+ let replay = languageConfirmed ? 8 : Self.holdUnknown+ languageConfirmed = true+ mismatch = false+ pendingSwitch = nil+ needsDetection = false+ askShown = false+ unsureStreak = 0+ sureStreak = 0+ modelProblem = nil+ UserDefaults.standard.set(lang.locale, forKey: "lastDetected")+ if lang == activeLang, recognizer != nil {+ updateHold()+ flushUnconfirmed()+ renderSubtitles()+ onStateChange?()+ } else {+ // The hold shrinks once the new model is attached, after it took the replay.+ unconfirmed = []+ Task { await switchTranscriber(to: lang, replaySeconds: replay) }+ }+ }+/// Records the sentences held back before the language was confirmed, with the translation/// they got meanwhile and their time of speaking.private func flushUnconfirmed() {diff --git a/Sources/LiveSubs/ModelProblem.swift b/Sources/LiveSubs/ModelProblem.swiftnew file mode 100644index 0000000..2fc4500--- /dev/null+++ b/Sources/LiveSubs/ModelProblem.swift@@ -0,0 +1,74 @@+import Foundation++/// A speech model that couldn't be had, and why: what 听不出 says and offers instead of a bare+/// "download failed". Only shown while it blocks listening; a quiet fetch at launch just tries+/// again next time.+struct ModelProblem: Equatable {+ enum Cause: Equatable {+ /// No network: carries on by itself once there is one.+ case offline+ /// The disk is (nearly) full: only the user can make room.+ case disk+ /// macOS keeps five speech models per app: Cicada gives one back and retries by itself,+ /// so this only shows when there is none it can give back.+ case limit+ /// macOS 14/15: the language (or Dictation itself) is added in Dictation settings, by the user.+ case dictation(String)+ /// Anything else; a message of Cicada's own (the Dictation hint on macOS 14/15) when there is one.+ case other(String?)+ }++ let lang: Lang+ let cause: Cause+ /// Picked from 听不出 (retrying picks it again) rather than fetched in the background.+ let picked: Bool++ /// Below this much free space a failed download is put down to the disk.+ static let lowDisk: Int64 = 1_000_000_000++ static func cause(of error: Error, online: Bool, freeBytes: Int64?) -> Cause {+ let chain = errorChain(error as NSError)+ if chain.contains(where: { $0.domain == "SFSpeechErrorDomain" && $0.code == 11 })+ || chain.contains(where: { $0.localizedDescription.contains("Too many allocated locales") }) {+ return .limit+ }+ if let own = chain.first(where: { Recognition.needsUser($0) }) { return .dictation(own.localizedDescription) }+ let offlineCodes = [NSURLErrorNotConnectedToInternet, NSURLErrorNetworkConnectionLost, NSURLErrorTimedOut,+ NSURLErrorCannotFindHost, NSURLErrorCannotConnectToHost, NSURLErrorDNSLookupFailed,+ NSURLErrorDataNotAllowed, NSURLErrorInternationalRoamingOff]+ if chain.contains(where: { $0.domain == NSURLErrorDomain && offlineCodes.contains($0.code) }) { return .offline }+ if chain.contains(where: { ($0.domain == NSCocoaErrorDomain && $0.code == NSFileWriteOutOfSpaceError)+ || ($0.domain == NSPOSIXErrorDomain && $0.code == Int(ENOSPC)) }) {+ return .disk+ }+ // The installer's own errors don't always say: what the Mac is like right now does.+ if !online { return .offline }+ if let freeBytes, freeBytes < lowDisk { return .disk }+ if let own = chain.first(where: { $0.domain == "LiveSubsSpeech" }) { return .other(own.localizedDescription) }+ return .other(nil)+ }++ private static func errorChain(_ error: NSError) -> [NSError] {+ var out = [error]+ if let under = error.userInfo[NSUnderlyingErrorKey] as? NSError { out += errorChain(under) }+ for under in error.userInfo[NSMultipleUnderlyingErrorsKey] as? [NSError] ?? [] { out += errorChain(under) }+ return out+ }++ static func freeBytes() -> Int64? {+ let values = try? URL(fileURLWithPath: NSHomeDirectory())+ .resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])+ return values?.volumeAvailableCapacityForImportantUsage+ }++ /// A made-up failure of `kind` (offline, disk, limit, other), for testing the 听不出 card.+ static func simulated(_ kind: String) -> NSError {+ switch kind {+ case "offline": return NSError(domain: NSURLErrorDomain, code: NSURLErrorNotConnectedToInternet)+ case "disk": return NSError(domain: NSCocoaErrorDomain, code: NSFileWriteOutOfSpaceError)+ case "limit": return NSError(domain: "SFSpeechErrorDomain", code: 11,+ userInfo: [NSLocalizedDescriptionKey: "Too many allocated locales, 5 maximum."])+ default: return NSError(domain: "SimulatedModelFailure", code: 1)+ }+ }+}diff --git a/Sources/LiveSubs/NotesViews.swift b/Sources/LiveSubs/NotesViews.swiftindex 8066735..d937dd7 100644--- a/Sources/LiveSubs/NotesViews.swift+++ b/Sources/LiveSubs/NotesViews.swift@@ -502,6 +502,13 @@ struct TranscriptListView<Partial: View>: View, Equatable {var speakers: [String: Int] = [:]/// When listening began, for the start mark shown before the first line.var startedAt: Date?+ /// Speech is coming in but its language isn't known yet: 此刻 says so instead of waiting.+ var identifying = false+ /// Voice → speaker number on show; with `onAssign`, a paragraph's name opens "这段是谁说的".+ var voices: [Int: Int] = [:]+ /// The voice being edited above: its paragraphs are tinted.+ var marked: Int?+ var onAssign: ((Set<String>, Int) -> Void)?@ViewBuilder var partial: Partial@State private var following = true@@ -593,7 +600,7 @@ struct TranscriptListView<Partial: View>: View, Equatable {}if lines.isEmpty && !partialShown {if live {- TranscriptWaitingView(startedAt: startedAt)+ TranscriptWaitingView(startedAt: startedAt, identifying: identifying)} else {Text("说话的内容会出现在这里").font(.system(size: 13)).foregroundStyle(Palette.tertiary).frame(maxWidth: .infinity).padding(.top, 40)@@ -802,6 +809,7 @@ extension View {/// lines will take, and 此刻 waiting for the first words.struct TranscriptWaitingView: View {var startedAt: Date?+ var identifying = falseprivate static let time: DateFormatter = { let f = DateFormatter(); f.dateFormat = "HH:mm"; return f }()@@ -827,7 +835,7 @@ struct TranscriptWaitingView: View {VStack(alignment: .leading, spacing: 6) {Text("此刻").font(.system(size: 11, weight: .bold)).foregroundStyle(Palette.accentInk)HStack(spacing: 3) {- Text("等有人开口").font(.system(size: 15)).foregroundStyle(Palette.tertiary)+ Text(identifying ? L("正在识别语言…") : L("等有人开口")).font(.system(size: 15)).foregroundStyle(Palette.tertiary)BlinkingCaret()}}diff --git a/Sources/LiveSubs/SessionStore.swift b/Sources/LiveSubs/SessionStore.swiftindex c2073fc..e441342 100644--- a/Sources/LiveSubs/SessionStore.swift+++ b/Sources/LiveSubs/SessionStore.swift@@ -68,10 +68,11 @@ final class SessionStore: ObservableObject {let root: URLprivate var saveWork: DispatchWorkItem?- init() {+ /// `root`: tests keep their meetings in a folder of their own.+ init(root: URL? = nil) {let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]- root = base.appendingPathComponent("\(DevBuild.supportFolder)/Sessions", isDirectory: true)- try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ self.root = root ?? base.appendingPathComponent("\(DevBuild.supportFolder)/Sessions", isDirectory: true)+ try? FileManager.default.createDirectory(at: self.root, withIntermediateDirectories: true)load()}@@ -115,21 +116,23 @@ final class SessionStore: ObservableObject {}/// `at`: when the meeting really ended, for one that ended by itself after a hang-up or a- /// long silence; the recordings are cut there too.- func end(at: Date? = nil) {+ /// long silence; the recordings are cut there too. `heardSpeech`: the recording holds speech,+ /// so a meeting is kept for it even when no line made it into the record (the language was+ /// never settled, say): an hour of a meeting must not vanish with its audio.+ func end(at: Date? = nil, heardSpeech: Bool = false) {guard let id = liveID, let i = index(id) else { liveID = nil; return }let now = Date()sessions[i].endedAt = at.map { min(now, max(sessions[i].startedAt, $0)) } ?? nowliveID = nil- if sessions[i].lines.isEmpty {+ sessions[i].hasAudio = [systemAudioURL(id), micAudioURL(id)].contains {+ FileManager.default.fileExists(atPath: $0.path) || FileManager.default.fileExists(atPath: AudioFileWriter.partial($0).path)+ }+ if sessions[i].lines.isEmpty, !(heardSpeech && sessions[i].hasAudio) {// Nothing was said: don't keep an empty meeting around.try? FileManager.default.removeItem(at: folder(id))sessions.remove(at: i)return}- sessions[i].hasAudio = [systemAudioURL(id), micAudioURL(id)].contains {- FileManager.default.fileExists(atPath: $0.path) || FileManager.default.fileExists(atPath: AudioFileWriter.partial($0).path)- }saveNow(id)finishAudio(id, until: at == nil ? nil : sessions[i].duration)}diff --git a/Sources/LiveSubs/Views.swift b/Sources/LiveSubs/Views.swiftindex 963cb89..93776ea 100644--- a/Sources/LiveSubs/Views.swift+++ b/Sources/LiveSubs/Views.swift@@ -164,6 +164,9 @@ struct MenuPanelView: View {}if let p = model.ending { MeetingEndingStrip(model: model, pending: p, compact: true) }+ // In subtitle-bar mode this is where the bar sends you to pick.+ if model.running { LanguageNotice(model: model) }+ if model.roomPrompt { roomPromptStrip }VStack(spacing: 8) {ChoiceRow(label: L("听到"), value: heardValue.0, badge: heardValue.1, sections: sourceSections) {@@ -854,7 +857,7 @@ struct MainWindowView: View {/// 此刻: the sentence being heard, pinned under the page while the meeting is live.@ViewBuilder private var liveNow: some View {let src = model.liveSource.trimmingCharacters(in: .whitespacesAndNewlines)- if !src.isEmpty {+ if !src.isEmpty || !model.languageAsk.isEmpty || model.modelFetch != nil {HStack(alignment: .top, spacing: 14) {HStack(spacing: 6) {BreathingDot(size: 6)@@ -864,10 +867,12 @@ struct MainWindowView: View {VStack(alignment: .leading, spacing: 3) {Text(src).font(.system(size: 13)).foregroundStyle(Palette.secondary).lineLimit(2).truncationMode(.head)- if !model.liveTranslation.isEmpty {+ // 听不出 replaces the stuck 正在识别语言…; it says what to do instead.+ if !model.liveTranslation.isEmpty, model.languageAsk.isEmpty {Text(model.liveTranslation).font(.system(size: 15)).foregroundStyle(Palette.ink).lineLimit(2).truncationMode(.head)}+ LanguageNotice(model: model).padding(.top, 4)}Spacer(minLength: 0)}@@ -1149,3 +1154,118 @@ struct SessionNotesView: View {}}}++/// Under 此刻 while "auto" can't tell the language yet: the second speech model coming in, or,+/// when nothing more will settle it, 听不出 with the likely languages to pick from.+struct LanguageNotice: View {+ @ObservedObject var model: AppModel++ var body: some View {+ if let problem = model.modelProblem, !model.languageAsk.isEmpty || model.modelBlocked {+ problemCard(problem)+ } else if model.languageNotInstalled {+ notInstalledCard+ } else if !model.languageAsk.isEmpty {+ VStack(alignment: .leading, spacing: 8) {+ Text("听不出是哪种语言,你来选一下").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)+ HStack(spacing: 8) {+ ForEach(model.languageAsk, id: \.locale) { lang in+ SoftButton(lang.name) { model.pickLanguage(lang) }+ }+ Menu {+ ForEach(sourceLanguages.filter { !model.languageAsk.contains($0) }, id: \.locale) { lang in+ Button(lang.name) { model.pickLanguage(lang) }+ }+ } label: {+ Text("更多…").font(.system(size: 12, weight: .semibold))+ }+ .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize()+ .foregroundStyle(Palette.secondary)+ }+ }+ } else if let fetch = model.modelFetch {+ HStack(spacing: 10) {+ ProgressView(value: max(0.02, fetch.fraction)).progressViewStyle(.linear).tint(Palette.tertiary).frame(width: 96)+ Text("正在补装 \(fetch.name) 语音模型,装好后自动判断语言").font(.system(size: 12)).foregroundStyle(Palette.secondary)+ .lineLimit(1).truncationMode(.tail)+ }+ }+ }++ /// None of the installed models hear their language: the likely ones not installed come first+ /// (picking one downloads it and replays the start), the installed ones in case the check was wrong.+ private var notInstalledCard: some View {+ let installed = model.candidates+ let names = installed.map(\.name)+ let title = names.count == 1 ? L("听着不像 \(names[0])")+ : names.count == 2 ? L("听着不像 \(names[0]) 或 \(names[1])") : L("听着不像已装的语言")+ return VStack(alignment: .leading, spacing: 8) {+ VStack(alignment: .leading, spacing: 3) {+ Text(title).font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)+ Text("选了就下载它的语音模型,开头这段也会补上").font(.system(size: 12)).foregroundStyle(Palette.secondary)+ .fixedSize(horizontal: false, vertical: true)+ }+ HStack(spacing: 8) {+ ForEach(model.languageAsk, id: \.locale) { lang in+ SoftButton(lang.name) { model.pickLanguage(lang) }+ }+ Menu {+ ForEach(sourceLanguages.filter { !model.languageAsk.contains($0) && !installed.contains($0) }, id: \.locale) { lang in+ Button(lang.name) { model.pickLanguage(lang) }+ }+ } label: {+ Text("更多…").font(.system(size: 12, weight: .semibold))+ }+ .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize()+ .foregroundStyle(Palette.secondary)+ }+ HStack(spacing: 10) {+ Text("其实是:").font(.system(size: 12)).foregroundStyle(Palette.secondary)+ ForEach(installed, id: \.locale) { lang in+ Button(lang.name) { model.pickLanguage(lang) }+ .buttonStyle(.plain).font(.system(size: 12, weight: .semibold))+ .foregroundStyle(Palette.secondary).underline()+ }+ }+ }+ }++ /// The model 听不出 needed couldn't be had: why, the one thing that helps, and the languages+ /// already on the Mac to go on with meanwhile.+ private func problemCard(_ p: ModelProblem) -> some View {+ // Chosen in settings, the language isn't swapped from here.+ let installed = model.settings.sourceMode == .auto ? model.candidates.filter { $0 != p.lang } : []+ return VStack(alignment: .leading, spacing: 8) {+ VStack(alignment: .leading, spacing: 3) {+ Text("没能下载 \(p.lang.name) 语音模型").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)+ if let reason = reason(p.cause) {+ Text(reason).font(.system(size: 12)).foregroundStyle(Palette.secondary).fixedSize(horizontal: false, vertical: true)+ }+ }+ HStack(spacing: 8) {+ switch p.cause {+ case .disk: SoftButton(L("打开存储空间"), dark: true) { model.openStorageSettings() }+ case .dictation: SoftButton(L("打开听写设置"), dark: true) { model.openDictationSettings() }+ case .other, .limit: SoftButton(L("再试一次"), dark: true) { model.retryModel() }+ case .offline: EmptyView()+ }+ if !installed.isEmpty {+ Text("先用已装的:").font(.system(size: 12)).foregroundStyle(Palette.secondary)+ ForEach(installed, id: \.locale) { lang in+ SoftButton(lang.name) { model.pickLanguage(lang) }+ }+ }+ }+ }+ }++ private func reason(_ cause: ModelProblem.Cause) -> String? {+ switch cause {+ case .offline: return L("网络连不上,连上后会自动继续")+ case .disk: return L("这台 Mac 的磁盘空间不够了")+ case .limit: return L("这台 Mac 上的语音模型已满 5 种")+ case .dictation(let message), .other(let message?): return message+ case .other(nil): return nil+ }+ }+}diff --git a/Tests/LiveSubsTests/LanguageTests.swift b/Tests/LiveSubsTests/LanguageTests.swiftindex 47bb4e0..87231e0 100644--- a/Tests/LiveSubsTests/LanguageTests.swift+++ b/Tests/LiveSubsTests/LanguageTests.swift@@ -68,4 +68,15 @@ import Testing#expect(speakLocale(forLanguage: "ja") == "ja-JP")#expect(speakLocale(forLanguage: "it") == "en-US")}++ @Test func likelyLanguagesPutLastThenSystemThenEnglish() {+ let locales = { (l: [Lang]) in l.map(\.locale) }+ // A Chinese Mac with nothing detected yet: Chinese first, English to compare it with.+ #expect(locales(likelySourceLanguages(last: nil, systemLanguages: ["zh-Hans-CN"])) == ["zh-CN", "en-US"])+ // Traditional Chinese still listens with the Mandarin model.+ #expect(locales(likelySourceLanguages(last: nil, systemLanguages: ["zh-Hant-TW", "en-US"])) == ["zh-CN", "en-US"])+ #expect(locales(likelySourceLanguages(last: "ja-JP", systemLanguages: ["fr-FR", "en-GB"])) == ["ja-JP", "fr-FR", "en-US"])+ // Languages with no speech model are skipped; English is always there.+ #expect(locales(likelySourceLanguages(last: "xx", systemLanguages: ["it-IT"])) == ["en-US"])+ }}diff --git a/Tests/LiveSubsTests/ModelProblemTests.swift b/Tests/LiveSubsTests/ModelProblemTests.swiftnew file mode 100644index 0000000..f4fc09d--- /dev/null+++ b/Tests/LiveSubsTests/ModelProblemTests.swift@@ -0,0 +1,42 @@+import Foundation+import Testing+@testable import LiveSubs++@Suite struct ModelProblemTests {+ private func cause(_ e: Error, online: Bool = true, free: Int64? = 50_000_000_000) -> ModelProblem.Cause {+ ModelProblem.cause(of: e, online: online, freeBytes: free)+ }++ @Test func fiveModelLimit() {+ #expect(cause(NSError(domain: "SFSpeechErrorDomain", code: 11)) == .limit)+ // The limit wins even offline: giving a model back needs no network.+ #expect(cause(ModelProblem.simulated("limit"), online: false) == .limit)+ }++ @Test func offlineFromTheErrorOrTheMac() {+ #expect(cause(NSError(domain: NSURLErrorDomain, code: NSURLErrorNotConnectedToInternet)) == .offline)+ let wrapped = NSError(domain: "AssetInventory", code: 7,+ userInfo: [NSUnderlyingErrorKey: NSError(domain: NSURLErrorDomain, code: NSURLErrorTimedOut)])+ #expect(cause(wrapped) == .offline)+ #expect(cause(NSError(domain: "Whatever", code: 1), online: false) == .offline)+ }++ @Test func diskFromTheErrorOrFreeSpace() {+ #expect(cause(NSError(domain: NSPOSIXErrorDomain, code: Int(ENOSPC))) == .disk)+ #expect(cause(NSError(domain: NSCocoaErrorDomain, code: NSFileWriteOutOfSpaceError)) == .disk)+ #expect(cause(NSError(domain: "Whatever", code: 1), free: 200_000_000) == .disk)+ }++ @Test func dictationOnOlderMacs() {+ let own = NSError(domain: "LiveSubsSpeech", code: 4, userInfo: [NSLocalizedDescriptionKey: "add it in Dictation"])+ // Offline or short of space doesn't matter: only Dictation settings help.+ #expect(cause(own, online: false) == .dictation("add it in Dictation"))+ }++ @Test func otherKeepsCicadasOwnMessage() {+ let own = NSError(domain: "LiveSubsSpeech", code: 1, userInfo: [NSLocalizedDescriptionKey: "not on this Mac"])+ #expect(cause(own) == .other("not on this Mac"))+ #expect(cause(NSError(domain: "Whatever", code: 1)) == .other(nil))+ #expect(cause(NSError(domain: "Whatever", code: 1), free: nil) == .other(nil))+ }+}diff --git a/Tests/LiveSubsTests/SessionStoreTests.swift b/Tests/LiveSubsTests/SessionStoreTests.swiftnew file mode 100644index 0000000..880699d--- /dev/null+++ b/Tests/LiveSubsTests/SessionStoreTests.swift@@ -0,0 +1,41 @@+import Foundation+import Testing+@testable import LiveSubs++/// Ending a meeting: an empty one goes, one whose recording holds speech stays (issue #5).+@MainActor @Suite struct SessionStoreTests {+ func store() -> SessionStore {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("cicada-store-\(UUID().uuidString)")+ return SessionStore(root: root)+ }++ /// The partial file the recorder writes while the meeting runs.+ func record(_ store: SessionStore, _ id: String) {+ FileManager.default.createFile(atPath: AudioFileWriter.partial(store.systemAudioURL(id)).path, contents: Data(count: 1024))+ }++ @Test func aMeetingWithNothingSaidIsDropped() {+ let s = store()+ let id = s.begin().id+ record(s, id)+ s.end()+ #expect(s.session(id) == nil)+ #expect(!FileManager.default.fileExists(atPath: s.folder(id).path))+ }++ @Test func aRecordingWithSpeechIsKeptWithoutLines() {+ let s = store()+ let id = s.begin().id+ record(s, id)+ s.end(heardSpeech: true)+ #expect(s.session(id)?.hasAudio == true)+ #expect(FileManager.default.fileExists(atPath: AudioFileWriter.partial(s.systemAudioURL(id)).path))+ }++ @Test func speechWithoutARecordingLeavesNothingToKeep() {+ let s = store()+ let id = s.begin().id+ s.end(heardSpeech: true)+ #expect(s.session(id) == nil)+ }+}diff --git a/tools/README.md b/tools/README.mdindex f2552bc..88fed43 100644--- a/tools/README.md+++ b/tools/README.md@@ -26,6 +26,7 @@- AI:`aiKeyFile:<路径>`(从 0600 文件读 key,不经过日志;测完就删掉文件)、`aiCheck`、`aiRemove`、`aiHide:<on|off>`(只在内存里当作没有 key,文件不动;用于截图)、`aiState`、`lingSimulate:<429|hijack|timeout|off>`、`translateFail:<n>`(接下来 n 句在所有翻译来源都失败,用来测重试)- 声音:`voice:<语言>[=<id>]`、`voicePreview:<语言>=<id>`、`voiceCloneFile:<wav>`、`voicePicker:<on|off>`- 诊断:`diagnostics:<on|off>`、`diagReport`+ - 语音模型与“听不出”:`models:<已装,…>/<系统语言,…>` 假装本机只装了这些语音模型、系统是这些语言(`models:none/zh-Hans-CN` 是一个都没装,末尾加 `@<秒>` 让后台下载至少花这么久;之后下载的会加进来),`models:off` 回到真实情况;`source:<auto|locale>` 改“听到”(自动识别或指定语言),`pickLanguage:<locale>` 等于在“听不出”里点这种语言,`releaseModel:<locale>` 退还一个本 App 保留的语音模型。`modelFail:<offline|disk|limit|other>` 让之后的语音模型下载都按这个原因失败(`modelFail:off` 结束),`network:<on|off|real>` 假装断网、联网或跟随真实网络,`modelRetry` 等于点“再试一次”。用没装过的语言(比如法语)能测真实的后台下载;注意 macOS 每个 App 最多保留 5 种语音模型- 更新与登录项:`updateFeed:<url>`、`updateCheck`、`updateInstall`、`updateState`、`loginItem[:on|off]`- 完整、最新的清单以 `AppModel.debugCommand` 里的 `switch` 为准。