知了 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
refactor(ios): remove code comments
wquguru1d42919a49da
diff --git a/ios/LiveActivity/CicadaLive.swift b/ios/LiveActivity/CicadaLive.swiftindex d1ba704..04d43d0 100644--- a/ios/LiveActivity/CicadaLive.swift+++ b/ios/LiveActivity/CicadaLive.swift@@ -2,11 +2,6 @@ import ActivityKitimport SwiftUIimport WidgetKit-// The CicadaLive extension: draws ListenActivity (ios/Sources/Cicada/ListenActivity.swift) on the-// lock screen and in the Dynamic Island, and 开始听 in Control Center. Built by ios/scripts/build.sh-// into PlugIns/CicadaLive.appex. Its buttons are App Intents (ios/Sources/Cicada/Intents.swift),-// which run in the app.-@mainstruct CicadaLiveBundle: WidgetBundle {var body: some Widget {@@ -15,7 +10,6 @@ struct CicadaLiveBundle: WidgetBundle {}}-/// 开始听 in Control Center and on the lock screen.struct StartListeningControl: ControlWidget {var body: some ControlWidgetConfiguration {StaticControlConfiguration(kind: "com.indaloop.cicada.start") {@@ -28,7 +22,6 @@ struct StartListeningControl: ControlWidget {}}-/// 暂停 / 继续 and 结束并出纪要, on the lock screen and in the expanded Dynamic Island.private struct LiveButtons: View {let paused: Boolvar dark = false@@ -73,7 +66,6 @@ private struct LiveLogo: View {}}-/// The elapsed time, counting up from the start, ticked by the system.private struct Elapsed: View {let since: Datevar body: some View {@@ -85,7 +77,6 @@ private struct Elapsed: View {struct ListenLiveActivity: Widget {var body: some WidgetConfiguration {ActivityConfiguration(for: ListenActivity.self) { context in- // Lock screen: the logo, 正在听 · time, the languages, and the newest line.VStack(alignment: .leading, spacing: 10) {HStack(spacing: 10) {LiveLogo(size: 34)@@ -150,7 +141,6 @@ struct ListenLiveActivity: Widget {LiveLogo(size: 20)}} compactTrailing: {- // Paused: a still pause mark, not a clock that keeps running as if it were listening.if context.state.paused {Image(systemName: "pause.fill").font(.caption.weight(.semibold)).foregroundStyle(.white.opacity(0.6))} else {diff --git a/ios/Sources/Cicada/AIServicePage.swift b/ios/Sources/Cicada/AIServicePage.swiftindex df749e0..4f38ace 100644--- a/ios/Sources/Cicada/AIServicePage.swift+++ b/ios/Sources/Cicada/AIServicePage.swift@@ -1,19 +1,12 @@import SwiftUI-/// 设置 › AI 服务, as on the Mac and Android: Ling (recommended), OpenRouter, ZenMux, OpenAI or the-/// user's own OpenAI-compatible service. The settings are the Mac's (`aiProvider`, `aiModels`,-/// `aiVoiceModels`, `aiCustomBase`, Ling's model in `aiModel`), each service with its own key file.-/// The custom service here is the Mac's plain one: one address, a text model and optionally a speech-/// model; recognition stays on the phone, notes use the same server.enum AIPrefs {static let provider = "aiProvider"static let models = "aiModels"static let voiceModels = "aiVoiceModels"static let customBase = "aiCustomBase"- /// 语音和文字只发给你的服务, the Mac's key: with the user's own service, Google is never asked.static let customOnly = "aiCustomOnly"- /// Whether the translator leaves Google out: only with the user's own service and the switch on.static var googleOff: Bool { current.id == .custom && d.bool(forKey: customOnly) }private static var d: UserDefaults { .standard }@@ -21,12 +14,10 @@ enum AIPrefs {static var modelMap: [String: String] { d.dictionary(forKey: models) as? [String: String] ?? [:] }static var voiceMap: [String: String] { d.dictionary(forKey: voiceModels) as? [String: String] ?? [:] }- /// What `LingClient` calls with, as the Mac's `AppSettings.aiConfig`.static var config: AIConfig {let p = currentswitch p.id {case .ling:- // Ming speaks 面对面 with the same key: without the voice model, every turn fell back to the phone's voice.return AIConfig(provider: p, base: p.base, textModel: d.string(forKey: Pref.model) ?? p.textModels.first?.id ?? "",voiceModel: p.voiceModels.first?.id, voiceBase: p.base)case .custom:@@ -40,7 +31,6 @@ enum AIPrefs {}}- /// 面对面's voices follow the service: Ming's with Ling, the speech model's with the others.static func applyVoices() {let c = configswitch c.provider.id {@@ -107,7 +97,6 @@ struct AIServicePage: View {Card {NavigationLink { KeyPage() } label: {HStack(spacing: 8) {- // No key: the status beside it says so; this shows what a key looks like.Text(verbatim: ling.key.map { $0.isEmpty ? L("不用 key") : AIKey.masked($0) } ?? "sk-…").font(.body.monospaced()).foregroundStyle(ling.key == nil ? Ink.secondary : Ink.ink).lineLimit(1)Spacer()@@ -153,7 +142,6 @@ struct AIServicePage: View {.navigationBarTitleDisplayMode(.inline)}- /// 语音和文字只发给你的服务, as on the Mac: Google is never asked.private var onlyRow: some View {Toggle(isOn: Binding(get: { customOnly }, set: { customOnly = $0; model.aiChanged() })) {Text("语音和文字只发给你的服务").foregroundStyle(Ink.ink)@@ -162,7 +150,6 @@ struct AIServicePage: View {.padding(.horizontal, 16).frame(minHeight: 50)}- /// What the switch costs, and while the service can't be reached, what stands in.private var onlyDetail: String {let down: Boolswitch ling.keyState {@@ -228,8 +215,6 @@ struct AIServicePage: View {}extension LingClient {- /// Opening AI 服务 after a failed check asks again: what was wrong may have been fixed on the- /// service's side (a key's model list, its credit) without anything changing here.func recheckIfFailed() {switch keyState {case .invalid, .unreachable, .unchecked: Task { await check() }@@ -239,7 +224,6 @@ extension LingClient {}extension AppModel {- /// 改用 Ling: another service can't be reached and a Ling key is here.var canSwitchToLing: Bool { AIPrefs.current.id != .ling && AIKey.read("ling") != nil }func switchToLing() {@@ -248,8 +232,6 @@ extension AppModel {aiChanged()}- /// The service, its address or a model changed: LingClient checks again and 面对面 takes the- /// service's voices.func aiChanged() {AIPrefs.applyVoices()translator.googleOff = AIPrefs.googleOffdiff --git a/ios/Sources/Cicada/AutoEnd.swift b/ios/Sources/Cicada/AutoEnd.swiftindex 2a892a4..1c88bb7 100644--- a/ios/Sources/Cicada/AutoEnd.swift+++ b/ios/Sources/Cicada/AutoEnd.swift@@ -1,10 +1,5 @@import SwiftUI-/// 结束会议 by itself, as on the Mac and Android: the shared `MeetingEndWatch` ticked every two-/// seconds (every second while counting down). iOS can't see another app's microphone, so only-/// silence counts: nothing recognised for 多久算没人说话 → the countdown, then the meeting ends-/// where the words did and its notes are written. A meeting started from the Action Button or the-/// lock screen and forgotten would otherwise listen to an empty room for hours.extension AppModel {var endConfig: MeetingEndWatch.Config {let d = UserDefaults.standard@@ -40,12 +35,10 @@ extension AppModel {guard var w = endWatch, room.isRunning else { return }let now = Date()w.config = endConfig- // Words, not sound: a new line, or the line being said changing (paused: nothing counts).if !room.paused, room.lines.count != endHeard.lines || (room.draft != endHeard.draft && !room.draft.isEmpty) {w.heard(at: now)}endHeard = (room.lines.count, room.draft)- // Paused by the user: they chose to stop listening for now, so it isn't silence.if room.paused { w.keepGoing(at: now) }let reason = w.tick(at: now, calls: [:], said: !room.lines.isEmpty)endWatch = w@@ -58,14 +51,12 @@ extension AppModel {scheduleEndTick(w.pending != nil ? 1 : 2)}- /// 继续记录 on the countdown.func keepRecording() {endWatch?.keepGoing(at: Date())ending = nildebugLog("meeting end: kept going")}- /// Ends where the meeting really ended: a little after the last words.private func autoEnd(_ reason: MeetingEndWatch.Reason, _ w: MeetingEndWatch) {stopWatchingEnd()if reason == .nobodySpoke {@@ -82,7 +73,6 @@ extension AppModel {}}-/// The countdown above 正在听's pages: 已经 10 分钟没人说话 · 60 秒后结束会议并整理纪要 · 继续记录.struct EndingStrip: View {@EnvironmentObject var model: AppModel@@ -91,7 +81,6 @@ struct EndingStrip: View {HStack(spacing: 12) {VStack(alignment: .leading, spacing: 2) {Text(verbatim: model.endingTitle(p)).font(.subheadline.weight(.semibold)).foregroundStyle(Ink.ink)- // Counts down by itself; the watch decides when it is over.TimelineView(.periodic(from: .now, by: 1)) { t inText(L("\(max(0, Int(p.deadline.timeIntervalSince(t.date).rounded()))) 秒后结束会议并整理纪要")).font(.footnote).foregroundStyle(Ink.secondary).monospacedDigit()diff --git a/ios/Sources/Cicada/AutoGain.swift b/ios/Sources/Cicada/AutoGain.swiftindex d1bfafa..2877613 100644--- a/ios/Sources/Cicada/AutoGain.swift+++ b/ios/Sources/Cicada/AutoGain.swift@@ -1,18 +1,11 @@import AVFoundationimport MediaToolbox-/// Brings a room recording up to speech level. The microphone runs in `.measurement` (no system-/// gain, so the recognizer hears the room as it is), which leaves voices across a table at about-/// -45 dBFS: played back on the phone's speaker that is next to silence. Used on what is written-/// (`RoomAudio`) and, for recordings made before that, on what is played (`GainTap`).struct AutoGain {- /// Slow estimate of the speech level (RMS), and the gain now applied.private var level: Float = 0.02private var gain: Float = 1- /// About -22 dBFS for speech; at most +30 dB, so a quiet room's hiss stays quiet.private static let target: Float = 0.08, maxGain: Float = 32- /// Below this (-64 dBFS) a buffer is silence: it would pull the gain up to the cap.private static let floor: Float = 0.0006mutating func apply(_ p: UnsafeMutablePointer<Float>, count n: Int) {@@ -26,7 +19,6 @@ struct AutoGain {let rms = (sum / Float(n)).squareRoot()if rms > Self.floor { level += (rms - level) * (rms > level ? 0.3 : 0.05) }let want = min(max(Self.target / max(level, 1e-4), 1), Self.maxGain, 0.9 / max(peak, 1e-6))- // Down at once (a loud word must not clip), up slowly (no pumping between words).let to = want < gain ? want : gain + (want - gain) * 0.1let step = (to - gain) / Float(n)for i in 0..<n {@@ -37,7 +29,6 @@ struct AutoGain {}}-/// `AutoGain` on an `AVPlayerItem`'s audio, through an audio processing tap.enum GainTap {private final class State {var gain = AutoGain()@@ -64,7 +55,6 @@ enum GainTap {guard state.float else { return }for b in UnsafeMutableAudioBufferListPointer(buffers) {guard let data = b.mData else { continue }- // Interleaved channels are measured together: one gain for all of them.state.gain.apply(data.assumingMemoryBound(to: Float.self), count: Int(b.mDataByteSize) / MemoryLayout<Float>.size)}})diff --git a/ios/Sources/Cicada/CicadaApp.swift b/ios/Sources/Cicada/CicadaApp.swiftindex b537692..e6de8b3 100644--- a/ios/Sources/Cicada/CicadaApp.swift+++ b/ios/Sources/Cicada/CicadaApp.swift@@ -25,87 +25,61 @@ struct CicadaApp: App {enum AppTab: String { case records, settings, search }-/// Settings the iOS app shares with the Mac by name (AppSettings in Settings.swift), so a record-/// and its languages mean the same thing on both.enum Pref {- /// 对方说: "auto" or a `sourceLanguages` locale.static let source = "sourceMode"- /// 翻译成: "system" or a `targetLanguages` code.static let target = "target"static let model = "aiModel"- /// 说话人识别.static let voices = "speakerVoices"- /// 纪要语言: "mine" (the language meetings are translated into) or "source" (the meeting's own).static let notesLanguage = "notesLanguage"- /// 会中改正听错的词, and 没见过的名字和专称先问我.static let fixMisheard = "fixMisheard"static let askNames = "askNames"- /// 声音来源 (iOS only): "room", people at the table, or "speaker", video this phone plays aloud.static let hear = "iosHear"- /// 面对面's 我说: a `sourceLanguages` locale (对方说 is `source`, as when listening).static let myLang = "iosMyLang"- /// 第一次打开's three steps are done (or skipped).static let welcomed = "iosWelcomed"- /// 保存会议录音, the Mac's and Android's recordAudio.static let recordAudio = "recordAudio"- /// 没人说话时: "prompt" (count down, then end), "end" or "off"; 多久算没人说话 in minutes. The Mac's names.static let silenceEnd = "silenceEnd"static let silenceMinutes = "silenceMinutes"static var speakerMode: Bool { UserDefaults.standard.string(forKey: hear) == "speaker" }- /// 对方说 is 自动识别: listening and imports hear which language it is (LanguageDetector).static var sourceAuto: Bool { (UserDefaults.standard.string(forKey: source) ?? "auto") == "auto" }- /// 对方说 as one language: the one picked, or with 自动识别 the one heard last (the Mac's- /// lastDetected), else the likeliest for this phone. Face to face and model downloads use it.static var sourceLang: Lang {let v = UserDefaults.standard.string(forKey: source) ?? "auto"if let lang = sourceLanguages.first(where: { $0.locale == v }) { return lang }let last = UserDefaults.standard.string(forKey: lastDetected)return likelySourceLanguages(last: last, systemLanguages: Locale.preferredLanguages).first ?? sourceLanguages[0]}- /// The language 自动识别 heard last, as the Mac keeps it.static let lastDetected = "lastDetected"- /// 对方说 in the UI's language ("英语", "English"), as the Mac's menu shows it.static func name(of lang: Lang) -> String {Locale.current.localizedString(forLanguageCode: lang.code) ?? lang.name}- /// 对方说's code for 翻译成: with 自动识别, none yet (跟随系统 is my language until one is heard).static var sourceCode: String { sourceAuto ? "auto" : sourceLang.code }static var sourceName: String { sourceAuto ? L("自动识别") : name(of: sourceLang) }- /// "英 → 中" for two translation codes, as a meeting row says it.static func pairText(_ source: String, _ target: String) -> String {let line = TranscriptLine(id: "", t: 0, speaker: "them", src: "", dst: nil, srcLang: source, dstLang: target)let s = Session(id: "", title: "", startedAt: Date(), endedAt: nil, lines: [line], hasAudio: false)return RecordList.pair(s, short: true) ?? ""}- /// What a meeting in `source` is translated into, as the Mac's `AppSettings.resolvedTarget`:- /// 跟随系统 is my language, unless they speak it; then the next system language (English UI and- /// an English meeting would otherwise "translate" English into English).static func target(for source: String) -> String {let t = UserDefaults.standard.string(forKey: target) ?? "system"return t == "system" ? followSystemTarget(source: source, systemLanguages: Locale.preferredLanguages) : t}- /// The reader's own language (纪要's 我的语言).static var targetCode: String {let t = UserDefaults.standard.string(forKey: target) ?? "system"return t == "system" ? myLanguage(systemLanguages: Locale.preferredLanguages) : t}}-/// 改正听错的词's two switches, by the Mac's names (AppSettings).@MainActorfinal class FixPrefs: FixSwitches {var fixMisheard: Bool { UserDefaults.standard.bool(forKey: Pref.fixMisheard) }var askNames: Bool { UserDefaults.standard.bool(forKey: Pref.askNames) }}-/// Wires the shared engines to the screens, like the Mac's AppModel. M1: the records, the key and-/// their notes.@MainActorfinal class AppModel: ObservableObject {@Published var store = SessionStore()@@ -117,31 +91,23 @@ final class AppModel: ObservableObject {t.onHealth = { [weak self] h in self?.translationHealth = h }return t}()- /// Whether translation can be reached: the live page, the import card and 面对面 say so.@Published var translationHealth = TranslationHealth()- /// Finished sentences are going untranslated because nothing can be reached (no key, no- /// Google, no on-device model), so what is on screen is only the original.var translationDown: Bool { translationHealth.googleDown && translationHealth.sentencesUntranslated }lazy var room: RoomListen = {let r = RoomListen(store: store, translator: translator, notes: notes)r.onStateChange = { [weak self] in self?.listeningChanged() }r.onLine = { [weak self] line in self?.showOnLockScreen(line) }- // The floating window follows the 字幕 page: what is being said, else the newest line.roomWatch = r.objectWillChange.sink { [weak self] _ inDispatchQueue.main.async { self?.showInPiP() }}return r}()- /// 导入录音或视频: the Mac's importer, with the iOS app's languages.let importPrefs = ImportPrefs()- /// 存到文件夹 (FolderPage.swift): the Mac's exporter, writing into a folder picked in Files.let folderPrefs = FolderPrefs()lazy var folderExport = FolderExporter(store: store, settings: folderPrefs)@Published var showFolder = falselazy var importer: FileImporter = {- // 记住的人 name the voices of imported files too.let i = FileImporter(store: store, settings: importPrefs, translator: translator, profiles: profiles)- // As on the Mac: a file transcribed to the end gets its notes when there is a key.i.onFinished = { [weak self] id inguard let self else { return }self.folderExport.ended(id)@@ -153,66 +119,43 @@ final class AppModel: ObservableObject {ImportBackground.importer = ireturn i}()- /// 面对面同声传译 (FaceView), over everything while it is open.lazy var face = FaceToFace(store: store, translator: translator, ling: ling)@Published var showFace = false- /// 记住的人 (PeoplePage.swift): the Mac's voiceprint store, what it holds, and the last problem.let profiles = SpeakerProfileStore()@Published var speakerProfiles: [SpeakerProfile] = []@Published var speakerMemoryBusy = false@Published var speakerProblem: (String, String)?@Published var showPeople = false- /// The notes piece open for editing (NotesEdit.swift), and the meeting whose notes were just copied.@Published var noteEdit: NoteEdit?@Published var copiedNotes: String?- /// 设置 › AI 服务, pushed (a debug command opens it).@Published var showAIService = false- /// 设置 › 念给对方的声音, pushed (a debug command opens it).@Published var showVoices = false- /// 设置 › 快速开始, pushed (a debug command opens it).@Published var showQuickStart = false- /// The meeting whose 导出 sheet is open.@Published var exporting: String?- /// Why a picked file wasn't imported.@Published var importProblem: String?let pip = PiPSubtitles()private var roomWatch: AnyCancellable?let liveActivity = LiveActivityController()- /// 词表 and 改正听错的词, the Mac's own engines.let vocabulary = Vocabulary(url: Vocabulary.defaultURL)lazy var fixes = makeFixes()- /// 结束会议 by itself (AutoEnd.swift): the countdown on screen, and the watch behind it.@Published var ending: MeetingEndWatch.Pending?var endWatch: MeetingEndWatch?var endTimer: Timer?var endHeard = (lines: 0, draft: "")- /// Debug (`endTimes:<silence>,<countdown>`): seconds instead of minutes, to test it.var endTimesOverride: (Double, Double)?- /// 正在听's 字幕 / 纪要 switch, so a debug command can flip it.@Published var livePage: LivePage = .subtitles- /// 收起 on the iPhone's 正在听: the meetings again while listening goes on; the bar brings it back.@Published var liveHidden = false- /// The record page's picked speaker (scheme A: only they are drawn in ink).@Published var focusSpeaker: Int?@Published var tab: AppTab = .records@Published var selection: String? { didSet { if selection != oldValue { recordPage = firstPage(selection) } } }- /// A meeting opened from 搜索 (iPhone).@Published var searchPath: [String] = [] { didSet { if searchPath.last != oldValue.last { recordPage = firstPage(searchPath.last) } } }- /// The record page's 文字记录 / 纪要 switch, kept here so a debug command can flip it.@Published var recordPage: RecordPage = .transcript@Published var query = ""- /// Which of the open meeting's matches the search is on (#33: a search opens the line, not just the meeting).@Published var searchMatch = 0- /// iPad: settings is a sheet over the records.@Published var showSettings = false- /// What the 听会议室 card and the import button would start; they come with M2 and M3.@Published var comingSoon: String?- /// "说话人 6 已改成 David · 撤销", for a few seconds after a speaker edit, as on the Mac.@Published var speakerUndo: SpeakerUndo?- /// The speaker number whose 是谁 prompt is open on the record page.@Published var namingSpeaker: Int?- /// 改正听错的词: the line being rewritten (改这句…), the record line tapped open, and 设置 › 词表's- /// state (pushed, 粘贴导入's text, the word being edited, the word just deleted).@Published var editingLine: LineEdit?@Published var openLine: String?@Published var showWordList = false@@ -220,10 +163,8 @@ final class AppModel: ObservableObject {@Published var editingWord: String?@Published var deletedWord: DeletedWord?@Published var wordConflict: WordConflict?- /// 第一次打开 (Welcome.swift) and its step.@Published var showWelcome = !UserDefaults.standard.bool(forKey: Pref.welcomed)@Published var welcomeStep = 0- /// Dev only: the iPad window size `window:` lays the app out at (DevWindow in Debug.swift).@Published var devWindow: CGSize?init() {@@ -231,12 +172,10 @@ final class AppModel: ObservableObject {Pref.fixMisheard: true, Pref.askNames: true, Pref.recordAudio: true,Pref.silenceEnd: "prompt", Pref.silenceMinutes: 10.0])TranscriptExport.voices = UserDefaults.standard.bool(forKey: Pref.voices)- // 设置 › AI 服务 (AIServicePage.swift): the Mac's services and settings.ling.config = { AIPrefs.config }AIPrefs.applyVoices()translator.googleOff = AIPrefs.googleOffwireNotes()- // 存到文件夹, as the Mac's AppModel: a meeting is written once settled and rewritten when it changes.folderExport.settling = { [weak self] id in self?.notes.settling(id) ?? false }store.onSave = { [weak self] id in self?.folderExport.saved(id) }notes.finalDone = { [weak self] id in self?.folderExport.settled(id) }@@ -262,7 +201,6 @@ final class AppModel: ObservableObject {liveHidden = falsesearchPath = []tab = .records- // 纪要 first, as the Mac's notes window; without a key there are none, so 字幕.livePage = ling.hasKey ? .notes : .subtitlesfixes.meetingStarted()room.start(source: Pref.sourceAuto ? "auto" : Pref.sourceLang.locale, target: Pref.target(for: Pref.sourceCode), voices: UserDefaults.standard.bool(forKey: Pref.voices),@@ -284,14 +222,12 @@ final class AppModel: ObservableObject {func stopListening() { room.stop() }- /// The Live Activity shows the line as fixed (改正听错的词), like the 字幕 page.func showOnLockScreen(_ line: RoomListen.Line) {var shown = lineif let rec = store.session(room.sessionID)?.lines.first(where: { $0.id == line.id }) { shown.src = rec.shown }liveActivity.update(line: shown)}- /// 快速开始 and the Live Activity's buttons.func intent(_ action: IntentHub.Action) {debugLog("intent: \(action)")switch action {@@ -317,23 +253,18 @@ final class AppModel: ObservableObject {}}- /// 纪要 first, as on the Mac; a meeting without notes opens on its 文字记录.private func firstPage(_ id: String?) -> RecordPage {store.session(id)?.notes == nil ? .transcript : .notes}- /// Full notes for a stored meeting, as the Mac's 生成纪要.func generateNotes(_ id: String) {guard ling.hasKey else { return }recordPage = .notesnotes.generate(for: id)}- /// Each finished sentence's translation also asks which words were misheard (Ling only); the- /// word list's known forms are fixed as soon as a line is written. As the Mac's AppModel.func wireFixes() {translator.fixContext = { [weak self] text in self?.fixes.context(for: text) }- // 复制诊断信息 (设置): the Mac's recorder, in memory only. Timings and counts, never text.diagnostics.enabled = { true }ling.onCall = { [weak self] in self?.diagnostics.record($0) }translator.onDraft = { [weak self] in self?.diagnostics.recordDraft(seconds: $0, ok: $1) }@@ -346,7 +277,6 @@ final class AppModel: ObservableObject {func makeFixes() -> LiveFixes {let f = LiveFixes(store: store, vocabulary: vocabulary, settings: FixPrefs())f.onChange = { [weak self] in self?.objectWillChange.send() }- // The lock screen follows a fix on the line it shows.f.onLineFixed = { [weak self] session, line inguard let self, session == self.room.sessionID, let last = self.room.lines.last, last.id == line.id else { return }self.showOnLockScreen(last)@@ -361,7 +291,6 @@ final class AppModel: ObservableObject {// MARK: Notes language (the Mac's AppModel.notesLanguageCode)- /// The language the other side spoke most in a meeting.func meetingLanguage(_ id: String) -> String? {let heard = store.session(id)?.lines.filter { $0.speaker != "me" }.map(\.srcLang) ?? []return Dictionary(heard.map { ($0, 1) }, uniquingKeysWith: +).max { $0.value < $1.value }?.key@@ -373,7 +302,6 @@ final class AppModel: ObservableObject {// MARK: Editing a record (the Mac's rules live in SessionStore)- /// An unchanged title isn't a rename; an empty one goes back to the automatic title.func rename(_ id: String, to title: String) {store.rename(id, to: title)debugLog("rename \(id) renamed=\(store.session(id)?.renamed ?? false)")@@ -392,7 +320,6 @@ final class AppModel: ObservableObject {// MARK: 词表- /// Swiped away: 撤销 in its place for a few seconds, as on the Mac.func deleteWord(_ t: Vocabulary.Term) {let index = vocabulary.terms.firstIndex(of: t) ?? 0vocabulary.remove(t.word)@@ -404,7 +331,6 @@ final class AppModel: ObservableObject {}}- /// A heard form typed on a word: added, or, when another word has it, asked about (改给 / 两个都留).func addHeard(_ text: String, to t: Vocabulary.Term) {let h = text.trimmingCharacters(in: .whitespaces)guard !h.isEmpty, h.count <= 40 else { return }@@ -417,7 +343,6 @@ final class AppModel: ObservableObject {// MARK: Speakers (the Mac's AppModel.renameSpeaker / mergeSpeaker / undoSpeakerEdit)- /// Name a voice ("" keeps 说话人 N, nil goes back to Ling's guess).func renameSpeaker(session id: String, voice: Int, _ name: String?) {guard let s = store.session(id) else { return }let n = SpeakerLabels.voiceNumbers(s)[voice] ?? 0@@ -427,7 +352,6 @@ final class AppModel: ObservableObject {if after != before { speakerUndo?.text = L("\(before) 已改成 \(after)") } else { speakerUndo = nil }}- /// Two voices are one person.func mergeSpeaker(session id: String, _ from: Int, into: Int) {guard let s = store.session(id) else { return }let numbers = SpeakerLabels.voiceNumbers(s), names = SpeakerLabels.names(s)@@ -454,7 +378,6 @@ final class AppModel: ObservableObject {}}- /// cicada-dev://debug?cmd=… (dev builds only).func open(_ url: URL) {guard DevBuild.isDev, url.scheme == "cicada-dev", url.host == "debug",let cmd = URLComponents(url: url, resolvingAgainstBaseURL: false)?@@ -464,7 +387,6 @@ final class AppModel: ObservableObject {}extension AppModel {- /// 复制诊断信息: the Mac's numbers, with the phone and system they came from. Safe to paste anywhere.var diagnosticsReport: String {var sys = utsname()uname(&sys)diff --git a/ios/Sources/Cicada/Components.swift b/ios/Sources/Cicada/Components.swiftindex cd9e939..966481a 100644--- a/ios/Sources/Cicada/Components.swift+++ b/ios/Sources/Cicada/Components.swift@@ -1,9 +1,5 @@import SwiftUI-// The pieces the design canvas (知了 iOS 设计) is built from: white cards on the grey ground,-// grey section labels, a grey pill switch, hairlines, and Liquid Glass for what floats.--/// A white card, the design's 22 pt corners.struct Card<Content: View>: View {var radius: CGFloat = 22@ViewBuilder var content: Content@@ -15,7 +11,6 @@ struct Card<Content: View>: View {}}-/// The grey label above a card ("今天", "AI 服务").struct SectionLabel: View {let text: String@@ -29,7 +24,6 @@ struct SectionLabel: View {}}-/// The 0.5 pt line between rows in a card, inset like the design's.struct Hairline: View {var inset: CGFloat = 16@@ -38,7 +32,6 @@ struct Hairline: View {}}-/// The design's two-way switch: a grey track, the picked side a white pill with a soft shadow.struct PillSwitch<Value: Hashable>: View {@Binding var selection: Valuelet options: [(Value, LocalizedStringKey)]@@ -70,7 +63,6 @@ struct PillSwitch<Value: Hashable>: View {}}-/// A row's trailing chevron.struct Chevron: View {var body: some View {Image(systemName: "chevron.right")@@ -80,7 +72,6 @@ struct Chevron: View {}}-/// The design's round glass buttons (back, import, the trailing pair on a record): 44 pt, ink icon.struct GlassIcon: View {let systemName: Stringvar size: CGFloat = 44@@ -94,7 +85,6 @@ struct GlassIcon: View {}}-/// Lays out chips left to right and wraps, so every voice shows without scrolling sideways.struct FlowLayout: Layout {var spacing: CGFloat = 8diff --git a/ios/Sources/Cicada/Debug.swift b/ios/Sources/Cicada/Debug.swiftindex d28b43f..df81e6c 100644--- a/ios/Sources/Cicada/Debug.swift+++ b/ios/Sources/Cicada/Debug.swift@@ -2,10 +2,6 @@ import SwiftUIimport UIKitimport os-/// The iOS side of the Mac's `AppModel.debugCommand`. `ios/scripts/ctl.sh <cmd>` writes the command-/// into the container's Caches/debug-command and posts a Darwin notification, which wakes us here;-/// `simctl openurl` with cicada-dev://debug?cmd=… works too but asks for confirmation every time.-/// Same names as on the Mac where the command means the same thing.enum DebugChannel {static let name = "com.indaloop.cicada.debug" as CFStringstatic var file: URL {@@ -22,7 +18,6 @@ enum DebugChannel {}, name, nil, .deliverImmediately)}- /// One command per line, run in order.@MainActor static func drain(_ model: AppModel) {guard let text = try? String(contentsOf: file, encoding: .utf8) else { return }try? FileManager.default.removeItem(at: file)@@ -31,7 +26,6 @@ enum DebugChannel {}extension AppModel {- /// The meeting a fix command means: the live one, else the open one, else the newest.private var fixSession: String { store.liveID ?? selection ?? store.sessions.first?.id ?? "" }func debugCommand(_ cmd: String) {@@ -42,7 +36,6 @@ extension AppModel {tab = .recordsselection = nilcase "settings":- // iPhone: the tab; iPad: the sheet (the app can't tell which from here, so both).tab = .settingsshowSettings = truecase "closeSettings":@@ -51,7 +44,6 @@ extension AppModel {case "listen", "start":startListening()case "window":- // window:half|landscape|landscapeHalf|full: the iPad window drawn at that size (DevWindow).let s = UIApplication.shared.connectedScenes.compactMap { ($0 as? UIWindowScene)?.screen.bounds.size }.first ?? .zerolet (short, long) = (min(s.width, s.height), max(s.width, s.height))switch arg {@@ -64,13 +56,10 @@ extension AppModel {case "stop":stopListening()case "pause":- // pause:on|off, the bar's 暂停 / 继续room.setPaused(arg != "off")case "liveHidden":- // liveHidden:on|off, 正在听's 收起 / tapping the barliveHidden = arg != "off"case "welcome":- // welcome:<0|1|2> opens 第一次打开 at that step; welcome:done closes it as 开始用知了 doesif arg == "done" { finishWelcome() } else { welcomeStep = Int(arg) ?? 0; showWelcome = true }case "samplePlay":welcomeStep = 1@@ -79,45 +68,35 @@ extension AppModel {case "sampleStop":stopSample()case "import":- // import:<path>[|<path>…], as if picked in Files: a file on the Mac the simulator runs on,- // or, relative, one copied into the app's container on a device (devicectl device copy to)importFiles(arg.split(separator: "|").map {$0.hasPrefix("/") ? URL(fileURLWithPath: String($0)) : URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent(String($0))})case "importStop":if let id = importer.current?.id { importer.cancel(id) }case "importRetry":- // importRetry:<id>[=<locale>], as on the Mac: 重新转写 (in that language).let parts = arg.split(separator: "=", maxSplits: 1).map(String.init)retranscribe(parts[0], lang: parts.count > 1 ? sourceLanguages.first { $0.locale == parts[1] } : nil)case "importExpire":- // What the system's expiration handler does when it takes the background time back.importer.cancelAll()case "hear":- // hear:room|speaker, 声音来源UserDefaults.standard.set(arg == "speaker" ? "speaker" : "room", forKey: Pref.hear)case "interrupt":- // interrupt:began|ended, what the system sends for a call or Siriroom.debugInterrupt(arg != "ended")case "quickStart":tab = .settingsshowSettings = trueshowQuickStart = arg != "off"case "intent":- // intent:start|stop|pause, as the Action button, Siri or the Live Activity's buttonsIntentHub.send(arg == "stop" ? .stop : arg == "pause" ? .togglePause : .start)case "pip":pip.start()case "livePage":livePage = arg == "notes" ? .notes : .subtitlescase "source":- // source:<locale>, 对方说 (en-US, ja-JP…)UserDefaults.standard.set(arg, forKey: Pref.source)case "target":- // target:<code|system>, 翻译成UserDefaults.standard.set(arg, forKey: Pref.target)case "focusSpeaker":- // focusSpeaker:<speaker number>, as tapping a chip; empty clears itfocusSpeaker = Int(arg)case "play":NotificationCenter.default.post(name: .debugPlay, object: Double(arg) ?? 0)@@ -127,17 +106,14 @@ extension AppModel {query = arglogSearch()case "searchOpen":- // searchOpen:<id>, as tapping a meeting in 搜索's results (no id: the first found)tab = .searchlet found = SearchView.matches(store.sessions, query)searchPath = [arg.isEmpty ? found.first?.id : arg].compactMap { $0 }logSearch()case "searchStep":- // searchStep:<1|-1>, 下一个 / 上一个 in the open meetingif let s = store.session(searchPath.last ?? selection ?? store.sessions.first?.id) { stepSearch(Int(arg) ?? 1, in: s) }logSearch()case "mainShow":- // mainShow:<id>[,transcript|notes]; an empty id is the newest meetinglet parts = arg.split(separator: ",", omittingEmptySubsequences: false).map(String.init)tab = .recordsselection = parts.first.flatMap { id in store.sessions.contains(where: { $0.id == id }) ? id : nil }@@ -153,10 +129,8 @@ extension AppModel {wireNotes()fixes = makeFixes()case "generateNotes":- // generateNotes:<id>, as the record page's 生成纪要 (needs a key).generateNotes(arg.isEmpty ? (selection ?? store.sessions.first?.id ?? "") : arg)case "rename":- // rename:<id>,<title> (an empty title goes back to the automatic one)let parts = arg.split(separator: ",", maxSplits: 1, omittingEmptySubsequences: false).map(String.init)rename(parts[0], to: parts.count > 1 ? parts[1] : "")case "delete":@@ -168,45 +142,34 @@ extension AppModel {case "notesLang":UserDefaults.standard.set(arg, forKey: Pref.notesLanguage)case "nameSpeaker":- // nameSpeaker:<id>,<voice>,<name>let p = arg.split(separator: ",", maxSplits: 2, omittingEmptySubsequences: false).map(String.init)if p.count == 3, let v = Int(p[1]) { renameSpeaker(session: p[0], voice: v, p[2]) }case "mergeSpeaker":- // mergeSpeaker:<id>,<from voice>,<into voice>let p = arg.split(separator: ",").map(String.init)if p.count == 3, let a = Int(p[1]), let b = Int(p[2]) { mergeSpeaker(session: p[0], a, into: b) }case "speakerPrompt":- // speakerPrompt:<speaker number>: the 是谁 prompt a chip's 改名字 opensnamingSpeaker = Int(arg)case "undoSpeaker":undoSpeakerEdit()- // 改正听错的词, by the Mac's names: switches, the word list, and the fixes of a meeting- // (the live one, or `<id>`, else the open one or the newest).case "fixes": UserDefaults.standard.set(arg != "off", forKey: Pref.fixMisheard)case "askNames": UserDefaults.standard.set(arg != "off", forKey: Pref.askNames)case "silentListen":- // A meeting without the microphone or the recognizer, fed lines by `heard:`.RoomListen.silent = arg != "off"case "heard": room.debugHeard(arg)case "modelFail":- // modelFail:<offline|disk|limit|other>: the next speech model download fails that way, as on the Mac.RoomListen.simulatedModelFailure = arg.isEmpty ? nil : argcase "recordTrack":- // recordTrack:on|off, 会后重听 for the next meeting (as the Mac's lsctl recordTrack:off).RoomListen.recordTrackOff = arg == "off"case "diag":debugLog("diag report:\n" + diagnosticsReport)case "switchToLing":switchToLing()case "startRetry":- // 再试一次 on the card under 开始听.room.retry()case "aiCustomOnly":- // aiCustomOnly:on|off, 语音和文字只发给你的服务, as on the Mac.UserDefaults.standard.set(arg == "on", forKey: AIPrefs.customOnly)aiChanged()case "aiService":- // aiService:<ling|openrouter|zenmux|openai|custom>[,<text model>]; aiService opens the pagelet p = arg.split(separator: ",", maxSplits: 1).map(String.init)if let k = p.first, !k.isEmpty {UserDefaults.standard.set(k, forKey: AIPrefs.provider)@@ -217,7 +180,6 @@ extension AppModel {showSettings = trueshowAIService = truecase "exportTo":- // exportTo:<folder in the app container>|off, as picking it in Files; exportAll; exportStateif arg == "off" { folderExport.turnOff() } else {let url = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent(arg, isDirectory: true)try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)@@ -232,7 +194,6 @@ extension AppModel {debugLog("folder export: on=\(x.on) folder=\(x.folder?.lastPathComponent ?? "-") files=\(x.index.files.count) pending=\(x.index.pending.count) last=\(x.index.lastFile ?? "-") problem=\(x.problem.map { "\($0)" } ?? "-")")case "aiBase": UserDefaults.standard.set(arg, forKey: AIPrefs.customBase); aiChanged()case "voices":- // voices[:off] opens 设置 › 念给对方的声音; voice:<lang>=<id> picks one; voiceSay:<lang> reads a sampletab = .settingsshowSettings = trueshowVoices = arg != "off"@@ -241,7 +202,6 @@ extension AppModel {if p.count == 2 { SpeakVoices.set(p[1], for: p[0]); objectWillChange.send() }debugLog("voices: \(SpeakVoices.all) own=\(VoiceReference.exists)")case "share":- // share:notes|full shares the open meeting (else the newest) as 分享链接 does; unshare revokes itguard let s = store.session(selection ?? store.sessions.first?.id) else { break }Task {switch await ShareClient.shared.share(s, .init(scope: arg == "full" ? .full : .notes)) {@@ -254,7 +214,6 @@ extension AppModel {guard let id = selection ?? store.sessions.first?.id, let r = ShareStore.read(id) else { break }Task { debugLog("share: revoked \(await ShareClient.shared.revoke(r, sessionID: id))") }case "endTimes":- // endTimes:<silence>,<countdown> in seconds (结束会议 by itself, to test it); endTimes:offlet p = arg.split(separator: ",").compactMap { Double($0) }endTimesOverride = p.count == 2 ? (p[0], p[1]) : nildebugLog("meeting end: times \(String(describing: endTimesOverride))")@@ -262,19 +221,16 @@ extension AppModel {debugLog("meeting end: pending=\(ending.map { "\($0.reason)" } ?? "-") watching=\(endWatch != nil)")case "keepRecording": keepRecording()case "translateFail":- // translateFail:<n>: the next n sentences fail on every provider, as on the Mac.translator.failNext = Int(arg) ?? 1case "googleDown":- // googleDown:<on|off>: Google fails as if there were no proxy, as on the Mac.translator.simulateGoogleDown = arg != "off"case "aiHide":- // aiHide:<on|off>: the key file stays; the app behaves as if there were none, as on the Mac.ling.hideKey = arg != "off"objectWillChange.send()case "heardT":let p = arg.split(separator: "|", maxSplits: 1).map(String.init)if p.count == 2 { room.debugHeard(p[0], translation: p[1]) }- case "vocabAdd": // vocabAdd:Morpho=莫拉、莫法 (several lines with "|")+ case "vocabAdd":let r = vocabulary.importText(arg.replacingOccurrences(of: "|", with: "\n"))debugLog("vocab: added=\(r.added) updated=\(r.updated) skipped=\(r.skipped)")case "vocabRemove": vocabulary.remove(arg)@@ -290,8 +246,6 @@ extension AppModel {for l in lines where l.fixes != nil {contentLog("FIXED \(l.id) \(l.fixes!.map { "\($0.from)→\($0.to)\($0.ask == true ? "?" : $0.off == true ? "✗" : "")" }) | \(l.shown)")}- // What the AI service would propose for a live line, without asking it (no key needed):- // proposeFix:<line id>=<from>><to>@<confidence>[|…]case "proposeFix":let p = arg.split(separator: "=", maxSplits: 1).map(String.init)guard p.count == 2, let id = store.liveID, let l = store.session(id)?.lines.first(where: { $0.id == p[0] }) else { break }@@ -302,14 +256,13 @@ extension AppModel {return Correction.Edit(from: ft[0], to: tc[0], confidence: tc.count > 1 ? Double(tc[1]) ?? 0.9 : 0.9)}fixes.received(l.src, edits)- case "fixAnswer": // fixAnswer:yes|no[,<id>]+ case "fixAnswer":let parts = arg.split(separator: ",", maxSplits: 1).map(String.init)let id = parts.count > 1 ? parts[1] : fixSessionif let first = fixes.asking(in: id) ?? fixes.pending(in: id).first.map({ ($0.line, $0.fix, 1, 1) }) {fixes.answer(first.fix, yes: parts.first == "yes", in: id)}- // The recheck without audio: line `<id>` settles as `<text>` and is translated (and fixed) again.- case "resettle": // resettle:<line id>=<text>+ case "resettle":let p = arg.split(separator: "=", maxSplits: 1).map(String.init)guard p.count == 2, let id = store.liveID, let rec = store.session(id)?.lines.first(where: { $0.id == p[0] }) else { break }store.setSource(in: id, lineID: rec.id, p[1])@@ -322,7 +275,7 @@ extension AppModel {let id = arg.isEmpty ? store.liveID ?? "" : argif let a = fixes.asking(in: id) { fixes.later(a.fix, in: id) }case "fixUndo": fixes.undo()- case "fixEdit": // fixEdit:<line id>=<new text>[|one|keep0][,<session id>]+ case "fixEdit":let (head, sid) = { () -> (String, String) inif let c = arg.lastIndex(of: ","), !arg[arg.index(after: c)...].contains("=") { return (String(arg[..<c]), String(arg[arg.index(after: c)...])) }return (arg, fixSession)@@ -332,17 +285,15 @@ extension AppModel {let opts = p[1].split(separator: "|").map(String.init)let n = fixes.edit(lineID: p[0], in: sid, to: opts[0], everywhere: !opts.contains("one"), remember: !opts.contains("keep0"))debugLog("fix edit changed \(n) lines")- case "fixRevert": // fixRevert:<line id>[,<session id>]: the line's first applied fix+ case "fixRevert":let parts = arg.split(separator: ",", maxSplits: 1).map(String.init)let id = parts.count > 1 ? parts[1] : fixSessionif let l = store.session(id)?.lines.first(where: { $0.id == parts.first }), let f = l.fixes?.first(where: \.applied) {fixes.revert(f, lineID: l.id, in: id)}- // The fix screens, for screenshots: a record line tapped open, 改这句… on a line (of the open- // record), 设置 › 词表, 粘贴导入 with text ("|" for new lines), a word opened, a word swiped away.case "openLine": openLine = arg.isEmpty ? nil : argcase "scrollTo": NotificationCenter.default.post(name: .debugScroll, object: arg)- case "fixEditor": // fixEditor:<line id>[=<start text>]+ case "fixEditor":let p = arg.split(separator: "=", maxSplits: 1).map(String.init)let sid = selection ?? fixSessionif let l = store.session(sid)?.lines.first(where: { $0.id == p.first }) {@@ -355,25 +306,21 @@ extension AppModel {showWordList = arg != "off"case "wordImport": wordImport = arg == "off" ? nil : arg.replacingOccurrences(of: "|", with: "\n")case "wordEdit": editingWord = arg.isEmpty ? nil : arg- case "wordHeard": // wordHeard:<word>=<heard form>, as typed on an opened word+ case "wordHeard":let p = arg.split(separator: "=", maxSplits: 1).map(String.init)if p.count == 2, let t = vocabulary.terms.first(where: { $0.word == p[0] }) { addHeard(p[1], to: t) }case "wordDelete":if let t = vocabulary.terms.first(where: { $0.word == arg }) { deleteWord(t) }case "export":- // export:[markdown|word|srt] opens 导出 on the open meeting (else the newest) with that formatlet id = selection ?? store.sessions.first?.idif !arg.isEmpty { UserDefaults.standard.set(arg, forKey: "iosExportFormat") }selection = idexporting = idcase "exportFile":- // exportFile:<format>[,<id>]: writes the file and logs its path, for checking it on the Maclet p = arg.split(separator: ",").map(String.init)if let f = ExportFormat(rawValue: p.first ?? ""), let s = store.session(p.count > 1 ? p[1] : selection ?? store.sessions.first?.id) {debugLog("export file: \((try? f.file(s).path) ?? "failed")")}- // 面对面: face opens it, faceClose ends it; faceSay:<me|them>=<text> is a press heard as that- // text without the microphone; facePress / faceRelease:<me|them> hold and let go for real.case "face": openFace()case "faceClose": closeFace()case "faceSay":@@ -383,14 +330,12 @@ extension AppModel {face.press(side)face.release(side)case "faceTurn":- // faceTurn:<me|them>=<said>|<translation>let p = arg.split(separator: "=", maxSplits: 1).map(String.init)let q = p.count == 2 ? p[1].split(separator: "|", maxSplits: 1).map(String.init) : []if q.count == 2, let side = FaceToFace.Side(rawValue: p[0]) { face.debugTurn(side, said: q[0], translation: q[1]) }case "facePress":if let side = FaceToFace.Side(rawValue: arg) { face.press(side) }case "faceRelease": if let side = FaceToFace.Side(rawValue: arg) { face.release(side) }case "faceLangs":- // faceLangs:<my locale>,<their locale>let p = arg.split(separator: ",").map(String.init)if p.count == 2, let m = FaceToFace.lang(p[0]), let t = FaceToFace.lang(p[1]) { face.setLanguages(mine: m, theirs: t) }case "faceHandsFree": face.setHandsFree(arg != "off")@@ -398,13 +343,11 @@ extension AppModel {case "copyNotes":if let s = store.session(selection ?? store.sessions.first?.id) { copyNotes(s) }case "noteEdit":- // noteEdit:<summary|n>[=<text>]: opens that piece of the open meeting's notes; with text, saves itlet p = arg.split(separator: "=", maxSplits: 1).map(String.init)let target: NoteEdit.Target = p.first == "summary" ? .summary : .item(Int(p.first ?? "") ?? 0)guard let id = selection ?? store.sessions.first?.id else { break }if p.count == 2 { saveNote(id, target, text: p[1]) } else { noteEdit = NoteEdit(session: id, target: target) }case "remember":- // remember:<voice>=<name> remembers that voice of the open meeting (no confirmation: debug)let p = arg.split(separator: "=", maxSplits: 1).map(String.init)if p.count == 2, let v = Int(p[0]), let id = selection ?? store.sessions.first?.id { rememberSpeaker(session: id, voice: v, name: p[1]) }case "voiceState":@@ -430,7 +373,6 @@ extension AppModel {}}- /// After the open meeting has settled: how many meetings the search finds, and where it is in the open one.private func logSearch() {DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { [self] inlet found = SearchView.matches(store.sessions, query)@@ -444,9 +386,6 @@ extension AppModel {}}-/// Dev only: the iPad windows the simulator can't be put into from a script. There is no-/// Simulator.app to rotate it, iPadOS refuses a programmatic rotation in windowed mode, and no API-/// sizes a window. So the app is laid out at that window's size and size class, scaled to fit.struct DevWindow: ViewModifier {@ObservedObject var model: AppModel@@ -455,7 +394,6 @@ struct DevWindow: ViewModifier {GeometryReader { geo inlet scale = min(1, geo.size.width / size.width, geo.size.height / size.height)content- // iPadOS gives a window regular width from about 678 points..environment(\.horizontalSizeClass, size.width >= 678 ? .regular : .compact).frame(width: size.width, height: size.height).clipShape(RoundedRectangle(cornerRadius: 22, style: .continuous))@@ -474,9 +412,6 @@ private extension Array where Element == String {var splitPair: (String, String) { (first ?? "", count > 1 ? self[1] : "") }}-/// What the phone has left while listening: how much the app takes, how much more it may take before-/// iOS ends it, and how warm it runs. Logged by `state` so a real-device pass can show whether a-/// second recognizer (the record's) fits.enum DeviceLoad {static var footprintMB: Int {var info = task_vm_info_data_t()diff --git a/ios/Sources/Cicada/DevBuild.swift b/ios/Sources/Cicada/DevBuild.swiftindex 742242d..7983e74 100644--- a/ios/Sources/Cicada/DevBuild.swift+++ b/ios/Sources/Cicada/DevBuild.swift@@ -1,15 +1,10 @@import Foundation-/// The iOS counterpart of the Mac's `DevBuild` and `debugLog` (`Sources/Cicada/DevBuild.swift`,-/// `Settings.swift`): the shared sources call them by the same names. No /tmp on iOS, so the log-/// lives in the app container, where `xcrun simctl get_app_container booted <id> data` finds it.enum DevBuild {- /// Where it came from ("main @ 1b3d7f7"), or nil for a release build.static let label: String? = Bundle.main.object(forInfoDictionaryKey: "LiveSubsDev") as? Stringstatic var isDev: Bool { label != nil }- /// Folder name under Application Support, kept the same as on the Mac.static var supportFolder: String { isDev ? "LiveSubs Dev" : "LiveSubs" }static var logPath: String {@@ -30,7 +25,6 @@ func debugLog(_ message: String) {}}-/// Transcript content is only logged when the `debug` default is on, as on the Mac.func contentLog(_ message: @autoclosure () -> String) {if UserDefaults.standard.bool(forKey: "debug") { debugLog(message()) }}diff --git a/ios/Sources/Cicada/Export.swift b/ios/Sources/Cicada/Export.swiftindex 10d0ed7..a1581aa 100644--- a/ios/Sources/Cicada/Export.swift+++ b/ios/Sources/Cicada/Export.swift@@ -1,9 +1,6 @@import SwiftUIimport UniformTypeIdentifiers-// 导出: Markdown and SRT are the Mac's own (TranscriptExport); Word is written here, since the Mac's-// `.officeOpenXML` writer is macOS-only. Same order and content as the Mac's `TranscriptExport.docx`.-enum ExportFormat: String, CaseIterable, Identifiable {case markdown, word, srtvar id: String { rawValue }@@ -16,7 +13,6 @@ enum ExportFormat: String, CaseIterable, Identifiable {}}- /// The file, under a temporary folder, named after the meeting.@MainActor func file(_ s: Session) throws -> URL {let dir = FileManager.default.temporaryDirectory.appendingPathComponent("export-\(UUID().uuidString)")try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)@@ -31,15 +27,13 @@ enum ExportFormat: String, CaseIterable, Identifiable {}}-/// A minimal .docx: three XML parts in a zip, stored uncompressed (Word reads that fine), no-/// third-party code.enum Docx {struct Para {var text: String- var size: Int // points+ var size: Intvar bold = falsevar grey = false- var after = 4 // points after+ var after = 4}@MainActor static func document(_ s: Session) -> Data {@@ -98,7 +92,6 @@ enum Docx {}static func escape(_ s: String) -> String {- // Control characters other than tab are not allowed in XML 1.0.let clean = String(String.UnicodeScalarView(s.unicodeScalars.filter { $0.value >= 0x20 || $0 == "\t" }))return clean.replacingOccurrences(of: "&", with: "&").replacingOccurrences(of: "<", with: "<").replacingOccurrences(of: ">", with: ">")@@ -107,7 +100,6 @@ enum Docx {static let contentTypes = #"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#static let rels = #"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#- /// A zip with every entry stored (method 0).static func zip(_ entries: [(String, String)]) -> Data {var out = Data(), central = Data()func u16(_ v: Int, _ d: inout Data) { d.append(contentsOf: [UInt8(v & 0xFF), UInt8(v >> 8 & 0xFF)]) }@@ -115,7 +107,6 @@ enum Docx {for (name, text) in entries {let data = Data(text.utf8), nameData = Data(name.utf8)let crc = crc32(data), offset = UInt32(out.count)- // Local header: signature, version 2.0, flags (bit 11: UTF-8 names), stored, no time.u32(0x0403_4B50, &out); u16(20, &out); u16(0x0800, &out); u16(0, &out); u16(0, &out); u16(0x21, &out)u32(crc, &out); u32(UInt32(data.count), &out); u32(UInt32(data.count), &out)u16(nameData.count, &out); u16(0, &out)@@ -147,7 +138,6 @@ enum Docx {}}-/// 分享和导出: 分享链接 (ShareCard), then the three formats and 分享 (the system share sheet with the file).struct ExportSheet: View {let session: Session@Environment(\.dismiss) private var dismissdiff --git a/ios/Sources/Cicada/FaceToFace.swift b/ios/Sources/Cicada/FaceToFace.swiftindex 1f4ab2a..6b5075f 100644--- a/ios/Sources/Cicada/FaceToFace.swift+++ b/ios/Sources/Cicada/FaceToFace.swift@@ -1,26 +1,17 @@import AVFoundationimport Foundation-/// 面对面同声传译: two people at one phone, each holding their own button. A press is heard in the-/// speaker's language on the device; on release it is translated and read out in the other's-/// language (Ming with a Ling key, else the phone's own voice), while nothing listens. The Mac's-/// SpeakEngine is bound to the virtual mic; this is the same idea for one speaker and two people.-/// Each turn is a line of a meeting record: "me" for the phone's owner, "them" for the other.@MainActorfinal class FaceToFace: ObservableObject {enum Side: String { case me, them }enum Phase: Equatable {case idle- /// The side's button is held: what has been heard so far, and its draft translation.case hearing(Side)- /// Released: the last words come back and are translated.case translating(Side)- /// The translation is read out to the other side.case speaking(Side)}- /// One turn, as both halves show it.struct Turn: Equatable {var side: Sidevar said: String@@ -32,7 +23,6 @@ final class FaceToFace: ObservableObject {@Published private(set) var heard = ""@Published private(set) var draftTranslation = ""@Published private(set) var last: Turn?- /// Why the last turn wasn't read out, in the UI's language; cleared by the next press.@Published private(set) var problem = ""@Published var mine: Lang@Published var theirs: Lang@@ -50,18 +40,12 @@ final class FaceToFace: ObservableObject {private var counter = 0private var draftAsked = Date.distantPastprivate var turnTask: Task<Void, Never>?- /// Debug (`faceSay:`): a press heard as this text, without the microphone.var debugText: String?- /// 不用按键: no holding. The two sides take turns: the side whose turn it is is heard until it- /// pauses (the Mac's HandsFreeDetector on the mic's level), then translated and read out, and the- /// turn passes across the table. Nothing listens while the phone speaks, so it doesn't hear itself.- /// A tap on a side gives it the turn.@Published private(set) var handsFree = UserDefaults.standard.bool(forKey: FaceToFace.handsFreeKey)@Published private(set) var turnSide: Side = .mestatic let handsFreeKey = "iosFaceHandsFree"private var detector = HandsFreeDetector()- /// Turns in a row that heard nothing: after a few, hands-free waits for a tap instead of listening on.private var misses = 0init(store: SessionStore, translator: TranslationService, ling: LingClient) {@@ -78,7 +62,6 @@ final class FaceToFace: ObservableObject {static func lang(_ locale: String?) -> Lang? { sourceLanguages.first { $0.locale == locale } }- /// The phone's own language among those the recognizer hears.static var defaultMine: Lang {let code = myLanguage(systemLanguages: Locale.preferredLanguages)return sourceLanguages.first { $0.code == code }@@ -92,7 +75,6 @@ final class FaceToFace: ObservableObject {mine = mtheirs = tUserDefaults.standard.set(m.locale, forKey: Pref.myLang)- // With 自动识别 for listening it stays on: their language is the one heard last.UserDefaults.standard.set(t.locale, forKey: Pref.sourceAuto ? Pref.lastDetected : Pref.source)}@@ -105,11 +87,9 @@ final class FaceToFace: ObservableObject {last = nilproblem = ""debugLog("face: open \(mine.locale) ⇄ \(theirs.locale)")- // 不用按键 stays on from last time: I start.if handsFree { turnSide = .me; misses = 0; listenNext(after: 0.3) }}- /// 结束: the record is kept when anyone was heard.func close() {guard active else { return }cancelTurn()@@ -129,7 +109,6 @@ final class FaceToFace: ObservableObject {func press(_ side: Side) {guard active else { return }- // A press while the other side is read out cuts it short: they have heard enough.if case .speaking = phase { voice.stop() }if case .hearing = phase { return }cancelTurn()@@ -212,7 +191,6 @@ final class FaceToFace: ObservableObject {translateDraft(side)}- /// What has been said so far, in the other language, at most every second (Google, never Ling: AGENTS.md).private func translateDraft(_ side: Side) {guard Date().timeIntervalSince(draftAsked) > 1, heard.count >= 4 else { return }draftAsked = Date()@@ -228,10 +206,8 @@ final class FaceToFace: ObservableObject {let from = lang(side), to = lang(side == .me ? .them : .me)guard let out = await translator.translate(text, source: from.code, target: to.code, kind: .speak),!out.isEmpty else {- // Never read out untranslated text (AGENTS.md).guard phase == .translating(side) else { return }phase = .idle- // Nothing reachable and no key: saying it again won't help, a key (or a network) will.problem = translator.health.googleDown && !ling.hasKey && ling.provider.id == .ling ? L("连不上翻译,填 Ling key 后不用代理也能用"): translator.health.googleDown ? L("网络连不上,连上后再说一次") : L("没翻译出来,再说一次")debugLog("face: translation failed")@@ -250,8 +226,6 @@ final class FaceToFace: ObservableObject {if phase == .speaking(side) { phase = .idle; turnOver(side, spoken: true) }}- /// Debug (`faceTurn:`): a turn with its translation given, to check the record and the voice- /// when no translation service answers (the simulator without a key).func debugTurn(_ side: Side, said: String, translation: String) {guard active else { return }let from = lang(side), to = lang(side == .me ? .them : .me)@@ -294,7 +268,6 @@ final class FaceToFace: ObservableObject {}}- /// A tap on a side (hands-free): it has the turn now.func giveTurn(_ side: Side) {guard handsFree, active else { return }if case .hearing(let s) = phase, s == side { return }@@ -319,7 +292,6 @@ final class FaceToFace: ObservableObject {}}- /// The mic's level while a side is heard: its pause ends the turn.private func level(_ rms: Float, _ seconds: Double) {guard handsFree, case .hearing(let side) = phase else { return }if case .ended = detector.feed(rms: rms, seconds: seconds) {@@ -328,7 +300,6 @@ final class FaceToFace: ObservableObject {}}- /// After a turn: read out → the other side; nothing heard or not translated → the same side again.private func turnOver(_ side: Side, spoken: Bool) {guard handsFree else { return }if spoken {@@ -355,18 +326,15 @@ final class FaceToFace: ObservableObject {phase = .idleheard = ""problem = message- // Listening on would fail the same way.if handsFree { misses = 3 }}}-/// The microphone for one press: `AVAudioEngine`'s input → the recognizer's format.final class FaceMic: @unchecked Sendable {private var engine = AVAudioEngine()private let queue = DispatchQueue(label: "com.indaloop.cicada.face")private let convert = PCMConverter()private var stream: RecognitionStream?- /// Each block's loudness (RMS) and length, on the audio thread: 不用按键 hears the pauses.var onLevel: ((Float, Double) -> Void)?func start(into stream: RecognitionStream) throws {@@ -399,7 +367,6 @@ final class FaceMic: @unchecked Sendable {}enum FaceAudio {- /// Listening and speaking take turns; the speaker, not the earpiece, so the table hears it.static func activate() throws {let s = AVAudioSession.sharedInstance()if s.category != .playAndRecord || s.mode != .default {@@ -409,8 +376,6 @@ enum FaceAudio {}}-/// Reads a translation out: Ming's stream (24 kHz 16-bit mono PCM) with a key, the phone's own-/// voice without one or when Ming sends nothing.@MainActorfinal class FaceVoice: NSObject, AVSpeechSynthesizerDelegate {private let engine = AVAudioEngine()@@ -427,10 +392,7 @@ final class FaceVoice: NSObject, AVSpeechSynthesizerDelegate {synth.delegate = self}- /// `voiceID`: a voice to try (设置 › 念给对方的声音); else the one chosen for the language.- /// `mine`: read to me (their words), never in my own cloned voice.func speak(_ text: String, language: String, ling: LingClient?, voiceID: String? = nil, mine: Bool = false) async {- // One voice at a time: a turn still being read out ends here.stop()try? FaceAudio.activate()let id = voiceID ?? SpeakVoices.chosenID(for: language, hasKey: ling != nil, mine: mine, clones: ling?.clones ?? false)@@ -439,7 +401,6 @@ final class FaceVoice: NSObject, AVSpeechSynthesizerDelegate {streaming = taskif await task.value { debugLog("face: spoke with \(id ?? "-")"); return }if Task.isCancelled || streaming == nil { return }- // Ling 不可用时自动换成手机的声音.debugLog("face: Ling sent nothing, the phone's voice instead")}let u = AVSpeechUtterance(string: text)@@ -453,7 +414,6 @@ final class FaceVoice: NSObject, AVSpeechSynthesizerDelegate {debugLog("face: spoke with the phone's voice")}- /// Ming's voice, or the user's own cloned from their recording; nil for the phone's.private static func stream(_ text: String, id: String?, language: String, ling: LingClient) -> AsyncThrowingStream<Data, Error>? {let lang = VoiceCatalog.mingLanguage(for: language)if id == VoiceCatalog.cloneOption.id {@@ -461,13 +421,11 @@ final class FaceVoice: NSObject, AVSpeechSynthesizerDelegate {guard let ref = VoiceReference.reference() else { return nil }return ling.speech(text, voice: nil, reference: ref, language: lang)}- // Another service's speech model: its voice by name, the same in every language.if let id, id.hasPrefix("cloud:") { return ling.speech(text, voice: String(id.dropFirst(6))) }guard let id, id.hasPrefix("ming:") else { return nil }return ling.speech(text, voice: String(id.dropFirst(5)), language: lang)}- /// Plays the chunks as they come; false when none came.private func play(_ stream: AsyncThrowingStream<Data, Error>) async -> Bool {var carry = Data(), frames = 0do {@@ -492,7 +450,6 @@ final class FaceVoice: NSObject, AVSpeechSynthesizerDelegate {debugLog("face: Ming failed: \(error)")}guard frames > 0 else { return false }- // Wait out what is queued: the length of the audio from when it started, roughly.let seconds = Double(frames) / 24_000if let t = player.lastRenderTime, let p = player.playerTime(forNodeTime: t) {let left = seconds - Double(p.sampleTime) / p.sampleRate@@ -507,7 +464,6 @@ final class FaceVoice: NSObject, AVSpeechSynthesizerDelegate {streaming = nilplayer.stop()if synth.isSpeaking { synth.stopSpeaking(at: .immediate) }- // Its caller returns now rather than waiting on a voice that was cut.if let s = spoken { spoken = nil; s.resume() }}diff --git a/ios/Sources/Cicada/FaceView.swift b/ios/Sources/Cicada/FaceView.swiftindex d3f248f..9ae0add 100644--- a/ios/Sources/Cicada/FaceView.swift+++ b/ios/Sources/Cicada/FaceView.swift@@ -1,8 +1,5 @@import SwiftUI-/// 面对面, as the design: the top half turned around for the person across the table, each half with-/// its own hold-to-talk button, and between them 结束 and the two languages. Each half speaks its-/// own language, so the other person's half is in theirs (the app's strings where it has them).struct FaceView: View {@EnvironmentObject var model: AppModel@ObservedObject var face: FaceToFace@@ -50,7 +47,6 @@ struct FaceView: View {}.disabled(face.phase != .idle).accessibilityLabel(Text("我说和对方说"))- // 不用按键, where a spacer balanced the close button.Button { face.setHandsFree(!face.handsFree) } label: {Image(systemName: face.handsFree ? "hand.raised.slash.fill" : "hand.raised.slash").font(.system(size: 16, weight: .semibold))@@ -75,7 +71,6 @@ struct FaceView: View {private func pick(mine l: String) {guard let m = FaceToFace.lang(l) else { return }- // Picking the other side's language swaps the two.face.setLanguages(mine: m, theirs: m == face.theirs ? face.mine : face.theirs)}@@ -124,7 +119,6 @@ private struct FaceHalf: View {.accessibilityElement(children: .contain)}- /// The big line, the grey one under it, and whether the big one is settled (ink) or not yet.private var content: (String, String, Bool) {switch face.phase {case .hearing(let s) where s == side:@@ -153,7 +147,6 @@ private struct FaceHalf: View {}}- /// The app's strings in this half's language: languages the app isn't translated into get English.private var bundle: Bundle { Self.bundle(lang.code) }static func bundle(_ code: String) -> Bundle {@@ -167,7 +160,6 @@ private struct FaceHalf: View {}}-/// The big round button: held, it listens (orange, with rings); let go, it translates and reads out.private struct HoldButton: View {@ObservedObject var face: FaceToFacelet side: FaceToFace.Side@@ -206,7 +198,6 @@ private struct HoldButton: View {.accessibilityElement().accessibilityLabel(Text(verbatim: label)).accessibilityAddTraits(.isButton)- // VoiceOver can't hold: a double tap starts, another one stops..accessibilityAction {if hearing { face.release(side) } else { face.press(side) }}@@ -218,7 +209,6 @@ private struct HoldButton: View {}}-/// 不用按键: the side being heard shows it (in its own language); a tap on the other gives it the turn.private struct TurnButton: View {@ObservedObject var face: FaceToFacelet side: FaceToFace.Side@@ -248,8 +238,6 @@ private struct TurnButton: View {}}-/// 面对面 under 开始听, a row of its own as tall as it: the icon and the name at full size, and-/// the languages and what happens (the phone reads it out), so it doesn't pass for another 开始听.struct FaceRow: View {@EnvironmentObject var model: AppModel@ObservedObject var face: FaceToFace@@ -264,7 +252,6 @@ struct FaceRow: View {.background(Ink.ground, in: Circle())VStack(alignment: .leading, spacing: 1) {Text("面对面").font(.headline).foregroundStyle(Ink.ink).lineLimit(1)- // Narrow (the iPad sidebar, English): the languages only, never a clipped sentence.let pair = "\(Pref.name(of: face.mine)) ⇄ \(Pref.name(of: face.theirs))"ViewThatFits(in: .horizontal) {Text(verbatim: pair + " · " + L("手机念给对方听"))diff --git a/ios/Sources/Cicada/FixViews.swift b/ios/Sources/Cicada/FixViews.swiftindex 2d52d87..d2e4297 100644--- a/ios/Sources/Cicada/FixViews.swift+++ b/ios/Sources/Cicada/FixViews.swift@@ -1,12 +1,6 @@import SwiftUI-// 改正听错的词 on iPhone and iPad: the Mac's FixViews and WordListSettings in iOS idiom. The engine-// is the Mac's own (`LiveFixes`, `Vocabulary`); these only show it and pass taps back.--/// A line as shown, its fixed words with the Mac's dotted underline.enum FixedText {- /// The line with its applied fixes; each fixed word dotted, a word still waiting (这样改对吗?)- /// on a pale wash as heard. The Mac's `TranscriptParagraphs.joinFixed` for one line.static func attributed(_ l: TranscriptLine) -> AttributedString {let (text, marks) = Correction.apply(l.fixes ?? [], to: l.src)var a = AttributedString(text)@@ -20,11 +14,9 @@ enum FixedText {return a}- /// The line's applied fixes, as the user sees them ("莫拉" → "Morpho").static func applied(_ l: TranscriptLine) -> [LineFix] { (l.fixes ?? []).filter(\.applied) }}-/// 改这句… open: the meeting, the line, and what the editor starts with.struct LineEdit: Identifiable, Equatable {var id: String { session + "/" + line }let session: String@@ -32,7 +24,6 @@ struct LineEdit: Identifiable, Equatable {let start: String}-/// A small button on a card or banner: ink for the answer that changes something, grey for the other.struct FixButton: View {let title: LocalizedStringKeyvar dark = false@@ -52,8 +43,6 @@ struct FixButton: View {}}-/// 这样改对吗? while listening: a name the app couldn't check by sound, asked about once. 对 fixes-/// every line waiting on it and adds it to the word list; 稍后再看 asks again after the meeting.struct FixAskCard: View {@EnvironmentObject var model: AppModel@ObservedObject var fixes: LiveFixes@@ -95,8 +84,6 @@ struct FixAskCard: View {}}-/// Above a finished meeting's transcript: how many words were fixed, and the ones waiting for the-/// user, one at a time (对 / 不对 / 改成…). Nothing when there was nothing to fix.struct FixReviewBanner: View {@ObservedObject var fixes: LiveFixeslet session: Session@@ -129,16 +116,12 @@ struct FixReviewBanner: View {.frame(maxWidth: .infinity, alignment: .leading).background(Ink.accent.opacity(0.05), in: RoundedRectangle(cornerRadius: 16, style: .continuous)).overlay(RoundedRectangle(cornerRadius: 16, style: .continuous).strokeBorder(Ink.accentWash, lineWidth: 1))- // Not scrolled to on opening, as the Mac does: on a phone the banner would leave the- // screen with it. A tap on the question goes there.} else if fixedCount > 0 {Text("改了 \(fixedCount) 处听错的词").font(.footnote).foregroundStyle(Ink.tertiary)}}}-/// Under a line tapped open in the record: each fixed word, what it was heard as, 改回; and 改这句….-/// The Mac shows the same while the line is pointed at.struct FixedWords: View {let line: TranscriptLinelet onRevert: (LineFix) -> Void@@ -167,8 +150,6 @@ struct FixedWords: View {}}-/// 改这句…: the line as shown, to rewrite. What changed becomes the user's own fix-/// (`LiveFixes.edit`), on every line heard the same way or only this one.struct LineEditorSheet: View {let edit: LineEdit@ObservedObject var fixes: LiveFixes@@ -246,7 +227,6 @@ struct LineEditorSheet: View {}}-/// The last fix decision said back for a few seconds, with 撤销: the speaker toast's look.struct FixToast: View {@ObservedObject var fixes: LiveFixes@@ -259,9 +239,6 @@ struct FixToast: View {// MARK: - 设置 › 词表-/// The switches for 改正听错的词 and the word list itself: each word, what it has been heard as,-/// where it came from and how often it fixed a line. Swipe to delete (撤销 in its place for a few-/// seconds), tap to change the spelling or the heard forms, 粘贴导入 for many at once.struct WordListPage: View {@EnvironmentObject var model: AppModel@EnvironmentObject var ling: LingClient@@ -342,7 +319,6 @@ struct WordListPage: View {.animation(.snappy(duration: 0.2), value: model.deletedWord?.term.word)}- /// Most recently useful first, then the rest newest first.private var shown: [Vocabulary.Term] {let q = Vocabulary.key(query)let all = vocabulary.terms.reversed().sorted { ($0.used ?? .distantPast) > ($1.used ?? .distantPast) }@@ -351,7 +327,6 @@ struct WordListPage: View {}}-/// 搜索词表 once the list is long enough to need it, as on the Mac (more than 12).private struct WordSearch: ViewModifier {let on: Bool@Binding var query: String@@ -361,21 +336,17 @@ private struct WordSearch: ViewModifier {}}-/// A heard form typed for a word that another word already has: whose it should be.struct WordConflict: Equatable {let word: Stringlet heard: Stringlet owner: String}-/// A deleted word, shown in its place with 撤销 for a few seconds.struct DeletedWord: Equatable {let term: Vocabulary.Termlet index: Int}-/// One word: its spelling, what it was heard as, where it came from and how often it fixed a line.-/// Tapped, it opens in place: the spelling to change, heard forms to take off or add.private struct WordRow: View {@EnvironmentObject var model: AppModellet term: Vocabulary.Term@@ -473,8 +444,6 @@ private struct WordRow: View {}}-/// 粘贴导入: many words at once, each line one word, heard forms after "=". The counts follow what-/// is pasted, and the button says how many go in.struct WordImportSheet: View {@ObservedObject var vocabulary: Vocabulary@Environment(\.dismiss) private var dismissdiff --git a/ios/Sources/Cicada/FolderPage.swift b/ios/Sources/Cicada/FolderPage.swiftindex c20801f..5ec1416 100644--- a/ios/Sources/Cicada/FolderPage.swift+++ b/ios/Sources/Cicada/FolderPage.swift@@ -1,8 +1,6 @@import SwiftUIimport UniformTypeIdentifiers-/// 存到文件夹's settings on iOS: the Mac's names (`exportOn`, `exportFolder`), plus the folder as a-/// security-scoped bookmark, since an app can reopen a folder picked in Files only through one.@MainActorfinal class FolderPrefs: FolderExportPrefs {private let d = UserDefaults.standard@@ -25,7 +23,6 @@ final class FolderPrefs: FolderExportPrefs {return url}- /// Keeps the picked folder for later launches. Must run while the picker's access is open.@discardableResultfunc remember(_ url: URL) -> Bool {let scoped = url.startAccessingSecurityScopedResource()@@ -39,8 +36,6 @@ final class FolderPrefs: FolderExportPrefs {}}-/// 设置 › 存到文件夹: on/off, the folder (picked in Files: iCloud Drive, an Obsidian vault, any-/// app's folder), what was saved last or why it wasn't, and the meetings from before.struct FolderPage: View {@EnvironmentObject var model: AppModel@ObservedObject var exporter: FolderExporterdiff --git a/ios/Sources/Cicada/HostRecognizer.swift b/ios/Sources/Cicada/HostRecognizer.swiftindex e8f0385..ddb1009 100644--- a/ios/Sources/Cicada/HostRecognizer.swift+++ b/ios/Sources/Cicada/HostRecognizer.swift@@ -2,11 +2,6 @@ import AVFoundationimport Foundation#if targetEnvironment(simulator)-/// The simulator's speech models are empty placeholders (every recognizer answers "model not-/// available"), so a dev build there sends its audio to the Mac it runs on: `ios/tools/host-recognizer`-/// reads it from the app's container and recognizes it on device with the Mac's own `Recognition`,-/// writing the pieces back. Same clock as any `RecognitionStream`: seconds of audio appended.-/// Only for testing in the simulator; an iPhone recognizes on itself.enum HostRecognizer {static var root: URL {FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("host-recognizer", isDirectory: true)@@ -47,7 +42,6 @@ final class HostStream: RecognitionStream, @unchecked Sendable {FileManager.default.createFile(atPath: dir.appendingPathComponent("results.jsonl").path, contents: nil)audio = try FileHandle(forWritingTo: audioURL)(results, out) = AsyncThrowingStream.makeStream(of: Recognition.Piece.self)- // Written last: the host starts on a folder once its request is there.let request = try JSONSerialization.data(withJSONObject: ["locale": locale, "drafts": drafts])try request.write(to: dir.appendingPathComponent("request.json"))let resultsURL = dir.appendingPathComponent("results.jsonl")@@ -97,7 +91,6 @@ final class HostStream: RecognitionStream, @unchecked Sendable {func finish() async {queue.sync { try? audio.close() }FileManager.default.createFile(atPath: dir.appendingPathComponent("end").path, contents: nil)- // The host finishes the last line and says done; don't wait forever on it.for _ in 0..<100 where reader?.isCancelled == false {if (try? String(contentsOf: dir.appendingPathComponent("results.jsonl"), encoding: .utf8))?.contains("\"done\"") == true { break }try? await Task.sleep(nanoseconds: 100_000_000)diff --git a/ios/Sources/Cicada/Importing.swift b/ios/Sources/Cicada/Importing.swiftindex 6fcb4f4..1040a29 100644--- a/ios/Sources/Cicada/Importing.swift+++ b/ios/Sources/Cicada/Importing.swift@@ -4,14 +4,6 @@ import PhotosUIimport SwiftUIimport UniformTypeIdentifiers-// 导入录音或视频: the Mac's FileImporter, fed from Files, Photos or another app's share sheet. Each-// file is copied into the app first (a picked file's access ends with the picker, and Photos hands-// over a temporary copy), and the copy is the record's source. While files are turning into-// records the system keeps the app running behind other apps (BGContinuedProcessingTask) and shows-// its progress.--/// 对方说 and 翻译成 as the iOS app has them: an import is in the language the user listens to-/// (自动识别: FileImporter hears it).@MainActorfinal class ImportPrefs: ImportSettings {var importLanguage: String { Pref.sourceAuto ? "auto" : Pref.sourceLang.locale }@@ -20,13 +12,11 @@ final class ImportPrefs: ImportSettings {}enum ImportFiles {- /// The app's own copies of imported files.static var folder: URL {FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent(DevBuild.supportFolder).appendingPathComponent("Imports")}- /// A copy under `folder`, keeping the file's name (it becomes the record's title).static func copy(_ url: URL) -> URL? {let access = url.startAccessingSecurityScopedResource()defer { if access { url.stopAccessingSecurityScopedResource() } }@@ -42,27 +32,23 @@ enum ImportFiles {}}- /// The copy goes with its record.static func remove(_ path: String?) {guard let path, path.hasPrefix(folder.path) else { return }try? FileManager.default.removeItem(at: URL(fileURLWithPath: path).deletingLastPathComponent())}}-/// A video from Photos, as a file.struct PickedMovie: Transferable {let url: URLstatic var transferRepresentation: some TransferRepresentation {FileRepresentation(contentType: .movie) { SentTransferredFile($0.url) } importing: { received in- // The received file is gone after this returns: our own copy is what is imported.guard let copy = ImportFiles.copy(received.file) else { throw CocoaError(.fileWriteUnknown) }return PickedMovie(url: copy)}}}-/// The system's progress for imports running behind other apps (iOS 26).@MainActorenum ImportBackground {static var identifier: String { (Bundle.main.bundleIdentifier ?? "com.indaloop.cicada") + ".import" }@@ -70,7 +56,6 @@ enum ImportBackground {private static var ticker: Timer?static weak var importer: FileImporter?- /// Before the app finishes launching, as BGTaskScheduler requires.static func register() {let ok = BGTaskScheduler.shared.register(forTaskWithIdentifier: identifier, using: .main) { t inMainActor.assumeIsolated { run(t) }@@ -94,7 +79,6 @@ enum ImportBackground {task = tt.progress.totalUnitCount = 1000t.expirationHandler = {- // The system wants the time back: what was transcribed stays, the record offers 重新转写.MainActor.assumeIsolated {debugLog("import: background time expired")importer?.cancelAll()@@ -123,7 +107,6 @@ enum ImportBackground {}extension AppModel {- /// Files from the picker, Photos or the share sheet: copied, then queued as records.func importFiles(_ urls: [URL], copied: Bool = false) {let files = urls.filter(FileImporter.importable).compactMap { copied ? $0 : ImportFiles.copy($0) }guard !files.isEmpty else {@@ -137,7 +120,6 @@ extension AppModel {}}- /// A file shared to the app ("用知了打开"): it arrives in the app's Inbox, already a copy.func openedFile(_ url: URL) -> Bool {guard url.isFileURL else { return false }importFiles([url])@@ -146,7 +128,6 @@ extension AppModel {}}-/// The import button's two sources.struct ImportMenu<Label: View>: View {@EnvironmentObject var model: AppModel@State private var files = false@@ -179,8 +160,6 @@ struct ImportMenu<Label: View>: View {}}-/// 正在导入, at the top of the records while files are turning into records: the file, how far-/// it has got, and 停止.struct ImportCard: View {@EnvironmentObject var model: AppModel@ObservedObject var importer: FileImporter@@ -234,15 +213,12 @@ private extension String {}extension AppModel {- /// 重新转写: a record that stopped halfway (the system took the background time back, or 停止),- /// or one heard badly, transcribed again from its file or recording; the old transcript is backed up.func retranscribe(_ id: String, lang: Lang? = nil) {importer.retry(id, lang: lang)guard importer.current?.id == id || importer.queue.contains(where: { $0.id == id }) else { return }ImportBackground.begin(store.session(id)?.displayTitle ?? "")}- /// Whether 重新转写 has something to hear: the imported file's copy, or the meeting's recording.func canRetranscribe(_ s: Session) -> Bool {if let path = s.sourcePath, FileManager.default.fileExists(atPath: path) { return true }return [store.systemAudioURL(s.id), store.micAudioURL(s.id), store.roomAudioURL(s.id)]@@ -250,7 +226,6 @@ extension AppModel {}}-/// 重新转写 by language, for a record's menus: not while it is live or being transcribed.struct RetranscribeMenu: View {@EnvironmentObject var model: AppModel@ObservedObject var importer: FileImporter@@ -268,8 +243,6 @@ struct RetranscribeMenu: View {}}-/// Under an imported record's title, as on the Mac: queued, how far transcribing got, or that it-/// stopped, with 重新转写.struct ImportStatusStrip: View {@EnvironmentObject var model: AppModel@ObservedObject var importer: FileImporter@@ -319,7 +292,6 @@ struct ImportStatusStrip: View {}}-/// The list row's word for a record still being worked on, as on the Mac.struct ImportRowTag: View {@ObservedObject var importer: FileImporterlet session: Sessiondiff --git a/ios/Sources/Cicada/Intents.swift b/ios/Sources/Cicada/Intents.swiftindex 42f9db4..eaee685 100644--- a/ios/Sources/Cicada/Intents.swift+++ b/ios/Sources/Cicada/Intents.swift@@ -1,14 +1,8 @@import AppIntentsimport Foundation-// 快速开始: 开始听 for the Action button, Control Center and Siri, and the Live Activity's 暂停 and-// 结束并出纪要. Compiled into the app and into the CicadaLive extension (its Control Center button-// names the intent); every intent runs in the app, which hands it to AppModel through `IntentHub`.-@MainActorenum IntentHub {- /// Set by AppModel. An intent that comes before it (the app launched by the intent) is kept- /// in `pending` and run once AppModel is there.static var run: ((Action) -> Void)? {didSet { if let run, let p = pending { pending = nil; run(p) } }}@@ -24,7 +18,6 @@ enum IntentHub {struct StartListeningIntent: AppIntent {static let title: LocalizedStringResource = "开始听"static let description = IntentDescription("用麦克风听会议室,出实时双语字幕和纪要")- /// The microphone starts with the app in front: iOS won't start recording from the background.static let openAppWhenRun = true@MainActor@@ -57,7 +50,6 @@ struct PauseListeningIntent: LiveActivityIntent {}#if !CICADA_LIVE-/// Siri and Spotlight (the app's only; the extension builds with CICADA_LIVE). Phrases in the languages people ask in; each must name the app.struct CicadaShortcuts: AppShortcutsProvider {static var appShortcuts: [AppShortcut] {AppShortcut(intent: StartListeningIntent(), phrases: [diff --git a/ios/Sources/Cicada/ListenActivity.swift b/ios/Sources/Cicada/ListenActivity.swiftindex 068d90c..26a3db6 100644--- a/ios/Sources/Cicada/ListenActivity.swift+++ b/ios/Sources/Cicada/ListenActivity.swift@@ -1,20 +1,14 @@import ActivityKitimport Foundation-/// 正在听 on the lock screen and in the Dynamic Island. Compiled into the app and into the-/// CicadaLive extension (ios/LiveActivity), which draws it; the app only starts, feeds and ends it.struct ListenActivity: ActivityAttributes {struct ContentState: Codable, Hashable {- /// The newest translated line and what was said.var line: Stringvar source: String- /// Distinct voices so far.var people: Int- /// 暂停 on the lock screen: the microphone is off until 继续.var paused = false}var startedAt: Date- /// "英 → 中".var pair: String}diff --git a/ios/Sources/Cicada/LiveActivityController.swift b/ios/Sources/Cicada/LiveActivityController.swiftindex 71fb5ed..62352be 100644--- a/ios/Sources/Cicada/LiveActivityController.swift+++ b/ios/Sources/Cicada/LiveActivityController.swift@@ -1,8 +1,6 @@import ActivityKitimport Foundation-/// Starts the Live Activity when listening starts, sends it each translated line (at most every-/// 1.5 s: the system throttles more anyway) and ends it with the meeting.@MainActorfinal class LiveActivityController {private var activity: Activity<ListenActivity>?@@ -57,7 +55,6 @@ final class LiveActivityController {Task { await activity.update(.init(state: state, staleDate: nil)) }}- /// 暂停 / 继续, shown at once (not held back by the line throttle).func setPaused(_ on: Bool) {guard let activity, paused != on else { return }paused = ondiff --git a/ios/Sources/Cicada/LiveViews.swift b/ios/Sources/Cicada/LiveViews.swiftindex 1cd5e10..dcee273 100644--- a/ios/Sources/Cicada/LiveViews.swift+++ b/ios/Sources/Cicada/LiveViews.swift@@ -1,17 +1,11 @@import SwiftUI-// The design's scheme 3 (知了当标题): the logo, the date and 会议记录 make the home's title, 开始听 is-// one glass bar under it, and while listening the same two places turn into 正在听 · 12:48 and the-// wave, who is talking and 结束. iPhone and the iPad's sidebar share them.--/// "11月4日 星期三 / 会议记录", or "● 正在听 · 12:48 / 会议室 · 英 → 中" while listening.struct HomeTitle: View {@EnvironmentObject var model: AppModel@EnvironmentObject var room: RoomListenvar logo: CGFloat = 52var titleSize: CGFloat = 28var trailing: AnyView? = nil- /// What stands at the right while listening (the iPhone's 收起).var liveTrailing: AnyView? = nilvar body: some View {@@ -28,14 +22,12 @@ struct HomeTitle: View {.foregroundStyle(room.paused ? Ink.secondary : Ink.accentText)}let pair = Pref.pairText(room.languagePair.source, room.languagePair.target)- // Same language both sides (Chinese heard, Chinese shown): no pair to name.Text(pair.isEmpty ? (room.speakerMode ? L("外放") : L("会议室")): (room.speakerMode ? L("外放 · \(pair)") : L("会议室 · \(pair)"))).font(.system(size: titleSize - 4, weight: .bold)).foregroundStyle(Ink.ink).lineLimit(1).minimumScaleFactor(0.7)} else {Text(dateText(Date(), "MMMdEEEE")).font(.footnote).foregroundStyle(Ink.secondary)- // iPad's narrow sidebar: "Meetings" shrinks rather than breaking in two.Text("会议记录").font(.system(size: titleSize, weight: .bold)).foregroundStyle(Ink.ink).lineLimit(1).minimumScaleFactor(0.7)}@@ -48,7 +40,6 @@ struct HomeTitle: View {}}-/// The orange dot that breathes while listening.struct LiveDot: View {@State private var on = false@@ -60,14 +51,12 @@ struct LiveDot: View {}}-/// 开始听 · 英语 → 简体中文 · the orange round button; while listening: the wave, who is talking, 结束.struct ListenBar: View {@EnvironmentObject var model: AppModel@EnvironmentObject var room: RoomListen@AppStorage(Pref.source) private var source = "auto"@AppStorage(Pref.target) private var target = "system"@AppStorage(Pref.hear) private var hear = "room"- /// Glass on the ground (iPhone); white on the iPad's glass sidebar.var onGlass = falsevar body: some View {@@ -95,7 +84,6 @@ struct ListenBar: View {Text("手机外放").tag("speaker")} label: { Text("声音来源") }.pickerStyle(.inline)- // The one grey line: what 手机外放 needs, else what iPhone can't hear at all.Text(hear == "speaker" ? L("别戴耳机,字幕会浮在小窗里") : L("听不到其他 app 的声音,线上会议请用电脑版"))}Picker(selection: $source) {@@ -130,7 +118,6 @@ struct ListenBar: View {private var live: some View {Group {- // 收起 left the meetings on screen: the wave and who is talking bring 正在听 back.Button { model.liveHidden = false } label: {HStack(spacing: 10) {Wave(level: room.level)@@ -175,7 +162,6 @@ private struct GlassCapsule: ViewModifier {}}-/// Five bars that follow the microphone's level.struct Wave: View {let level: Float@@ -194,7 +180,6 @@ struct Wave: View {}}-/// 正在听 on the iPhone: the title and bar as on the home, 字幕 / 纪要, and the lines as cards.struct LivePhone: View {@EnvironmentObject var model: AppModel@EnvironmentObject var room: RoomListen@@ -239,8 +224,6 @@ struct LivePhone: View {enum LivePage: String { case subtitles, notes }-/// Under 纪要: what is being said now (else the newest line), so the notes page still shows the-/// room live; a tap goes to 字幕.struct SayingNow: View {@EnvironmentObject var model: AppModel@EnvironmentObject var room: RoomListen@@ -270,14 +253,10 @@ struct SayingNow: View {}}-/// 连不上翻译: why the subtitles are only the original. Without a key, the key is the fix (Ling-/// needs no proxy in mainland China), so the card opens 设置; with one, it comes back by itself.struct TranslateDownCard: View {@EnvironmentObject var model: AppModelvar body: some View {- // 语音和文字只发给你的服务, and the service doesn't translate: it picks up by itself, and no- // other service is offered, which would send the meeting elsewhere (as the Mac's notes window).if model.translationHealth.googleOff, model.translationHealth.sentencesUntranslated {HStack(alignment: .top, spacing: 10) {Image(systemName: "hourglass").foregroundStyle(Ink.secondary).padding(.top, 2)@@ -311,7 +290,6 @@ struct TranslateDownCard: View {}}-/// The lines so far as white cards, the one being said outlined in the accent; follows the newest.struct LiveLines: View {@EnvironmentObject var model: AppModel@EnvironmentObject var room: RoomListen@@ -331,7 +309,6 @@ struct LiveLines: View {.frame(maxWidth: .infinity).padding(.top, 40)}ForEach(room.lines) { l in- // The record's line, so its fixed words show (改正听错的词); `room.lines` keeps what was heard.let rec = session?.lines.first { $0.id == l.id }card(who: numbers[l.id].map { SpeakerLabels.label($0, names) }, time: l.t,src: rec.map(FixedText.attributed) ?? AttributedString(l.src), dst: l.dst, live: false)@@ -366,7 +343,6 @@ struct LiveLines: View {}}-/// 正在听 on the iPad, beside the sidebar: 字幕 and 纪要 side by side when wide, switched when not.struct LivePad: View {@EnvironmentObject var model: AppModel@EnvironmentObject var room: RoomListen@@ -383,7 +359,6 @@ struct LivePad: View {}GeometryReader { g inif g.size.width >= 820 {- // 纪要 on the left and wider, 字幕 beside it, as the Mac's notes window reads.HStack(alignment: .top, spacing: 22) {column(notesTitle) {ScrollView {@@ -426,8 +401,6 @@ struct LivePad: View {}}-/// A speech model on its way: the system says only "not yet" or "done", so a moving bar and the time-/// waited show it is still coming (the Mac's download card).struct ModelWaitCard: View {@EnvironmentObject var room: RoomListen@@ -451,8 +424,6 @@ struct ModelWaitCard: View {}}-/// Under 开始听 when it didn't start: why, and the one thing that helps (the Mac's 听不出 card for a-/// speech model; the microphone permission; anything else, 再试一次).struct StartProblemCard: View {@EnvironmentObject var room: RoomListen@@ -519,9 +490,6 @@ struct StartProblemCard: View {}}-/// The notes' trouble while listening, in one line, as the Mac's notes window: a dead key stops-/// them (换 key), a busy or unreachable service only delays them (改用 Ling when there is its key),-/// and the subtitles carry on either way.struct NotesStatusLine: View {@EnvironmentObject var model: AppModel@EnvironmentObject var room: RoomListen@@ -550,7 +518,6 @@ struct NotesStatusLine: View {}}- /// Where the notes stopped, in meeting time; 0 before they covered anything.private var lastCovered: Double {guard let s = model.store.session(room.sessionID), notes.notes.covered > 0, notes.notes.covered <= s.lines.count else { return 0 }return s.lines[notes.notes.covered - 1].t@@ -566,7 +533,6 @@ struct NotesStatusLine: View {case .rateLimited:return (L("\(service) 很忙 · 纪要稍后补上,字幕照常"), false, nil)case .unreachable where unreachable, .updating where unreachable:- // 语音和文字只发给你的服务: TranslateDownCard says it, and 改用 Ling would send the meeting elsewhere.if model.translationHealth.googleOff, model.translationHealth.sentencesUntranslated { return nil }return (lastCovered > 0 ? L("纪要等 \(service) 恢复 · 停在 \(NotesEngine.clock(lastCovered)),字幕照常") : L("纪要等 \(service) 恢复 · 字幕照常"),false, model.canSwitchToLing ? (L("改用 Ling"), { model.switchToLing() }) : nil)diff --git a/ios/Sources/Cicada/NotesEdit.swift b/ios/Sources/Cicada/NotesEdit.swiftindex c04a33f..5856bc7 100644--- a/ios/Sources/Cicada/NotesEdit.swift+++ b/ios/Sources/Cicada/NotesEdit.swift@@ -2,10 +2,7 @@ import SwiftUIimport UIKitimport UniformTypeIdentifiers-/// 复制纪要 and changing a finished meeting's notes in place, as on the Mac (RichCopy.swift,-/// NotesEditing.swift): the summary, a conclusion or a to-do; topics are the AI's to rewrite.extension AppModel {- /// Not while the meeting is being written, nor while an import is still transcribing.func canEditNotes(_ s: Session) -> Bool {s.id != store.liveID && importer.current?.id != s.id && !(s.notes?.isEmpty ?? true)}@@ -27,8 +24,6 @@ extension AppModel {debugLog("notes edit: saved \(target) in \(id)")}- /// 复制纪要: HTML for document apps (Feishu, DingTalk, Notion, Notes), the Markdown as plain text- /// for chats; each app takes the one it reads.func copyNotes(_ s: Session) {let n = s.notes.map { SpeakerLabels.named($0, SpeakerLabels.names(s)) }let html = TranscriptExport.htmlDocument("<h1>\(TranscriptExport.esc(s.displayTitle))</h1>\n" + TranscriptExport.notesHTML(n))@@ -43,7 +38,6 @@ extension AppModel {}}-/// One editable piece of the notes: the text, a tap opens a field in place with 取消 and 完成.struct EditableNote<Label: View>: View {let target: NoteEdit.Targetlet text: String@@ -84,7 +78,6 @@ struct EditableNote<Label: View>: View {}}-/// 已复制纪要, dark above the player for a few seconds.struct CopiedToast: View {var body: some View {HStack(spacing: 10) {diff --git a/ios/Sources/Cicada/PeoplePage.swift b/ios/Sources/Cicada/PeoplePage.swiftindex 2a51aaa..0613381 100644--- a/ios/Sources/Cicada/PeoplePage.swift+++ b/ios/Sources/Cicada/PeoplePage.swift@@ -1,16 +1,10 @@import SwiftUI-/// 记住的人, as the Mac's 人员库 (SpeakerLibraryView, AppModel.rememberSpeaker): a voice in a-/// meeting is remembered only when the user asks and confirms (voiceprints are biometric data),-/// from the meeting's own recording; later meetings name it as soon as it is heard. Everything stays-/// on this phone and every row can be deleted.extension AppModel {- /// The confirmation's question, and then the voiceprint built from the meeting's recording.func rememberSpeaker(session id: String, voice: Int, name: String) {guard let s = store.session(id) else { return }let chosen = name.trimmingCharacters(in: .whitespacesAndNewlines)guard !chosen.isEmpty else { speakerProblem = (L("先给这个人起个名字"), L("在“是谁”里输入名字后,再记住这个声音。")); return }- // An imported file's own audio, else the meeting's recording (still partial while it goes on).let fm = FileManager.defaultlet audio = store.systemAudioURL(s.id), partial = AudioFileWriter.partial(audio)let source = s.sourceFile != nil ? s.sourcePath.map(Self.inThisContainer) : nil@@ -47,8 +41,6 @@ extension AppModel {}}- /// An imported file's stored path under the app's container as it is now: the container's folder- /// changes when the app is reinstalled (and can on an update), the part inside it doesn't.static func inThisContainer(_ path: String) -> URL {let marker = "/Library/Application Support/"guard !FileManager.default.fileExists(atPath: path), let r = path.range(of: marker) else { return URL(fileURLWithPath: path) }@@ -68,7 +60,6 @@ extension AppModel {}}-/// 设置 › 人员库: who is remembered, a note for each (公司、职位、下次要记住的事), delete one or all.struct PeoplePage: View {@EnvironmentObject var model: AppModel@State private var confirmAll = falsediff --git a/ios/Sources/Cicada/PiPSubtitles.swift b/ios/Sources/Cicada/PiPSubtitles.swiftindex c63a4c9..15de53a 100644--- a/ios/Sources/Cicada/PiPSubtitles.swift+++ b/ios/Sources/Cicada/PiPSubtitles.swift@@ -3,12 +3,8 @@ import AVKitimport SwiftUIimport UIKit-/// 手机外放's subtitles over other apps: iOS lets an app float only a picture-in-picture video, so-/// the newest line is drawn into frames and fed to a sample buffer layer as a live stream. It starts-/// by itself when the app goes to the background while listening to video played aloud.@MainActorfinal class PiPSubtitles: NSObject, ObservableObject {- /// The layer PiP takes its frames from; it has to sit in the window (PiPHost).let layer = AVSampleBufferDisplayLayer()@Published private(set) var isActive = falseprivate var controller: AVPictureInPictureController?@@ -22,7 +18,6 @@ final class PiPSubtitles: NSObject, ObservableObject {var note: String}- /// 32:10 at the scale the window is drawn: wide enough for two lines of Chinese.static let size = CGSize(width: 960, height: 300)override init() {@@ -31,7 +26,6 @@ final class PiPSubtitles: NSObject, ObservableObject {draw(Caption(src: "", dst: "", note: L("正在听外放…")))}- /// On while 手机外放 is listening, so leaving the app floats the window; off otherwise.func setEnabled(_ on: Bool) {if on, controller == nil, AVPictureInPictureController.isPictureInPictureSupported() {let source = AVPictureInPictureController.ContentSource(sampleBufferDisplayLayer: layer, playbackDelegate: self)@@ -45,7 +39,6 @@ final class PiPSubtitles: NSObject, ObservableObject {debugLog("pip: enabled=\(on) supported=\(AVPictureInPictureController.isPictureInPictureSupported())")}- /// Debug (`pip`): float it now, as leaving the app would.func start() {debugLog("pip: start possible=\(controller?.isPictureInPicturePossible ?? false)")controller?.startPictureInPicture()@@ -56,7 +49,6 @@ final class PiPSubtitles: NSObject, ObservableObject {guard c != shown else { return }pending = cguard !drawing else { return }- // A few frames a second at most: a draft changes on every word.drawing = trueDispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [weak self] inguard let self else { return }@@ -73,7 +65,6 @@ final class PiPSubtitles: NSObject, ObservableObject {renderer.enqueue(buffer)}- /// The design's dark card: 知了 · 正在听 in the accent, what was said in grey, the translation in white.private static func frame(_ c: Caption) -> CMSampleBuffer? {let image = UIGraphicsImageRenderer(size: size, format: { let f = UIGraphicsImageRendererFormat(); f.scale = 1; return f }()).image { ctx inUIColor(red: 0x15 / 255, green: 0x17 / 255, blue: 0x1C / 255, alpha: 1).setFill()@@ -97,7 +88,6 @@ final class PiPSubtitles: NSObject, ObservableObject {let wrap = NSMutableParagraphStyle()wrap.lineBreakMode = .byWordWrappingwrap.lineSpacing = 6- // The end of a long line matters most: keep its last two lines.let font = UIFont.systemFont(ofSize: 46, weight: .medium)let attrs: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: UIColor.white, .paragraphStyle: wrap]let text = tail(main, fitting: CGSize(width: width, height: size.height - y - 24), attrs)@@ -128,7 +118,6 @@ final class PiPSubtitles: NSObject, ObservableObject {return sample}- /// The shortest ending of `text` that fills `box`, starting at a character boundary.private static func tail(_ text: String, fitting box: CGSize, _ attrs: [NSAttributedString.Key: Any]) -> String {func fits(_ s: String) -> Bool {(s as NSString).boundingRect(with: CGSize(width: box.width, height: .greatestFiniteMagnitude),@@ -156,7 +145,6 @@ extension PiPSubtitles: AVPictureInPictureControllerDelegate, AVPictureInPicturenonisolated func pictureInPictureController(_ c: AVPictureInPictureController, setPlaying playing: Bool) {}- /// A live stream: no timeline, no skipping.nonisolated func pictureInPictureControllerTimeRangeForPlayback(_ c: AVPictureInPictureController) -> CMTimeRange {CMTimeRange(start: .negativeInfinity, duration: .positiveInfinity)}@@ -169,7 +157,6 @@ extension PiPSubtitles: AVPictureInPictureControllerDelegate, AVPictureInPicturecompletion: @escaping () -> Void) { completion() }}-/// Holds the PiP layer in the window, as PiP requires; a few points, under the page.struct PiPHost: UIViewRepresentable {let pip: PiPSubtitlesdiff --git a/ios/Sources/Cicada/RecordView.swift b/ios/Sources/Cicada/RecordView.swiftindex 6b86d1b..59fe467 100644--- a/ios/Sources/Cicada/RecordView.swift+++ b/ios/Sources/Cicada/RecordView.swift@@ -3,22 +3,16 @@ import SwiftUIenum RecordPage: String { case transcript, notes }-/// One meeting, as the design's 会议记录 screen: one white sheet with the title, the voices as-/// chips, the 文字记录 / 纪要 switch, and the recording on a glass bar at the bottom.struct RecordView: View {@EnvironmentObject var model: AppModel@EnvironmentObject var ling: LingClient@EnvironmentObject var notes: NotesEnginelet session: Session- /// Opened from 搜索 (or the iPad's sidebar search): the transcript opens at the first line found,- /// every match marked, as the Mac's records (#33).var searching = false@StateObject private var player = RecordPlayer()@State private var needsKey = false- /// What's typed into the title; nil until it is touched, so opening it changes nothing.@State private var titleDraft: String?@FocusState private var titleFocused: Bool- /// The speaker picked on a chip (scheme A: only they are drawn in ink); nil follows the recording.private var picked: Int? { model.focusSpeaker }@AppStorage(Pref.voices) private var voicesOn = true@@ -26,10 +20,6 @@ struct RecordView: View {ScrollViewReader { proxy inScrollView {VStack(alignment: .leading, spacing: 0) {- // The design's 28 pt title; the day is in the line below, so a notes title's- // leading "11月3日" goes.- // Editable in place, as on the Mac: an unchanged title isn't a rename, an emptied- // one goes back to the automatic title.TextField(text: Binding(get: { titleDraft ?? shownTitle }, set: setTitle), axis: .vertical) {Text("未命名会议")}@@ -62,7 +52,6 @@ struct RecordView: View {switch model.recordPage {case .transcript:- // 改正听错的词 after the meeting: the waiting fixes, one at a time.if session.id != model.store.liveID {FixReviewBanner(fixes: model.fixes, session: session,onShow: { id in withAnimation { proxy.scrollTo(id, anchor: .center) } },@@ -79,7 +68,6 @@ struct RecordView: View {}.frame(maxWidth: .infinity).padding(.top, 40)} else {- // Ling wrote "说话人 6" before anyone was named; show the names since given.NotesPage(notes: session.notes.map { SpeakerLabels.named($0, SpeakerLabels.names(session)) },edit: model.editHooks(session)).padding(.top, 18)@@ -97,14 +85,12 @@ struct RecordView: View {}.onAppear {showMatches()- // The lazy list needs a moment to lay out (and the page to switch) before it can go to the line found.if let id = currentMatch { DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { proxy.scrollTo(id, anchor: .center) } }}.onChange(of: model.query) { showMatches() }.onChange(of: currentMatch) { _, id inif let id, model.recordPage == .transcript { withAnimation { proxy.scrollTo(id, anchor: .center) } }}- // The transcript follows the recording while it plays, until scrolled by hand (as on the Mac)..onScrollPhaseChange { _, phase in if phase == .interacting { player.userScrolled() } }.onChange(of: player.lineID(in: session)) { _, id inif player.playing, player.following, model.recordPage == .transcript, let id { withAnimation { proxy.scrollTo(id, anchor: .center) } }@@ -115,7 +101,6 @@ struct RecordView: View {}.background(Color.white).navigationBarTitleDisplayMode(.inline)- // The design's trailing glass pair: 生成纪要 and 导出, in ink like the back button..toolbar {ToolbarItemGroup(placement: .topBarTrailing) {Button {@@ -172,7 +157,6 @@ struct RecordView: View {}.padding(.horizontal, 16).padding(.bottom, 8)- // The page fades out under the bar, as in the design, so text doesn't show through the glass..background(alignment: .bottom) {LinearGradient(colors: [.white.opacity(0), .white], startPoint: .top, endPoint: .center).padding(.top, -24)@@ -195,7 +179,6 @@ struct RecordView: View {}}- /// The search in this meeting: its terms (misheard names too), and the line being looked at.private var searchTerms: [String] { searching ? model.searchTerms(session) : [] }private var matches: [String] { TranscriptSearch.matches(session.lines, searchTerms) }private var currentMatch: String? {@@ -203,7 +186,6 @@ struct RecordView: View {return ms.isEmpty ? nil : ms[min(model.searchMatch, ms.count - 1)]}- /// A search that finds lines here opens the transcript at the first one.private func showMatches() {guard searching else { return }model.searchMatch = 0@@ -216,7 +198,6 @@ struct RecordView: View {return SearchMatchBar(index: min(model.searchMatch, n - 1), count: n) { model.stepSearch($0, in: session) }}- /// The speaker the recording is at, while it plays.private func playingNumber(_ numbers: [String: Int]) -> Int? {guard player.playing, let id = player.lineID(in: session) else { return nil }return numbers[id]@@ -224,7 +205,6 @@ struct RecordView: View {private var shownTitle: String { RecordList.untitled(session) ? "" : RecordList.listTitle(session) }- /// Return ends the edit (the field wraps long titles, so it would otherwise add a line).private func setTitle(_ v: String) {if v.contains("\n") {titleDraft = v.replacingOccurrences(of: "\n", with: "")@@ -240,7 +220,6 @@ struct RecordView: View {model.rename(session.id, to: draft)}- /// "今天 10:02 · 48 分钟 · 英 → 中".static func meta(_ s: Session) -> String {var parts = [dateText(s.startedAt, "MMMdHHmm"), RecordList.length(s)]if let pair = RecordList.pair(s, short: true) { parts.append(pair) }@@ -248,33 +227,25 @@ struct RecordView: View {}}-/// The voices told apart in this meeting, as chips in their colours ("Sarah", "说话人 3"); only-/// with 说话人识别 on, as the transcript. A chip renames the voice or merges it into another.struct SpeakerChips: View {@EnvironmentObject var model: AppModellet session: Session- /// Each speaker number's share of the meeting, shown on the chip ("Sarah · 58%").var shares: [Int: Double] = [:]- /// Drawn in ink: the picked speaker, or the one playing.var focus: Int? = nil@Binding var picked: Int?@AppStorage(Pref.voices) private var voicesOn = true@State private var draft = ""- /// 记住这个声音: the voice and the name, waiting for the user to confirm.@State private var remembering: (voice: Int, name: String)?- /// The speaker number being named; on the model so a debug command can open it too.private var naming: Int? { model.namingSpeaker }var body: some View {let names = SpeakerLabels.names(session)let voices = voicesOn ? SpeakerLabels.voiceNumbers(session) : [:]- // Voice id by its speaker number.let byNumber = Dictionary(uniqueKeysWithValues: voices.map { ($1, $0) })let numbers = byNumber.keys.sorted()if !numbers.isEmpty {FlowLayout(spacing: 8) {ForEach(numbers, id: \.self) { n in- // Tap picks the speaker (only they stay in ink); a long press renames or merges.Menu {Button { draft = names[n] ?? ""; model.namingSpeaker = n } label: { Label("改名字", systemImage: "pencil") }if let v = byNumber[n] {@@ -325,7 +296,6 @@ struct SpeakerChips: View {}}- /// The Mac's rule: keeping Ling's guess stores nothing, so a later, better guess can still replace it.private func save(_ byNumber: [Int: Int]) {guard let n = naming, let voice = byNumber[n] else { return }model.namingSpeaker = nil@@ -336,7 +306,6 @@ struct SpeakerChips: View {}}-/// "说话人 6 已改成 David · 撤销", dark above the player, the Mac toast's pale accent on 撤销, for a few seconds.struct SpeakerUndoBar: View {let text: Stringlet undo: () -> Void@@ -359,27 +328,19 @@ struct SpeakerUndoBar: View {struct TranscriptList: View {@EnvironmentObject var model: AppModellet session: Session- /// The line the recording is at, highlighted like the design's.let playing: String?- /// Scheme A: this speaker's lines carry an ink bar, the rest a light grey one.var focus: Int? = nil- /// A speaker was picked on purpose: the others' lines step back.var dimOthers = false- /// With a recording, a tap on a line plays from it (and opens what was fixed in it, if anything).var playable = false- /// A search's terms, marked in place; the line it is on stands out.var terms: [String] = []var found: String? = nillet seek: (Double) -> Void@Environment(\.dynamicTypeSize) private var typeSize- /// The design's 14 pt grey original over a 16 pt translation, scaling with the text size.@ScaledMetric(relativeTo: .subheadline) private var srcSize: CGFloat = 14@ScaledMetric(relativeTo: .callout) private var dstSize: CGFloat = 16var body: some View {let numbers = TranscriptExport.speakerNumbers(session), names = SpeakerLabels.names(session)- // At the largest text sizes the time column would squeeze the text: the time goes on the- // speaker's line instead.let inline = typeSize.isAccessibilitySizeLazyVStack(alignment: .leading, spacing: 0) {ForEach(Array(session.lines.enumerated()), id: \.element.id) { i, l in@@ -390,7 +351,6 @@ struct TranscriptList: View {VStack(alignment: .leading, spacing: 4) {HStack(spacing: 8) {if inline { time(l, on) }- // An imported file names a line once its voice is told apart (the Mac's saysWho).if session.sourceFile == nil || numbers[l.id] != nil {Text(TranscriptExport.speakerName(l, numbers, names)).font(.caption.weight(.semibold))@@ -401,7 +361,6 @@ struct TranscriptList: View {if let d = l.dst, d != l.src, d != l.shown {Text(TranscriptSearch.highlighted(AttributedString(d), terms, current: l.id == found)).font(.system(size: dstSize)).foregroundStyle(Ink.ink).lineSpacing(4)}- // Tapped open: what its fixed words were heard as, 改回, and 改这句….if model.openLine == l.id {FixedWords(line: l, onRevert: { f in model.fixes.revert(f, lineID: l.id, in: session.id) },onEdit: { edit(l) })@@ -415,7 +374,6 @@ struct TranscriptList: View {withAnimation(.snappy(duration: 0.2)) { model.openLine = model.openLine == l.id ? nil : l.id }}}- // Held: the same, and 拷贝 (a long press here can't also select text)..contextMenu {Button { edit(l) } label: { Label("改这句…", systemImage: "pencil") }ForEach(Array(FixedText.applied(l).enumerated()), id: \.offset) { _, f in@@ -436,7 +394,6 @@ struct TranscriptList: View {.padding(.vertical, 14).padding(.horizontal, 20).background(on ? Ink.accent.opacity(0.06) : .clear)- // The upright strip beside the text: each line in its speaker's run..overlay(alignment: .leading) {if !numbers.isEmpty {RoundedRectangle(cornerRadius: 2).fill(mine ? SpeakerRail.focus : SpeakerRail.rest)@@ -457,7 +414,6 @@ struct TranscriptList: View {model.editingLine = LineEdit(session: session.id, line: l.id, start: l.shown)}- /// The time; with a recording it plays from that line.private func time(_ l: TranscriptLine, _ on: Bool) -> some View {Button { seek(l.t) } label: {Text(TranscriptExport.clock(l.t))@@ -470,9 +426,7 @@ struct TranscriptList: View {struct NotesPage: View {let notes: MeetingNotes?- /// A finished meeting's: the summary, conclusions and to-dos open in place on a tap.var edit: NotesEditHooks? = nil- /// The design's 16 pt notes text, as the transcript's translation.@ScaledMetric(relativeTo: .callout) private var size: CGFloat = 16var body: some View {@@ -559,7 +513,6 @@ struct NotesPage: View {}}-/// A topic's fishbone as the narrow Mac window draws it upright: the question, then each cause.struct FishboneList: View {let fishbone: Fishbone@@ -580,17 +533,12 @@ struct FishboneList: View {// MARK: - The recording-/// Plays what the record was heard from, as the Mac's RecordingPlayer: the meeting's own recording,-/// or an imported file (audio or video) where it was copied in. The transcript follows it while it-/// plays, until scrolled by hand; a line, or the bar, seeks.@MainActorfinal class RecordPlayer: ObservableObject {@Published private(set) var now: Double = 0@Published private(set) var playing = false@Published private(set) var rate: Float = 1@Published private(set) var following = true- /// The record says there is audio, but the file isn't there (`own`: the meeting's recording,- /// else the imported file).@Published private(set) var missing = false@Published private(set) var own = true@Published private(set) var duration: Double = 0@@ -601,7 +549,6 @@ final class RecordPlayer: ObservableObject {var available: Bool { player != nil }- /// Another meeting's replaces it (the page is reused when one is picked).func load(store: SessionStore, session: Session) {guard loaded != session.id else { return }unload()@@ -630,7 +577,6 @@ final class RecordPlayer: ObservableObject {ended = NotificationCenter.default.addObserver(forName: AVPlayerItem.didPlayToEndTimeNotification, object: p.currentItem, queue: .main) { [weak self] _ inMainActor.assumeIsolated { self?.playing = false }}- // Recordings made before RoomAudio leveled them are too quiet to hear: leveled as they play.if own, let item = p.currentItem { Task { await GainTap.attach(to: item) } }Task {if let d = try? await p.currentItem?.asset.load(.duration).seconds, d.isFinite { duration = d }@@ -667,7 +613,6 @@ final class RecordPlayer: ObservableObject {playing.toggle()}- /// Plays from `t` (a line, the bar): the transcript follows again from there.func play(from t: Double) {guard player != nil else { return }seek(t)@@ -687,21 +632,17 @@ final class RecordPlayer: ObservableObject {if playing { player?.rate = rate }}- /// The transcript was scrolled by hand while it plays: it stops following until 回到正在播放.func userScrolled() { if following, playing { following = false } }func follow() { following = true }func stop() { player?.pause(); playing = false }- /// The last line that started at or before the playhead, once playing has begun.func lineID(in s: Session) -> String? {guard playing || now > 0 else { return nil }return s.lines.last(where: { $0.t <= now + 0.2 })?.id}}-/// The design's glass bar: play / pause, the time, a bar to drag, the length and the speed; when the-/// file is gone, why it can't play.struct PlayerBar: View {@ObservedObject var player: RecordPlayer@@ -744,7 +685,6 @@ struct PlayerBar: View {}}-/// 回到正在播放: the transcript was scrolled away while it plays.struct FollowPill: View {@ObservedObject var player: RecordPlayervar body: some View {@@ -761,7 +701,6 @@ struct FollowPill: View {}extension TranscriptSearch {- /// The Mac's marks in iOS's colours: every term on the pale accent, the line being looked at solid.static func highlighted(_ base: AttributedString, _ terms: [String], current: Bool) -> AttributedString {var a = basefor term in terms where !term.isEmpty {@@ -777,8 +716,6 @@ extension TranscriptSearch {}extension Notification.Name {- /// Debug `play:<seconds>`: the open record plays from there.static let debugPlay = Notification.Name("cicada.debugPlay")- /// Debug `scrollTo:<line id>`: the open record scrolls there.static let debugScroll = Notification.Name("cicada.debugScroll")}diff --git a/ios/Sources/Cicada/RecordsView.swift b/ios/Sources/Cicada/RecordsView.swiftindex 10dc701..84b9623 100644--- a/ios/Sources/Cicada/RecordsView.swift+++ b/ios/Sources/Cicada/RecordsView.swift@@ -1,8 +1,5 @@import SwiftUI-/// 会议记录 (iPhone), as the design's home: the title with the import button, the 听会议室 card,-/// then the meetings as grouped white cards on the grey ground. Grouping and titles are the Mac's-/// (RecordList).struct RecordsSplit: View {@EnvironmentObject var model: AppModel@EnvironmentObject var room: RoomListen@@ -50,8 +47,6 @@ struct RecordsSplit: View {}}-/// The app icon, drawn by the Mac's renderer at build time (ios/scripts/build.sh); its macOS margin-/// is cropped so the tile fills the frame.struct Logo: View {let size: CGFloatprivate static let image = Bundle.main.path(forResource: "logo", ofType: "png").flatMap(UIImage.init(contentsOfFile:))@@ -70,8 +65,6 @@ struct Logo: View {}}-/// iPad: the design's glass sidebar (title, import, settings, a search field, the meetings) beside-/// the open meeting, which is the newest until one is picked, as on the Mac.struct PadRoot: View {@EnvironmentObject var model: AppModel@EnvironmentObject var room: RoomListen@@ -153,7 +146,6 @@ struct PadRoot: View {}}-/// The sidebar's small white round buttons.struct PadIcon: View {let systemName: String@@ -174,8 +166,6 @@ struct EmptyRecords: View {}}-/// 今天 / 昨天 / 本周 / months, each a card of rows (iPhone) or plain rows with the picked one on a-/// white card (iPad's sidebar, as in the design's iPad screen).struct RecordGroups: View {@EnvironmentObject var model: AppModelenum Style { case cards, sidebar }@@ -203,7 +193,6 @@ struct RecordGroups: View {ForEach(group.sessions) { s inButton { pick(s.id) } label: {RecordRow(session: s, chevron: false)- // White on the light glass needs a soft edge to read as picked..background(RoundedRectangle(cornerRadius: 14, style: .continuous).fill(s.id == picked ? Color.white : .clear).shadow(color: Ink.ink.opacity(s.id == picked ? 0.10 : 0), radius: 6, y: 2))@@ -219,7 +208,6 @@ struct RecordGroups: View {.frame(maxWidth: .infinity, alignment: .leading)}- /// The Mac's row menu, less what iOS can't do (Finder, the original file).@ViewBuilder private func menu(_ s: Session) -> some View {if s.renamed ?? !s.title.hasPrefix("会议 "), s.notes?.title != nil {Button { model.rename(s.id, to: "") } label: { Label("恢复自动标题", systemImage: "arrow.uturn.backward") }@@ -230,7 +218,6 @@ struct RecordGroups: View {}}-/// A pressed row darkens slightly, like a system list cell.struct RowPress: ButtonStyle {func makeBody(configuration: Configuration) -> some View {configuration.label.background(configuration.isPressed ? Ink.ink.opacity(0.05) : .clear)@@ -241,7 +228,6 @@ struct RecordRow: View {@EnvironmentObject var model: AppModellet session: Sessionlet chevron: Bool- /// Watched here so "3 人" comes and goes with 说话人识别 (a row's session doesn't change).@AppStorage(Pref.voices) private var voices = trueprivate var runs: [SpeakerRail.Run] {@@ -265,7 +251,6 @@ struct RecordRow: View {}}.padding(.leading, runs.isEmpty ? 0 : 14)- // Scheme A's upright strip: each person's turns in grey, a bookmark of the meeting..overlay(alignment: .leading) {if !runs.isEmpty { RailView(runs: runs, axis: .upright, thickness: 4).padding(.vertical, 2) }}@@ -278,7 +263,6 @@ struct RecordRow: View {.contentShape(Rectangle())}- /// "10:02 · 48 分钟 · 3 人 · 英 → 中 · 会议室", as in the design's rows.static func meta(_ s: Session, voices on: Bool) -> String {var parts = [RecordList.when(s), RecordList.length(s)]let voices = on ? SpeakerLabels.voiceNumbers(s).count : 0@@ -289,8 +273,6 @@ struct RecordRow: View {}}-/// Search on its own tab: titles and every line, original and translation. A meeting opened from-/// here opens at the first line found (RecordView's `searching`).struct SearchView: View {@EnvironmentObject var model: AppModel@ObservedObject var store: SessionStore@@ -299,7 +281,6 @@ struct SearchView: View {let q = query.trimmingCharacters(in: .whitespaces)guard !q.isEmpty else { return sessions }return sessions.filter { s in- // As the Mac's records: a name the notes say was misheard finds those lines too.let terms = TranscriptSearch.terms(q, notes: s.notes?.terms ?? [])return s.displayTitle.localizedCaseInsensitiveContains(q) || s.lines.contains { TranscriptSearch.matches($0, terms) }}@@ -324,18 +305,14 @@ struct SearchView: View {.navigationDestination(for: String.self) { id inif let s = store.sessions.first(where: { $0.id == id }) { RecordView(session: s, searching: true) }}- // At the top, under the title: the bottom is the tab bar's..searchable(text: $model.query, placement: .navigationBarDrawer(displayMode: .always), prompt: Text("搜索文字记录"))}}}extension AppModel {- /// The search in a meeting: the query, plus how its notes say those names were heard.func searchTerms(_ s: Session) -> [String] { TranscriptSearch.terms(query, notes: s.notes?.terms ?? []) }- /// The ids of the lines the search finds in a meeting, in order.func searchMatches(_ s: Session) -> [String] { TranscriptSearch.matches(s.lines, searchTerms(s)) }- /// 上一个 / 下一个, round from the last back to the first.func stepSearch(_ d: Int, in s: Session) {let n = searchMatches(s).countguard n > 0 else { return }@@ -343,7 +320,6 @@ extension AppModel {}}-/// Where the search is in the open meeting (本场 2 / 7), and the way to the previous and next line.struct SearchMatchBar: View {let index: Intlet count: Intdiff --git a/ios/Sources/Cicada/RoomListen.swift b/ios/Sources/Cicada/RoomListen.swiftindex f6c2847..e6c87d0 100644--- a/ios/Sources/Cicada/RoomListen.swift+++ b/ios/Sources/Cicada/RoomListen.swift@@ -2,14 +2,8 @@ import AVFoundationimport Foundationimport Network-/// 听会议室 on iPhone and iPad: the microphone → the shared recognizer (`Recognition`) → the shared-/// translation chain → the meeting record, with live notes from the shared `NotesEngine`. The Mac's-/// `ListenEngine` is bound to Core Audio and AppKit; this is the same pipeline cut down to one source.-/// 对方说 is one language, or 自动识别: listening starts in the likeliest one and the first words-/// settle it (`LanguageDetector`, as on the Mac), heard again in another language if that's the one.@MainActorfinal class RoomListen: ObservableObject {- /// One sentence on the 字幕 page.struct Line: Identifiable, Equatable {let id: Stringvar src: String@@ -21,56 +15,35 @@ final class RoomListen: ObservableObject {@Published private(set) var isRunning = false@Published private(set) var startedAt: Date?@Published private(set) var lines: [Line] = []- /// The sentence in progress and its draft translation.@Published private(set) var draft = ""@Published private(set) var draftTranslation = ""- /// 0–1, for the wave.@Published private(set) var level: Float = 0@Published private(set) var status = ""@Published private(set) var sessionID: String?- /// 手机外放: a video app plays aloud while we listen from the background, so its audio keeps- /// playing beside ours and the subtitles go to the picture-in-picture window (PiPSubtitles).@Published private(set) var speakerMode = false- /// A call, Siri or another app took the audio, or 暂停 on the lock screen: the microphone is- /// off until it ends.@Published private(set) var paused = false- /// The pause is the user's (暂停): an interruption ending doesn't end it.private var userPaused = false- /// Why 开始听 didn't start, shown under it: listening has stopped, so the live screen (where- /// `status` goes) is gone and a bare status would never be seen.enum StartProblem: Equatable {case microphone- /// A speech model that couldn't be had (the Mac's `ModelProblem`, its causes and words).case model(ModelProblem)case other(String)}@Published private(set) var problem: StartProblem?- /// A speech model on its way since then (约 140 MB · 已等 …).@Published private(set) var downloading: (name: String, since: Date)?- /// Debug (`modelFail:<offline|disk|limit|other>`): the next model download fails that way.static var simulatedModelFailure: String?- /// How the last 开始听 was asked, for 再试一次 and the network coming back.private var lastStart: (source: String, target: String, voices: Bool, speaker: Bool)?private let path = NWPathMonitor()private var online = true- /// Every finished line, for the Live Activity.var onLine: ((Line) -> Void)?- /// A line was written or its words changed (a joined sentence): the word list's known- /// misheard forms are fixed at once (`LiveFixes.applyKnown`).var onHeard: ((_ session: String, _ lineID: String) -> Void)?- /// A meeting was stored as ended (存到文件夹 writes it once its notes are done).var onEnded: ((_ session: String) -> Void)?- /// Debug (`silentListen`): a meeting with no microphone and no recognizer, fed by `heard:`.static var silent = falseprivate var silentClock = 0.0var onStateChange: (() -> Void)?- /// A meeting began (true) or closed (false), for the diagnostics.var onMeeting: ((Bool) -> Void)?- /// Each finished sentence's timings (never its text), for 复制诊断信息.var onTiming: ((SentenceTiming) -> Void)?- /// Line id → when its words were final and how long recognizing took after the last word.private var finalTiming: [String: (at: Date, recognize: Double)] = [:]private let store: SessionStore@@ -80,20 +53,15 @@ final class RoomListen: ObservableObject {private let audio = RoomAudio()private var stream: RecognitionStream?private var reader: Task<Void, Never>?- /// The last meeting still closing: its recognizer flushes the last sentence before its session ends.private var stopping: Task<Void, Never>?private var lang = sourceLanguages[0]private var target = "zh-Hans"private var counter = 0- /// The last line written, with where it sits on the recognizer's clock, for joining a sentence a pause cut.private var last: (id: String, src: String, end: Double)?private var draftAsked = Date.distantPastprivate var draftEpoch = 0- /// The microphone heard something loud enough to be a voice, for keeping a meeting with no lines.private var heardVoice = false- /// 自动识别: until the language is settled, finished lines wait in `held` (written once it is- /// the one listened in) and the microphone's audio is kept to hear again in another.private var auto = falseprivate var settled = trueprivate var candidates: [Lang] = []@@ -101,23 +69,16 @@ final class RoomListen: ObservableObject {private var held: [Recognition.Piece] = []private var detector: Task<Void, Never>?private var lastVoiceAt = Date.distantPast- /// The recognizer in use: pieces from one replaced (another language) are dropped.private var generation = 0- /// 会后重听, as on the Mac: a second recognizer, never hurried for the subtitles, hears the same- /// audio and its words replace the live ones in the record (`RecordRefiner`). Each finished- /// piece is a segment; a line (one or more joined pieces) changes once all its segments settled.private var refiner: RecordRefiner?private var refinerGen = 0private var recordTask: Task<Void, Never>?private var segCounter = 0private var lineOfSegment: [Int: String] = [:]private var refining: [String: [(id: Int, text: String, settled: String?)]] = [:]- /// Debug (`recordTrack:off`): the record keeps the live recognizer's words, for comparing.static var recordTrackOff = false- /// Models compared at once: each check transcribes the clip with every one of them.private static let maxCandidates = 4- /// Kept audio after which the language stays as it is (nobody spoke a clear sentence).private static let giveUpSeconds = 90.0init(store: SessionStore, translator: TranslationService, notes: NotesEngine) {@@ -129,7 +90,6 @@ final class RoomListen: ObservableObject {self.store.setVoice(lineID: lineID, voice)if let i = self.lines.firstIndex(where: { $0.id == lineID }) { self.lines[i].voice = voice }}- // 记住的人: a remembered voice is named as soon as it is heard, as on the Mac.speakers.onProfile = { [weak self] lineID, voice, match inguard let self, let id = self.store.liveID else { return }self.store.setVoice(lineID: lineID, voice)@@ -138,7 +98,6 @@ final class RoomListen: ObservableObject {if let i = self.lines.firstIndex(where: { $0.id == lineID }) { self.lines[i].voice = voice }debugLog("voice profiles: heard \(match.profile.name) (\(String(format: "%.2f", match.similarity)))")}- // A download that failed for want of a network starts again once there is one (as on the Mac).path.pathUpdateHandler = { [weak self] p inlet up = p.status == .satisfiedDispatchQueue.main.async {@@ -152,7 +111,6 @@ final class RoomListen: ObservableObject {path.start(queue: .global(qos: .utility))}- /// 再试一次: 开始听 again as it was asked.func retry() {guard !isRunning, let s = lastStart else { return }debugLog("room: start again after \(String(describing: problem))")@@ -161,13 +119,10 @@ final class RoomListen: ObservableObject {func dismissProblem() { problem = nil }- /// 记住的人 (PeoplePage.swift): voices remembered by voiceprint, matched while listening.var profiles: SpeakerProfileStore? { didSet { speakers.profiles = profiles } }- /// A voice just remembered in the meeting still going: it keeps that name from now on.func bind(voice: Int, profile: SpeakerProfile) { speakers.bind(voice: voice, profile: profile) }- /// Distinct voices heard so far.var speakerCount: Int { Set(lines.compactMap(\.voice)).count }var elapsed: TimeInterval { startedAt.map { Date().timeIntervalSince($0) } ?? 0 }@@ -192,8 +147,6 @@ final class RoomListen: ObservableObject {}private func begin(voices: Bool) async {- // Started again right after 结束: the last meeting's closing would otherwise cancel this one's- // reader and end this one's session, leaving the microphone on with nothing coming in.await stopping?.valueguard isRunning else { return }lines = []@@ -242,14 +195,12 @@ final class RoomListen: ObservableObject {guard isRunning else { await stream.cancel(); return }self.stream = streamlet s = store.begin()- // Video played aloud is what the computer plays, not people in the room (the Mac's 会议室 tag).if !speakerMode { store.markLiveInRoom() }sessionID = s.idstartedAt = s.startedAtnotes.begin(s.id)audio.voices = voicesaudio.onInterruption = { [weak self] began in self?.interrupted(began) }- // 保存会议录音 off: nothing is written; voiceprints still read the last minute in memory.let keep = UserDefaults.standard.bool(forKey: Pref.recordAudio)try audio.start(recognizer: stream, recording: keep ? AudioFileWriter.partial(store.systemAudioURL(s.id)) : nil,keep: !settled)@@ -289,10 +240,8 @@ final class RoomListen: ObservableObject {do {for try await piece in stream.results { self?.handle(piece, gen) }} catch {- // A recognizer replaced by another language's ends as it should.guard let self, gen == self.generation else { return }debugLog("room: recognizer ended: \(error)")- // The meeting so far is kept; listening stops with a reason rather than hearing nothing.guard self.isRunning else { return }self.stop()self.status = L("识别中断了,请重新开始听")@@ -302,8 +251,6 @@ final class RoomListen: ObservableObject {// MARK: 自动识别- /// The models to compare: the two likeliest for this phone (downloaded if they aren't yet),- /// then any other already here.private func autoCandidates() async -> [Lang] {let likely = likelySourceLanguages(last: UserDefaults.standard.string(forKey: Pref.lastDetected),systemLanguages: Locale.preferredLanguages).prefix(2)@@ -323,7 +270,6 @@ final class RoomListen: ObservableObject {return out}- /// Checks the language each time a few more seconds of speech came in, until it is settled.private func watchLanguage() {detector?.cancel()detector = Task { [weak self] in@@ -338,7 +284,6 @@ final class RoomListen: ObservableObject {self.settle()return}- // Someone spoke just now, and enough of it since the last check to tell.guard kept >= 5, kept - checkedAt >= 4, Date().timeIntervalSince(self.lastVoiceAt) < 3 else { continue }checkedAt = keptlet ranked = await LanguageDetector.rank(self.audio.keptClip(last: 8), candidates: self.candidates)@@ -350,14 +295,12 @@ final class RoomListen: ObservableObject {case .switchTo(let other, _):await self.switchTo(other)default:- // Too close to call twice: the language listened in stands.if self.detection.settledEnough { self.settle() }}}}}- /// The language listened in is the one: the lines held come out.private func settle() {guard !settled else { return }settled = true@@ -371,7 +314,6 @@ final class RoomListen: ObservableObject {onStateChange?()}- /// Another language: a recognizer for it hears everything kept so far, then the microphone.private func switchTo(_ other: Lang) async {guard let live = try? await Recognition.start(other.locale, drafts: true, confidence: true) else {debugLog("room: auto can't start \(other.locale), staying in \(lang.locale)")@@ -396,8 +338,6 @@ final class RoomListen: ObservableObject {settle()}- /// Paused while the audio is taken, then on again by itself; if the system won't give the- /// microphone back yet (the app is still behind a call screen), again when the app comes back.private func interrupted(_ began: Bool) {guard isRunning else { return }if began {@@ -426,7 +366,6 @@ final class RoomListen: ObservableObject {private var resumeWhenActive = false- /// 暂停 / 继续 (the Live Activity's button): the microphone off and on, the meeting going on.func setPaused(_ on: Bool) {guard isRunning, sessionID != nil, on != userPaused else { return }userPaused = on@@ -452,14 +391,12 @@ final class RoomListen: ObservableObject {onStateChange?()}- /// The app is in front again: a pause whose end came too early to take the microphone back.func appBecameActive() {guard resumeWhenActive, isRunning, paused else { return }resumeWhenActive = falseinterrupted(false)}- /// 手机外放 with nothing loud enough after ten seconds: most likely headphones or a low volume.private func watchSilence(_ id: String) {Task { [weak self] intry? await Task.sleep(nanoseconds: 10_000_000_000)@@ -469,14 +406,10 @@ final class RoomListen: ObservableObject {}}- /// Debug (`interrupt:began|ended`): what the system sends for a call or Siri.func debugInterrupt(_ began: Bool) { audio.debugInterrupt(began) }- /// A speech model that couldn't be had, as the start's error: the card under 开始听 says why.struct ModelFailure: Error { let problem: ModelProblem }- /// Downloads `lang`'s speech model. At the five-model limit one this app isn't using (and isn't a- /// likely language) is given back and the download tried once more, as on the Mac.private func fetch(_ lang: Lang) async throws {status = L("正在下载 \(lang.name) 语音模型…")downloading = (lang.name, Date())@@ -522,14 +455,11 @@ final class RoomListen: ObservableObject {onStateChange?()}- /// `endedAt`: when the meeting really ended (结束会议 by itself: a little after the last words).func stop(endedAt: Date? = nil) {guard isRunning else { return }detector?.cancel()detector = nil- // Ended before the language was settled: what was heard is kept, in the language listened in.if !settled, sessionID != nil { settle() }- // A piece still hearing its voice is recorded now, on its own, before the meeting closes.if let h = heldJoin {heldJoin = nilvoicePending[h.piece.start] = appendLine(h.piece, h.text)@@ -546,10 +476,8 @@ final class RoomListen: ObservableObject {stopping = Task {await stream?.finish()reader?.cancel()- // The record's last sentences settle their lines before the notes' final round reads them.await recordTask?.valuenotes.finish()- // A meeting with no line is kept only when the microphone heard voices (its recording holds them).let ended = sessionIDstore.end(at: endedAt, heardSpeech: heardVoice)if let ended, store.session(ended) != nil { onEnded?(ended) }@@ -565,14 +493,11 @@ final class RoomListen: ObservableObject {private func handle(_ piece: Recognition.Piece, _ gen: Int) {guard gen == generation else { return }- // Words heard are a voice too: across a room the level stays under the voice mark (a laptop- // a metre away peaked at 0.26), and without this 自动识别 never checked and held every line 90 s.if !piece.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {heardVoice = truelastVoiceAt = Date()if !settled, status.isEmpty { status = L("正在识别语言…") }}- // 自动识别 not settled: a line in what may be the wrong language waits, and no draft shows.guard settled else {if piece.isFinal { held.append(piece) }return@@ -591,15 +516,12 @@ final class RoomListen: ObservableObject {draftEpoch += 1guard final.contains(where: \.isLetter), startedAt != nil else { return }contentLog("FINAL [\(lang.locale)] \(final)")- // A piece still waiting for its voice is overtaken: it stands on its own.if let h = heldJoin {heldJoin = nilvoicePending[h.piece.start] = appendLine(h.piece, h.text)}- // One sentence a pause cut in two: the earlier line takes the rest.if let prev = last, lines.last?.id == prev.id,HeardText.continues(prev.src, final, gap: piece.start - prev.end, cut: false) {- // Two voices never share a line: hear whose this is first (a few hundredths of a second), as on the Mac.if audio.voices, final.filter(\.isLetter).count >= 2,let samples = audio.voiceSamples(from: piece.start, to: piece.end) {heldJoin = (piece, final)@@ -616,27 +538,23 @@ final class RoomListen: ObservableObject {}}- /// A finished piece waiting to hear whether its voice is the line before's.private var heldJoin: (piece: Recognition.Piece, text: String)?- /// Pieces recorded on their own while their voice was being heard, by start time.private var voicePending: [Double: String] = [:]private func heardVoice(_ key: Double, _ a: SpeakerAssignment) {guard let h = heldJoin, h.piece.start == key else {- // Already recorded on its own (another line came first).if let id = voicePending.removeValue(forKey: key) { apply(a, to: id) }return}heldJoin = nilif let prev = last, let line = lines.last, line.id == prev.id,a.voice == nil || line.voice == nil || a.voice == line.voice {- joinLine(h.piece, h.text, onto: prev) // the earlier line's voice stays+ joinLine(h.piece, h.text, onto: prev)} else {apply(a, to: appendLine(h.piece, h.text))}}- /// A voice heard for a line not recorded yet, put on it once it is.private func apply(_ a: SpeakerAssignment, to id: String) {guard let voice = a.voice else { return }if let match = a.match, match.kind == .auto { speakers.onProfile?(id, voice, match) } else { speakers.onVoice?(id, voice) }@@ -657,7 +575,6 @@ final class RoomListen: ObservableObject {private func appendLine(_ piece: Recognition.Piece, _ final: String) -> String {counter += 1let id = "r\(counter)"- // Where the sentence started, in meeting time: the recognizer's clock runs on the audio fed.let t = max(0, Date().timeIntervalSince(startedAt ?? Date()) - max(0, audio.fedSeconds - piece.start))store.append(TranscriptLine(id: id, t: t, speaker: "them", src: final, dst: nil,srcLang: lang.code, dstLang: target))@@ -673,8 +590,6 @@ final class RoomListen: ObservableObject {// MARK: 会后重听- /// `live` with the record's own recognizer beside it, fed the same audio (`TeeStream`), or `live`- /// alone where there is none (`Recognition.recordTrack`: not the simulator nor the older model).private func withRecord(_ live: RecognitionStream, locale: String? = nil) async -> RecognitionStream {recordTask?.cancel()recordTask = nil@@ -705,7 +620,6 @@ final class RoomListen: ObservableObject {return TeeStream(live: live, record: record)}- /// A finished piece, a segment of line `line`, for the record's recognizer to settle.private func emitted(_ piece: Recognition.Piece, _ text: String, line: String) {guard refiner != nil else { return }segCounter += 1@@ -719,8 +633,6 @@ final class RoomListen: ObservableObject {for o in out { refined(o.id, o.text, session: session ?? sessionID) }}- /// The record's recognizer settled segment `seg`. Once every segment of its line has, the line- /// takes the record's words and is translated again; a segment it heard nothing in keeps its own.private func refined(_ seg: Int, _ text: String, session: String?) {guard let session, let line = lineOfSegment.removeValue(forKey: seg), var segs = refining[line],let k = segs.firstIndex(where: { $0.id == seg }) else { return }@@ -732,7 +644,6 @@ final class RoomListen: ObservableObject {let parts = segs.map { $0.settled! }let whole = parts.dropFirst().reduce(parts[0]) { HeardText.join($0, $1) }guard let rec = store.session(session)?.lines.first(where: { $0.id == line }), whole != rec.src else { return }- // The line's later pieces may still come (joined): they start a new round for it.store.setSource(in: session, lineID: line, whole)if let i = lines.firstIndex(where: { $0.id == line }) { lines[i].src = whole }if last?.id == line { last?.src = whole }@@ -747,18 +658,13 @@ final class RoomListen: ObservableObject {}}- /// Debug (`heard:<text>`): a finished sentence as if the recognizer gave it, in a silent meeting.- /// The record, its translation and fixes, and the 字幕 page all follow.func debugHeard(_ text: String) {guard isRunning, Self.silent, sessionID != nil else { return }- // Half a minute apart, so two lines are never joined as one sentence a pause cut.silentClock += 30let at = silentClockhandle(Recognition.Piece(text: text, isFinal: true, start: at, end: at + 2, confidence: nil), generation)}- /// Debug (`heardT:<text>|<translation>`): as `debugHeard`, with the translation given, for- /// screenshots when no translation service answers.func debugHeard(_ text: String, translation: String) {debugHeard(text)guard let i = lines.lastIndex(where: { $0.src == text }) else { return }@@ -767,8 +673,6 @@ final class RoomListen: ObservableObject {onLine?(lines[i])}- /// `retry`: every provider failed before (Ling busy while Google answers 429): asked again a- /// little later, twice at most, as the Mac does.private func translate(_ id: String, _ text: String, retry: Int = 0) {let source = lang.code, target = self.targetlet trace = TranslateTrace(), asked = Date()@@ -787,7 +691,6 @@ final class RoomListen: ObservableObject {translate(id, text, retry: retry + 1)return}- // Joined meanwhile: only the whole sentence's translation counts.guard let i = lines.firstIndex(where: { $0.id == id }), lines[i].src == text else { return }lines[i].dst = outstore.setTranslation(lineID: id, out)@@ -796,7 +699,6 @@ final class RoomListen: ObservableObject {}}- /// The line in progress, at most every second (Google, never Ling: AGENTS.md).private func translateDraft() {guard Date().timeIntervalSince(draftAsked) > 1, draft.count >= 6 else { return }draftAsked = Date()@@ -809,18 +711,13 @@ final class RoomListen: ObservableObject {}}-/// The microphone side, off the main actor: `AVAudioEngine`'s input tap → the recognizer's format,-/// the meeting's recording, a level and the last minute of 16 kHz audio for voiceprints.final class RoomAudio: @unchecked Sendable {var voices = truevar onLevel: (@MainActor (Float) -> Void)?- /// true when a call, Siri or another app takes the audio, false when it gives it back.var onInterruption: (@MainActor (Bool) -> Void)?private var observers: [NSObjectProtocol] = []- /// Inside an interruption: a configuration change then must not take the microphone back.private var held = false- /// A new engine for each meeting: one restarted after `stop` hears only silence in the simulator.private var engine = AVAudioEngine()private let queue = DispatchQueue(label: "com.indaloop.cicada.room", qos: .userInitiated)private var toRecognizer = PCMConverter()@@ -830,12 +727,10 @@ final class RoomAudio: @unchecked Sendable {private var recorder: AVAudioFile?private var recordGain = AutoGain()private var recordingURL: URL?- /// Recognizer-clock seconds of audio appended, and the voice ring (its first sample's time).private var fed = 0.0private var ring: [Float] = []private var ringStart = 0.0private var lastLevel = Date.distantPast- /// 自动识别: the 16 kHz audio since the start, until the language is settled.private var keeping = falseprivate var kept: [AVAudioPCMBuffer] = []private var keptFrames = 0@@ -843,7 +738,6 @@ final class RoomAudio: @unchecked Sendable {var fedSeconds: Double { queue.sync { fed } }var keptSeconds: Double { queue.sync { Double(keptFrames) / 16_000 } }- /// The last `seconds` of the audio kept, for a language check.func keptClip(last seconds: Double) -> [AVAudioPCMBuffer] {queue.sync {var out: [AVAudioPCMBuffer] = [], frames = 0@@ -863,8 +757,6 @@ final class RoomAudio: @unchecked Sendable {}}- /// Settled on another language: `recognizer` takes over and first hears everything kept, so- /// nothing said before is lost and its clock runs from the meeting's start as the old one did.func replay(into recognizer: RecognitionStream) {queue.sync {stream = recognizer@@ -884,10 +776,6 @@ final class RoomAudio: @unchecked Sendable {func start(recognizer: RecognitionStream, recording: URL?, keep: Bool = false) throws {let session = AVAudioSession.sharedInstance()- // .measurement: no voice processing, which would duck what the room says as "echo".- // .defaultToSpeaker sends every app's sound to the speaker, not the earpiece, while we record.- // .mixWithOthers in both modes: listening plays nothing, and a non-mixable session would stop- // a video that's playing when 开始听 is tapped, and be stopped itself when one starts.try session.setCategory(.playAndRecord, mode: .measurement, options: [.defaultToSpeaker, .mixWithOthers])try session.setActive(true)engine = AVAudioEngine()@@ -919,13 +807,11 @@ final class RoomAudio: @unchecked Sendable {try engine.start()}- /// 暂停: nothing is heard or recorded until `resume`.func pause() {held = trueengine.pause()}- /// The microphone again after an interruption, in whatever format the route now has.func resume() throws {held = falsetry AVAudioSession.sharedInstance().setActive(true)@@ -944,7 +830,6 @@ final class RoomAudio: @unchecked Sendable {let cb = self?.onInterruptionMainActor.assumeIsolated { cb?(began) }},- // A route change (headphones in or out) stops the engine: on again in the new format.center.addObserver(forName: .AVAudioEngineConfigurationChange, object: engine, queue: .main) { [weak self] _ inguard let self, !self.held, !self.engine.isRunning else { return }debugLog("room: engine configuration changed")@@ -979,7 +864,6 @@ final class RoomAudio: @unchecked Sendable {guard let v = toVoice.convert(buffer, to: voiceFormat), let p = v.floatChannelData?[0] else { return }let n = Int(v.frameLength)if recorder == nil, let url = recordingURL { recorder = AudioFileWriter.open(url, format: voiceFormat) }- // The file gets speech level (AutoGain); recognizer and voiceprints keep the room as heard.if let recorder, let loud = v.copy() as? AVAudioPCMBuffer, let q = loud.floatChannelData?[0] {recordGain.apply(q, count: n)try? recorder.write(from: loud)@@ -996,7 +880,6 @@ final class RoomAudio: @unchecked Sendable {ring.removeFirst(drop)ringStart += Double(drop) / 16_000}- // The ring runs on the voice clock; it tracks the recognizer's since both see every buffer.} else {ringStart = fed}@@ -1005,7 +888,6 @@ final class RoomAudio: @unchecked Sendable {var sum: Float = 0for i in 0..<n { sum += p[i] * p[i] }let rms = n > 0 ? (sum / Float(n)).squareRoot() : 0- // -50…-10 dBFS onto 0…1.let db = 20 * log10(max(rms, 1e-6))let v = max(0, min(1, (db + 50) / 40))let cb = onLevel@@ -1013,7 +895,6 @@ final class RoomAudio: @unchecked Sendable {}}- /// 16 kHz mono audio between two recognizer-clock times, if still in the ring and long enough.func voiceSamples(from: Double, to: Double) -> [Float]? {queue.sync {guard voices else { return nil }diff --git a/ios/Sources/Cicada/RootView.swift b/ios/Sources/Cicada/RootView.swiftindex ce4b517..54b979d 100644--- a/ios/Sources/Cicada/RootView.swift+++ b/ios/Sources/Cicada/RootView.swift@@ -1,9 +1,5 @@import SwiftUI-/// The design's shell. iPhone: 会议记录 and 设置 on a glass bar, search a glass circle beside it, and-/// the bar only on those top screens (a meeting has the page to itself). iPad: a glass sidebar of-/// meetings beside the open one, settings as a sheet. The system TabView can't draw either: it-/// merges search into the bar and puts a tab pill over the iPad's detail.struct RootView: View {@EnvironmentObject var model: AppModel@Environment(\.horizontalSizeClass) private var sizeClass@@ -17,7 +13,6 @@ struct RootView: View {}}.tint(Ink.accent)- // The Mac's palette is light only (Palette in Views.swift); a dark one comes later, for both..preferredColorScheme(.light).fullScreenCover(isPresented: $model.showFace, onDismiss: { model.closeFace() }) {FaceView(face: model.face).environmentObject(model)@@ -41,7 +36,6 @@ struct PhoneRoot: View {var body: some View {ZStack {- // Each tab keeps its place while another is shown, like a tab bar's.RecordsSplit(store: model.store).opacity(model.tab == .records ? 1 : 0).allowsHitTesting(model.tab == .records)SettingsView().opacity(model.tab == .settings ? 1 : 0)@@ -64,7 +58,6 @@ struct PhoneRoot: View {}}-/// Two tabs in a glass capsule, the picked one on a faint accent pill, and search on its own.struct TabBar: View {@EnvironmentObject var model: AppModel@@ -114,7 +107,6 @@ struct TabBar: View {}private func pick(_ tab: AppTab) {- // Tapping the open tab again goes back to its top, as a tab bar does.if model.tab == tab {if tab == .records { model.selection = nil }if tab == .search { model.searchPath = [] }diff --git a/ios/Sources/Cicada/SettingsView.swift b/ios/Sources/Cicada/SettingsView.swiftindex fe559ff..51d2a85 100644--- a/ios/Sources/Cicada/SettingsView.swift+++ b/ios/Sources/Cicada/SettingsView.swift@@ -1,9 +1,6 @@import SwiftUI-/// 设置, as the design's: grey section labels over white cards: the Ling key and model (纪要), the-/// language meetings are translated into, 说话人识别, 面对面's own language, and 快速开始.struct SettingsView: View {- /// iPad shows it as a sheet, with 完成.var sheet = false@EnvironmentObject var model: AppModel@EnvironmentObject var ling: LingClient@@ -78,7 +75,6 @@ struct SettingsView: View {.tint(Ink.ok)}, L("只存在这台手机上,会议记录里能回放原声"))}- // As on the Mac and Android, minus 会议应用挂断后结束: iOS can't see another app's microphone.SectionLabel(text: L("结束会议"))Card {helped(row(Text("没人说话时")) {@@ -104,7 +100,6 @@ struct SettingsView: View {SectionLabel(text: L("纪要"))Card {row(Text("纪要语言")) {- // The menu names the language; the row only the choice, so it fits on one line in English.Menu {Picker(selection: $notesLanguage) {Text(L("我的语言 · \(targetName(Pref.targetCode))")).tag("mine")@@ -163,7 +158,6 @@ struct SettingsView: View {.font(.footnote).foregroundStyle(Ink.tertiary).frame(maxWidth: .infinity).padding(.top, 28)- // For a bug report: numbers only (timings, counts, the service and model), never what was said.Button {UIPasteboard.general.string = model.diagnosticsReportcopiedDiagnostics = true@@ -176,7 +170,6 @@ struct SettingsView: View {}.padding(.horizontal, 16).padding(.bottom, 120)- // On iPad a readable column, not the whole width..frame(maxWidth: 640).frame(maxWidth: .infinity)}@@ -200,7 +193,6 @@ struct SettingsView: View {.tint(Ink.ink)}- /// A row with its one grey helper line under it.private func helped<R: View>(_ row: R, _ help: String) -> some View {VStack(alignment: .leading, spacing: 0) {row@@ -210,7 +202,6 @@ struct SettingsView: View {}}- /// 念给对方的声音 at a glance: the voice the other person hears.private var voiceSummary: String {let lang = model.face.theirs.codelet id = SpeakVoices.chosenID(for: lang, hasKey: ling.hasKey, clones: ling.clones)@@ -231,7 +222,6 @@ struct SettingsView: View {}}-/// "● 已连接" and the other key states, as on the Mac's AI 服务 page.struct KeyStatus: View {let state: LingClient.KeyState@@ -262,7 +252,6 @@ struct KeyStatus: View {}}-/// Paste or type the key; it is checked with one tiny request and kept only in the app's file.struct KeyPage: View {@EnvironmentObject var ling: LingClient@AppStorage(Pref.model) private var aiModel = LingClient.models[0]@@ -324,7 +313,6 @@ struct KeyPage: View {}if ling.key != nil && !editing {HStack {- // Any state: a key fixed on the service's side (its model list, its credit) is checked again here.Button("重新检查") { Task { await ling.check() } }.disabled(ling.keyState == .checking)Spacer()@@ -363,10 +351,7 @@ struct KeyPage: View {}}-/// 设置 › 快速开始: where 开始听 can be put. iOS lets only the user choose them, in the system's own-/// settings; this page says where.struct QuickStartPage: View {- /// What Siri and the Action button list the app as.private let name = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String ?? appDisplayNamevar body: some View {diff --git a/ios/Sources/Cicada/ShareCard.swift b/ios/Sources/Cicada/ShareCard.swiftindex b42e83a..8b6902f 100644--- a/ios/Sources/Cicada/ShareCard.swift+++ b/ios/Sources/Cicada/ShareCard.swift@@ -1,9 +1,6 @@import SwiftUIimport UIKit-/// 分享链接 at the top of 导出: the Mac's share (ShareClient, cicada.indaloop.app) in one card.-/// 只分享纪要 or 纪要和双语全文, valid 7 days, no password (the Mac's defaults); the server checks-/// for sensitive content first, and flagged parts can be left out and checked again.struct ShareCard: View {let session: Sessionprivate enum Step: Equatable {@@ -146,7 +143,6 @@ struct ShareCard: View {.background(Ink.accentWash, in: RoundedRectangle(cornerRadius: 10, style: .continuous))}- /// As the Mac's: an hour's slack, so a fresh 7-day link reads 7, not 8.private static func daysLeft(_ r: ShareRecord) -> Int { max(1, Int(ceil((r.expiresAt.timeIntervalSinceNow - 3600) / 86400))) }private func validity(_ r: ShareRecord) -> String {@@ -154,12 +150,10 @@ struct ShareCard: View {return left >= 365 ? L("1 年内有效") : L("\(left) 天内有效")}- /// What 复制链接 puts on the clipboard, as the Mac's: the title, the link, how long it lasts.private func clipboard(_ r: ShareRecord) -> String {[L("「\(session.displayTitle)」会议记录"), r.url, validity(r)].joined(separator: "\n")}- /// The Mac's wording for the server's codes (ShareViews.swift).static func message(_ code: String) -> String {switch code {case "rate_limited", "too_many_shares": return L("分享得太频繁了,请稍后再试。")diff --git a/ios/Sources/Cicada/SpeakerRail.swift b/ios/Sources/Cicada/SpeakerRail.swiftindex aad35cb..cd58c86 100644--- a/ios/Sources/Cicada/SpeakerRail.swift+++ b/ios/Sources/Cicada/SpeakerRail.swift@@ -1,21 +1,15 @@import SwiftUI-/// Scheme A of the speaker colours (the design page 说话人配色): everyone's stretch of the meeting-/// is the same light grey, so a strip shows how many turns and how long; only the person you are-/// looking for, picked on a chip or the one the recording is at, is drawn in ink. Names stay ink-/// or grey text. The accent keeps meaning "live" and the playhead.enum SpeakerRail {static let rest = Color(hex: 0xD5D8DE)static let focus = Ink.ink- /// One person's unbroken stretch: consecutive lines of the same voice are one run.struct Run: Equatable {var number: Int?var start: Doublevar length: Double}- /// The meeting as runs, by its lines' times (a line lasts until the next one starts).static func runs(_ s: Session, numbers: [String: Int]) -> [Run] {let lines = s.linesguard !lines.isEmpty else { return [] }@@ -35,8 +29,6 @@ enum SpeakerRail {return out}- /// What a strip can draw: a turn under `minShare` of the meeting joins the one before it (a- /// strip beside a row is a few dozen points tall), and neighbours of the same person merge.static func compact(_ runs: [Run], minShare: Double) -> [Run] {let total = runs.reduce(0) { $0 + $1.length }guard total > 0 else { return runs }@@ -49,7 +41,6 @@ enum SpeakerRail {out.append(r)}}- // A short first turn swallowed nothing before it: fold it into the next.if out.count > 1, out[0].length < total * minShare {out[1].start = out[0].startout[1].length += out[0].length@@ -62,7 +53,6 @@ enum SpeakerRail {return merged}- /// Each speaker number's share of the time (0–1).static func shares(_ runs: [Run]) -> [Int: Double] {let total = runs.reduce(0) { $0 + $1.length }guard total > 0 else { return [:] }@@ -72,7 +62,6 @@ enum SpeakerRail {}}-/// The strip: across under a meeting's title, or upright beside a row.struct RailView: View {enum Axis { case across, upright }let runs: [SpeakerRail.Run]@@ -85,7 +74,6 @@ struct RailView: View {let length = axis == .across ? g.size.width : g.size.heightlet runs = SpeakerRail.compact(self.runs, minShare: axis == .across ? 0.01 : 0.08)let total = max(0.001, runs.reduce(0) { $0 + $1.length })- // Too many turns for the room: no gaps, rather than a dotted line.let gap: CGFloat = CGFloat(runs.count) > length / 5 ? 0 : 2let room = length - gap * CGFloat(max(0, runs.count - 1))let layout = axis == .across ? AnyLayout(HStackLayout(spacing: gap)) : AnyLayout(VStackLayout(spacing: gap))@@ -105,11 +93,9 @@ struct RailView: View {}}-/// The record page's strip with the playhead: an accent mark where the recording is.struct MeetingRail: View {let runs: [SpeakerRail.Run]let focus: Int?- /// 0–1, nil before playing.let playhead: Double?var body: some View {diff --git a/ios/Sources/Cicada/Theme.swift b/ios/Sources/Cicada/Theme.swiftindex 1f75d7a..4df3bb4 100644--- a/ios/Sources/Cicada/Theme.swift+++ b/ios/Sources/Cicada/Theme.swift@@ -1,33 +1,24 @@import SwiftUI-/// The Mac's colours (AGENTS.md › Design): grey ground, white cards, one accent for "live".enum Ink {static let ground = Color(red: 0xF3 / 255, green: 0xF4 / 255, blue: 0xF6 / 255)static let ink = Color(red: 0x15 / 255, green: 0x17 / 255, blue: 0x1C / 255)static let accent = Color(red: 0xE8 / 255, green: 0x55 / 255, blue: 0x2B / 255)- /// The accent as text on white: ≥ 4.5:1, the plain accent is not.static let accentText = Color(red: 0xC8 / 255, green: 0x43 / 255, blue: 0x1D / 255)static let secondary = Color(red: 0x5A / 255, green: 0x5F / 255, blue: 0x6B / 255)static let tertiary = Color(red: 0x6B / 255, green: 0x70 / 255, blue: 0x80 / 255)- /// Hairlines between rows.static let line = Color(red: 0xE2 / 255, green: 0xE4 / 255, blue: 0xE9 / 255)- /// The selected tab's pill: the accent, faint.static let accentWash = Color(red: 0xE8 / 255, green: 0x55 / 255, blue: 0x2B / 255).opacity(0.12)- /// 已连接.static let ok = Color(red: 0x2F / 255, green: 0x9E / 255, blue: 0x5B / 255)- /// Numbers that order the notes: the Mac's `Palette.link`, the logo's orange as ink.static let link = Color(red: 0.70, green: 0.23, blue: 0.08)}-/// 说话人 1, 2, 3…: the design canvas's chips (blue, orange…), each a pale fill with a dark ink of the-/// same hue that passes 4.5:1 on it and on white. The Mac's `SpeakerColor` uses other hues.enum SpeakerInk {private static let pairs: [(ink: UInt32, tint: UInt32)] = [(0x1F4E8C, 0xDCE7F7), (0x8A3A16, 0xF6E2D6), (0x1E6B45, 0xDDEFE4), (0x5B3A8C, 0xE9E1F5), (0x3F434C, 0xE7E9EE),]private static func pair(_ number: Int) -> (ink: UInt32, tint: UInt32) { pairs[(max(1, number) - 1) % pairs.count] }static func ink(_ number: Int) -> Color { Color(hex: pair(number).ink) }- /// The chip behind a speaker's name.static func tint(_ number: Int) -> Color { Color(hex: pair(number).tint) }}diff --git a/ios/Sources/Cicada/VoicesPage.swift b/ios/Sources/Cicada/VoicesPage.swiftindex b6deed8..8e8d622 100644--- a/ios/Sources/Cicada/VoicesPage.swift+++ b/ios/Sources/Cicada/VoicesPage.swift@@ -1,17 +1,11 @@import AVFoundationimport SwiftUI-/// 每种语言各记一个声音: the Mac's `speakVoices` (language key → voice id), read by 面对面.enum SpeakVoices {static let key = "speakVoices"static var all: [String: String] { UserDefaults.standard.dictionary(forKey: key) as? [String: String] ?? [:] }- /// The voice for a language: the one picked, while it can still be used (Ming and the clone need- /// the key, the clone its recording), else the catalog's default. `mine`: read for me (their- /// words in my language), where my own voice would make no sense.- /// `clones`: the service can speak in the user's own voice (Ling only). A voice of another- /// service (Ming's picked under Ling, then ZenMux chosen) gives way to the default.static func chosenID(for language: String, hasKey: Bool, mine: Bool = false, clones: Bool = true) -> String? {if let id = all[VoiceCatalog.key(for: language)] {if id.hasPrefix("system:") { return id }@@ -31,8 +25,6 @@ enum SpeakVoices {}}-/// 设置 › 念给对方的声音: 用你自己的声音 (a recording Ming clones), then each language 面对面-/// speaks, with Ming's voices and the phone's; ▶ tries one with a line in that language.struct VoicesPage: View {@EnvironmentObject var model: AppModel@EnvironmentObject var ling: LingClient@@ -69,7 +61,6 @@ struct VoicesPage: View {.onDisappear { voice.stop() }}- /// Theirs first: what 面对面 reads to the other person; then mine, what it reads to me.private var languages: [String] {let both = [face.theirs.code, face.mine.code]return both.enumerated().filter { i, c in both.prefix(i).allSatisfy { VoiceCatalog.key(for: $0) != VoiceCatalog.key(for: c) } }.map(\.1)@@ -121,7 +112,6 @@ struct VoicesPage: View {private func section(_ lang: String) -> some View {let options = VoiceCatalog.options(for: lang)let mine = VoiceCatalog.key(for: lang) == VoiceCatalog.key(for: face.mine.code) && lang != face.theirs.code- // My own voice only for what is read to the other person (这是我自己的声音。只在我说话时用它替我翻译。).let rows = (!mine && hasOwn && ling.clones ? [VoiceCatalog.cloneOption] : []) + optionslet current = SpeakVoices.chosenID(for: lang, hasKey: ling.hasKey, mine: mine, clones: ling.clones)return VStack(alignment: .leading, spacing: 6) {@@ -187,7 +177,6 @@ struct VoicesPage: View {}}-/// 录制你的声音: the passage to read, a meter and the seconds, 读完了; then 录好了,先听听像不像.struct OwnVoiceSheet: View {@EnvironmentObject var ling: LingClientlet locale: String@@ -261,7 +250,6 @@ struct OwnVoiceSheet: View {.buttonStyle(.plain)}- /// What the other person will hear: a line in their language, in the voice just recorded.private func listen() {if trying { voice.stop(); trying = false; return }trying = true@@ -273,9 +261,6 @@ struct OwnVoiceSheet: View {}}-/// Records the user reading the passage: 16 kHz mono into a WAV, with a level for the meter;-/// stops by itself at 30 s. Saved as `VoiceReference` with the passage as what it says (the Mac-/// transcribes its recording; here the passage is read as shown, and Ming only needs it close).@MainActorfinal class OwnVoiceRecorder: ObservableObject {enum Phase: Equatable { case idle, recording, ready, failed(String) }diff --git a/ios/Sources/Cicada/Welcome.swift b/ios/Sources/Cicada/Welcome.swiftindex 4732629..902cac4 100644--- a/ios/Sources/Cicada/Welcome.swift+++ b/ios/Sources/Cicada/Welcome.swift@@ -1,10 +1,6 @@import AVFoundationimport SwiftUI-// 第一次打开: three steps, as the design canvas (知了 iOS M2–M4). iPhone can't hear other apps or-// speak into them, so the Mac's system-audio and BlackHole steps have no place here: the microphone-// and the speech model, a sample meeting played aloud, then the Ling key.-struct Welcome: View {@EnvironmentObject var model: AppModel@@ -30,7 +26,6 @@ struct Welcome: View {}}-/// Where the user is: the current step a short bar, the others dots.private struct Dots: View {let step: Int@@ -46,7 +41,6 @@ private struct Dots: View {}}-/// The black capsule every step ends on.struct PrimaryButton: View {let title: Stringvar enabled = true@@ -293,7 +287,6 @@ private struct SampleLine: View {}}-/// sample.m4a through the speaker while the microphone listens: the room pipeline end to end.@MainActorfinal class SampleRun: NSObject, ObservableObject, AVAudioPlayerDelegate {static let shared = SampleRun()@@ -425,8 +418,6 @@ private struct WelcomeKey: View {}extension AppModel {- /// The sample on step 2: listening starts (in English, the sample's language), and the sample- /// plays once the microphone is on; the meeting ends shortly after it does, so its last line lands.func playSample() {let sample = SampleRun.sharedguard !sample.playing else { return }diff --git a/ios/scripts/build.sh b/ios/scripts/build.shindex da24973..7d9cd50 100755--- a/ios/scripts/build.sh+++ b/ios/scripts/build.sh@@ -1,12 +1,4 @@#!/usr/bin/env bash-# Builds Cicada.app: the shared Mac sources (ios/shared-sources.txt) and ios/Sources in one module,-# bundled by hand like the Mac's scripts/build.sh (no .xcodeproj).-# Without RELEASE=1 it is a dev build: "Cicada Dev", bundle id com.indaloop.cicada.dev, cicada-dev:// commands.-# ios/scripts/build.sh the simulator: ios/build/Cicada.app, signed ad hoc-# DEVICE=1 ios/scripts/build.sh an iPhone or iPad: ios/build/device/Cicada.app, signed with-# SIGN_IDENTITY and the profiles PROFILE (app) and PROFILE_LIVE-# (the extension); ios/scripts/provision.sh makes them-# BUILD_NUMBER sets CFBundleVersion (TestFlight wants it to grow); default: the commit count.set -euo pipefailcd "$(dirname "$0")/../.."@@ -29,15 +21,11 @@ while IFS= read -r line; do [[ -z $line || $line == \#* ]] || files+=("$line");while IFS= read -r f; do files+=("$f"); done < <(find ios/Sources -name '*.swift' | sort)SDKPATH=$(xcrun --show-sdk-path --sdk "$SDK")-# App Intents (Intents.swift) need the metadata Xcode extracts from the compiler's constant values:-# without Metadata.appintents in the bundle, Siri, Shortcuts, Control Center and the Live-# Activity's buttons don't know the intents. Each module is compiled whole (-wmo) to one-# .swiftconstvalues file, then appintentsmetadataprocessor writes the metadata into its bundle.WORK=$(mktemp -d)trap 'rm -rf "$WORK"' EXITprintf '%s' '["AppIntent","AppEntity","TransientAppEntity","AppEnum","EntityQuery","AppShortcutsProvider","AppShortcutProviding","DynamicOptionsProvider","LiveActivityIntent","ControlConfigurationIntent","WidgetConfigurationIntent","_IntentValueRepresentable","AppIntentsPackage"]' > "$WORK/protocols.json"CONST=(-wmo -Xfrontend -const-gather-protocols-file -Xfrontend "$WORK/protocols.json")-intents_metadata() { # <module> <bundle dir> <binary> <sources...>+intents_metadata() {local module=$1 out=$2 binary=$3; shift 3printf '%s\n' "$@" > "$WORK/$module.sources"printf '%s\n' "$WORK/$module.swiftconstvalues" > "$WORK/$module.constvals"@@ -49,7 +37,6 @@ intents_metadata() { # <module> <bundle dir> <binary> <sources...>[[ -d "$out/Metadata.appintents" ]] || { echo "no App Intents metadata for $module"; exit 1; }}-# STRINGS_OUT=<dir>: also write the UI text keys there (scripts/strings.py).extra=()[[ -n "${STRINGS_OUT:-}" ]] && extra=(-emit-localized-strings -emit-localized-strings-path "$STRINGS_OUT")xcrun --sdk "$SDK" swiftc -O -swift-version 5 -parse-as-library -module-name Cicada \@@ -59,8 +46,6 @@ intents_metadata Cicada "$APP" "$APP/Cicada" "${files[@]}"cp ios/Resources/Info.plist "$APP/Info.plist"cp ios/Resources/PrivacyInfo.xcprivacy "$APP/"-# The home screen icon: the Mac's renderer draws the full-bleed iOS square (no alpha), actool-# compiles it into Assets.car and says which Info.plist keys point at it.ICON_TOOL=.build/release/CicadaIcon[[ -x $ICON_TOOL ]] || swift build -c release --product CicadaIcon >/dev/nullmkdir -p "$WORK/Assets.xcassets/AppIcon.appiconset"@@ -72,26 +57,18 @@ xcrun actool "$WORK/Assets.xcassets" --compile "$APP" --platform "$SDK" --minimu--app-icon AppIcon --target-device iphone --target-device ipad \--output-partial-info-plist "$WORK/assets.plist" --output-format human-readable-text >/dev/null/usr/libexec/PlistBuddy -c "Merge $WORK/assets.plist" "$APP/Info.plist" >/dev/null-# UI text is the Mac's: the Chinese source is the key, the other languages translate it.for d in Resources/*.lproj; domkdir -p "$APP/$(basename "$d")"cp "$d/Localizable.strings" "$APP/$(basename "$d")/" 2>/dev/null || truedonecp -R "$APP/zh-Hans.lproj" "$APP/zh-Hant.lproj"cp Resources/sample/sample.m4a "$APP/"-# 说话人识别's voiceprint model, compiled on first use as on the Mac (SpeakerID.swift).cp -R Resources/models/SpeakerEmbedding.mlpackage "$APP/"-# The logo on the 听会议室 card: the Mac's own icon renderer (Sources/CicadaIcon), not a fourth-# copy of the geometry. It is a host tool, built once.ICONS=$(mktemp -d)"$ICON_TOOL" "$ICONS/logo.iconset" >/dev/nullcp "$ICONS/logo.iconset/[email protected]" "$APP/logo.png"rm -rf "$ICONS"-# The Live Activity (lock screen, Dynamic Island): a WidgetKit extension in PlugIns. The attributes-# type is compiled into both, so the app and the extension agree on it. Linked like Xcode links an-# app extension: entered through _NSExtensionMain, which runs the @main WidgetBundle on the main-# queue (the plain Swift entry point dies in libdispatch before the bundle loads).APPEX="$APP/PlugIns/CicadaLive.appex"mkdir -p "$APPEX"LIVE=(ios/LiveActivity/*.swift ios/Sources/Cicada/ListenActivity.swift ios/Sources/Cicada/Intents.swift)@@ -110,7 +87,6 @@ for p in "$PLIST" "$APPEX/Info.plist"; do/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $(tr -d '[:space:]' < VERSION)" \-c "Set :CFBundleVersion $BUILD" -c "Set :CFBundleSupportedPlatforms:0 $PLATFORM" "$p"done-# What Xcode writes into every bundle it builds; App Store Connect checks them.SDKVER=$(xcrun --sdk "$SDK" --show-sdk-version)SDKBUILD=$(xcrun --sdk "$SDK" --show-sdk-build-version)XCBUILD=$(xcodebuild -version | awk '/Build version/{print $3}')@@ -136,10 +112,8 @@ if [[ "${DEVICE:-}" != 1 ]]; thencodesign --force --sign - "$APPEX" 2>/dev/nullcodesign --force --sign - "$APP" 2>/dev/nullelse- # A device needs a real signature: each bundle carries its profile, and is signed with the- # entitlements that profile grants (the extension first, then the app around it).: "${SIGN_IDENTITY:?DEVICE=1 needs SIGN_IDENTITY (and PROFILE, PROFILE_LIVE): see ios/scripts/provision.sh}"- sign() { # <bundle> <profile>+ sign() {cp "$2" "$1/embedded.mobileprovision"security cms -D -i "$2" > "$WORK/profile.plist"/usr/libexec/PlistBuddy -x -c "Print :Entitlements" "$WORK/profile.plist" > "$WORK/entitlements.plist"diff --git a/ios/scripts/ctl.sh b/ios/scripts/ctl.shindex 088b246..024f6db 100755--- a/ios/scripts/ctl.sh+++ b/ios/scripts/ctl.sh@@ -1,11 +1,4 @@#!/usr/bin/env bash-# Sends debug commands to the dev build (ios/Sources/Cicada/Debug.swift), the iOS counterpart of-# tools/lsctl: ios/scripts/ctl.sh [-d "<device>"] <cmd> [<cmd>...]-# A simulator gets them through the container and a Darwin notification. A connected iPhone or iPad-# (its UDID, as `xcrun devicectl list devices` prints it) gets each one as a cicada-dev://debug URL,-# which devicectl opens without the confirmation simctl's openurl asks for.-# ios/scripts/ctl.sh -d <UDID> --log [<lines>] the device's debug log, last 40 lines by default-# ios/scripts/ctl.sh -d <UDID> --shot <file.png> a screenshot of the deviceset -euo pipefailDEVICE=bootedif [[ ${1:-} == -d ]]; then DEVICE=$2; shift 2; fidiff --git a/ios/scripts/device.sh b/ios/scripts/device.shindex eaf969e..4e02d26 100755--- a/ios/scripts/device.sh+++ b/ios/scripts/device.sh@@ -1,8 +1,4 @@#!/usr/bin/env bash-# Builds the dev app for a connected iPhone or iPad, installs and opens it.-# ios/scripts/device.sh [<device name or UDID>]-# Signing: the variables ios/tools/provision.py development prints, read from-# ~/.cicada-signing/ios-development.env (run provision.py once and save its output there).set -euo pipefailcd "$(dirname "$0")/../.."ENV=~/.cicada-signing/ios-development.envdiff --git a/ios/scripts/host-recognizer.sh b/ios/scripts/host-recognizer.shindex 27c79fc..c467732 100755--- a/ios/scripts/host-recognizer.sh+++ b/ios/scripts/host-recognizer.sh@@ -1,7 +1,4 @@#!/usr/bin/env bash-# Runs the Mac-side recognizer for the iOS simulator's dev build (ios/tools/host-recognizer):-# the simulator has no working speech models, so the app's audio is recognized here, on device.-# ios/scripts/host-recognizer.sh ["<device>"...] (default: every booted simulator)set -euo pipefailcd "$(dirname "$0")/../.."OUT=ios/build/host-recognizer@@ -9,7 +6,6 @@ mkdir -p ios/buildxcrun --sdk macosx swiftc -O -swift-version 5 -parse-as-library -target arm64-apple-macos26.0 \Sources/Cicada/Recognition.swift Sources/Cicada/Languages.swift Sources/Cicada/AudioFiles.swift \ios/tools/host-recognizer/main.swift ios/tools/host-recognizer/CloudStubs.swift -o "$OUT"-# Simulator UDIDs: the booted ones, or the named devices.if [[ $# -eq 0 ]]; thenids=($(xcrun simctl list devices booted | grep -oE '[0-9A-F-]{36}'))elsediff --git a/ios/scripts/run.sh b/ios/scripts/run.shindex f4a37e4..6bb402b 100755--- a/ios/scripts/run.sh+++ b/ios/scripts/run.sh@@ -1,8 +1,4 @@#!/usr/bin/env bash-# Installs ios/build/Cicada.app into a simulator and launches it.-# ios/scripts/run.sh [device name] [--seed <session folder>...]-# --seed copies Mac meeting folders (…/LiveSubs Dev/Sessions/<id>) into the app first.-# Then drive it: xcrun simctl openurl "<device>" 'cicada-dev://debug?cmd=…' (commands: ios/Sources/Cicada/Debug.swift).set -euo pipefailcd "$(dirname "$0")/../.."DEVICE=${1:-"iPhone 18 Pro"}; shift || truediff --git a/ios/scripts/testflight.sh b/ios/scripts/testflight.shindex bde3930..9b1b3c8 100755--- a/ios/scripts/testflight.sh+++ b/ios/scripts/testflight.sh@@ -1,11 +1,4 @@#!/usr/bin/env bash-# Builds the release app for the App Store, packs it as an .ipa and uploads it to App Store Connect,-# where it shows up in TestFlight after processing (10–30 min).-# ios/scripts/testflight.sh build, pack and upload-# ios/scripts/testflight.sh --no-upload-# Signing: ~/.cicada-signing/ios-appstore.env (ios/tools/provision.py appstore > that file).-# Upload: ASC_KEY_ID and ASC_ISSUER_ID, with the key's .p8 in ~/.cicada-signing (altool looks there-# through API_PRIVATE_KEYS_DIR). The app's record must exist in App Store Connect first.set -euo pipefailcd "$(dirname "$0")/../.."ENV=~/.cicada-signing/ios-appstore.envdiff --git a/ios/scripts/typecheck.sh b/ios/scripts/typecheck.shindex df23b55..64cdaf4 100755--- a/ios/scripts/typecheck.sh+++ b/ios/scripts/typecheck.sh@@ -1,7 +1,4 @@#!/usr/bin/env bash-# Typechecks the Mac sources the iOS app shares (ios/shared-sources.txt) together with ios/Sources.-# Without Xcode only the macOS SDK is there: SDK=macosx proves the shared set is self-contained and-# AppKit-free, not that every API exists on iOS. With Xcode, the default checks against the simulator SDK.set -euo pipefailcd "$(dirname "$0")/../.."SDK=${SDK:-iphonesimulator}@@ -10,7 +7,6 @@ files=()while IFS= read -r line; do [[ -z $line || $line == \#* ]] || files+=("$line"); done < ios/shared-sources.txtshared=("${files[@]}")while IFS= read -r f; do files+=("$f"); done < <(find ios/Sources -name '*.swift' | sort)-# Frameworks iOS doesn't have: the macOS SDK would accept them, so catch them here.bad=$(awk '/^#if (os\(macOS\)|canImport\(AppKit\)|!CICADA_IOS)/{g=1} /^#endif/{g=0} !g && /^import (AppKit|CoreAudio|Carbon|SwiftUI|ServiceManagement|IOKit)$/{print FILENAME": "$0}' "${shared[@]}")if [[ -n $bad ]]; then echo "Mac-only imports in shared sources:"; echo "$bad"; exit 1; fixcrun swiftc -typecheck -swift-version 5 -module-name Cicada -sdk "$(xcrun --show-sdk-path --sdk "$SDK")" "${TARGET[@]}" \diff --git a/ios/tools/asc.py b/ios/tools/asc.pyindex de2a88a..f2f7d7a 100755--- a/ios/tools/asc.py+++ b/ios/tools/asc.py@@ -20,7 +20,6 @@ def b64url(b: bytes) -> str:def der_to_raw(der: bytes) -> bytes:- """openssl's ECDSA signature is DER (SEQUENCE of two INTEGERs); a JWT wants r || s, 32 bytes each."""def read_int(buf, i):assert buf[i] == 0x02n = buf[i + 1]diff --git a/ios/tools/host-recognizer/CloudStubs.swift b/ios/tools/host-recognizer/CloudStubs.swiftindex 58fbc79..2145ede 100644--- a/ios/tools/host-recognizer/CloudStubs.swift+++ b/ios/tools/host-recognizer/CloudStubs.swift@@ -1,8 +1,5 @@import AVFoundation-// The host recognizer only uses the speech models; Recognition.swift also names the AI service's-// stream (CloudHearing.swift), which would pull in the whole AI client. These stand in for it here.-struct CloudHeard: Equatable, Sendable {}final class CloudStream: RecognitionStream, @unchecked Sendable {diff --git a/ios/tools/host-recognizer/main.swift b/ios/tools/host-recognizer/main.swiftindex 981c908..2cef83b 100644--- a/ios/tools/host-recognizer/main.swift+++ b/ios/tools/host-recognizer/main.swift@@ -1,12 +1,6 @@import AVFoundationimport Foundation-// Recognizes speech for the iOS simulator's dev build, whose speech models are empty placeholders-// (ios/Sources/Cicada/HostRecognizer.swift). Watches each app container's Caches/host-recognizer:-// a folder with request.json is one stream; its audio.f32 (16 kHz mono Float32, growing) goes-// through the Mac's own Recognition.swift, and every piece is appended to results.jsonl.-// ios/scripts/host-recognizer.sh (builds this and watches the booted simulators)-enum DevBuild { static let isDev = true }func debugLog(_ message: String) { print("\(Date()) \(message)") }func contentLog(_ message: @autoclosure () -> String) {}@@ -76,8 +70,6 @@ func serve(_ dir: URL) async {}}-/// Every simulator app container's Caches/host-recognizer, found again on each pass: reinstalling-/// the app moves its container.func roots(_ devices: [String]) -> [URL] {let fm = FileManager.defaultlet base = fm.homeDirectoryForCurrentUser.appendingPathComponent("Library/Developer/CoreSimulator/Devices")diff --git a/ios/tools/provision.py b/ios/tools/provision.pyindex 80b1de1..ffdc53b 100755--- a/ios/tools/provision.py+++ b/ios/tools/provision.py@@ -1,16 +1,4 @@#!/usr/bin/env python3-"""Makes what a signed iOS build needs, through the App Store Connect API (ios/tools/asc.py):-the App IDs, the connected devices, a certificate whose private key is on this Mac, and the two-provisioning profiles (the app and the CicadaLive extension). Prints the variables-ios/scripts/build.sh signs with. Safe to run again: it reuses what is there.-- ios/tools/provision.py development Apple Development, the dev bundle ids, this Mac's devices- ios/tools/provision.py appstore Apple Distribution, the release bundle ids (TestFlight)--Needs ASC_KEY_ID, ASC_ISSUER_ID, ASC_KEY_PATH for a key that may manage Certificates,-Identifiers & Profiles (Admin, or App Manager with that access). Keys and certificates live in-~/.cicada-signing (0700); the certificate goes into the login keychain, usable by codesign only.-"""import base64, json, os, re, subprocess, sys, urllib.parsesys.path.insert(0, os.path.dirname(__file__))from asc import call@@ -46,7 +34,6 @@ def bundle_id(identifier, name):def devices():- """Physical devices this Mac is paired with, registered if they aren't yet."""out = run("xcrun", "devicectl", "list", "devices")udids = {m.group(2): m.group(1).strip() for m in re.finditer(r"^(\S.*?)\s{2,}.*?([0-9A-F]{8}-[0-9A-F]{16}) \(UDID\)", out, re.M)}_, r = call("GET", "/v1/devices?limit=200&fields[devices]=udid,name,status")@@ -65,7 +52,6 @@ def devices():def certificate():- """A certificate of this kind whose private key is in ~/.cicada-signing; made if there is none."""key, cer = f"{HOME}/ios-{KIND}.key", f"{HOME}/ios-{KIND}.cer"_, r = call("GET", f"/v1/certificates?filter[certificateType]={CERT_TYPE}&fields[certificates]=certificateContent,serialNumber,expirationDate")if os.path.exists(key) and os.path.exists(cer):@@ -92,18 +78,12 @@ def sha1(cer):def into_keychain(key, cer):- """The certificate and its key in the login keychain, the key usable by codesign without a prompt."""- # The intermediate it is issued by (WWDR G3), shipped inside Xcode; without it the identity- # isn't valid and codesign can't use it.- # Imported every time; the keychain refuses a duplicate, which is fine.subprocess.run(["security", "import", "/Applications/Xcode.app/Contents/SharedFrameworks/DVTFoundation.framework/Versions/A/Resources/AppleWWDRCA-2030.cer","-k", os.path.expanduser("~/Library/Keychains/login.keychain-db")], capture_output=True)if sha1(cer) in run("security", "find-identity", "-v", "-p", "codesigning"):returnp12, password = f"{HOME}/ios-{KIND}.p12", base64.b64encode(os.urandom(18)).decode()pem = run("openssl", "x509", "-inform", "der", "-in", cer)- # OpenSSL 3 writes a cipher the keychain can't read unless told -legacy; macOS's LibreSSL- # writes the old one already and doesn't know the flag.legacy = ["-legacy"] if run("openssl", "version").startswith("OpenSSL 3") else []run("openssl", "pkcs12", "-export", *legacy, "-inkey", key, "-out", p12, "-passout", f"pass:{password}", input=pem)try:@@ -117,7 +97,7 @@ def into_keychain(key, cer):def profile(identifier, bundle, cert, device_ids):name = f"Cicada {KIND} {identifier}"_, r = call("GET", f"/v1/profiles?filter[name]={urllib.parse.quote(name)}&fields[profiles]=name,profileState")- for p in r.get("data", []): # remade each time, so it always holds today's devices and certificate+ for p in r.get("data", []):call("DELETE", f"/v1/profiles/{p['id']}")rel = {"bundleId": {"data": {"type": "bundleIds", "id": bundle}},"certificates": {"data": [{"type": "certificates", "id": cert}]}}