From bc4787c15f271ca25158517370ede452aa70af9d Mon Sep 17 00:00:00 2001 From: Doug Hatcher Date: Sun, 22 Nov 2026 19:18:08 -0500 Subject: [PATCH 1/4] Record per-capture audio routes, source clocks and write counters --- .../Audio/AudioCaptureMetrics.swift | 51 ++++++++ Sources/TranscriptsMac/AppController.swift | 43 ++++++- .../Capture/AudioInputDevices.swift | 34 ++++++ .../Capture/CaptureDiagnostics.swift | 75 ++++++++++++ Sources/TranscriptsMac/Capture/Recorder.swift | 53 ++++++++- .../Capture/SystemAudioCapturer.swift | 60 +++++++++- .../TranscriptsMac/Support/SelfCheck.swift | 13 ++ .../AudioCaptureMetricsTests.swift | 53 +++++++++ docs/design/capture-diagnostics.md | 48 ++++++++ scripts/audit-call-audio.py | 111 ++++++++++++++++++ 10 files changed, 533 insertions(+), 8 deletions(-) create mode 100644 Sources/TranscriptsCore/Audio/AudioCaptureMetrics.swift create mode 100644 Sources/TranscriptsMac/Capture/CaptureDiagnostics.swift create mode 100644 Tests/TranscriptsCoreTests/AudioCaptureMetricsTests.swift create mode 100644 docs/design/capture-diagnostics.md create mode 100644 scripts/audit-call-audio.py diff --git a/Sources/TranscriptsCore/Audio/AudioCaptureMetrics.swift b/Sources/TranscriptsCore/Audio/AudioCaptureMetrics.swift new file mode 100644 index 0000000..78aec52 --- /dev/null +++ b/Sources/TranscriptsCore/Audio/AudioCaptureMetrics.swift @@ -0,0 +1,51 @@ +import Foundation + +/// Counters only: no samples or transcript text. The capturer supplies its own +/// lock. Capture time is the source clock, never callback arrival time. +public struct AudioCaptureMetrics: Codable, Sendable { + public private(set) var receivedBuffers = 0 + public private(set) var writtenBuffers = 0 + public private(set) var droppedBuffers = 0 + public private(set) var writeFailures = 0 + public private(set) var framesWritten: Int64 = 0 + public private(set) var writtenSeconds: Double = 0 + public private(set) var firstCaptureSeconds: Double? + public private(set) var lastCaptureSeconds: Double? + public private(set) var firstArrivalAt: Date? + public private(set) var lastArrivalAt: Date? + public private(set) var discontinuities = 0 + public private(set) var largestGapSeconds: Double = 0 + private var expectedNextCaptureSeconds: Double? + + public init() {} + + public mutating func observe(frames: Int, sampleRate: Double, + captureSeconds: Double?, arrivalAt: Date = Date(), + written: Bool, writeFailed: Bool = false) { + receivedBuffers += 1 + if firstArrivalAt == nil { firstArrivalAt = arrivalAt } + lastArrivalAt = arrivalAt + let duration = frames > 0 && sampleRate.isFinite && sampleRate > 0 + ? Double(frames) / sampleRate : 0 + if let time = captureSeconds, time.isFinite { + if firstCaptureSeconds == nil { firstCaptureSeconds = time } + if let expected = expectedNextCaptureSeconds { + let gap = time - expected + if abs(gap) > 0.05 { + discontinuities += 1 + largestGapSeconds = max(largestGapSeconds, abs(gap)) + } + } + lastCaptureSeconds = time + expectedNextCaptureSeconds = time + duration + } + if written { + writtenBuffers += 1 + framesWritten += Int64(max(0, frames)) + writtenSeconds += duration + } else { + droppedBuffers += 1 + } + if writeFailed { writeFailures += 1 } + } +} diff --git a/Sources/TranscriptsMac/AppController.swift b/Sources/TranscriptsMac/AppController.swift index 2c711d6..018301f 100644 --- a/Sources/TranscriptsMac/AppController.swift +++ b/Sources/TranscriptsMac/AppController.swift @@ -457,6 +457,14 @@ final class AppController: ObservableObject { let dir = HistoryStore.capturesDir.appendingPathComponent(recordID.uuidString, isDirectory: true) do { try rec.start(into: dir) + rec.diagnostics?.event("input-selection", [ + "requestedUID": device.uid, "requestedName": device.name, + "overrideUID": self.config.overrideInputUID ?? "none", + "favoriteUIDs": self.config.favoriteInputUIDs, + "callDeviceUIDs": callUIDs, "inMeeting": inMeeting, + "isRecovery": isRecovery, "continuing": continuing, + "systemAudioEnabled": self.config.captureSystemAudio, + ]) self.recorder = rec self.recordingInput = device self.currentRecordID = recordID @@ -551,6 +559,20 @@ final class AppController: ObservableObject { recording.systemAudioStartOffset = capturer?.firstSampleAt?.timeIntervalSince(recording.startedAt) } + rec.diagnostics?.event("capture-stopped", [ + "carryForward": carryForward, + "micFile": recording.audioURL.lastPathComponent, + "systemFile": sysURL?.lastPathComponent ?? "none", + "systemCallbackStartOffsetSeconds": recording.systemAudioStartOffset ?? 0, + "startedAt": recording.startedAt.timeIntervalSince1970, + "endedAt": recording.endedAt?.timeIntervalSince1970 ?? 0, + "carriedFragments": self.carriedFragments.map { fragment -> [String: Any] in + ["micPath": fragment.micAudioURL.path, + "systemPath": fragment.systemAudioURL?.path ?? "none", + "startedAt": fragment.startedAt.timeIntervalSince1970, + "systemStartOffsetSeconds": fragment.systemAudioStartOffset ?? 0] + }, + ]) // A deliberate stop while a switch was finalizing saves this // slice normally instead of letting the queued switch resume it. @@ -578,11 +600,20 @@ final class AppController: ObservableObject { if let sysURL, let micURL = recording.micAudioURL { let mixed = micURL.deletingLastPathComponent().appendingPathComponent("call-mixed.m4a") + rec.diagnostics?.event("archive-mix", [ + "micPath": micURL.path, "systemPath": (recording.systemAudioURL ?? sysURL).path, + "outputPath": mixed.path, "micPlacementSeconds": 0, "systemPlacementSeconds": 0, + "transcriptionSystemOffsetSeconds": recording.systemAudioStartOffset ?? 0, + "assembledFragments": hadFragments, + ]) if let mixedURL = await AudioMixer.mix([micURL, recording.systemAudioURL ?? sysURL], into: mixed, log: { Log.write($0) }) { recording.audioURL = mixedURL self.updateRecord(recordID) { $0.audioPath = mixedURL.path } Log.write("call: mixed your mic + the other participants for transcription") + rec.diagnostics?.event("archive-mix-completed", ["file": mixedURL.lastPathComponent]) + } else { + rec.diagnostics?.event("archive-mix-failed") } } // Both sides came back empty: the mic read digital zero and the @@ -681,11 +712,15 @@ final class AppController: ObservableObject { guard config.captureSystemAudio, MeetingDetector.isMeetingAppRunning else { return } guard explainSystemAudioPermissionIfNeeded() else { return } let capturer = SystemAudioCapturer() + capturer.diagnostics = recorder?.diagnostics systemCapturer = capturer let sysURL = scratchDir.appendingPathComponent("system.caf") Task { @MainActor in let ok = await capturer.start(into: sysURL) - if !ok { self.systemCapturer = nil; return } + if !ok { + capturer.diagnostics?.event("system-unavailable") + self.systemCapturer = nil; return + } if #available(macOS 26, *) { self.attachLiveSystemTranscriber(to: capturer) } } } @@ -1027,7 +1062,11 @@ final class AppController: ObservableObject { self.micSilentWhileCallAudible = micQuiet >= Self.deadMicSeconds && farSideLive // Window titles improve mid-call (join screen → the real // meeting window) — re-sample every ~15s and upgrade. - if self.tick % 15 == 0 { self.refreshMeetingContext() } + if self.tick % 15 == 0 { + self.refreshMeetingContext() + rec.snapshotDiagnostics() + self.systemCapturer?.snapshotDiagnostics() + } // Keeps the relaunch marker fresh, so a three-hour session // stays resumable rather than ageing out of the window. if self.tick % 30 == 0 { self.relaunch.heartbeat() } diff --git a/Sources/TranscriptsMac/Capture/AudioInputDevices.swift b/Sources/TranscriptsMac/Capture/AudioInputDevices.swift index d60d707..ab658ad 100644 --- a/Sources/TranscriptsMac/Capture/AudioInputDevices.swift +++ b/Sources/TranscriptsMac/Capture/AudioInputDevices.swift @@ -229,6 +229,40 @@ enum AudioInputDevices { // MARK: - CoreAudio plumbing + /// Include output routes as well as inputs: a Continuity mic listening to + /// Mac speakers and an AirPods call have very different echo paths. + static func diagnosticRoute(actualInputID: AudioDeviceID?, requestedInputID: AudioDeviceID) -> [String: Any] { + var outputAddress = AudioObjectPropertyAddress( + mSelector: kAudioHardwarePropertyDefaultOutputDevice, + mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMain) + var output = AudioDeviceID(kAudioObjectUnknown) + var size = UInt32(MemoryLayout.size) + let outputStatus = AudioObjectGetPropertyData(AudioObjectID(kAudioObjectSystemObject), + &outputAddress, 0, nil, &size, &output) + var fields: [String: Any] = [ + "requestedInputID": requestedInputID, + "devices": deviceIDs().map { id -> [String: Any] in + let uid = stringProperty(id, kAudioDevicePropertyDeviceUID) ?? "unknown" + let name = stringProperty(id, kAudioObjectPropertyName) ?? "unknown" + var device: [String: Any] = [ + "id": id, + "uid": uid, "name": name, + "nominalSampleRate": nominalSampleRate(id), + "transportType": transportType(id), + "inputChannels": inputChannelCount(id), + "aggregateSubDeviceUIDs": aggregateSubDeviceUIDs(id), + ] + let candidate = AudioInputDevice(uid: uid, name: name, deviceID: id) + if let muted = isInputMuted(candidate) { device["inputMuted"] = muted } + return device + }, + ] + fields["actualInputID"] = actualInputID + fields["defaultInputID"] = defaultInput() + if outputStatus == noErr { fields["defaultOutputID"] = output } + return fields + } + private static func deviceIDs() -> [AudioDeviceID] { var addr = AudioObjectPropertyAddress( mSelector: kAudioHardwarePropertyDevices, diff --git a/Sources/TranscriptsMac/Capture/CaptureDiagnostics.swift b/Sources/TranscriptsMac/Capture/CaptureDiagnostics.swift new file mode 100644 index 0000000..7dc2a0b --- /dev/null +++ b/Sources/TranscriptsMac/Capture/CaptureDiagnostics.swift @@ -0,0 +1,75 @@ +import Foundation +import TranscriptsCore +import TranscriptsEngine + +/// Append-only, per-capture evidence. Survives a crash and follows the capture's +/// existing retention policy. No audio, window titles, or transcript text. +/// Encoding and disk IO never run on the audio callback. +final class CaptureDiagnostics: @unchecked Sendable { + private let queue = DispatchQueue(label: "ltd.hatcher.transcripts.capture-diagnostics", qos: .utility) + private let url: URL + private var failed = false + + init(directory: URL) { + url = directory.appendingPathComponent("capture-diagnostics.jsonl") + event("capture-open", [ + "schemaVersion": 1, + "captureID": directory.lastPathComponent, + "app": Bundle.main.bundleIdentifier ?? "unknown", + "version": Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "unknown", + "build": Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "unknown", + "os": ProcessInfo.processInfo.operatingSystemVersionString, + "processID": ProcessInfo.processInfo.processIdentifier, + ]) + } + + func event(_ name: String, _ fields: [String: Any] = [:]) { + // Freeze mutable caller-owned dictionaries before crossing queues. + let envelope: [String: Any] = ["event": name, "at": Date().timeIntervalSince1970, "data": fields] + guard JSONSerialization.isValidJSONObject(envelope), + var data = try? JSONSerialization.data(withJSONObject: envelope, options: [.sortedKeys]) else { return } + data.append(0x0a) + let line = data + queue.async { [self] in + do { + if !FileManager.default.fileExists(atPath: url.path) { + guard FileManager.default.createFile(atPath: url.path, contents: nil) else { + throw CocoaError(.fileWriteUnknown) + } + } + let handle = try FileHandle(forWritingTo: url) + defer { try? handle.close() } + try handle.seekToEnd() + try handle.write(contentsOf: line) + } catch { + if !failed { Log.write("capture diagnostics: could not write \(url.path): \(error)"); failed = true } + } + } + } + + func metrics(_ name: String, _ metrics: AudioCaptureMetrics, extra: [String: Any] = [:]) { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + guard let data = try? encoder.encode(metrics), + var fields = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { return } + fields.merge(extra) { _, new in new } + event(name, fields) + } + + /// For the hardware self-check before it removes its scratch directory. + /// Never call from an audio callback. + func flush() -> URL { + queue.sync {} + return url + } + + /// Timer/main-thread snapshots, and explicit start/stop snapshots. Query the + /// actual AudioUnit device as selection can fail or reset on reconfiguration. + func route(_ name: String, actualInputID: UInt32?, requestedInputID: UInt32) { + var fields = AudioInputDevices.diagnosticRoute(actualInputID: actualInputID, + requestedInputID: requestedInputID) + fields["meetingDeviceUIDs"] = CallDetector.meetingAppDeviceUIDs() + fields["meetingApp"] = CallDetector.meetingAppUsingInput() ?? "none" + event(name, fields) + } +} diff --git a/Sources/TranscriptsMac/Capture/Recorder.swift b/Sources/TranscriptsMac/Capture/Recorder.swift index 0a2306b..5faade7 100644 --- a/Sources/TranscriptsMac/Capture/Recorder.swift +++ b/Sources/TranscriptsMac/Capture/Recorder.swift @@ -35,6 +35,24 @@ final class Recorder { private var startedAt: Date? private var activeApp: ActiveAppContext? private var windowTitles: [String] = [] + private(set) var diagnostics: CaptureDiagnostics? + private var captureMetrics = AudioCaptureMetrics() + + private var actualInputID: AudioDeviceID? { + guard let unit = engine.inputNode.audioUnit else { return nil } + var id = AudioDeviceID(kAudioObjectUnknown) + var size = UInt32(MemoryLayout.size) + guard AudioUnitGetProperty(unit, kAudioOutputUnitProperty_CurrentDevice, + kAudioUnitScope_Global, 0, &id, &size) == noErr else { return nil } + return id == kAudioObjectUnknown ? nil : id + } + + /// Called from the existing UI timer, never the audio thread. + func snapshotDiagnostics(_ event: String = "mic-progress") { + meter.lock(); let metrics = captureMetrics; let peakSeen = peak; meter.unlock() + diagnostics?.metrics(event, metrics, extra: ["peak": peakSeen, "clock": "host-seconds"]) + diagnostics?.route("audio-route", actualInputID: actualInputID, requestedInputID: device.deviceID) + } /// The format the CAF was opened with. Every tap buffer is delivered in this /// format, through a converter when the device has moved on — so a mid-call @@ -70,6 +88,8 @@ final class Recorder { guard !isRecording else { throw RecorderError.alreadyRecording } try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + diagnostics = CaptureDiagnostics(directory: directory) + captureMetrics = AudioCaptureMetrics() // Crash-safe container: LPCM-in-CAF is readable at any truncation point, // so a kill/crash/power-loss mid-recording still leaves recoverable audio. // (AAC .m4a is worthless without its final header — two live-call @@ -85,12 +105,18 @@ final class Recorder { let status = AudioUnitSetProperty(unit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &dev, UInt32(MemoryLayout.size)) + diagnostics?.event("mic-bind", ["requestedDeviceID": dev, "status": status]) if status != noErr { Log.write("recorder: ⚠️ could not select device '\(device.name)' (status \(status)); using engine default") } } let format = input.outputFormat(forBus: 0) + diagnostics?.event("mic-format", ["sampleRate": format.sampleRate, + "channels": format.channelCount, + "voiceProcessingEnabled": input.isVoiceProcessingEnabled, + "hardwareSampleRate": AudioInputDevices.nominalSampleRate(device.deviceID)]) + diagnostics?.route("audio-route-start", actualInputID: actualInputID, requestedInputID: device.deviceID) Log.write("recorder: device='\(device.name)' uid=\(device.uid) format=\(Int(format.sampleRate))Hz \(format.channelCount)ch mic auth=\(Recorder.micAuthDescription)") guard format.sampleRate > 0, format.channelCount > 0 else { throw RecorderError.engineStart("selected device reports no channels") @@ -126,6 +152,7 @@ final class Recorder { do { try engine.start() } catch { + diagnostics?.event("mic-start-failed", ["error": String(describing: error)]) input.removeTap(onBus: 0) audioFile = nil throw RecorderError.engineStart(error.localizedDescription) @@ -150,6 +177,7 @@ final class Recorder { isRecording = true currentURL = url startedAt = Date() + diagnostics?.event("mic-started", ["recordingStartedAt": startedAt?.timeIntervalSince1970 ?? 0]) activeApp = ActiveAppProvider.current() windowTitles = captureWindowTitles ? WindowTitleProvider.meetingWindowTitles() : [] if !windowTitles.isEmpty { Log.write("recorder: meeting window(s): \(windowTitles.joined(separator: " | "))") } @@ -189,6 +217,7 @@ final class Recorder { rebuildPending = nil engine.inputNode.removeTap(onBus: 0) engine.stop() + snapshotDiagnostics("mic-stopped") audioFile = nil isRecording = false @@ -212,6 +241,9 @@ final class Recorder { /// downstream (file, meter, live transcriber) in `fileFormat` — converted /// when the two differ, passed straight through when they don't. private func installTap(tapFormat: AVAudioFormat) { + diagnostics?.event("mic-tap-format", ["sampleRate": tapFormat.sampleRate, + "channels": tapFormat.channelCount, + "fileSampleRate": fileFormat?.sampleRate ?? 0]) let converter: AVAudioConverter? if let fileFormat, fileFormat != tapFormat { converter = AVAudioConverter(from: tapFormat, to: fileFormat) @@ -219,8 +251,18 @@ final class Recorder { converter = nil } let outFormat = fileFormat - engine.inputNode.installTap(onBus: 0, bufferSize: 4096, format: tapFormat) { [weak self] buffer, _ in + engine.inputNode.installTap(onBus: 0, bufferSize: 4096, format: tapFormat) { [weak self] buffer, time in guard let self else { return } + let arrival = Date() + var written = false + var writeFailed = false + defer { + self.meter.lock() + self.captureMetrics.observe(frames: Int(buffer.frameLength), sampleRate: buffer.format.sampleRate, + captureSeconds: time.isHostTimeValid ? AVAudioTime.seconds(forHostTime: time.hostTime) : nil, + arrivalAt: arrival, written: written, writeFailed: writeFailed) + self.meter.unlock() + } let delivered: AVAudioPCMBuffer if let converter, let outFormat { let ratio = outFormat.sampleRate / buffer.format.sampleRate @@ -240,7 +282,10 @@ final class Recorder { delivered = buffer } self.measure(delivered) - if let file = self.audioFile { try? file.write(from: delivered) } + if let file = self.audioFile { + do { try file.write(from: delivered); written = true } + catch { writeFailed = true } + } self.onBuffer?(delivered) } } @@ -250,6 +295,7 @@ final class Recorder { /// back to the format the file was opened with. private func rebuildAfterConfigurationChange() { guard isRecording else { return } + snapshotDiagnostics("mic-reconfiguration") engine.inputNode.removeTap(onBus: 0) engine.stop() @@ -257,9 +303,10 @@ final class Recorder { // engine's input back to the system default. if let unit = engine.inputNode.audioUnit { var dev = device.deviceID - AudioUnitSetProperty(unit, kAudioOutputUnitProperty_CurrentDevice, + let status = AudioUnitSetProperty(unit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &dev, UInt32(MemoryLayout.size)) + diagnostics?.event("mic-rebind", ["requestedDeviceID": dev, "status": status]) } let newFormat = engine.inputNode.outputFormat(forBus: 0) diff --git a/Sources/TranscriptsMac/Capture/SystemAudioCapturer.swift b/Sources/TranscriptsMac/Capture/SystemAudioCapturer.swift index 246aebb..3fa7965 100644 --- a/Sources/TranscriptsMac/Capture/SystemAudioCapturer.swift +++ b/Sources/TranscriptsMac/Capture/SystemAudioCapturer.swift @@ -34,6 +34,26 @@ final class SystemAudioCapturer: NSObject, SCStreamOutput, SCStreamDelegate, @un private var startedSession = false private let queue = DispatchQueue(label: "ltd.hatcher.transcripts.sysaudio") private let lock = NSLock() + var diagnostics: CaptureDiagnostics? + private var captureMetrics = AudioCaptureMetrics() + private var sourceSampleRate: Double = 0 + private var sourceChannels: UInt32 = 0 + private var sourceFormatFlags: UInt32 = 0 + private var sourceBitsPerChannel: UInt32 = 0 + + func snapshotDiagnostics(_ event: String = "system-progress") { + lock.lock() + let metrics = captureMetrics + let extra: [String: Any] = ["sampleRate": sourceSampleRate, "channels": sourceChannels, + "formatFlags": sourceFormatFlags, "bitsPerChannel": sourceBitsPerChannel, + "clock": "source-presentation-seconds", "writerStatus": writer?.status.rawValue ?? -1, + "writerError": writer?.error?.localizedDescription ?? "none", + "latestPeak": levelValue, + "firstWrittenCallbackAt": firstSampleAt?.timeIntervalSince1970 ?? 0, + "lastAudibleAt": lastAudibleAt?.timeIntervalSince1970 ?? 0] + lock.unlock() + diagnostics?.metrics(event, metrics, extra: extra) + } private(set) var outputURL: URL? private(set) var wroteAnySamples = false /// Wall-clock time of the first written sample — aligns this track's timeline @@ -67,6 +87,8 @@ final class SystemAudioCapturer: NSObject, SCStreamOutput, SCStreamDelegate, @un /// on success; false means we couldn't start (no permission / no display) — /// caller continues mic-only. func start(into url: URL) async -> Bool { + diagnostics?.event("system-requested", ["screenRecordingGranted": CGPreflightScreenCaptureAccess(), + "excludesCurrentProcessAudio": true]) // The tap is preferred — but not when the Screen Recording grant already // exists. ScreenCaptureKit then starts silently, and moving a working // setup onto a new permission dialog would be a regression wearing a @@ -103,6 +125,8 @@ final class SystemAudioCapturer: NSObject, SCStreamOutput, SCStreamDelegate, @un return false } lock.lock(); self.tapEngine = tap; lock.unlock() + diagnostics?.event("system-started", ["engine": "core-audio-process-tap", "file": url.lastPathComponent, + "scope": "global-except-current-process"]) Log.write("sysaudio: capturing system audio (other participants) via Core Audio tap → \(url.lastPathComponent)") return true } @@ -140,9 +164,12 @@ final class SystemAudioCapturer: NSObject, SCStreamOutput, SCStreamDelegate, @un self.firstSampleAt = nil lock.unlock() + diagnostics?.event("system-started", ["engine": "screen-capture-kit", "file": url.lastPathComponent, + "scope": "display-audio-except-current-process"]) Log.write("sysaudio: capturing system audio (other participants) → \(url.lastPathComponent)") return true } catch { + diagnostics?.event("system-start-failed", ["engine": "screen-capture-kit", "error": String(describing: error)]) Log.write("sysaudio: ⚠️ could not start (\(error.localizedDescription)). Likely Screen Recording not granted — recording mic only. Grant it in System Settings ▸ Privacy & Security ▸ Screen Recording.") return false } @@ -185,12 +212,15 @@ final class SystemAudioCapturer: NSObject, SCStreamOutput, SCStreamDelegate, @un let writer = self.writer let input = self.input let url = self.outputURL - let wrote = self.wroteAnySamples - let audible = self.lastAudibleAt lock.unlock() if #available(macOS 14.2, *), let tap = tapEngine as? SystemAudioTap { tap.stop() } if let stream { try? await stream.stopCapture() } + // Both engines deliver on this queue. Drain callbacks already in flight + // before marking the writer finished or reading the final counters. + await withCheckedContinuation { (continuation: CheckedContinuation) in + queue.async { continuation.resume() } + } // markAsFinished() raises unless the writer is actually .writing, and // the writer only gets there when the first sample reaches ingest(). A // recording that captured no system audio at all — a mic-only note in a @@ -204,7 +234,11 @@ final class SystemAudioCapturer: NSObject, SCStreamOutput, SCStreamDelegate, @un await writer.finishWriting() } + snapshotDiagnostics("system-stopped") + lock.lock() + let wrote = self.wroteAnySamples + let audible = self.lastAudibleAt self.stream = nil; self.tapEngine = nil; self.writer = nil; self.input = nil lock.unlock() @@ -225,6 +259,23 @@ final class SystemAudioCapturer: NSObject, SCStreamOutput, SCStreamDelegate, @un /// buffer, appends, and keeps the level/audibility bookkeeping. private func ingest(_ sampleBuffer: CMSampleBuffer) { guard CMSampleBufferDataIsReady(sampleBuffer) else { return } + let arrival = Date() + let frames = CMSampleBufferGetNumSamples(sampleBuffer) + let pts = CMSampleBufferGetPresentationTimeStamp(sampleBuffer).seconds + let format = CMSampleBufferGetFormatDescription(sampleBuffer) + .flatMap { CMAudioFormatDescriptionGetStreamBasicDescription($0)?.pointee } + var written = false + var writeFailed = false + defer { + lock.lock() + if let format { + sourceSampleRate = format.mSampleRate; sourceChannels = format.mChannelsPerFrame + sourceFormatFlags = format.mFormatFlags; sourceBitsPerChannel = format.mBitsPerChannel + } + captureMetrics.observe(frames: frames, sampleRate: format?.mSampleRate ?? 0, + captureSeconds: pts, arrivalAt: arrival, written: written, writeFailed: writeFailed) + lock.unlock() + } lock.lock() guard let writer, let input else { lock.unlock(); return } if !startedSession { @@ -238,7 +289,10 @@ final class SystemAudioCapturer: NSObject, SCStreamOutput, SCStreamDelegate, @un lock.unlock() if ready { - input.append(sampleBuffer) + // A refused append is not captured audio. Retain the error/counters + // instead of claiming success and feeding a nonexistent file track. + guard input.append(sampleBuffer) else { writeFailed = true; return } + written = true let level = Self.signalLevel(sampleBuffer) lock.lock() if !wroteAnySamples { firstSampleAt = Date() } diff --git a/Sources/TranscriptsMac/Support/SelfCheck.swift b/Sources/TranscriptsMac/Support/SelfCheck.swift index c1b743f..006eaf7 100644 --- a/Sources/TranscriptsMac/Support/SelfCheck.swift +++ b/Sources/TranscriptsMac/Support/SelfCheck.swift @@ -67,6 +67,7 @@ enum SelfCheck { var sysOK = false do { try recorder.start(into: scratch) + capturer.diagnostics = recorder.diagnostics started = await capturer.start(into: sysURL) try await Task.sleep(for: .seconds(2)) if started { sysOK = await capturer.stop() != nil } @@ -76,6 +77,18 @@ enum SelfCheck { return 1 } + guard let diagnosticsURL = recorder.diagnostics?.flush(), + let lines = try? String(contentsOf: diagnosticsURL, encoding: .utf8).split(separator: "\n"), + let events = try? lines.map({ line in + try JSONSerialization.jsonObject(with: Data(line.utf8)) as? [String: Any] + }), + events.contains(where: { $0?["event"] as? String == "mic-stopped" }), + !started || events.contains(where: { $0?["event"] as? String == "system-stopped" }) else { + print("✗ capture diagnostics: missing or unreadable final counters") + return 1 + } + print("✓ capture diagnostics: \(events.count) JSON events, routes and final counters saved") + let attrs = try? FileManager.default.attributesOfItem(atPath: recording.audioURL.path) let size = (attrs?[.size] as? Int) ?? 0 guard size > 0 else { diff --git a/Tests/TranscriptsCoreTests/AudioCaptureMetricsTests.swift b/Tests/TranscriptsCoreTests/AudioCaptureMetricsTests.swift new file mode 100644 index 0000000..e70cdef --- /dev/null +++ b/Tests/TranscriptsCoreTests/AudioCaptureMetricsTests.swift @@ -0,0 +1,53 @@ +import Foundation +import Testing +@testable import TranscriptsCore + +@Suite struct AudioCaptureMetricsTests { + @Test func distinguishesBackpressureFromFailedWrites() { + var metrics = AudioCaptureMetrics() + metrics.observe(frames: 480, sampleRate: 48_000, captureSeconds: 10, written: true) + metrics.observe(frames: 480, sampleRate: 48_000, captureSeconds: 10.01, written: false) + metrics.observe(frames: 480, sampleRate: 48_000, captureSeconds: 10.02, + written: false, writeFailed: true) + #expect(metrics.receivedBuffers == 3) + #expect(metrics.writtenBuffers == 1) + #expect(metrics.droppedBuffers == 2) + #expect(metrics.writeFailures == 1) + #expect(metrics.framesWritten == 480) + #expect(abs(metrics.writtenSeconds - 0.01) < 0.000001) + // A refused write is not a source-clock gap. + #expect(metrics.discontinuities == 0) + } + + @Test func detectsGapsAndClockResetsWithoutConfusingCallbackDelay() { + var metrics = AudioCaptureMetrics() + let arrival = Date(timeIntervalSince1970: 1_000) + metrics.observe(frames: 480, sampleRate: 48_000, captureSeconds: 10, + arrivalAt: arrival, written: true) + metrics.observe(frames: 480, sampleRate: 48_000, captureSeconds: 10.01, + arrivalAt: arrival.addingTimeInterval(2), written: true) + #expect(metrics.discontinuities == 0) + metrics.observe(frames: 480, sampleRate: 48_000, captureSeconds: 10.52, written: true) + metrics.observe(frames: 480, sampleRate: 48_000, captureSeconds: 9, written: true) + #expect(metrics.discontinuities == 2) + #expect(abs(metrics.largestGapSeconds - 1.53) < 0.000001) + #expect(metrics.firstCaptureSeconds == 10) + #expect(metrics.lastCaptureSeconds == 9) + #expect(metrics.firstArrivalAt == arrival) + } + + @Test func handlesRateChangesAndInvalidTimestamps() throws { + var metrics = AudioCaptureMetrics() + metrics.observe(frames: 480, sampleRate: 48_000, captureSeconds: 10, written: true) + metrics.observe(frames: 240, sampleRate: 24_000, captureSeconds: 10.01, written: true) + metrics.observe(frames: 0, sampleRate: 0, captureSeconds: .nan, written: false) + metrics.observe(frames: 240, sampleRate: 24_000, captureSeconds: .infinity, written: true) + #expect(metrics.discontinuities == 0) + #expect(metrics.lastCaptureSeconds == 10.01) + #expect(abs(metrics.writtenSeconds - 0.03) < 0.000001) + // Invalid clock values must not poison the JSON sidecar. + let encoded = try JSONEncoder().encode(metrics) + let decoded = try JSONDecoder().decode(AudioCaptureMetrics.self, from: encoded) + #expect(decoded.writtenBuffers == 3) + } +} diff --git a/docs/design/capture-diagnostics.md b/docs/design/capture-diagnostics.md new file mode 100644 index 0000000..a678519 --- /dev/null +++ b/docs/design/capture-diagnostics.md @@ -0,0 +1,48 @@ +# Capture diagnostics + +Each new macOS capture writes `capture-diagnostics.jsonl` beside its audio in +Application Support. Scribe uses the renamed Application Support directory. +The sidecar follows existing capture-backup retention; it is not copied into +meeting notes or sent anywhere. + +The first event includes the capture ID, application/build/OS and process ID. +Start, stop and 15-second snapshots record requested and actual AudioUnit input, +Core Audio default input/output, device names/UIDs/rates, aggregate membership, +mute state, meeting-app device UIDs and whether mic voice processing is enabled. +The system start event identifies Core Audio tap versus ScreenCaptureKit and the +capture scope. `input-selection` records the preferences and call inputs used to +choose the microphone. + +Per-track counters distinguish received, written, dropped and failed-write +buffers. First/last source timestamps, callback arrival dates, written duration +and source-clock discontinuities help separate capture latency, missing data and +clock changes. Mic source time is host seconds; system source time is the incoming +presentation timestamp. Do not substitute callback arrival dates for source +clock alignment. Mic frame counts refer to the input buffers; a format converter +can change the frame count written to the file while preserving its duration. + +Recovery events link the prior capture paths and their placements. Archive mix +events record the files and actual placements, separately from the offset used +for transcription. This exposes the current zero-offset archive mix behavior. +The sidecar contains no audio samples, window titles or transcript content. +Device UIDs are local diagnostic identifiers, so inspect the file before sharing. + +Run the installed app with `TRANSCRIPTS_SELFCHECK=1` to exercise both capture +flows and validate the diagnostic file. The self-check deletes its test capture. +For Scribe, the environment variable is renamed to `SCRIBE_SELFCHECK`. + +## Shared-signal audit + +`scripts/audit-call-audio.py ` compares saved separate tracks. +Run it with a Python environment containing NumPy and SciPy; decoding uses macOS +`afconvert`. `--self-test` checks a known delayed copy, unrelated signal and +silence. `--output ` also saves the JSON results. + +The audit bandpasses mono audio to 250–3000 Hz, compares 10-second windows every +30 seconds, and searches up to 10 seconds either side. Correlation magnitude at +least 0.3 flags shared-signal evidence. It skips silent mic windows and guards +against numerical noise in silent system windows. It does not establish the +source of the shared signal, detect every kind of echo, or rate audibility. +Reported lag is system index minus mic index on the stored file timelines; +assembled backups can already contain offsets. Compare the diagnostic placements +before interpreting that number as physical acoustic latency. diff --git a/scripts/audit-call-audio.py b/scripts/audit-call-audio.py new file mode 100644 index 0000000..9774a0b --- /dev/null +++ b/scripts/audit-call-audio.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""Look for shared signal in saved mic/system tracks (macOS, offline). + +Requires numpy and scipy in the invoking Python environment. Uses afconvert for +AAC/CAF decoding. This detects shared audio, not its cause or audible severity. +Example: python scripts/audit-call-audio.py '/path/to/captures/' +""" +import argparse +import json +from pathlib import Path +import subprocess +import tempfile +import warnings + +import numpy as np +from scipy.io import wavfile +from scipy.signal import butter, correlate, sosfilt + +RATE = 8000 + + +def match(mic, system, start, seconds=10, max_lag=10): + a = int(start * RATE) + x = mic[a:a + seconds * RATE] + lo = max(0, a - max_lag * RATE) + y = system[lo:min(len(system), a + len(x) + max_lag * RATE)] + power = np.dot(x, x) + if len(x) < seconds * RATE or len(y) < len(x) or power < len(x) * 1e-10: + return None + cross = correlate(y, x, mode="valid", method="fft") + sums = np.r_[0, np.cumsum(y * y)] + energy = sums[len(x):] - sums[:-len(x)] + # FFT roundoff in digital silence must not become a giant false correlation. + valid = energy > len(x) * 1e-8 + scores = np.divide(cross, np.sqrt(np.maximum(1e-20, energy * power)), + out=np.zeros_like(cross), where=valid) + k = int(np.argmax(abs(scores))) + # Recompute the winning score directly, avoiding cumsum cancellation. + candidate = y[k:k + len(x)] + denominator = np.linalg.norm(x) * np.linalg.norm(candidate) + score = float(np.dot(x, candidate) / denominator) if denominator else 0 + return {"micStartSeconds": start, "correlation": round(score, 4), + "systemMinusMicIndexMilliseconds": round((lo + k - a) / RATE * 1000, 3), + "micRMS": round(float(np.sqrt(power / len(x))), 7)} + + +def source(directory, names): + for name in names: + path = directory / name + if path.exists(): + return path + raise ValueError(f"No separate track in {directory}: expected one of {names}") + + +def decode(path, target): + subprocess.run(["afconvert", "-f", "WAVE", "-d", f"LEI16@{RATE}", + "-c", "1", str(path), str(target)], check=True, capture_output=True) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", wavfile.WavFileWarning) + rate, samples = wavfile.read(target) + assert rate == RATE + filtered = sosfilt(butter(4, [250, 3000], fs=RATE, btype="bandpass", output="sos"), + samples.astype(float) / 32768) + return filtered + + +def self_test(): + rng = np.random.default_rng(42) + mic = rng.normal(0, 0.05, 30 * RATE) + system = np.r_[np.zeros(1000), mic[:-1000]] + found = match(mic, system, 10) + assert found["correlation"] > 0.99, found + assert found["systemMinusMicIndexMilliseconds"] == 125, found + assert abs(match(mic, rng.normal(0, 0.05, len(mic)), 10)["correlation"]) < 0.1 + assert match(np.zeros_like(mic), system, 10) is None + assert abs(match(mic, np.zeros_like(system), 10)["correlation"]) == 0 + print("Passed delayed-copy, unrelated-signal, and silence checks.") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("capture", type=Path, nargs="?") + parser.add_argument("--output", type=Path) + parser.add_argument("--self-test", action="store_true") + args = parser.parse_args() + if args.self_test: + self_test() + return + if args.capture is None: + parser.error("supply a capture directory or --self-test") + mic_file = source(args.capture, ["meeting-mic.m4a", "audio.caf"]) + sys_file = source(args.capture, ["meeting-system.m4a", "system.caf"]) + with tempfile.TemporaryDirectory(prefix="call-audio-audit-") as temp: + mic = decode(mic_file, Path(temp) / "mic.wav") + system = decode(sys_file, Path(temp) / "system.wav") + windows = [match(mic, system, t) for t in range(10, int(min(len(mic), len(system)) / RATE) - 10, 30)] + windows = [w for w in windows if w is not None] + strong = [w for w in windows if abs(w["correlation"]) >= 0.3] + result = {"captureID": args.capture.name, "micFile": mic_file.name, "systemFile": sys_file.name, + "micSeconds": len(mic) / RATE, "systemSeconds": len(system) / RATE, + "sampledWindows": len(windows), "strongMatches": len(strong), + "matches": strong, "bestWindows": sorted(windows, key=lambda w: abs(w["correlation"]), reverse=True)[:5], + "caveat": "Sampled shared-signal evidence; not a full recording verdict. Lag is on stored file timelines, which may include assembly offsets."} + text = json.dumps(result, indent=2) + if args.output: + args.output.write_text(text + "\n") + print(text) + + +if __name__ == "__main__": + main() From e7ad798ad1c03e5a7941352c6f64b6508f76802f Mon Sep 17 00:00:00 2001 From: Doug Hatcher Date: Sun, 22 Nov 2026 19:19:20 -0500 Subject: [PATCH 2/4] Include active audio renderers and output channel topology in diagnostics --- .../Capture/AudioInputDevices.swift | 10 ++++++---- .../TranscriptsMac/Capture/CallDetector.swift | 19 +++++++++++++++++++ .../Capture/CaptureDiagnostics.swift | 1 + docs/design/capture-diagnostics.md | 3 ++- 4 files changed, 28 insertions(+), 5 deletions(-) diff --git a/Sources/TranscriptsMac/Capture/AudioInputDevices.swift b/Sources/TranscriptsMac/Capture/AudioInputDevices.swift index ab658ad..379507a 100644 --- a/Sources/TranscriptsMac/Capture/AudioInputDevices.swift +++ b/Sources/TranscriptsMac/Capture/AudioInputDevices.swift @@ -53,7 +53,7 @@ enum AudioInputDevices { static func all() -> [AudioInputDevice] { if let staged = staged() { return staged } return deviceIDs().compactMap { id in - guard inputChannelCount(id) > 0 else { return nil } + guard channelCount(id) > 0 else { return nil } guard let uid = stringProperty(id, kAudioDevicePropertyDeviceUID), let name = stringProperty(id, kAudioObjectPropertyName) else { return nil } guard !uid.hasPrefix(systemAudioTapUIDPrefix) else { return nil } @@ -249,7 +249,8 @@ enum AudioInputDevices { "uid": uid, "name": name, "nominalSampleRate": nominalSampleRate(id), "transportType": transportType(id), - "inputChannels": inputChannelCount(id), + "inputChannels": channelCount(id), + "outputChannels": channelCount(id, scope: kAudioObjectPropertyScopeOutput), "aggregateSubDeviceUIDs": aggregateSubDeviceUIDs(id), ] let candidate = AudioInputDevice(uid: uid, name: name, deviceID: id) @@ -276,10 +277,11 @@ enum AudioInputDevices { return ids } - private static func inputChannelCount(_ device: AudioDeviceID) -> Int { + private static func channelCount(_ device: AudioDeviceID, + scope: AudioObjectPropertyScope = kAudioObjectPropertyScopeInput) -> Int { var addr = AudioObjectPropertyAddress( mSelector: kAudioDevicePropertyStreamConfiguration, - mScope: kAudioObjectPropertyScopeInput, + mScope: scope, mElement: kAudioObjectPropertyElementMain) var size: UInt32 = 0 guard AudioObjectGetPropertyDataSize(device, &addr, 0, nil, &size) == noErr, size > 0 else { return 0 } diff --git a/Sources/TranscriptsMac/Capture/CallDetector.swift b/Sources/TranscriptsMac/Capture/CallDetector.swift index ab03e2d..efab924 100644 --- a/Sources/TranscriptsMac/Capture/CallDetector.swift +++ b/Sources/TranscriptsMac/Capture/CallDetector.swift @@ -106,6 +106,25 @@ final class CallDetector { // MARK: - CoreAudio process objects + /// Active audio clients, including renderers outside the meeting app. A + /// monitor/loopback renderer is relevant when a global system tap contains + /// a second copy. Device UIDs can include both inputs and outputs. + static func diagnosticProcesses() -> [[String: Any]] { + processObjects().compactMap { proc in + let input = isRunningInput(proc) + var addr = AudioObjectPropertyAddress( + mSelector: kAudioProcessPropertyIsRunningOutput, + mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMain) + var output: UInt32 = 0 + var size = UInt32(MemoryLayout.size) + let status = AudioObjectGetPropertyData(proc, &addr, 0, nil, &size, &output) + guard input || (status == noErr && output != 0) else { return nil } + return ["processObjectID": proc, "bundleID": bundleID(proc) ?? "unknown", + "runningInput": input, "runningOutput": output != 0, + "deviceUIDs": processDevices(proc).compactMap { deviceUID($0) }] + } + } + private static func processObjects() -> [AudioObjectID] { var addr = AudioObjectPropertyAddress( mSelector: kAudioHardwarePropertyProcessObjectList, diff --git a/Sources/TranscriptsMac/Capture/CaptureDiagnostics.swift b/Sources/TranscriptsMac/Capture/CaptureDiagnostics.swift index 7dc2a0b..29e3477 100644 --- a/Sources/TranscriptsMac/Capture/CaptureDiagnostics.swift +++ b/Sources/TranscriptsMac/Capture/CaptureDiagnostics.swift @@ -70,6 +70,7 @@ final class CaptureDiagnostics: @unchecked Sendable { requestedInputID: requestedInputID) fields["meetingDeviceUIDs"] = CallDetector.meetingAppDeviceUIDs() fields["meetingApp"] = CallDetector.meetingAppUsingInput() ?? "none" + fields["activeAudioProcesses"] = CallDetector.diagnosticProcesses() event(name, fields) } } diff --git a/docs/design/capture-diagnostics.md b/docs/design/capture-diagnostics.md index a678519..59b9690 100644 --- a/docs/design/capture-diagnostics.md +++ b/docs/design/capture-diagnostics.md @@ -8,7 +8,8 @@ meeting notes or sent anywhere. The first event includes the capture ID, application/build/OS and process ID. Start, stop and 15-second snapshots record requested and actual AudioUnit input, Core Audio default input/output, device names/UIDs/rates, aggregate membership, -mute state, meeting-app device UIDs and whether mic voice processing is enabled. +mute state, meeting-app device UIDs, active audio processes (capture/render), +and whether mic voice processing is enabled. The system start event identifies Core Audio tap versus ScreenCaptureKit and the capture scope. `input-selection` records the preferences and call inputs used to choose the microphone. From ac1b1b754dbf5dbff72f6f89c97169cefb2936ff Mon Sep 17 00:00:00 2001 From: Doug Hatcher Date: Sun, 22 Nov 2026 19:20:05 -0500 Subject: [PATCH 3/4] Import shared capture metrics in the system capturer --- Sources/TranscriptsMac/Capture/SystemAudioCapturer.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/TranscriptsMac/Capture/SystemAudioCapturer.swift b/Sources/TranscriptsMac/Capture/SystemAudioCapturer.swift index 3fa7965..05625e1 100644 --- a/Sources/TranscriptsMac/Capture/SystemAudioCapturer.swift +++ b/Sources/TranscriptsMac/Capture/SystemAudioCapturer.swift @@ -1,6 +1,7 @@ import Foundation import AVFoundation import ScreenCaptureKit +import TranscriptsCore import TranscriptsEngine /// Captures **system audio** — everything playing out of the Mac's output, which From cef7dfced07f070a465d387a44a810bd2c8d2a05 Mon Sep 17 00:00:00 2001 From: Doug Hatcher Date: Sun, 22 Nov 2026 20:02:30 -0500 Subject: [PATCH 4/4] Add a problem-report entry point and a shareable technical diagnostic summary --- .../Audio/SupportDiagnostics.swift | 48 +++++++++++++++++++ .../TranscriptsMac/MenuBar/MenuBarView.swift | 7 +++ .../Support/SupportReporter.swift | 48 +++++++++++++++++++ .../SupportDiagnosticsTests.swift | 19 ++++++++ 4 files changed, 122 insertions(+) create mode 100644 Sources/TranscriptsCore/Audio/SupportDiagnostics.swift create mode 100644 Sources/TranscriptsMac/Support/SupportReporter.swift create mode 100644 Tests/TranscriptsCoreTests/SupportDiagnosticsTests.swift diff --git a/Sources/TranscriptsCore/Audio/SupportDiagnostics.swift b/Sources/TranscriptsCore/Audio/SupportDiagnostics.swift new file mode 100644 index 0000000..c0463fd --- /dev/null +++ b/Sources/TranscriptsCore/Audio/SupportDiagnostics.swift @@ -0,0 +1,48 @@ +import Foundation + +/// Explicitly selected technical fields for sharing. Raw capture sidecars stay +/// local: they contain routes, UIDs and paths useful for private investigation. +public enum SupportDiagnostics { + private static let keys: Set = [ + "schemaVersion", "app", "version", "build", "os", "receivedBuffers", "writtenBuffers", "droppedBuffers", + "writeFailures", "framesWritten", "writtenSeconds", "firstCaptureSeconds", "lastCaptureSeconds", + "firstArrivalAt", "lastArrivalAt", "discontinuities", "largestGapSeconds", "clock", "sampleRate", "channels", + "fileSampleRate", "hardwareSampleRate", "voiceProcessingEnabled", "writerStatus", "formatFlags", "bitsPerChannel", + "peak", "latestPeak", "systemCallbackStartOffsetSeconds", "micPlacementSeconds", "systemPlacementSeconds", + "transcriptionSystemOffsetSeconds", "assembledFragments", "isRecovery", "continuing", "inMeeting", "systemAudioEnabled" + ] + + private static func kind(_ name: String) -> String { + let value = name.lowercased() + if value.contains("iphone") { return "continuity-iphone" } + if value.contains("airpod") || value.contains("bluetooth") { return "bluetooth" } + if value.contains("built-in") || value.contains("macbook") { return "built-in" } + if value.contains("usb") || value.contains("brio") || value.contains("c920") { return "usb" } + return "other" + } + + public static func summary(jsonLines: Data) throws -> Data { + let text = String(decoding: jsonLines, as: UTF8.self) + // Keep the beginning (capture setup) and tail (recent changes and stop). + let lines = text.split(separator: "\n") + let selected = lines.count > 100 ? Array(lines.prefix(10)) + Array(lines.suffix(90)) : Array(lines) + let events: [[String: Any]] = selected.compactMap { line in + guard let event = try? JSONSerialization.jsonObject(with: Data(line.utf8)) as? [String: Any], + let name = event["event"] as? String, + let input = event["data"] as? [String: Any] else { return nil } + var safe = input.filter { key, value in + keys.contains(key) && (value is NSNumber || ((value as? String)?.count ?? Int.max) <= 160) + } + if let requested = input["requestedName"] as? String { safe["selectedInputKind"] = kind(requested) } + if let devices = input["devices"] as? [[String: Any]] { + for (idKey, target) in [("actualInputID", "selectedInputKind"), ("defaultOutputID", "defaultOutputKind")] { + if let id = input[idKey] as? NSNumber, + let device = devices.first(where: { ($0["id"] as? NSNumber) == id }), + let deviceName = device["name"] as? String { safe[target] = kind(deviceName) } + } + } + return ["event": String(name.prefix(64)), "data": safe] + } + return try JSONSerialization.data(withJSONObject: events, options: [.prettyPrinted, .sortedKeys]) + } +} diff --git a/Sources/TranscriptsMac/MenuBar/MenuBarView.swift b/Sources/TranscriptsMac/MenuBar/MenuBarView.swift index f0af8e6..0ed496a 100644 --- a/Sources/TranscriptsMac/MenuBar/MenuBarView.swift +++ b/Sources/TranscriptsMac/MenuBar/MenuBarView.swift @@ -88,6 +88,13 @@ struct MenuBarView: View { Divider() } + HStack { + Button { SupportReporter.report() } label: { + Label("Report a Problem…", systemImage: "ladybug") + } + Spacer() + Button("Save Diagnostics…") { SupportReporter.saveDiagnostics() } + } HStack { Button("Settings…") { controller.openSettings() } Button("Recordings…") { controller.openRecordings(nil) } diff --git a/Sources/TranscriptsMac/Support/SupportReporter.swift b/Sources/TranscriptsMac/Support/SupportReporter.swift new file mode 100644 index 0000000..60cbcc4 --- /dev/null +++ b/Sources/TranscriptsMac/Support/SupportReporter.swift @@ -0,0 +1,48 @@ +import AppKit +import UniformTypeIdentifiers +import TranscriptsCore +import TranscriptsEngine + +@MainActor +enum SupportReporter { + static func report() { + let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "unknown" + if let base = Bundle.main.object(forInfoDictionaryKey: "SupportReportURL") as? String, + let url = URL(string: base)?.appendingPathComponent(version) { + NSWorkspace.shared.open(url) + } else { + var url = URLComponents(string: "https://github.com/doughatcher/transcripts-support/issues/new")! + url.queryItems = [URLQueryItem(name: "body", value: "App version: \(version)\nmacOS: \(ProcessInfo.processInfo.operatingSystemVersionString)\n\nWhat happened?\n\nWhat did you expect?\n")] + if let url = url.url { NSWorkspace.shared.open(url) } + } + } + + static func saveDiagnostics() { + let fm = FileManager.default + let entries = (try? fm.contentsOfDirectory(at: HistoryStore.capturesDir, includingPropertiesForKeys: [.contentModificationDateKey])) ?? [] + let candidates = entries.map { $0.appendingPathComponent("capture-diagnostics.jsonl") } + .filter { fm.fileExists(atPath: $0.path) } + .sorted { ((try? $0.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast) + > ((try? $1.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast) } + guard let source = candidates.first else { + show("No diagnostic summary yet", "Record a session with this version first. No audio or transcript is needed in the report.") + return + } + let panel = NSSavePanel() + panel.allowedContentTypes = [.json] + panel.nameFieldStringValue = "transcripts-diagnostic-summary.json" + panel.message = "Save technical counters from the most recent capture. Audio, transcripts, paths and device identifiers are excluded." + guard panel.runModal() == .OK, let url = panel.url else { return } + do { + let data = try SupportDiagnostics.summary(jsonLines: Data(contentsOf: source)) + try data.write(to: url, options: .atomic) + show("Diagnostic summary saved", "You can attach this JSON file on the Report a Problem page. Nothing has been uploaded.") + } catch { + show("Couldn't save diagnostics", error.localizedDescription) + } + } + + private static func show(_ title: String, _ message: String) { + let alert = NSAlert(); alert.messageText = title; alert.informativeText = message; alert.runModal() + } +} diff --git a/Tests/TranscriptsCoreTests/SupportDiagnosticsTests.swift b/Tests/TranscriptsCoreTests/SupportDiagnosticsTests.swift new file mode 100644 index 0000000..35318d7 --- /dev/null +++ b/Tests/TranscriptsCoreTests/SupportDiagnosticsTests.swift @@ -0,0 +1,19 @@ +import Foundation +import Testing +@testable import TranscriptsCore + +@Test func supportSummaryExcludesMeetingContentAndPersonalIdentifiers() throws { + let event: [String: Any] = ["event": "audio-route", "at": 123, "data": [ + "actualInputID": 1, "defaultOutputID": 2, + "devices": [["id": 1, "name": "iPhone Microphone", "uid": "secret-uid"], ["id": 2, "name": "Doug’s AirPods", "uid": "other-secret"]], + "transcript": "private meeting words", "path": "/Users/private-person/recordings", "writtenBuffers": 24, + "writerError": "error opening /Users/private-person/secret" + ]] + let raw = try JSONSerialization.data(withJSONObject: event) + let summary = try SupportDiagnostics.summary(jsonLines: raw) + let text = String(decoding: summary, as: UTF8.self) + #expect(text.contains("continuity-iphone")) + #expect(text.contains("bluetooth")) + #expect(text.contains("writtenBuffers")) + for hidden in ["secret-uid", "other-secret", "Doug", "private meeting", "/Users/"] { #expect(!text.contains(hidden)) } +}