Skip to content

Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more

merge: bring meeting/prd-capture-amendments into Beta 5

altic-dev159f5eecb255
diff --cc Fluid.xcodeproj/project.pbxproj
index c7139fbc,8fb305b7..78bc5b13
--- a/Fluid.xcodeproj/project.pbxproj
+++ b/Fluid.xcodeproj/project.pbxproj
@@@ -193,7 -402,23 +407,24 @@@
C0DE63700000000000000001 /* WhisperLanguageSelectionTests.swift */,
CACEC0010000000000000001 /* KeychainServiceCacheTests.swift */,
0B05F11E000000000000A001 /* SupportedFileExtensionsTests.swift */,
+ FEED67600000000000000001 /* PasteDeliveryCoordinatorTests.swift */,
+ CD0E00000000000000000001 /* MeetingOverlayModelsTests.swift */,
+ CD0F00000000000000000001 /* MeetingProcessingConfigurationTests.swift */,
+ CD100000000000000000000001 /* MeetingProviderOptionsTests.swift */,
+ CD110000000000000000000001 /* MeetingASRPreparationOwnerTests.swift */,
+ D2A000000000000000000001 /* MeetingReferenceSynchronizerTests.swift */,
+ D2A000000000000000000003 /* MeetingStage05EvidenceTests.swift */,
+ D2A000000000000000000005 /* MeetingStage05SCKFrameAdapterTests.swift */,
+ AEC3B0000000000000000001 /* MeetingAEC3Tests.swift */,
+ CD120000000000000000000001 /* MeetingReferenceAttributionContractsTests.swift */,
+ E5EC000000000000000000B1 /* MeetingVoiceProcessingProbeTests.swift */,
+ E5EC000000000000000000C1 /* MeetingSCKPairedDiagnosticsTests.swift */,
+ F1A000000000000000000001 /* MeetingAudioChunkSinkTests.swift */,
+ F1A000000000000000000003 /* MeetingAudioAssetCompatibilityTests.swift */,
+ F1A000000000000000000005 /* MeetingAudioChunkLedgerTests.swift */,
+ F1A000000000000000000007 /* MeetingAudioChunkLedgerRecoveryTests.swift */,
+ F1A000000000000000000009 /* MeetingPCMStoragePolicyTests.swift */,
+ E5EC000000000000000000D1 /* MeetingSCKPairedHardwareTests.swift */,
);
path = FluidDictationIntegrationTests;
sourceTree = "<group>";
@@@ -378,7 -748,40 +755,41 @@@
C0DE63700000000000000002 /* WhisperLanguageSelectionTests.swift in Sources */,
CACEC0010000000000000002 /* KeychainServiceCacheTests.swift in Sources */,
0B05F11E000000000000A002 /* SupportedFileExtensionsTests.swift in Sources */,
+ FEED67600000000000000002 /* PasteDeliveryCoordinatorTests.swift in Sources */,
+ CD0E00000000000000000002 /* MeetingOverlayModelsTests.swift in Sources */,
+ CD0F00000000000000000002 /* MeetingProcessingConfigurationTests.swift in Sources */,
+ CD100000000000000000000002 /* MeetingProviderOptionsTests.swift in Sources */,
+ CD110000000000000000000002 /* MeetingASRPreparationOwnerTests.swift in Sources */,
+ D2A000000000000000000002 /* MeetingReferenceSynchronizerTests.swift in Sources */,
+ D2A000000000000000000004 /* MeetingStage05EvidenceTests.swift in Sources */,
+ D2A000000000000000000006 /* MeetingStage05SCKFrameAdapterTests.swift in Sources */,
+ AEC3B0000000000000000002 /* MeetingAEC3Tests.swift in Sources */,
+ CD120000000000000000000002 /* MeetingReferenceAttributionContractsTests.swift in Sources */,
+ E5EC000000000000000000B2 /* MeetingVoiceProcessingProbeTests.swift in Sources */,
+ E5EC000000000000000000C2 /* MeetingSCKPairedDiagnosticsTests.swift in Sources */,
+ F1A000000000000000000002 /* MeetingAudioChunkSinkTests.swift in Sources */,
+ F1A000000000000000000004 /* MeetingAudioAssetCompatibilityTests.swift in Sources */,
+ F1A000000000000000000006 /* MeetingAudioChunkLedgerTests.swift in Sources */,
+ F1A000000000000000000008 /* MeetingAudioChunkLedgerRecoveryTests.swift in Sources */,
+ F1A00000000000000000000A /* MeetingPCMStoragePolicyTests.swift in Sources */,
+ E5EC000000000000000000D2 /* MeetingSCKPairedHardwareTests.swift in Sources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ A5B000000000000000000006 /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ A5B00000000000000000000B /* main.swift in Sources */,
+ A5B000000000000000000024 /* MeetingReferenceSynchronizerReplayCLI.swift in Sources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ A5B00000000000000000001E /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ CD110000000000000000000003 /* MeetingASRPreparationOwnerTests.swift in Sources (ASR baseline) */,
);
runOnlyForDeploymentPostprocessing = 0;
};
diff --cc Sources/Fluid/AppDelegate.swift
index c209b39a,861eab0c..8e44cbe8
--- a/Sources/Fluid/AppDelegate.swift
+++ b/Sources/Fluid/AppDelegate.swift
@@@ -46,7 -24,29 +46,30 @@@ class AppDelegate: NSObject, NSApplicat
}
func applicationDidFinishLaunching(_ notification: Notification) {
+ AccessibilityMessagingTimeout.configure()
+ #if DEBUG
+ // Stage 0.5, Trial A, and C2 autoruns must return before Core Audio observers,
+ // logging, AppServices, and UI startup. Each owns one bounded diagnostic stream.
+ if MeetingStage05EvidenceAutorun.startIfRequested() {
+ return
+ }
+ if MeetingExternalReferenceTrialAAutorun.startIfRequested() {
+ return
+ }
+ if MeetingSCKPairedAutorun.startIfRequested() {
+ return
+ }
+ // Must precede every Core Audio observer. Disabled unless explicitly
+ // requested through the Phase 0 diagnostics environment.
+ AudioTopologyDiagnostics.shared.startIfRequested()
+ // App-hosted XCTest otherwise starts the normal UI/audio services alongside the
+ // exclusive VPIO hardware probe. Keep that opt-in diagnostic launch isolated.
+ if ProcessInfo.processInfo.environment["FLUIDVOICE_MIC_PHASE1"] != nil
+ || ProcessInfo.processInfo.environment["FLUIDVOICE_VPIO_ACOUSTIC"] == "1"
+ {
+ return
+ }
+ #endif
// Bring up file logging + crash handlers immediately during launch.
_ = FileLogger.shared
TypingService.startKeyboardLayoutTracking()
@@@ -109,22 -110,10 +136,22 @@@
}
func applicationWillTerminate(_ notification: Notification) {
+ if Self.restartPrepared {
+ // Launch only after this process exits: never overlap two app instances.
+ let helper = Process()
+ helper.executableURL = URL(fileURLWithPath: "/bin/sh")
+ let waitForExit = "i=0; while kill -0 \"$1\" 2>/dev/null; do i=$((i+1)); [ \"$i\" -lt 120 ] || exit 1; sleep 1; done; exec /usr/bin/open \"$2\""
+ helper.arguments = ["-c", waitForExit, "fluidvoice-restart", String(ProcessInfo.processInfo.processIdentifier), Bundle.main.bundlePath]
+ do { try helper.run() } catch {
+ DebugLogger.shared.error("Could not schedule relaunch: \(error)", source: "AppDelegate")
+ }
+ }
DebugLogger.shared.info("Application will terminate", source: "AppDelegate")
- self.shutdownPrivateAIRuntimeForTermination()
- self.shutdownASRRuntimeForTermination()
+ if !Self.restartPrepared {
+ self.shutdownPrivateAIRuntimeForTermination()
+ self.shutdownASRRuntimeForTermination()
+ }
- self.closeZeppelinForTermination();
+ self.closeZeppelinForTermination()
LocalAPIServer.shared.stop()
// Clean up the update check timer
self.updateCheckTimer?.invalidate()
diff --cc Sources/Fluid/ContentView.swift
index 3b121235,b100569b..590286e0
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@@ -1084,8 -1086,8 +1091,10 @@@ struct ContentView: View
self.navigateToApp(.aiEnhancements)
case .history:
self.navigateToApp(.history)
+ case .dictationShortcuts:
+ self.openSettings(.shortcuts)
+ case .meetingTranscription:
+ self.navigateToApp(.meetingTranscription)
}
}
@@@ -4420,8 -4109,22 +4447,22 @@@
}
}
+ private func presentExclusiveActivityBlockIfNeeded() -> Bool {
+ guard let activity = self.asr.activeExclusiveActivity else { return false }
+ let message = "Wait for the active \(activity.displayName) to finish."
+ self.asr.errorTitle = "Dictation Unavailable"
+ self.asr.errorMessage = message
+ self.asr.showError = true
+ AccessibilityNotification.Announcement("Dictation unavailable. \(message)").post()
+ DebugLogger.shared.info(
+ "ContentView: dictation start blocked by \(activity.rawValue)",
+ source: "ContentView"
+ )
+ return true
+ }
+
private func prewarmPrivateAIDictationIfNeeded(for slot: SettingsStore.DictationShortcutSlot) {
- let appBundleID = self.recordingAppInfo?.bundleId
+ let appBundleID = self.asr.isRunningOrStarting ? self.recordingAppInfo?.bundleId : DictationAppSession.shared.appID
let settings = SettingsStore.shared
let route = DictationProviderRoute.resolve(
settings: settings,
@@@ -5023,8 -4733,8 +5067,9 @@@ extension ContentView
mode: ActiveRecordingMode,
startMethod: AnalyticsOnboardingTryoutStartMethod = .hotkey
) {
+ guard !self.presentExclusiveActivityBlockIfNeeded() else { return }
DebugLogger.shared.debug("Begin dictation recording for slot \(slot.rawValue)", source: "ContentView")
+ DebugLogger.shared.debug("CLOSE_DETAIL nextStartRequested uptime=\(ProcessInfo.processInfo.systemUptime)", source: "StopTiming")
self.appBench("begin_recording slot=\(slot.rawValue) mode=\(mode.rawValue)")
if self.isOnboardingVoicePlaygroundStepActive {
self.asr.finalText = ""
diff --cc Sources/Fluid/Persistence/BackupService.swift
index f664846a,555f3c1f..92ae6179
--- a/Sources/Fluid/Persistence/BackupService.swift
+++ b/Sources/Fluid/Persistence/BackupService.swift
@@@ -86,11 -86,7 +88,12 @@@ struct SettingsBackupPayload: Codable,
let overlayPosition: SettingsStore.OverlayPosition
let overlayBottomOffset: Double
let overlaySize: SettingsStore.OverlaySize
+ let overlayMaterial: SettingsStore.OverlayMaterial?
+ let overlayGlassOpacity: Double?
+ let overlayTint: SettingsStore.OverlayTint?
+ let overlayHighlight: Double?
+ let overlayClosingAnimationEnabled: Bool?
+ let meetingOverlayPreference: MeetingOverlayPreference?
let transcriptionPreviewCharLimit: Int
let userTypingWPM: Int
let saveTranscriptionHistory: Bool
diff --cc Sources/Fluid/Persistence/SettingsStore.swift
index 59789c7e,081cde59..ca7a8475
--- a/Sources/Fluid/Persistence/SettingsStore.swift
+++ b/Sources/Fluid/Persistence/SettingsStore.swift
@@@ -2384,42 -2272,21 +2454,57 @@@ final class SettingsStore: ObservableOb
}
}
+ var overlayMaterial: OverlayMaterial {
+ get {
+ guard let raw = self.defaults.string(forKey: Keys.overlayMaterial),
+ let material = OverlayMaterial(rawValue: raw)
+ else {
+ return .smokedGlass
+ }
+ return material
+ }
+ set {
+ guard newValue != self.overlayMaterial else { return }
+ objectWillChange.send()
+ self.defaults.set(newValue.rawValue, forKey: Keys.overlayMaterial)
+ }
+ }
+
+ var overlayGlassOpacity: Double {
+ get {
+ guard self.defaults.object(forKey: Keys.overlayGlassOpacity) != nil else {
+ return Self.defaultOverlayGlassOpacity
+ }
+ return Self.normalizedOverlayGlassOpacity(self.defaults.double(forKey: Keys.overlayGlassOpacity))
+ }
+ set {
+ let normalized = Self.normalizedOverlayGlassOpacity(newValue)
+ guard normalized != self.overlayGlassOpacity else { return }
+ objectWillChange.send()
+ self.defaults.set(normalized, forKey: Keys.overlayGlassOpacity)
+ }
+ }
+
+ private static func normalizedOverlayGlassOpacity(_ value: Double) -> Double {
+ guard value.isFinite else { return self.defaultOverlayGlassOpacity }
+ return min(max(value, self.overlayGlassOpacityRange.lowerBound), self.overlayGlassOpacityRange.upperBound)
+ }
+
+ var meetingOverlayPreference: MeetingOverlayPreference {
+ get {
+ guard let raw = self.defaults.string(forKey: Keys.meetingOverlayPreference),
+ let preference = MeetingOverlayPreference(rawValue: raw)
+ else {
+ return .pill
+ }
+ return preference
+ }
+ set {
+ objectWillChange.send()
+ self.defaults.set(newValue.rawValue, forKey: Keys.meetingOverlayPreference)
+ }
+ }
+
/// How many recent transcription characters show in overlays (default: 150)
var transcriptionPreviewCharLimit: Int {
get {
@@@ -3547,11 -3403,7 +3633,12 @@@
overlayPosition: self.overlayPosition,
overlayBottomOffset: self.overlayBottomOffset,
overlaySize: self.overlaySize,
+ overlayMaterial: self.overlayMaterial,
+ overlayGlassOpacity: self.overlayGlassOpacity,
+ overlayTint: self.overlayTint,
+ overlayHighlight: self.overlayHighlight,
+ overlayClosingAnimationEnabled: self.overlayClosingAnimationEnabled,
+ meetingOverlayPreference: self.meetingOverlayPreference,
transcriptionPreviewCharLimit: self.transcriptionPreviewCharLimit,
userTypingWPM: self.userTypingWPM,
saveTranscriptionHistory: self.saveTranscriptionHistory,
@@@ -3713,21 -3566,9 +3805,24 @@@
self.overlayPosition = payload.overlayPosition
self.overlayBottomOffset = payload.overlayBottomOffset
self.overlaySize = payload.overlaySize
+ if let overlayMaterial = payload.overlayMaterial {
+ self.overlayMaterial = overlayMaterial
+ }
+ if let overlayGlassOpacity = payload.overlayGlassOpacity {
+ self.overlayGlassOpacity = overlayGlassOpacity
+ }
+ if let overlayTint = payload.overlayTint {
+ self.overlayTint = overlayTint
+ }
+ if let overlayHighlight = payload.overlayHighlight {
+ self.overlayHighlight = overlayHighlight
+ }
+ if let enabled = payload.overlayClosingAnimationEnabled {
+ self.overlayClosingAnimationEnabled = enabled
+ }
+ if let meetingOverlayPreference = payload.meetingOverlayPreference {
+ self.meetingOverlayPreference = meetingOverlayPreference
+ }
self.transcriptionPreviewCharLimit = payload.transcriptionPreviewCharLimit
self.userTypingWPM = payload.userTypingWPM
self.saveTranscriptionHistory = payload.saveTranscriptionHistory
@@@ -5846,8 -5655,7 +5946,9 @@@ private extension SettingsStore
static let overlayBottomOffset = "OverlayBottomOffset"
static let overlayBottomOffsetMigratedTo50 = "OverlayBottomOffsetMigratedTo50"
static let overlaySize = "OverlaySize"
+ static let overlayMaterial = "OverlayMaterial"
+ static let overlayGlassOpacity = "OverlayGlassOpacity"
+ static let meetingOverlayPreference = "MeetingOverlayPreference"
static let transcriptionPreviewCharLimit = "TranscriptionPreviewCharLimit"
/// Media Playback Control
diff --cc Sources/Fluid/Services/ASRService.swift
index 60d9cb37,cfa238a7..700ca302
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@@ -2882,11 -3225,10 +3247,12 @@@ final class ASRService: ObservableObjec
defer {
self.applyPendingParakeetVocabularyReloadIfNeeded()
self.isDictionaryTrainingCaptureActive = false
+ self.releaseDictationActivityIfNeeded()
}
+ traceStop("route_cleanup_begin")
await self.cancelAudioRouteRecoveryAndWait()
+ traceStop("route_cleanup_end")
guard self.isRunning, self.benchmarkSessionID == stoppingSessionID else {
self.recordingBufferHandoffGate.complete(bufferHandoffToken)
completedBufferHandoff = true
diff --cc Sources/Fluid/Services/AppNavigationRouter.swift
index 7a3f0e1e,9d667a74..3fff549a
--- a/Sources/Fluid/Services/AppNavigationRouter.swift
+++ b/Sources/Fluid/Services/AppNavigationRouter.swift
@@@ -3,7 -3,7 +3,8 @@@ import Foundatio
enum AppNavigationDestination {
case aiEnhancements
case history
+ case dictationShortcuts
+ case meetingTranscription
}
@MainActor
diff --cc Sources/Fluid/Services/MenuBarManager.swift
index d11035d8,b00aa5ec..595e8058
--- a/Sources/Fluid/Services/MenuBarManager.swift
+++ b/Sources/Fluid/Services/MenuBarManager.swift
@@@ -633,14 -758,38 +823,40 @@@ final class MenuBarManager: NSObject, O
}
private func updateMenuBarIcon() {
- guard let statusItem = statusItem else { return }
+ guard let statusItem = statusItem, statusItem.button?.image == nil else { return }
- // Use MenuBarIcon asset - vectorized from logo
+ // The template icon is identical in every state. Assigning a fresh
+ // NSImage on each recording change forced a status item redraw plus a
+ // WindowServer fence (about 200 ms measured) on every start and stop.
if let image = NSImage(named: "MenuBarIcon") {
- image.isTemplate = true
- statusItem.button?.image = image
+ switch self.meetingMenuPresentation.activity {
+ case .recording, .stopping:
+ statusItem.button?.image = self.menuBarActivityImage(baseImage: image, activity: .recording)
+ statusItem.button?.setAccessibilityLabel(
+ self.meetingMenuPresentation.activity == .stopping
+ ? "FluidVoice, stopping meeting recording"
+ : "FluidVoice, meeting recording"
+ )
+ case .preparing, .processing:
+ statusItem.button?.image = self.menuBarActivityImage(baseImage: image, activity: .processing)
+ statusItem.button?.setAccessibilityLabel(
+ self.meetingMenuPresentation.activity == .preparing
+ ? "FluidVoice, starting meeting recording"
+ : "FluidVoice, transcribing meeting"
+ )
+ case .interrupted, .failed:
+ statusItem.button?.image = self.menuBarActivityImage(baseImage: image, activity: .interrupted)
+ let status = self.meetingMenuPresentation.attentionStatus ?? "Meeting needs attention"
+ statusItem.button?.setAccessibilityLabel("FluidVoice, \(status.lowercased())")
+ case .inactive:
+ image.isTemplate = true
+ statusItem.button?.image = image
+ statusItem.button?.setAccessibilityLabel("FluidVoice")
+ case .completed:
+ image.isTemplate = true
+ statusItem.button?.image = image
+ statusItem.button?.setAccessibilityLabel("FluidVoice, meeting transcription complete")
+ }
}
}
diff --cc Sources/Fluid/UI/FileTranscriptionView.swift
index 00000000,d0b13baf..f9dc0ae3
mode 000000,100644..100644
--- a/Sources/Fluid/UI/FileTranscriptionView.swift
+++ b/Sources/Fluid/UI/FileTranscriptionView.swift
@@@ -1,0 -1,807 +1,807 @@@
+ import SwiftUI
+ import UniformTypeIdentifiers
+
+ struct FileTranscriptionView: View {
+ @ObservedObject var asrService: ASRService
+ @ObservedObject private var transcriptionService: FileTranscriptionService
+ @ObservedObject private var fileHistoryStore = FileTranscriptionHistoryStore.shared
+ @ObservedObject private var settings = SettingsStore.shared
+ @State private var selectedFileURL: URL?
+ @Environment(\.theme) private var theme
+
+ init(asrService: ASRService, transcriptionService: FileTranscriptionService) {
+ self.asrService = asrService
+ _transcriptionService = ObservedObject(wrappedValue: transcriptionService)
+ }
+
+ @State private var showingFilePicker = false
+ @State private var showingExportDialog = false
+ @State private var exportResult: TranscriptionResult?
+ @State private var exportFormat: ExportFormat = .text
+ @State private var showingCopyConfirmation = false
+ @State private var isDropTargeted = false
+ @State private var dropErrorMessage: String?
+
+ enum ExportFormat: String, CaseIterable {
+ case text = "Text (.txt)"
+ case json = "JSON (.json)"
+
+ var fileExtension: String {
+ switch self {
+ case .text: return "txt"
+ case .json: return "json"
+ }
+ }
+ }
+
+ private var selectedFileIsVideo: Bool {
+ guard let fileExtension = (self.selectedFileURL ?? self.transcriptionService.currentFileURL)?
+ .pathExtension.lowercased()
+ else { return false }
+ return UTType(filenameExtension: fileExtension)?.conforms(to: .movie) ?? false
+ }
+
+ private var conflictingActivity: ASRExclusiveActivity? {
+ guard let activity = self.asrService.activeExclusiveActivity,
+ activity != .fileTranscription
+ else {
+ return nil
+ }
+ return activity
+ }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ // Header
+ VStack(spacing: 8) {
+ Image(systemName: "waveform.circle.fill")
- .font(.system(size: 48))
++ .font(.fluidSystem(size: 48))
+ .foregroundStyle(Color.fluidGreen.gradient)
+
+ Text("File Transcription")
- .font(.title2)
++ .font(.fluidSystem(.title2))
+ .fontWeight(.semibold)
+
+ Text("Choose an audio or video file to transcribe")
- .font(.subheadline)
++ .font(.fluidSystem(.subheadline))
+ .foregroundColor(.secondary)
+ }
+ .padding(.top, 40)
+ .padding(.bottom, 30)
+
+ // Main Content Area
+ ScrollView {
+ VStack(spacing: 24) {
+ if let activity = self.conflictingActivity {
+ self.activityConflictCard(activity: activity)
+ }
+
+ // File Selection Card
+ self.fileSelectionCard
+
+ // Progress Card (only show when transcribing)
+ if self.transcriptionService.isTranscribing {
+ self.progressCard
+ }
+
+ // Results Card (only show when we have results)
+ if let result = transcriptionService.result {
+ self.resultsCard(result: result)
+ }
+
+ // Error Card (only show when we have an error)
+ if let error = transcriptionService.error {
+ self.errorCard(error: error)
+ }
+
+ // Drop error (unsupported file type)
+ if let message = self.dropErrorMessage {
+ self.dropErrorCard(message: message)
+ }
+
+ // Recent transcriptions (persisted history)
+ if !self.fileHistoryStore.entries.isEmpty {
+ Divider()
+ .padding(.vertical, 8)
+ self.recentTranscriptionsSection
+ }
+ }
+ .padding(24)
+ }
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .background(self.theme.palette.windowBackground)
+ .overlay(alignment: .topTrailing) {
+ if self.showingCopyConfirmation {
+ Text("Copied!")
- .font(.caption)
++ .font(.fluidSystem(.caption))
+ .padding(.horizontal, 12)
+ .padding(.vertical, 6)
+ .background(Color.fluidGreen.opacity(0.9))
+ .foregroundColor(.white)
+ .cornerRadius(8)
+ .padding()
+ .transition(.move(edge: .top).combined(with: .opacity))
+ }
+ }
+ .fileExporter(
+ isPresented: self.$showingExportDialog,
+ document: TranscriptionDocument(
+ result: self.exportResult ?? TranscriptionResult(text: "", confidence: 0, duration: 0, processingTime: 0, fileName: "transcript"),
+ format: self.exportFormat,
+ service: self.transcriptionService
+ ),
+ contentType: self.exportFormat == .text ? .plainText : .json,
+ defaultFilename: "\((self.exportResult?.fileName).map { "\($0)_transcript" } ?? "transcript").\(self.exportFormat.fileExtension)"
+ ) { exportCompletion in
+ switch exportCompletion {
+ case .success:
+ DebugLogger.shared.info("File exported successfully", source: "FileTranscriptionView")
+ case let .failure(error):
+ DebugLogger.shared.error("Export failed: \(error)", source: "FileTranscriptionView")
+ }
+ self.exportResult = nil
+ }
+ .onChange(of: self.transcriptionService.isTranscribing) { _, isTranscribing in
+ guard isTranscribing else { return }
+ AccessibilityNotification.Announcement("File transcription started").post()
+ }
+ .onChange(of: self.transcriptionService.result?.id) { _, resultID in
+ guard resultID != nil else { return }
+ AccessibilityNotification.Announcement("File transcription complete").post()
+ }
+ .onChange(of: self.transcriptionService.error) { _, error in
+ guard let error, !error.isEmpty else { return }
+ AccessibilityNotification.Announcement("File transcription failed. \(error)").post()
+ }
+ .onAppear {
+ if self.selectedFileURL == nil {
+ self.selectedFileURL = self.transcriptionService.currentFileURL
+ }
+ }
+ }
+
+ private func activityConflictCard(activity: ASRExclusiveActivity) -> some View {
+ Label(
+ "File transcription is paused while \(activity.displayName) is active.",
+ systemImage: activity == .meeting ? "person.2.wave.2.fill" : "waveform.badge.mic"
+ )
- .font(.subheadline)
++ .font(.fluidSystem(.subheadline))
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding()
+ .background(
+ RoundedRectangle(cornerRadius: 12, style: .continuous)
+ .fill(self.theme.palette.cardBackground)
+ .overlay(
+ RoundedRectangle(cornerRadius: 12, style: .continuous)
+ .stroke(self.theme.palette.cardBorder.opacity(0.45), lineWidth: 1)
+ )
+ )
+ .accessibilityLabel(
+ "File transcription unavailable. Wait for the active \(activity.displayName) to finish."
+ )
+ }
+
+ // MARK: - File Selection Card
+
+ private var fileSelectionCard: some View {
+ VStack(spacing: 16) {
+ if let fileURL = selectedFileURL ?? self.transcriptionService.currentFileURL {
+ // Show selected file
+ HStack {
+ Image(systemName: "doc.fill")
- .font(.title2)
++ .font(.fluidSystem(.title2))
+ .foregroundColor(Color.fluidGreen)
+
+ VStack(alignment: .leading, spacing: 4) {
+ Text(fileURL.lastPathComponent)
- .font(.headline)
++ .font(.fluidSystem(.headline))
+
+ Text(self.formatFileSize(fileURL: fileURL))
- .font(.caption)
++ .font(.fluidSystem(.caption))
+ .foregroundColor(.secondary)
+ }
+
+ Spacer()
+
+ Button(action: {
+ self.selectedFileURL = nil
+ self.transcriptionService.reset()
+ }) {
+ Image(systemName: "xmark.circle.fill")
+ .foregroundColor(.secondary)
+ }
+ .buttonStyle(.plain)
+ .disabled(self.transcriptionService.isTranscribing)
+ .help(self.transcriptionService.isTranscribing ? "Wait for transcription to finish" : "Remove file")
+ }
+ .padding()
+ .background(
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill(self.theme.palette.cardBackground)
+ .overlay(
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .stroke(self.theme.palette.cardBorder.opacity(0.5), lineWidth: 1)
+ )
+ )
+
+ // Speaker labeling options (unavailable on Intel Macs)
+ if SpeakerDiarizationService.isSupported {
+ VStack(spacing: 10) {
+ Toggle(isOn: self.$settings.fileTranscriptionSpeakerLabelsEnabled) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text("Label speakers")
- .font(.subheadline)
++ .font(.fluidSystem(.subheadline))
+
+ Text(self.selectedFileIsVideo
+ ? "Available for audio files only"
+ : "Identify who said what (downloads speaker models on first use)")
- .font(.caption)
++ .font(.fluidSystem(.caption))
+ .foregroundColor(.secondary)
+ }
+ }
+ .toggleStyle(.switch)
+ .disabled(self.selectedFileIsVideo || self.transcriptionService.isTranscribing)
+
+ if self.settings.fileTranscriptionSpeakerLabelsEnabled, !self.selectedFileIsVideo {
+ HStack {
+ Text("Number of speakers")
- .font(.subheadline)
++ .font(.fluidSystem(.subheadline))
+
+ Spacer()
+
+ Picker("", selection: self.$settings.fileTranscriptionExpectedSpeakerCount) {
+ Text("Auto").tag(0)
+ ForEach(2...8, id: \.self) { count in
+ Text("\(count)").tag(count)
+ }
+ }
+ .pickerStyle(.menu)
+ .labelsHidden()
+ .frame(width: 90)
+ .disabled(self.transcriptionService.isTranscribing)
+ }
+ }
+ }
+ .padding()
+ .background(
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill(self.theme.palette.cardBackground)
+ .overlay(
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .stroke(self.theme.palette.cardBorder.opacity(0.5), lineWidth: 1)
+ )
+ )
+ }
+
+ // Transcribe Button
+ Button(action: {
+ Task {
+ await self.transcribeFile()
+ }
+ }) {
+ HStack {
+ Image(systemName: "waveform")
+ Text("Transcribe")
+ }
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, 12)
+ }
+ .buttonStyle(.borderedProminent)
+ .disabled(
+ self.transcriptionService.isTranscribing ||
+ self.conflictingActivity != nil
+ )
+ .help(
+ self.conflictingActivity != nil
+ ? "Wait for the active transcription to finish"
+ : "Transcribe the selected file"
+ )
+
+ } else {
+ // File picker button – whole area is tappable; supports drag-and-drop
+ Button(action: {
+ self.showingFilePicker = true
+ }) {
+ VStack(spacing: 12) {
+ Image(systemName: "arrow.up.doc.fill")
- .font(.system(size: 32))
++ .font(.fluidSystem(size: 32))
+
+ Text("Drag and drop a file here, or click to open")
- .font(.headline)
++ .font(.fluidSystem(.headline))
+
+ Text(FileTranscriptionService.supportedFormatsDescription)
- .font(.caption)
++ .font(.fluidSystem(.caption))
+ .foregroundColor(.secondary)
+ }
+ .frame(maxWidth: .infinity)
+ .padding(32)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .background(
+ RoundedRectangle(cornerRadius: 12, style: .continuous)
+ .fill(self.theme.palette.cardBackground)
+ .overlay(
+ RoundedRectangle(cornerRadius: 12, style: .continuous)
+ .stroke(self.theme.palette.cardBorder.opacity(0.45), lineWidth: 1)
+ )
+ )
+ .overlay(
+ RoundedRectangle(cornerRadius: 12)
+ .strokeBorder(style: StrokeStyle(lineWidth: 2, dash: [8]))
+ .foregroundColor(Color.fluidGreen.opacity(self.isDropTargeted ? 0.7 : 0.3))
+ )
+ .onDrop(of: [.fileURL], isTargeted: self.$isDropTargeted) { providers in
+ self.handleDrop(providers: providers)
+ }
+ }
+ }
+ .fileImporter(
+ isPresented: self.$showingFilePicker,
+ allowedContentTypes: FileTranscriptionService.allowedContentTypes,
+ allowsMultipleSelection: false
+ ) { result in
+ switch result {
+ case let .success(urls):
+ if let url = urls.first {
+ self.selectedFileURL = url
+ self.transcriptionService.reset()
+ }
+ case let .failure(error):
+ DebugLogger.shared.error("File picker error: \(error)", source: "FileTranscriptionView")
+ }
+ }
+ }
+
+ // MARK: - Progress Card
+
+ private var progressCard: some View {
+ VStack(spacing: 16) {
+ ProgressView(value: self.transcriptionService.progress)
+ .progressViewStyle(.linear)
+
+ HStack {
+ ProgressView()
+ .controlSize(.small)
+ .fixedSize()
+
+ Text(self.transcriptionService.currentStatus)
- .font(.subheadline)
++ .font(.fluidSystem(.subheadline))
+ .foregroundColor(.secondary)
+ }
+ }
+ .padding()
+ .background(
+ RoundedRectangle(cornerRadius: 12, style: .continuous)
+ .fill(self.theme.palette.cardBackground)
+ .overlay(
+ RoundedRectangle(cornerRadius: 12, style: .continuous)
+ .stroke(self.theme.palette.cardBorder.opacity(0.45), lineWidth: 1)
+ )
+ )
+ }
+
+ // MARK: - Results Card
+
+ private func resultsCard(result: TranscriptionResult) -> some View {
+ VStack(alignment: .leading, spacing: 16) {
+ // Header with stats
+ HStack {
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Transcription Complete")
- .font(.headline)
++ .font(.fluidSystem(.headline))
+
+ HStack(spacing: 16) {
+ Label("\(String(format: "%.1f", result.duration))s", systemImage: "clock")
+ Label("\(String(format: "%.0f%%", result.confidence * 100))", systemImage: "checkmark.circle")
+ Label(
+ "\(String(format: "%.1f", result.duration / result.processingTime))x",
+ systemImage: "speedometer"
+ )
+ }
- .font(.caption)
++ .font(.fluidSystem(.caption))
+ .foregroundColor(.secondary)
+ }
+
+ Spacer()
+
+ // Action buttons
+ HStack(spacing: 8) {
+ Button(action: {
+ self.copyToClipboard(result.text)
+ }) {
+ Image(systemName: "doc.on.doc")
+ }
+ .help("Copy to clipboard")
+
+ Button(action: {
+ self.exportResult = result
+ self.showingExportDialog = true
+ }) {
+ Image(systemName: "square.and.arrow.up")
+ }
+ .help("Export transcription")
+ }
+ .buttonStyle(.borderless)
+ }
+
+ if let notice = result.speakerLabelingNotice ?? transcriptionService.fallbackNotice {
+ Label(notice, systemImage: "exclamationmark.triangle.fill")
- .font(.caption)
++ .font(.fluidSystem(.caption))
+ .foregroundColor(.secondary)
+ }
+
+ Divider()
+
+ // Transcription text
+ ScrollView {
+ if !result.speakerSegments.isEmpty {
+ VStack(alignment: .leading, spacing: 12) {
+ ForEach(result.speakerSegments) { segment in
+ VStack(alignment: .leading, spacing: 2) {
+ HStack(spacing: 6) {
+ Text(segment.speaker)
- .font(.caption)
++ .font(.fluidSystem(.caption))
+ .fontWeight(.semibold)
+ .foregroundColor(Color.fluidGreen)
+
+ Text(segment.timestampText)
- .font(.caption2)
++ .font(.fluidSystem(.caption2))
+ .foregroundColor(.secondary)
+ }
+
+ Text(segment.text)
- .font(.body)
++ .font(.fluidSystem(.body))
+ .textSelection(.enabled)
+ }
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding()
+ } else {
+ Text(result.text)
- .font(.body)
++ .font(.fluidSystem(.body))
+ .textSelection(.enabled)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding()
+ }
+ }
+ .frame(maxHeight: 300)
+ .background(
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill(self.theme.palette.contentBackground)
+ .overlay(
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .stroke(self.theme.palette.cardBorder.opacity(0.45), lineWidth: 1)
+ )
+ )
+ }
+ .padding()
+ .background(
+ RoundedRectangle(cornerRadius: 12, style: .continuous)
+ .fill(self.theme.palette.cardBackground)
+ .overlay(
+ RoundedRectangle(cornerRadius: 12, style: .continuous)
+ .stroke(self.theme.palette.cardBorder.opacity(0.45), lineWidth: 1)
+ )
+ )
+ }
+
+ // MARK: - Recent Transcriptions Section
+
+ private var recentTranscriptionsSection: some View {
+ VStack(alignment: .leading, spacing: 16) {
+ HStack {
+ Text("Recent transcriptions")
- .font(.headline)
++ .font(.fluidSystem(.headline))
+ Spacer()
+ if !self.fileHistoryStore.entries.isEmpty {
+ Button("Clear all") {
+ self.fileHistoryStore.clearAll()
+ }
+ .buttonStyle(.plain)
+ .foregroundColor(.secondary)
- .font(.caption)
++ .font(.fluidSystem(.caption))
+ }
+ }
+
+ VStack(spacing: 8) {
+ ForEach(self.fileHistoryStore.entries) { entry in
+ self.recentEntryRow(entry: entry)
+ }
+ }
+
+ if let entry = self.fileHistoryStore.selectedEntry {
+ self.historyDetailCard(entry: entry)
+ }
+ }
+ }
+
+ private func recentEntryRow(entry: FileTranscriptionEntry) -> some View {
+ let isSelected = self.fileHistoryStore.selectedEntryID == entry.id
+ return Button(action: {
+ self.fileHistoryStore.selectedEntryID = entry.id
+ }) {
+ HStack {
+ Image(systemName: "doc.text.fill")
- .font(.body)
++ .font(.fluidSystem(.body))
+ .foregroundColor(Color.fluidGreen)
+ .frame(width: 24)
+
+ VStack(alignment: .leading, spacing: 2) {
+ Text(entry.fileName)
- .font(.system(size: 14, weight: .medium))
++ .font(.fluidSystem(size: 14, weight: .medium))
+ .lineLimit(1)
+ Text(entry.relativeTimeString)
- .font(.caption)
++ .font(.fluidSystem(.caption))
+ .foregroundColor(.secondary)
+ Text(entry.previewText)
- .font(.caption)
++ .font(.fluidSystem(.caption))
+ .foregroundColor(.secondary)
+ .lineLimit(1)
+ }
+
+ Spacer()
+
+ if isSelected {
+ Image(systemName: "chevron.right.circle.fill")
+ .foregroundColor(Color.fluidGreen)
+ }
+ }
+ .padding(12)
+ .background(
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill(self.theme.palette.cardBackground)
+ .overlay(
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .stroke(isSelected ? Color.fluidGreen.opacity(0.5) : self.theme.palette.cardBorder.opacity(0.3), lineWidth: isSelected ? 2 : 1)
+ )
+ )
+ }
+ .buttonStyle(.plain)
+ }
+
+ private func historyDetailCard(entry: FileTranscriptionEntry) -> some View {
+ let result = entry.toTranscriptionResult()
+ return VStack(alignment: .leading, spacing: 16) {
+ HStack {
+ VStack(alignment: .leading, spacing: 4) {
+ Text("From history")
- .font(.headline)
++ .font(.fluidSystem(.headline))
+ HStack(spacing: 16) {
+ Label("\(String(format: "%.1f", entry.duration))s", systemImage: "clock")
+ Label("\(String(format: "%.0f%%", entry.confidence * 100))", systemImage: "checkmark.circle")
+ Label(entry.fullDateString, systemImage: "calendar")
+ }
- .font(.caption)
++ .font(.fluidSystem(.caption))
+ .foregroundColor(.secondary)
+ }
+ Spacer()
+ HStack(spacing: 8) {
+ Button(action: { self.copyToClipboard(entry.text) }) {
+ Image(systemName: "doc.on.doc")
+ }
+ .help("Copy to clipboard")
+ Button(action: {
+ self.exportResult = result
+ self.showingExportDialog = true
+ }) {
+ Image(systemName: "square.and.arrow.up")
+ }
+ .help("Export transcription")
+ Button(action: {
+ self.fileHistoryStore.deleteEntry(id: entry.id)
+ }) {
+ Image(systemName: "trash")
+ }
+ .help("Remove from history")
+ }
+ .buttonStyle(.borderless)
+ }
+ Divider()
+ ScrollView {
+ Text(entry.text)
- .font(.body)
++ .font(.fluidSystem(.body))
+ .textSelection(.enabled)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding()
+ }
+ .frame(maxHeight: 300)
+ .background(
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill(self.theme.palette.contentBackground)
+ .overlay(
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .stroke(self.theme.palette.cardBorder.opacity(0.45), lineWidth: 1)
+ )
+ )
+ }
+ .padding()
+ .background(
+ RoundedRectangle(cornerRadius: 12, style: .continuous)
+ .fill(self.theme.palette.cardBackground)
+ .overlay(
+ RoundedRectangle(cornerRadius: 12, style: .continuous)
+ .stroke(self.theme.palette.cardBorder.opacity(0.45), lineWidth: 1)
+ )
+ )
+ }
+
+ // MARK: - Error Card
+
+ private func errorCard(error: String) -> some View {
+ HStack {
+ Image(systemName: "exclamationmark.triangle.fill")
+ .foregroundColor(.red)
+
+ Text(error)
- .font(.subheadline)
++ .font(.fluidSystem(.subheadline))
+
+ Spacer()
+
+ Button("Dismiss") {
+ self.transcriptionService.reset()
+ }
+ .buttonStyle(.borderless)
+ }
+ .padding()
+ .background(
+ RoundedRectangle(cornerRadius: 12, style: .continuous)
+ .fill(Color.red.opacity(0.12))
+ .overlay(
+ RoundedRectangle(cornerRadius: 12, style: .continuous)
+ .stroke(Color.red.opacity(0.4), lineWidth: 1)
+ )
+ )
+ }
+
+ // MARK: - Drop Error Card
+
+ private func dropErrorCard(message: String) -> some View {
+ HStack {
+ Image(systemName: "exclamationmark.triangle.fill")
+ .foregroundColor(.red)
+
+ Text(message)
- .font(.subheadline)
++ .font(.fluidSystem(.subheadline))
+
+ Spacer()
+
+ Button("Dismiss") {
+ self.dropErrorMessage = nil
+ }
+ .buttonStyle(.borderless)
+ }
+ .padding()
+ .background(
+ RoundedRectangle(cornerRadius: 12, style: .continuous)
+ .fill(Color.red.opacity(0.12))
+ .overlay(
+ RoundedRectangle(cornerRadius: 12, style: .continuous)
+ .stroke(Color.red.opacity(0.4), lineWidth: 1)
+ )
+ )
+ }
+
+ // MARK: - Helper Functions
+
+ private static let supportedFileExtensions = FileTranscriptionService.supportedFileExtensions
+
+ private static let dropErrorCopy = FileTranscriptionService.dropErrorCopy
+
+ private func handleDrop(providers: [NSItemProvider]) -> Bool {
+ guard let provider = providers.first else { return false }
+ provider.loadItem(forTypeIdentifier: UTType.fileURL.identifier, options: nil) { item, _ in
+ let url: URL? = (item as? URL) ?? (item as? Data).flatMap { URL(dataRepresentation: $0, relativeTo: nil) }
+ guard let url = url else { return }
+ let ext = url.pathExtension.lowercased()
+ guard Self.supportedFileExtensions.contains(ext) else {
+ DispatchQueue.main.async {
+ self.dropErrorMessage = Self.dropErrorCopy
+ DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
+ self.dropErrorMessage = nil
+ }
+ }
+ return
+ }
+ DispatchQueue.main.async {
+ self.selectedFileURL = url
+ self.transcriptionService.reset()
+ self.dropErrorMessage = nil
+ }
+ }
+ return true
+ }
+
+ private func transcribeFile() async {
+ guard let fileURL = selectedFileURL else { return }
+
+ do {
+ _ = try await self.transcriptionService.transcribeFile(fileURL)
+ } catch {
+ DebugLogger.shared.error("Transcription error: \(error)", source: "FileTranscriptionView")
+ }
+ }
+
+ private func formatFileSize(fileURL: URL) -> String {
+ guard let attributes = try? FileManager.default.attributesOfItem(atPath: fileURL.path),
+ let fileSize = attributes[.size] as? Int64
+ else {
+ return "Unknown size"
+ }
+
+ let formatter = ByteCountFormatter()
+ formatter.countStyle = .file
+ return formatter.string(fromByteCount: fileSize)
+ }
+
+ private func copyToClipboard(_ text: String) {
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(text, forType: .string)
+
+ withAnimation {
+ self.showingCopyConfirmation = true
+ }
+
+ DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
+ withAnimation {
+ self.showingCopyConfirmation = false
+ }
+ }
+ }
+ }
+
+ // MARK: - Document for Export
+
+ struct TranscriptionDocument: FileDocument {
+ static var readableContentTypes: [UTType] {
+ [.plainText, .json]
+ }
+
+ let result: TranscriptionResult
+ let format: FileTranscriptionView.ExportFormat
+ let service: FileTranscriptionService
+
+ init(
+ result: TranscriptionResult,
+ format: FileTranscriptionView.ExportFormat,
+ service: FileTranscriptionService
+ ) {
+ self.result = result
+ self.format = format
+ self.service = service
+ }
+
+ init(configuration: ReadConfiguration) throws {
+ throw CocoaError(.fileReadUnknown)
+ }
+
+ func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
+ let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent("temp.\(self.format.fileExtension)")
+
+ switch self.format {
+ case .text:
+ try self.service.exportToText(self.result, to: tempURL)
+ case .json:
+ try self.service.exportToJSON(self.result, to: tempURL)
+ }
+
+ let data = try Data(contentsOf: tempURL)
+ try? FileManager.default.removeItem(at: tempURL)
+
+ return FileWrapper(regularFileWithContents: data)
+ }
+ }
+
+ // MARK: - Preview
+
+ #Preview {
+ let asrService = ASRService()
+ FileTranscriptionView(
+ asrService: asrService,
+ transcriptionService: FileTranscriptionService(asrService: asrService)
+ )
+ .frame(width: 700, height: 800)
+ }
diff --cc Sources/Fluid/UI/MeetingDetectionPrompt.swift
index 00000000,6d402ffc..d56f3894
mode 000000,100644..100644
--- a/Sources/Fluid/UI/MeetingDetectionPrompt.swift
+++ b/Sources/Fluid/UI/MeetingDetectionPrompt.swift
@@@ -1,0 -1,711 +1,711 @@@
+ import AppKit
+ import ApplicationServices
+ import Combine
+ import SwiftUI
+
+ /// Floating "Meeting detected" prompt — a NEW controller, deliberately separate from
+ /// `MeetingRecordingPillController`. The pill's contract (state-driven order-out, fixed 84×32
+ /// size, recording a11y label) fights a prompt mode, so this reuses only the shared panel
+ /// factory, not the pill's controller.
+ @MainActor
+ final class MeetingDetectionPromptController: ObservableObject {
+ static let shared = MeetingDetectionPromptController()
+
+ enum SuppressionReason: String, Equatable {
+ case dictationOverlay = "dictation-overlay"
+ case fullscreenOtherApp = "fullscreen-other-app"
+ }
+
+ static let panelSize = NSSize(width: 392, height: 120)
+ private static let defaultTopInset: CGFloat = 12
+ static let autoDismissSeconds: TimeInterval = 20
+ static let suppressionRetryInterval: TimeInterval = 0.5
+
+ enum ReminderPresentationDecision: Equatable {
+ case present
+ case retryAfter(TimeInterval)
+ case timeout
+ }
+
+ enum IncomingPromptPolicy: Equatable {
+ case ignore
+ case timeoutIncoming
+ case replaceExisting
+ }
+
+ enum PrimaryAction: Equatable {
+ case startRecording
+ case openSetup
+ }
+
+ static func primaryAction(for cta: MeetingAutoDetector.PromptCTA) -> PrimaryAction {
+ cta == .setup ? .openSetup : .startRecording
+ }
+
+ enum CheapSuppressionDecision: Equatable {
+ case suppressed(SuppressionReason)
+ case presentNow
+ case queryFullscreen(pid_t)
+ }
+
+ @Published private(set) var request: MeetingAutoDetector.PromptRequest?
+ @Published private(set) var appIcon: NSImage?
+ @Published private(set) var appDisplayName: String = ""
+ @Published private(set) var startErrorMessage: String?
+ @Published private(set) var isStarting = false
+
+ var onStart: ((UUID) async throws -> Void)?
+ var onSetup: ((UUID) -> Void)?
+ var onDismiss: ((UUID) -> Void)?
+ var onTimeout: ((UUID) -> Void)?
+
+ private var panel: MeetingFloatingCaptionsPanel?
+ private var autoDismissTask: Task<Void, Never>?
+ private var suppressionRetryTask: Task<Void, Never>?
+ private var startTask: Task<Void, Never>?
+ private var autoDismissLegStartedAt: Date?
+ private var remainingAutoDismissSeconds: TimeInterval = 0
+ private var isAutoDismissPaused = false
+ private var pendingSuppressedRequest: MeetingAutoDetector.PromptRequest?
+ private var hasLoggedCurrentSuppression = false
+
+ private init() {}
+
+ func present(_ request: MeetingAutoDetector.PromptRequest) {
+ switch Self.incomingPromptPolicy(
+ isStarting: self.isStarting,
+ currentEpisodeID: self.request?.episodeID,
+ pendingEpisodeID: self.pendingSuppressedRequest?.episodeID,
+ incomingEpisodeID: request.episodeID
+ ) {
+ case .ignore:
+ return
+ case .timeoutIncoming:
+ DebugLogger.shared.log(
+ "prompt-suppressed reason=start-in-progress bundle=\(request.bundleIdentifier)",
+ source: "MeetingAutoDetector"
+ )
+ self.onTimeout?(request.episodeID)
+ return
+ case .replaceExisting:
+ break
+ }
+ self.timeoutReplacedEpisodes(incoming: request.episodeID)
+ self.startErrorMessage = nil
+ self.isStarting = false
+
+ switch self.cheapSuppressionDecision(for: request) {
+ case .suppressed, .queryFullscreen:
+ self.beginSuppressedRetry(request)
+ case .presentNow:
+ self.showVisiblePrompt(request, remainingSeconds: Self.autoDismissSeconds)
+ }
+ }
+
+ func invalidateEpisode(_ episodeID: UUID) {
+ guard Self.shouldSilentlyInvalidatePrompt(
+ episodeID: episodeID,
+ visibleEpisodeID: self.request?.episodeID,
+ pendingEpisodeID: self.pendingSuppressedRequest?.episodeID
+ ) else { return }
+ if self.request?.episodeID == episodeID {
+ self.hide()
+ return
+ }
+ self.pendingSuppressedRequest = nil
+ self.cancelSuppressionRetry()
+ self.clearAutoDismiss()
+ }
+
+ func startTapped() {
+ guard let request, !self.isStarting else { return }
+ guard Self.primaryAction(for: request.cta) == .startRecording else {
+ let episodeID = request.episodeID
+ self.hide()
+ self.onSetup?(episodeID)
+ return
+ }
+ self.isStarting = true
+ self.startErrorMessage = nil
+ self.pauseAutoDismiss()
+ let episodeID = request.episodeID
+ self.startTask?.cancel()
+ self.startTask = Task { @MainActor [weak self] in
+ guard let self else { return }
+ do {
+ guard let onStart = self.onStart else {
+ self.isStarting = false
+ return
+ }
+ try await onStart(episodeID)
+ guard !Task.isCancelled, self.request?.episodeID == episodeID else { return }
+ self.hide()
+ } catch {
+ guard !Task.isCancelled, self.request?.episodeID == episodeID else { return }
+ DebugLogger.shared.log("prompt-start-failed error=\(error)", source: "MeetingAutoDetector")
+ self.startErrorMessage = Self.startErrorMessage(from: error, appDisplayName: self.appDisplayName)
+ self.isStarting = false
+ if !self.isPointerInsidePanel() {
+ self.resumeAutoDismiss()
+ }
+ }
+ }
+ }
+
+ func dismissTapped() {
+ guard let request, !self.isStarting else { return }
+ self.hide()
+ self.onDismiss?(request.episodeID)
+ }
+
+ func pauseAutoDismiss() {
+ guard self.request != nil, !self.isAutoDismissPaused, let startedAt = self.autoDismissLegStartedAt else { return }
+ self.remainingAutoDismissSeconds = Self.remainingAutoDismissSeconds(
+ self.remainingAutoDismissSeconds,
+ after: Date().timeIntervalSince(startedAt)
+ )
+ self.autoDismissTask?.cancel()
+ self.autoDismissTask = nil
+ self.autoDismissLegStartedAt = nil
+ self.isAutoDismissPaused = true
+ }
+
+ func resumeAutoDismiss() {
+ guard let request = self.request, self.isAutoDismissPaused, !self.isStarting else { return }
+ self.isAutoDismissPaused = false
+ self.scheduleAutoDismiss(for: request.episodeID)
+ }
+
+ private func hide() {
+ self.startTask?.cancel()
+ self.startTask = nil
+ self.isStarting = false
+ self.startErrorMessage = nil
+ self.cancelSuppressionRetry()
+ self.pendingSuppressedRequest = nil
+ self.hasLoggedCurrentSuppression = false
+ self.clearAutoDismiss()
+ self.panel?.orderOut(nil)
+ self.request = nil
+ }
+
+ private func showVisiblePrompt(_ request: MeetingAutoDetector.PromptRequest, remainingSeconds: TimeInterval) {
+ self.pendingSuppressedRequest = nil
+ self.cancelSuppressionRetry()
+ self.request = request
+ let resolved = NSWorkspace.shared.urlForApplication(withBundleIdentifier: request.bundleIdentifier)
+ self.appIcon = resolved.map { NSWorkspace.shared.icon(forFile: $0.path) }
+ self.appDisplayName = resolved.flatMap {
+ FileManager.default.displayName(atPath: $0.path).replacingOccurrences(of: ".app", with: "")
+ } ?? "Meeting"
+
+ let panel = self.panelOrCreate()
+ self.placeAtDefaultPosition(panel)
+ let reduceMotion = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion
+ panel.alphaValue = reduceMotion ? 1 : 0
+ panel.orderFrontRegardless()
+ if !reduceMotion {
+ NSAnimationContext.runAnimationGroup { context in
+ context.duration = 0.18
+ context.timingFunction = CAMediaTimingFunction(name: .easeOut)
+ panel.animator().alphaValue = 1
+ }
+ }
+ DebugLogger.shared.log("prompt-shown bundle=\(request.bundleIdentifier)", source: "MeetingAutoDetector")
+ AccessibilityNotification.Announcement(
+ "Meeting detected in \(self.appDisplayName). Nothing is recording yet."
+ ).post()
+
+ self.clearAutoDismiss()
+ self.remainingAutoDismissSeconds = remainingSeconds
+ self.isAutoDismissPaused = self.isPointerInsidePanel(panel)
+ self.scheduleAutoDismiss(for: request.episodeID)
+ }
+
+ private func beginSuppressedRetry(_ request: MeetingAutoDetector.PromptRequest) {
+ self.request = nil
+ self.panel?.orderOut(nil)
+ self.pendingSuppressedRequest = request
+ self.hasLoggedCurrentSuppression = false
+ self.autoDismissTask?.cancel()
+ self.autoDismissTask = nil
+ self.autoDismissLegStartedAt = nil
+ self.isAutoDismissPaused = false
+ self.remainingAutoDismissSeconds = Self.autoDismissSeconds
+ self.scheduleSuppressionRetry()
+ }
+
+ private func timeoutReplacedEpisodes(incoming: UUID) {
+ if let existing = Self.episodeToTimeoutOnReplacement(existing: self.request?.episodeID, incoming: incoming) {
+ self.onTimeout?(existing)
+ self.request = nil
+ }
+ if let pending = Self.episodeToTimeoutOnReplacement(existing: self.pendingSuppressedRequest?.episodeID, incoming: incoming) {
+ self.onTimeout?(pending)
+ self.pendingSuppressedRequest = nil
+ }
+ self.startTask?.cancel()
+ self.startTask = nil
+ self.cancelSuppressionRetry()
+ self.clearAutoDismiss()
+ }
+
+ private func scheduleSuppressionRetry() {
+ self.suppressionRetryTask?.cancel()
+ self.suppressionRetryTask = nil
+ guard let pending = self.pendingSuppressedRequest else { return }
+ switch self.cheapSuppressionDecision(for: pending) {
+ case let .suppressed(reason):
+ self.finishSuppressionEvaluation(pending: pending, reason: reason)
+ case .presentNow:
+ self.finishSuppressionEvaluation(pending: pending, reason: nil)
+ case let .queryFullscreen(pid):
+ let episodeID = pending.episodeID
+ self.suppressionRetryTask = Task { [weak self] in
+ let isFullScreen = await Task.detached(priority: .userInitiated) {
+ MeetingDetectionPromptController.isProcessFullScreen(processIdentifier: pid)
+ }.value
+ guard !Task.isCancelled, let self else { return }
+ guard self.pendingSuppressedRequest?.episodeID == episodeID else { return }
+ self.applyFullscreenQueryResult(pending: pending, queriedPid: pid, isFullScreen: isFullScreen)
+ }
+ }
+ }
+
+ private func applyFullscreenQueryResult(
+ pending: MeetingAutoDetector.PromptRequest,
+ queriedPid: pid_t,
+ isFullScreen: Bool
+ ) {
+ switch self.cheapSuppressionDecision(for: pending) {
+ case let .suppressed(reason):
+ self.finishSuppressionEvaluation(pending: pending, reason: reason)
+ case .presentNow:
+ self.finishSuppressionEvaluation(pending: pending, reason: nil)
+ case let .queryFullscreen(currentPid):
+ guard currentPid == queriedPid else {
+ self.scheduleSuppressionRetry()
+ return
+ }
+ let reason = Self.suppressionReason(
+ frontmostBundleIdentifier: NSWorkspace.shared.frontmostApplication?.bundleIdentifier,
+ isFrontmostFullScreen: isFullScreen,
+ isDictationOverlayPresented: false,
+ requestBundleIdentifier: pending.bundleIdentifier
+ )
+ self.finishSuppressionEvaluation(pending: pending, reason: reason)
+ }
+ }
+
+ private func finishSuppressionEvaluation(
+ pending: MeetingAutoDetector.PromptRequest,
+ reason: SuppressionReason?
+ ) {
+ if let reason, !self.hasLoggedCurrentSuppression {
+ self.hasLoggedCurrentSuppression = true
+ DebugLogger.shared.log(
+ "prompt-suppressed reason=\(reason.rawValue) bundle=\(pending.bundleIdentifier)",
+ source: "MeetingAutoDetector"
+ )
+ }
+ switch Self.reminderPresentationDecision(
+ remainingBudget: self.remainingAutoDismissSeconds,
+ isSuppressed: reason != nil
+ ) {
+ case .timeout:
+ self.pendingSuppressedRequest = nil
+ self.onTimeout?(pending.episodeID)
+ case .present:
+ self.showVisiblePrompt(pending, remainingSeconds: self.remainingAutoDismissSeconds)
+ case let .retryAfter(delay):
+ let delayNanoseconds = UInt64(delay * 1_000_000_000)
+ let startedAt = Date()
+ let episodeID = pending.episodeID
+ self.suppressionRetryTask = Task { [weak self] in
+ try? await Task.sleep(nanoseconds: delayNanoseconds)
+ guard !Task.isCancelled, let self else { return }
+ guard self.pendingSuppressedRequest?.episodeID == episodeID else { return }
+ self.remainingAutoDismissSeconds = Self.remainingAutoDismissSeconds(
+ self.remainingAutoDismissSeconds,
+ after: Date().timeIntervalSince(startedAt)
+ )
+ self.scheduleSuppressionRetry()
+ }
+ }
+ }
+
+ private func cancelSuppressionRetry() {
+ self.suppressionRetryTask?.cancel()
+ self.suppressionRetryTask = nil
+ }
+
+ private func cheapSuppressionDecision(for request: MeetingAutoDetector.PromptRequest) -> CheapSuppressionDecision {
+ let frontmostApplication = NSWorkspace.shared.frontmostApplication
+ return Self.cheapSuppressionDecision(
+ frontmostBundleIdentifier: frontmostApplication?.bundleIdentifier,
+ frontmostProcessIdentifier: frontmostApplication?.processIdentifier,
+ isDictationOverlayPresented: NotchContentState.shared.isBottomOverlayPresented,
+ requestBundleIdentifier: request.bundleIdentifier
+ )
+ }
+
+ private func isPointerInsidePanel(_ panel: NSPanel? = nil) -> Bool {
+ let target = panel ?? self.panel
+ guard let target else { return false }
+ return target.frame.contains(NSEvent.mouseLocation)
+ }
+
+ private func clearAutoDismiss() {
+ self.autoDismissTask?.cancel()
+ self.autoDismissTask = nil
+ self.autoDismissLegStartedAt = nil
+ self.remainingAutoDismissSeconds = 0
+ self.isAutoDismissPaused = false
+ }
+
+ private func scheduleAutoDismiss(for episodeID: UUID) {
+ guard !self.isAutoDismissPaused else { return }
+ guard self.remainingAutoDismissSeconds > 0 else {
+ self.onTimeout?(episodeID)
+ self.hide()
+ return
+ }
+ let delayNanoseconds = UInt64(self.remainingAutoDismissSeconds * 1_000_000_000)
+ self.autoDismissLegStartedAt = Date()
+ self.autoDismissTask = Task { [weak self] in
+ try? await Task.sleep(nanoseconds: delayNanoseconds)
+ guard !Task.isCancelled, let self, self.request?.episodeID == episodeID else { return }
+ self.onTimeout?(episodeID)
+ self.hide()
+ }
+ }
+
+ static func remainingAutoDismissSeconds(_ remaining: TimeInterval, after elapsed: TimeInterval) -> TimeInterval {
+ max(0, remaining - max(0, elapsed))
+ }
+
+ static func reminderPresentationDecision(
+ remainingBudget: TimeInterval,
+ isSuppressed: Bool,
+ retryInterval: TimeInterval = MeetingDetectionPromptController.suppressionRetryInterval
+ ) -> ReminderPresentationDecision {
+ if remainingBudget <= 0 { return .timeout }
+ if !isSuppressed { return .present }
+ return .retryAfter(min(retryInterval, remainingBudget))
+ }
+
+ static func episodeToTimeoutOnReplacement(existing: UUID?, incoming: UUID) -> UUID? {
+ guard let existing, existing != incoming else { return nil }
+ return existing
+ }
+
+ static func incomingPromptPolicy(
+ isStarting: Bool,
+ currentEpisodeID: UUID?,
+ pendingEpisodeID: UUID?,
+ incomingEpisodeID: UUID
+ ) -> IncomingPromptPolicy {
+ if incomingEpisodeID == currentEpisodeID || incomingEpisodeID == pendingEpisodeID {
+ return .ignore
+ }
+ if isStarting {
+ return .timeoutIncoming
+ }
+ return .replaceExisting
+ }
+
+ static func shouldSilentlyInvalidatePrompt(
+ episodeID: UUID,
+ visibleEpisodeID: UUID?,
+ pendingEpisodeID: UUID?
+ ) -> Bool {
+ episodeID == visibleEpisodeID || episodeID == pendingEpisodeID
+ }
+
+ static func cheapSuppressionDecision(
+ frontmostBundleIdentifier: String?,
+ frontmostProcessIdentifier: pid_t?,
+ isDictationOverlayPresented: Bool,
+ requestBundleIdentifier: String
+ ) -> CheapSuppressionDecision {
+ if isDictationOverlayPresented { return .suppressed(.dictationOverlay) }
+ if frontmostBundleIdentifier == requestBundleIdentifier { return .presentNow }
+ guard let frontmostProcessIdentifier else { return .presentNow }
+ return .queryFullscreen(frontmostProcessIdentifier)
+ }
+
+ static func startErrorMessage(from error: Error, appDisplayName: String) -> String {
+ if case MeetingCaptureError.applicationUnavailable = error {
+ return "\(appDisplayName) is no longer available to record."
+ }
+ return (error as? LocalizedError)?.errorDescription ?? "Can't start recording right now."
+ }
+
+ static func suppressionReason(
+ frontmostBundleIdentifier: String?,
+ isFrontmostFullScreen: Bool,
+ isDictationOverlayPresented: Bool,
+ requestBundleIdentifier: String
+ ) -> SuppressionReason? {
+ if isDictationOverlayPresented { return .dictationOverlay }
+ if isFrontmostFullScreen, frontmostBundleIdentifier != requestBundleIdentifier {
+ return .fullscreenOtherApp
+ }
+ return nil
+ }
+
+ nonisolated static func isProcessFullScreen(processIdentifier: pid_t) -> Bool {
+ let appElement = AXUIElementCreateApplication(processIdentifier)
+ _ = AXUIElementSetMessagingTimeout(appElement, 0.3)
+ var windowValue: CFTypeRef?
+ guard AXUIElementCopyAttributeValue(appElement, kAXFocusedWindowAttribute as CFString, &windowValue) == .success,
+ let window = windowValue
+ else { return false }
+ // swiftlint:disable:next force_cast
+ let windowElement = window as! AXUIElement
+ var fullScreenValue: CFTypeRef?
+ guard AXUIElementCopyAttributeValue(windowElement, "AXFullScreen" as CFString, &fullScreenValue) == .success else { return false }
+ return (fullScreenValue as? Bool) ?? false
+ }
+
+ private func panelOrCreate() -> MeetingFloatingCaptionsPanel {
+ if let panel { return panel }
+ let content = AnyView(
+ AdaptiveAppTheme(accent: SettingsStore.shared.accentColor) {
+ MeetingDetectionPromptContent(controller: self)
+ }
+ )
+ let panel = MeetingFloatingPanelFactory.make(size: Self.panelSize, resizable: false, content: content)
+ panel.acceptsMouseMovedEvents = true
+ self.placeAtDefaultPosition(panel)
+ self.panel = panel
+ return panel
+ }
+
+ private func placeAtDefaultPosition(_ panel: NSPanel) {
+ let screen = OverlayScreenResolver.screenForCurrentPointer() ?? NSScreen.main
+ guard let screen else { return }
+ let visible = screen.visibleFrame
+ panel.setFrame(Self.defaultFrame(panelSize: Self.panelSize, visibleFrame: visible), display: false)
+ }
+
+ static func defaultFrame(panelSize: NSSize, visibleFrame: NSRect) -> NSRect {
+ NSRect(
+ x: visibleFrame.midX - panelSize.width / 2,
+ y: visibleFrame.maxY - panelSize.height - Self.defaultTopInset,
+ width: panelSize.width,
+ height: panelSize.height
+ )
+ }
+ }
+
+ private struct MeetingDetectionPromptContent: View {
+ @ObservedObject var controller: MeetingDetectionPromptController
+
+ @Environment(\.theme) private var theme
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ HStack(spacing: 10) {
+ if let icon = self.controller.appIcon {
+ Image(nsImage: icon)
+ .resizable()
+ .aspectRatio(contentMode: .fit)
+ .frame(width: 34, height: 34)
+ .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
+ } else {
+ Image(systemName: "person.2.wave.2.fill")
- .font(.system(size: 20))
++ .font(.fluidSystem(size: 20))
+ .foregroundStyle(self.theme.palette.accent)
+ .frame(width: 34, height: 34)
+ .background(
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill(self.theme.palette.accent.opacity(0.12))
+ )
+ }
+ VStack(alignment: .leading, spacing: 2) {
+ Text("Meeting detected")
+ .font(self.theme.typography.bodyStrong)
+ .foregroundStyle(self.theme.palette.primaryText)
+ Text("\(self.controller.appDisplayName) appears to be in a call")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .lineLimit(1)
+ }
+ Spacer()
+ }
+
+ HStack(spacing: 8) {
+ if let startErrorMessage = self.controller.startErrorMessage {
+ Label(startErrorMessage, systemImage: "exclamationmark.triangle.fill")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.warning)
+ .lineLimit(1)
+ } else if self.controller.isStarting {
+ Label("Starting…", systemImage: "waveform")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ } else {
+ Label(
+ self.controller.request?.cta == .setup ? "Recording hasn’t started — setup required" : "Not recording yet",
+ systemImage: "mic.slash.fill"
+ )
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+
+ Spacer(minLength: 8)
+
+ Button("Not now") {
+ self.controller.dismissTapped()
+ }
+ .fluidButton(.compact, size: .small)
+ .disabled(self.controller.isStarting)
+
+ Button {
+ self.controller.startTapped()
+ } label: {
+ Label(
+ self.controller.request?.cta == .setup ? "Open recording setup" : "Record & transcribe",
+ systemImage: self.controller.request?.cta == .setup ? "gearshape" : "waveform"
+ )
+ }
+ .fluidButton(.accent, size: .small)
+ .disabled(self.controller.isStarting)
+ }
+ }
+ .padding(14)
+ .frame(
+ width: MeetingDetectionPromptController.panelSize.width,
+ height: MeetingDetectionPromptController.panelSize.height,
+ alignment: .top
+ )
+ .background(
+ RoundedRectangle(cornerRadius: 16, style: .continuous)
+ .fill(self.theme.palette.contentBackground.opacity(0.98))
+ )
+ .overlay(
+ RoundedRectangle(cornerRadius: 16, style: .continuous)
+ .stroke(self.theme.palette.separator.opacity(0.55), lineWidth: 1)
+ )
+ .shadow(color: .black.opacity(0.35), radius: 16, x: 0, y: 6)
+ .onHover { hovering in
+ if hovering {
+ self.controller.pauseAutoDismiss()
+ } else {
+ self.controller.resumeAutoDismiss()
+ }
+ }
+ .accessibilityElement(children: .contain)
+ .accessibilityLabel("Meeting detected in \(self.controller.appDisplayName). Nothing is recording yet. Record and transcribe, or dismiss.")
+ }
+ }
+
+ /// "Still recording?" nudge — passive, pill-adjacent, shown once per recording session while our
+ /// own recording's originating meeting evidence has been gone for a while.
+ @MainActor
+ final class MeetingStillRecordingNudgeController: ObservableObject {
+ static let shared = MeetingStillRecordingNudgeController()
+
+ private static let panelSize = NSSize(width: 260, height: 64)
+ private static let autoDismissSeconds: TimeInterval = 20
+
+ @Published private(set) var isPresented = false
+ var onStop: (() -> Void)?
+
+ private var panel: MeetingFloatingCaptionsPanel?
+ private var autoDismissTask: Task<Void, Never>?
+
+ private init() {}
+
+ func present() {
+ guard !self.isPresented else { return }
+ self.isPresented = true
+ let panel = self.panelOrCreate()
+ if let pillFrame = MeetingRecordingPillController.shared.currentOverlayFrame ?? self.pillFrameFallback() {
+ var frame = pillFrame
+ frame.origin.y += pillFrame.height + 8
+ frame.size = Self.panelSize
+ panel.setFrame(frame, display: false)
+ }
+ panel.orderFrontRegardless()
+ self.autoDismissTask?.cancel()
+ self.autoDismissTask = Task { [weak self] in
+ try? await Task.sleep(nanoseconds: UInt64(Self.autoDismissSeconds * 1_000_000_000))
+ guard !Task.isCancelled else { return }
+ self?.hide()
+ }
+ }
+
+ func hide() {
+ self.autoDismissTask?.cancel()
+ self.isPresented = false
+ self.panel?.orderOut(nil)
+ }
+
+ private func pillFrameFallback() -> NSRect? {
+ let screen = OverlayScreenResolver.screenForCurrentPointer() ?? NSScreen.main
+ guard let screen else { return nil }
+ let visible = screen.visibleFrame
+ return NSRect(x: visible.midX - 42, y: visible.minY + 64, width: 84, height: 32)
+ }
+
+ private func panelOrCreate() -> MeetingFloatingCaptionsPanel {
+ if let panel { return panel }
+ let content = AnyView(
+ AdaptiveAppTheme(accent: SettingsStore.shared.accentColor) {
+ MeetingStillRecordingNudgeContent(controller: self)
+ }
+ )
+ let panel = MeetingFloatingPanelFactory.make(size: Self.panelSize, resizable: false, content: content)
+ self.panel = panel
+ return panel
+ }
+ }
+
+ /// Backs the "Turn off automatic detection?" affordance after 3 explicit dismissals in 14 days.
+ /// Session-scoped: the settings sheet reads and clears it; it does not persist across launches.
+ @MainActor
+ final class MeetingAutoDetectDismissalAdvisor: ObservableObject {
+ static let shared = MeetingAutoDetectDismissalAdvisor()
+
+ @Published var shouldSuggest = false
+
+ private init() {}
+ }
+
+ private struct MeetingStillRecordingNudgeContent: View {
+ @ObservedObject var controller: MeetingStillRecordingNudgeController
+
+ @Environment(\.theme) private var theme
+
+ var body: some View {
+ HStack(spacing: 10) {
+ Image(systemName: "questionmark.circle.fill")
+ .foregroundStyle(self.theme.palette.warning)
+ Text("Meeting ended?")
+ .font(self.theme.typography.bodySmall)
+ .foregroundStyle(self.theme.palette.primaryText)
+ Spacer()
+ Button("Stop & Transcribe") {
+ self.controller.onStop?()
+ self.controller.hide()
+ }
+ .fluidButton(.compact, size: .small)
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 10)
+ .frame(width: 260, height: 64)
+ .background(
+ RoundedRectangle(cornerRadius: 14, style: .continuous)
+ .fill(self.theme.palette.contentBackground.opacity(0.96))
+ )
+ .overlay(
+ RoundedRectangle(cornerRadius: 14, style: .continuous)
+ .stroke(self.theme.palette.separator.opacity(0.55), lineWidth: 1)
+ )
+ .shadow(color: .black.opacity(0.3), radius: 12, x: 0, y: 4)
+ .accessibilityElement(children: .contain)
+ .accessibilityLabel("Meeting may have ended. Stop and transcribe?")
+ }
+ }
diff --cc Sources/Fluid/UI/MeetingFloatingCaptionsPanel.swift
index 00000000,b8f5662b..85b1f33c
mode 000000,100644..100644
--- a/Sources/Fluid/UI/MeetingFloatingCaptionsPanel.swift
+++ b/Sources/Fluid/UI/MeetingFloatingCaptionsPanel.swift
@@@ -1,0 -1,250 +1,250 @@@
+ import AppKit
+ import Combine
+ import SwiftUI
+
+ /// Borderless, non-activating panel that mirrors the live captions card while FluidVoice is buried
+ /// under a meeting app. `canBecomeKey` stays false and `title` stays unset so MenuBarManager's
+ /// main-window heuristics (level == .normal, styleMask.contains(.titled), canBecomeKey) never treat
+ /// it as the app's main window — see MenuBarManager.isFluidMainWindow.
+ final class MeetingFloatingCaptionsPanel: NSPanel {
+ override var canBecomeKey: Bool { false }
+ }
+
+ /// Swallows first-mouse so clicks and drags work while FluidVoice is inactive — this panel's
+ /// normal state, since it exists precisely so captions stay visible while another app has focus.
+ final class MeetingFloatingHostingView: NSHostingView<AnyView> {
+ var overlayHitPadding: MeetingOverlayPadding?
+
+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
+
+ override func hitTest(_ point: NSPoint) -> NSView? {
+ if let padding = self.overlayHitPadding {
+ let visible = NSRect(
+ x: self.bounds.minX + padding.left,
+ y: self.bounds.minY + padding.bottom,
+ width: self.bounds.width - padding.left - padding.right,
+ height: self.bounds.height - padding.top - padding.bottom
+ )
+ guard visible.contains(point) else { return nil }
+ }
+ return super.hitTest(point)
+ }
+ }
+
+ enum MeetingFloatingPanelFactory {
+ @MainActor
+ static func make(
+ size: NSSize,
+ resizable: Bool,
+ content: AnyView,
+ overlayHitPadding: MeetingOverlayPadding? = nil
+ ) -> MeetingFloatingCaptionsPanel {
+ var styleMask: NSWindow.StyleMask = [.borderless, .nonactivatingPanel]
+ if resizable { styleMask.insert(.resizable) }
+ let panel = MeetingFloatingCaptionsPanel(
+ contentRect: NSRect(origin: .zero, size: size),
+ styleMask: styleMask,
+ backing: .buffered,
+ defer: false
+ )
+ panel.isFloatingPanel = true
+ panel.level = .floating
+ panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
+ // Default true would hide the panel the instant the user clicks into Zoom — these panels
+ // exist precisely to stay visible while FluidVoice is not the active app.
+ panel.hidesOnDeactivate = false
+ panel.animationBehavior = .none
+ panel.isOpaque = false
+ panel.backgroundColor = .clear
+ panel.hasShadow = false
+ panel.isMovableByWindowBackground = true
+ // Must never appear in the user's own screen share.
+ panel.sharingType = .none
+
+ let hostingView = MeetingFloatingHostingView(rootView: content)
+ hostingView.overlayHitPadding = overlayHitPadding
+ hostingView.wantsLayer = true
+ hostingView.layer?.backgroundColor = .clear
+ panel.contentView = hostingView
+ return panel
+ }
+ }
+
+ @MainActor
+ final class MeetingFloatingCaptionsController: ObservableObject {
+ static let shared = MeetingFloatingCaptionsController()
+
+ private static let panelSize = NSSize(width: 400, height: 480)
+ private static let minimumSize = NSSize(width: 320, height: 240)
+ private static let autosaveName = "MeetingFloatingCaptions"
+ private static let defaultEdgeInset: CGFloat = 24
+
+ private var panel: MeetingFloatingCaptionsPanel?
+ private var stateSubscription: AnyCancellable?
+ private var screenParametersObserver: NSObjectProtocol?
+
+ private init() {}
+
+ static func isVisible(for state: MeetingCoordinatorState) -> Bool {
+ switch state {
+ case .recording, .recordingDegraded:
+ return true
+ case .idle, .preparing, .stopping, .processing, .completed, .interrupted, .failed:
+ return false
+ }
+ }
+
+ func show() {
+ let coordinator = AppServices.shared.meetingSessionCoordinator
+ let panel = self.panelOrCreate(coordinator: coordinator)
+ self.subscribeIfNeeded(coordinator: coordinator)
+
+ let sourceFrame = MeetingRecordingPillController.shared.resolveCaptionsSourceFrame()
+ let reduceMotion = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion
+ if let sourceFrame, !panel.isVisible, !reduceMotion {
+ let targetFrame = panel.frame
+ panel.setFrame(sourceFrame, display: false)
+ panel.orderFrontRegardless()
+ NSAnimationContext.runAnimationGroup { context in
+ context.duration = 0.55
+ context.timingFunction = CAMediaTimingFunction(controlPoints: 0.22, 1.0, 0.36, 1.0)
+ panel.animator().setFrame(targetFrame, display: true)
+ }
+ } else {
+ panel.orderFrontRegardless()
+ }
+ MeetingRecordingPillController.shared.collapse()
+ }
+
+ func hide() {
+ self.panel?.orderOut(nil)
+ }
+
+ private func panelOrCreate(coordinator: MeetingSessionCoordinator) -> MeetingFloatingCaptionsPanel {
+ if let panel { return panel }
+
+ let content = AnyView(
+ AdaptiveAppTheme(accent: SettingsStore.shared.accentColor) {
+ MeetingFloatingCaptionsContent(coordinator: coordinator)
+ }
+ )
+ let panel = MeetingFloatingPanelFactory.make(size: Self.panelSize, resizable: true, content: content)
+ panel.minSize = Self.minimumSize
+
+ panel.setFrameAutosaveName(Self.autosaveName)
+ // setFrameAutosaveName alone does not restore a saved frame; it only enables saving on move.
+ if !panel.setFrameUsingName(Self.autosaveName) {
+ self.placeAtDefaultPosition(panel)
+ }
+ self.clampIntoVisibleFrame(panel)
+
+ self.panel = panel
+ self.installScreenParametersObserverIfNeeded()
+ return panel
+ }
+
+ private func subscribeIfNeeded(coordinator: MeetingSessionCoordinator) {
+ guard self.stateSubscription == nil else { return }
+ self.stateSubscription = coordinator.$state
+ .receive(on: DispatchQueue.main)
+ .sink { [weak self] state in
+ guard Self.isVisible(for: state) else {
+ self?.hide()
+ return
+ }
+ }
+ }
+
+ private func placeAtDefaultPosition(_ panel: NSPanel) {
+ let screen = OverlayScreenResolver.screenForCurrentPointer() ?? NSScreen.main
+ guard let screen else { return }
+ let visible = screen.visibleFrame
+ let origin = NSPoint(
+ x: visible.maxX - Self.panelSize.width - Self.defaultEdgeInset,
+ y: visible.midY - Self.panelSize.height / 2
+ )
+ panel.setFrame(NSRect(origin: origin, size: Self.panelSize), display: false)
+ }
+
+ private func clampIntoVisibleFrame(_ panel: NSPanel) {
+ let visible = (panel.screen ?? NSScreen.main)?.visibleFrame
+ guard let visible else { return }
+ var frame = panel.frame
+ frame.origin.x = min(max(frame.origin.x, visible.minX), visible.maxX - frame.width)
+ frame.origin.y = min(max(frame.origin.y, visible.minY), visible.maxY - frame.height)
+ panel.setFrame(frame, display: false)
+ }
+
+ private func installScreenParametersObserverIfNeeded() {
+ guard self.screenParametersObserver == nil else { return }
+ self.screenParametersObserver = NotificationCenter.default.addObserver(
+ forName: NSApplication.didChangeScreenParametersNotification,
+ object: nil,
+ queue: .main
+ ) { [weak self] _ in
+ Task { @MainActor [weak self] in
+ self?.repositionIfOffscreen()
+ }
+ }
+ }
+
+ private func repositionIfOffscreen() {
+ guard let panel else { return }
+ let stillOnScreen = NSScreen.screens.contains { $0.visibleFrame.intersects(panel.frame) }
+ guard !stillOnScreen else { return }
+ self.placeAtDefaultPosition(panel)
+ self.clampIntoVisibleFrame(panel)
+ }
+ }
+
+ struct MeetingFloatingCaptionsContent: View {
+ @ObservedObject var coordinator: MeetingSessionCoordinator
+
+ @Environment(\.theme) private var theme
+
+ private var rows: [MeetingLiveBubbleComposer.Row] {
+ MeetingLiveBubbleComposer.rows(for: self.coordinator.liveTranscript)
+ }
+
+ var body: some View {
+ let rows = self.rows
+
+ VStack(alignment: .leading, spacing: 8) {
+ HStack {
+ Text("Live captions")
+ .font(self.theme.typography.captionStrong)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ Spacer()
+ Button {
+ MeetingFloatingCaptionsController.shared.hide()
+ } label: {
+ Image(systemName: "xmark")
- .font(.system(size: 11, weight: .semibold))
++ .font(.fluidSystem(size: 11, weight: .semibold))
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Close floating captions")
+ }
+
+ if rows.isEmpty {
+ Text("Listening…")
+ .font(self.theme.typography.bodySmall)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
+ } else {
+ MeetingLiveBubbleScrollList(rows: rows, hidesPartialFromAccessibility: false)
+ }
+ }
+ .padding(14)
+ .frame(minWidth: 320, maxWidth: .infinity, minHeight: 240, maxHeight: .infinity, alignment: .topLeading)
+ .background(
+ RoundedRectangle(cornerRadius: 16, style: .continuous)
+ .fill(self.theme.palette.contentBackground.opacity(0.96))
+ )
+ .overlay(
+ RoundedRectangle(cornerRadius: 16, style: .continuous)
+ .stroke(self.theme.palette.separator.opacity(0.55), lineWidth: 1)
+ )
+ .shadow(color: .black.opacity(0.35), radius: 16, x: 0, y: 6)
+ }
+ }
diff --cc Sources/Fluid/UI/MeetingLiveCaptionBubbles.swift
index 00000000,1815059d..7f4c2602
mode 000000,100644..100644
--- a/Sources/Fluid/UI/MeetingLiveCaptionBubbles.swift
+++ b/Sources/Fluid/UI/MeetingLiveCaptionBubbles.swift
@@@ -1,0 -1,155 +1,155 @@@
+ import SwiftUI
+
+ /// Shared bubble look for final transcript and live captions; callers own alignment, labels, and insets.
+ struct MeetingBubbleStyle {
+ var font: Font
+ var lineSpacing: CGFloat
+ var horizontalPadding: CGFloat
+ var verticalPadding: CGFloat
+ var cornerRadius: CGFloat
+ var fill: Color
+ var foreground: Color
+
+ static func final(fill: Color, foreground: Color) -> MeetingBubbleStyle {
+ MeetingBubbleStyle(
+ font: .system(size: 15, design: .monospaced), lineSpacing: 5,
+ horizontalPadding: 18, verticalPadding: 12, cornerRadius: 18,
+ fill: fill, foreground: foreground
+ )
+ }
+ }
+
+ extension View {
+ func meetingBubbleStyle(_ style: MeetingBubbleStyle) -> some View {
+ self
+ .font(style.font)
+ .lineSpacing(style.lineSpacing)
+ .foregroundStyle(style.foreground)
+ .padding(.horizontal, style.horizontalPadding)
+ .padding(.vertical, style.verticalPadding)
+ .background(style.fill, in: RoundedRectangle(cornerRadius: style.cornerRadius, style: .continuous))
+ }
+ }
+
+ /// Auto-follows the newest row only while the user is pinned to the bottom; scrolling up suspends
+ /// following and shows a jump-to-bottom button.
+ struct MeetingLiveBubbleScrollList: View {
+ let rows: [MeetingLiveBubbleComposer.Row]
+ var hidesPartialFromAccessibility = true
+
+ @Environment(\.theme) private var theme
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @State private var isPinnedToBottom = true
+
+ private var trailingPartialLength: Int {
+ guard let last = self.rows.last, last.isPartial else { return 0 }
+ return last.text.count
+ }
+
+ var body: some View {
+ let rowIDs = self.rows.map(\.id)
+ ScrollViewReader { proxy in
+ ZStack(alignment: .bottomTrailing) {
+ ScrollView {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.sm) {
+ ForEach(self.rows) { row in
+ MeetingLiveBubbleRow(row: row, hidesPartialFromAccessibility: self.hidesPartialFromAccessibility)
+ .equatable()
+ .id(row.id)
+ .transition(.opacity)
+ }
+ }
+ }
+ .animation(self.reduceMotion ? nil : .easeInOut(duration: 0.2), value: rowIDs)
+ // Wide threshold so a growing partial (one wrapped line ≈ 20pt) can't out-race the
+ // follow-up scrollTo and read as the user scrolling away; only a deliberate
+ // scroll-up (> 80pt) disengages following.
+ .onScrollGeometryChange(for: Bool.self) { geometry in
+ let bottomOffset = geometry.contentSize.height - geometry.containerSize.height
+ return geometry.contentOffset.y >= bottomOffset - 80
+ } action: { _, isPinned in
+ self.isPinnedToBottom = isPinned
+ }
+ .onChange(of: self.rows.count) {
+ self.scrollToBottomIfPinned(proxy: proxy)
+ }
+ .onChange(of: self.trailingPartialLength) {
+ self.scrollToBottomIfPinned(proxy: proxy)
+ }
+
+ if !self.isPinnedToBottom {
+ Button {
+ self.isPinnedToBottom = true
+ self.scrollToBottom(proxy: proxy, animated: true)
+ } label: {
+ Image(systemName: "chevron.down")
- .font(.system(size: 12, weight: .semibold))
++ .font(.fluidSystem(size: 12, weight: .semibold))
+ .foregroundStyle(self.theme.palette.primaryText)
+ .frame(width: 28, height: 28)
+ .background(self.theme.palette.contentBackground, in: Circle())
+ }
+ .buttonStyle(.plain)
+ .padding(6)
+ }
+ }
+ }
+ }
+
+ private func scrollToBottomIfPinned(proxy: ScrollViewProxy) {
+ guard self.isPinnedToBottom else { return }
+ self.scrollToBottom(proxy: proxy, animated: false)
+ }
+
+ private func scrollToBottom(proxy: ScrollViewProxy, animated: Bool) {
+ guard let lastID = self.rows.last?.id else { return }
+ guard animated, !self.reduceMotion else {
+ proxy.scrollTo(lastID, anchor: .bottom)
+ return
+ }
+ withAnimation(.easeInOut(duration: 0.2)) {
+ proxy.scrollTo(lastID, anchor: .bottom)
+ }
+ }
+ }
+
+ struct MeetingLiveBubbleRow: View, Equatable {
+ let row: MeetingLiveBubbleComposer.Row
+ var hidesPartialFromAccessibility: Bool = true
+
+ @Environment(\.theme) private var theme
+
+ static func == (lhs: MeetingLiveBubbleRow, rhs: MeetingLiveBubbleRow) -> Bool {
+ lhs.row == rhs.row && lhs.hidesPartialFromAccessibility == rhs.hidesPartialFromAccessibility
+ }
+
+ private var isMicrophone: Bool { self.row.speaker == .you }
+
+ private var sourceLabel: String {
+ self.isMicrophone ? "Microphone" : "Meeting audio"
+ }
+
+ /// Distinguish capture sources without claiming that either source belongs to a person.
+ private var fill: Color {
+ let base = self.isMicrophone ? self.theme.palette.accent : MeetingSpeakerPalette.tint(forSpeakerIndex: 0)
+ return base.opacity(self.row.isPartial ? 0.05 : 0.10)
+ }
+
+ var body: some View {
+ VStack(alignment: self.isMicrophone ? .trailing : .leading, spacing: 4) {
+ if self.row.showsLabel {
+ Text(self.sourceLabel)
+ .font(self.theme.typography.captionStrong)
+ .foregroundStyle(self.isMicrophone ? self.theme.palette.accent : self.theme.palette.secondaryText)
+ }
+ Text(self.row.text)
+ // The partial→final color swap solidifies in place; it must never animate.
+ .transaction { $0.animation = nil }
+ .meetingBubbleStyle(.final(fill: self.fill, foreground: self.row.isPartial ? self.theme.palette.secondaryText : self.theme.palette.primaryText))
+ }
+ .frame(maxWidth: .infinity, alignment: self.isMicrophone ? .trailing : .leading)
+ .padding(self.isMicrophone ? .leading : .trailing, 32)
+ .accessibilityElement(children: .combine)
+ .accessibilityLabel("\(self.sourceLabel), \(self.row.text)")
+ .accessibilityHidden(self.hidesPartialFromAccessibility && self.row.isPartial)
+ }
+ }
diff --cc Sources/Fluid/UI/MeetingRecordingPill.swift
index 00000000,536ffd3a..68f246ae
mode 000000,100644..100644
--- a/Sources/Fluid/UI/MeetingRecordingPill.swift
+++ b/Sources/Fluid/UI/MeetingRecordingPill.swift
@@@ -1,0 -1,663 +1,663 @@@
+ import AppKit
+ import Combine
+ import SwiftUI
+
+ /// Small always-on-top overlay shown automatically while a meeting is recording: live mic level and a
+ /// stop button, visible even when FluidVoice is buried under the meeting app.
+ @MainActor
+ final class MeetingRecordingPillController: ObservableObject {
+ static let shared = MeetingRecordingPillController()
+
+ @Published private(set) var presentation: MeetingOverlayPresentation = .pill
+
+ fileprivate static let overlayPadding = MeetingOverlayPadding.uniform(24)
+ private static let legacyAutosaveName = "MeetingRecordingPill"
+ private static let anchorCenterXKey = "MeetingRecordingOverlay.visibleAnchor.centerX"
+ private static let anchorBottomYKey = "MeetingRecordingOverlay.visibleAnchor.bottomY"
+ private static let defaultBottomInset: CGFloat = 64
+ private static let morphDuration: TimeInterval = 0.55
+
+ private var panel: MeetingFloatingCaptionsPanel?
+ private var reducer = MeetingOverlayPresentationReducer()
+ private var visibleAnchor: MeetingOverlayVisibleAnchor?
+ private var stateSubscription: AnyCancellable?
+ private var screenParametersObserver: NSObjectProtocol?
+ private var windowMoveObserver: NSObjectProtocol?
+ private var transitionGeneration = 0
+ private var inFlightTransitionGeneration: Int?
+ private var isApplyingProgrammaticFrame = false
+
+ private init() {}
+
+ func activate(coordinator: MeetingSessionCoordinator) {
+ guard self.stateSubscription == nil else { return }
+ self.stateSubscription = coordinator.$state
+ .receive(on: DispatchQueue.main)
+ .sink { [weak self, weak coordinator] state in
+ guard let self, let coordinator else { return }
+ self.handleCoordinatorState(state, coordinator: coordinator)
+ }
+ }
+
+ func toggleExpanded() {
+ self.reducer.apply(.toggleRequested)
+ guard let presentation = self.reducer.presentation else { return }
+ self.setPresentation(presentation)
+ }
+
+ /// Collapses back to the smallest pill — also called when the full captions window opens.
+ func collapse() {
+ guard self.reducer.presentation == .captions else { return }
+ self.reducer.apply(.toggleRequested)
+ self.setPresentation(self.reducer.presentation ?? .pill)
+ }
+
+ /// Visible surface of the current overlay, excluding transparent shadow padding.
+ var currentOverlayFrame: NSRect? {
+ guard let panel, panel.isVisible else { return nil }
+ return Self.visibleSurfaceFrame(from: panel.frame)
+ }
+
+ /// Source frame for the full captions window: a completed Captions surface only.
+ func resolveCaptionsSourceFrame() -> NSRect? {
+ guard self.presentation == .captions, self.panel?.isVisible == true else { return nil }
+ if self.inFlightTransitionGeneration != nil {
+ self.applyFrame(for: .captions, animated: false)
+ }
+ return self.currentOverlayFrame
+ }
+
+ private func handleCoordinatorState(_ state: MeetingCoordinatorState, coordinator: MeetingSessionCoordinator) {
+ switch state {
+ case .recording(let sessionID), .recordingDegraded(let sessionID):
+ if self.reducer.sessionID != sessionID {
+ self.invalidateTransition()
+ self.reducer.apply(.preferenceChanged(SettingsStore.shared.meetingOverlayPreference))
+ self.reducer.apply(.recordingStarted(sessionID: sessionID))
+ self.presentation = self.reducer.presentation ?? .pill
+ self.show(coordinator: coordinator, resetFrameToPresentation: true)
+ } else {
+ self.show(coordinator: coordinator, resetFrameToPresentation: false)
+ }
+ case .idle, .preparing, .stopping, .processing, .completed, .interrupted, .failed:
+ self.hideOverlay()
+ }
+ }
+
+ private func show(coordinator: MeetingSessionCoordinator, resetFrameToPresentation: Bool) {
+ let panel = self.panelOrCreate(coordinator: coordinator)
+ if resetFrameToPresentation {
+ self.applyFrame(for: self.presentation, animated: false)
+ }
+ panel.orderFrontRegardless()
+ }
+
+ private func hideOverlay() {
+ self.invalidateTransition()
+ self.reducer.apply(.recordingStopped)
+ self.presentation = .pill
+ self.panel?.orderOut(nil)
+ }
+
+ private func setPresentation(_ presentation: MeetingOverlayPresentation) {
+ guard self.presentation != presentation, self.panel != nil else {
+ self.presentation = presentation
+ return
+ }
+ self.presentation = presentation
+ self.applyFrame(for: presentation, animated: true)
+ }
+
+ private func applyFrame(for presentation: MeetingOverlayPresentation, animated: Bool) {
+ guard let panel else { return }
+ let anchor = self.resolvedAnchor(for: panel)
+ let screenVisible = self.screenVisibleFrame(for: anchor, panel: panel)
+ guard screenVisible.width > 0, screenVisible.height > 0 else { return }
+ let layout = MeetingOverlayGeometry.layout(
+ anchor: anchor,
+ visibleSize: presentation.visibleSize,
+ padding: Self.overlayPadding,
+ screenVisible: screenVisible
+ )
+ self.visibleAnchor = MeetingOverlayVisibleAnchor(
+ centerX: layout.visibleSurfaceFrame.midX,
+ bottomY: layout.visibleSurfaceFrame.minY
+ )
+
+ self.transitionGeneration += 1
+ let generation = self.transitionGeneration
+ self.inFlightTransitionGeneration = nil
+
+ let reduceMotion = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion
+ let canAnimate = animated
+ && panel.isVisible
+ && !reduceMotion
+ && !panel.frame.equalTo(layout.panelFrame)
+
+ self.isApplyingProgrammaticFrame = true
+ if !canAnimate {
+ NSAnimationContext.runAnimationGroup { context in
+ context.duration = 0
+ panel.animator().setFrame(layout.panelFrame, display: true)
+ }
+ self.isApplyingProgrammaticFrame = false
+ self.persistAnchor()
+ return
+ }
+
+ self.inFlightTransitionGeneration = generation
+ NSAnimationContext.runAnimationGroup { context in
+ context.duration = Self.morphDuration
+ context.timingFunction = CAMediaTimingFunction(controlPoints: 0.22, 1.0, 0.36, 1.0)
+ panel.animator().setFrame(layout.panelFrame, display: true)
+ } completionHandler: { [weak self] in
+ Task { @MainActor [weak self] in
+ guard let self, generation == self.transitionGeneration else { return }
+ self.isApplyingProgrammaticFrame = false
+ self.inFlightTransitionGeneration = nil
+ if let panel = self.panel {
+ self.captureAnchor(from: panel)
+ self.persistAnchor()
+ }
+ }
+ }
+ }
+
+ private func invalidateTransition() {
+ self.transitionGeneration += 1
+ self.inFlightTransitionGeneration = nil
+ self.isApplyingProgrammaticFrame = false
+ }
+
+ private func panelOrCreate(coordinator: MeetingSessionCoordinator) -> MeetingFloatingCaptionsPanel {
+ if let panel { return panel }
+
+ let presentation = self.presentation
+ if self.visibleAnchor == nil {
+ self.visibleAnchor = self.loadPersistedAnchor() ?? self.defaultAnchor()
+ }
+ let anchor = self.resolvedAnchor(for: nil)
+ let screenVisible = self.screenVisibleFrame(for: anchor, panel: nil)
+ let layout = MeetingOverlayGeometry.layout(
+ anchor: anchor,
+ visibleSize: presentation.visibleSize,
+ padding: Self.overlayPadding,
+ screenVisible: screenVisible.width > 0 ? screenVisible : CGRect(x: 0, y: 0, width: 1440, height: 900)
+ )
+
+ let content = AnyView(
+ AdaptiveAppTheme(accent: SettingsStore.shared.accentColor) {
+ MeetingRecordingPillContent(coordinator: coordinator)
+ }
+ )
+ let panel = MeetingFloatingPanelFactory.make(
+ size: layout.panelFrame.size,
+ resizable: false,
+ content: content,
+ overlayHitPadding: Self.overlayPadding
+ )
+
+ if self.loadPersistedAnchor() == nil, panel.setFrameUsingName(Self.legacyAutosaveName) {
+ let restored = panel.frame
+ self.visibleAnchor = MeetingOverlayVisibleAnchor(centerX: restored.midX, bottomY: restored.minY)
+ self.persistAnchor()
+ }
+
+ self.panel = panel
+ self.applyFrame(for: presentation, animated: false)
+ self.installWindowMoveObserverIfNeeded(for: panel)
+ self.installScreenParametersObserverIfNeeded()
+ return panel
+ }
+
+ private func defaultAnchor() -> MeetingOverlayVisibleAnchor {
+ let screen = OverlayScreenResolver.screenForCurrentPointer() ?? NSScreen.main
+ let visible = screen?.visibleFrame ?? CGRect(x: 0, y: 0, width: 1440, height: 900)
+ return MeetingOverlayVisibleAnchor(
+ centerX: visible.midX,
+ bottomY: visible.minY + Self.defaultBottomInset
+ )
+ }
+
+ private func resolvedAnchor(for panel: NSPanel?) -> MeetingOverlayVisibleAnchor {
+ if let visibleAnchor { return visibleAnchor }
+ if let panel {
+ return self.anchor(from: Self.visibleSurfaceFrame(from: panel.frame))
+ }
+ return self.defaultAnchor()
+ }
+
+ private func screenVisibleFrame(for anchor: MeetingOverlayVisibleAnchor, panel: NSPanel?) -> CGRect {
+ if let panel, let screen = panel.screen {
+ return screen.visibleFrame
+ }
+ let point = NSPoint(x: anchor.centerX, y: anchor.bottomY)
+ if let screen = NSScreen.screens.first(where: { $0.frame.contains(point) || $0.visibleFrame.contains(point) }) {
+ return screen.visibleFrame
+ }
+ return (OverlayScreenResolver.screenForCurrentPointer() ?? NSScreen.main)?.visibleFrame ?? .zero
+ }
+
+ private static func visibleSurfaceFrame(from panelFrame: CGRect) -> CGRect {
+ let padding = Self.overlayPadding
+ return CGRect(
+ x: panelFrame.minX + padding.left,
+ y: panelFrame.minY + padding.bottom,
+ width: max(0, panelFrame.width - padding.left - padding.right),
+ height: max(0, panelFrame.height - padding.top - padding.bottom)
+ )
+ }
+
+ private func anchor(from visible: CGRect) -> MeetingOverlayVisibleAnchor {
+ MeetingOverlayVisibleAnchor(centerX: visible.midX, bottomY: visible.minY)
+ }
+
+ private func captureAnchor(from panel: NSPanel) {
+ self.visibleAnchor = self.anchor(from: Self.visibleSurfaceFrame(from: panel.frame))
+ }
+
+ private func loadPersistedAnchor() -> MeetingOverlayVisibleAnchor? {
+ let defaults = UserDefaults.standard
+ guard defaults.object(forKey: Self.anchorCenterXKey) != nil,
+ defaults.object(forKey: Self.anchorBottomYKey) != nil
+ else { return nil }
+ return MeetingOverlayVisibleAnchor(
+ centerX: CGFloat(defaults.double(forKey: Self.anchorCenterXKey)),
+ bottomY: CGFloat(defaults.double(forKey: Self.anchorBottomYKey))
+ )
+ }
+
+ private func persistAnchor() {
+ guard let visibleAnchor else { return }
+ let defaults = UserDefaults.standard
+ defaults.set(Double(visibleAnchor.centerX), forKey: Self.anchorCenterXKey)
+ defaults.set(Double(visibleAnchor.bottomY), forKey: Self.anchorBottomYKey)
+ }
+
+ private func installWindowMoveObserverIfNeeded(for panel: NSPanel) {
+ guard self.windowMoveObserver == nil else { return }
+ self.windowMoveObserver = NotificationCenter.default.addObserver(
+ forName: NSWindow.didMoveNotification,
+ object: panel,
+ queue: .main
+ ) { [weak self] _ in
+ Task { @MainActor [weak self] in
+ guard let self, !self.isApplyingProgrammaticFrame, let panel = self.panel else { return }
+ self.captureAnchor(from: panel)
+ self.persistAnchor()
+ }
+ }
+ }
+
+ private func installScreenParametersObserverIfNeeded() {
+ guard self.screenParametersObserver == nil else { return }
+ self.screenParametersObserver = NotificationCenter.default.addObserver(
+ forName: NSApplication.didChangeScreenParametersNotification,
+ object: nil,
+ queue: .main
+ ) { [weak self] _ in
+ Task { @MainActor [weak self] in
+ self?.repositionForDisplayChange()
+ }
+ }
+ }
+
+ private func repositionForDisplayChange() {
+ guard let panel, panel.isVisible else { return }
+ self.applyFrame(for: self.presentation, animated: false)
+ }
+ }
+
+ struct MeetingRecordingPillContent: View {
+ @ObservedObject var coordinator: MeetingSessionCoordinator
+
+ @Environment(\.theme) private var theme
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @State private var isStopping = false
+ @State private var meetingAppIcon: NSImage? = NSApplication.shared.applicationIconImage
+
+ private var microphoneLevel: Float {
+ self.coordinator.trackHealth[.microphone]?.level ?? 0
+ }
+
+ private var isRecordingActive: Bool {
+ MeetingFloatingCaptionsController.isVisible(for: self.coordinator.state)
+ }
+
+ @ObservedObject private var pill = MeetingRecordingPillController.shared
+
+ var body: some View {
+ Group {
+ switch self.pill.presentation {
+ case .captions:
+ self.subtitleStrip
+ case .pill:
+ self.compactPill
+ }
+ }
+ // The panel and its view persist across meetings; re-arm the stop button per recording.
+ .onChange(of: self.isRecordingActive) { _, active in
+ if active { self.isStopping = false }
+ }
+ .onChange(of: self.coordinator.activeSession?.capturedApplication) { _, application in
+ self.meetingAppIcon = Self.resolveMeetingAppIcon(for: application)
+ }
+ .onAppear {
+ self.meetingAppIcon = Self.resolveMeetingAppIcon(
+ for: self.coordinator.activeSession?.capturedApplication
+ )
+ }
+ .animation(nil, value: self.pill.presentation)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom)
+ .padding(.top, MeetingRecordingPillController.overlayPadding.top)
+ .padding(.leading, MeetingRecordingPillController.overlayPadding.left)
+ .padding(.bottom, MeetingRecordingPillController.overlayPadding.bottom)
+ .padding(.trailing, MeetingRecordingPillController.overlayPadding.right)
+ .accessibilityElement(children: .contain)
+ .accessibilityLabel("Meeting recording in progress")
+ .accessibilityAction(named: "Stop Meeting Recording") {
+ self.stopRecording()
+ }
+ }
+
+ private var compactSurface: some View {
+ FluidOverlaySurface(
+ cornerRadius: 16,
+ border: .staticAngular(angle: .degrees(0), lineWidth: 1.2),
+ shadow: .init(opacity: 0.32, radius: 10, y: 4)
+ )
+ }
+
+ private var captionsSurface: some View {
+ FluidOverlaySurface(
+ cornerRadius: 16,
+ border: .linear(topOpacity: 0.15, bottomOpacity: 0.08, lineWidth: 1),
+ shadow: .init(opacity: 0.35, radius: 16, y: 6)
+ )
+ }
+
+ private var compactPill: some View {
+ HStack(spacing: 7) {
+ MeetingRecordingLevelBars(level: self.microphoneLevel, animated: !self.reduceMotion)
+ .frame(width: 20, height: 11)
+
+ self.stopButton
+ }
+ .padding(.horizontal, 9)
+ .padding(.vertical, 5)
+ .frame(
+ width: MeetingOverlayPresentation.pill.visibleSize.width,
+ height: MeetingOverlayPresentation.pill.visibleSize.height
+ )
+ .contentShape(Capsule())
+ // The whole capsule expands; only the stop button opts out (inner Button wins its hits).
+ .onTapGesture { self.pill.toggleExpanded() }
+ .background(self.compactSurface)
+ .accessibilityAddTraits(.isButton)
+ .accessibilityLabel("Show live captions")
+ .accessibilityAction(named: "Show Captions") {
+ self.pill.toggleExpanded()
+ }
+ }
+
+ @State private var isHoveringStrip = false
+
+ private var subtitleStrip: some View {
+ let rows = MeetingLiveBubbleComposer.rows(for: self.coordinator.liveTranscript)
+ return VStack(spacing: 0) {
+ VStack(spacing: 0) {
+ Color.clear
+ .frame(height: MeetingOverlayPresentation.captionsControlsHeight)
+
+ Color.clear
+ .frame(height: MeetingOverlayPresentation.captionsTopInset)
+
+ Group {
+ if rows.isEmpty {
+ Text(self.emptyCaptionStatusText)
- .font(.system(size: 13, design: .monospaced))
++ .font(.fluidSystem(size: 13, design: .monospaced))
+ // The overlay surface is intentionally always dark, independent of the
+ // app theme. System label colors can resolve dark in light mode and made
+ // this text indistinguishable from the black surface.
+ .foregroundStyle(Color.white.opacity(0.62))
+ .multilineTextAlignment(.center)
+ .lineLimit(2)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
+ .accessibilityHidden(true)
+ } else {
+ MeetingRollingCaptionView(
+ text: self.rollingSubtitle(rows: rows),
+ foregroundColor: NSColor.white.withAlphaComponent(0.94)
+ )
+ .frame(
+ width: MeetingOverlayPresentation.captionsContentWidth,
+ height: MeetingOverlayPresentation.captionsContentHeight,
+ alignment: .bottomLeading
+ )
+ .accessibilityHidden(true)
+ }
+ }
+ .frame(
+ width: MeetingOverlayPresentation.captionsContentWidth,
+ height: MeetingOverlayPresentation.captionsContentHeight
+ )
+ // Clip strictly to the content rectangle; the TextKit view itself also draws only
+ // the selected suffix inside this frame.
+ .clipped()
+
+ Color.clear
+ .frame(height: MeetingOverlayPresentation.captionsBottomInset)
+ }
+ .frame(
+ width: MeetingOverlayPresentation.captions.visibleSize.width,
+ height: MeetingOverlayPresentation.captionsViewportHeight
+ )
+ .clipped()
+
+ self.meetingStatusFooter
+ .frame(
+ width: MeetingOverlayPresentation.captions.visibleSize.width,
+ height: MeetingOverlayPresentation.captionsFooterHeight
+ )
+ }
+ .frame(
+ width: MeetingOverlayPresentation.captions.visibleSize.width,
+ height: MeetingOverlayPresentation.captions.visibleSize.height
+ )
+ .background(self.captionsSurface)
+ // Hover controls stay inside their permanently reserved top strip, never over text.
+ .overlay(alignment: .topTrailing) {
+ if self.isHoveringStrip {
+ HStack(spacing: 8) {
+ MeetingRecordingLevelBars(level: self.microphoneLevel, animated: !self.reduceMotion)
+ .frame(width: 18, height: 10)
+ Button {
+ MeetingFloatingCaptionsController.shared.show()
+ } label: {
+ Image(systemName: "rectangle.portrait.and.arrow.right")
- .font(.system(size: 10, weight: .semibold))
++ .font(.fluidSystem(size: 10, weight: .semibold))
+ .foregroundStyle(Color.white.opacity(0.68))
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Open captions window")
+ Button {
+ self.pill.collapse()
+ } label: {
+ Image(systemName: "chevron.down")
- .font(.system(size: 10, weight: .semibold))
++ .font(.fluidSystem(size: 10, weight: .semibold))
+ .foregroundStyle(Color.white.opacity(0.68))
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Collapse captions")
+ self.stopButton
+ }
+ .padding(.horizontal, 8)
+ .padding(.vertical, 4)
+ .background(Capsule().fill(Color.black.opacity(0.82)))
+ .padding(6)
+ .transition(.opacity)
+ }
+ }
+ .onHover { hovering in
+ withAnimation(.easeInOut(duration: 0.15)) { self.isHoveringStrip = hovering }
+ }
+ .accessibilityAction(named: "Hide Captions") {
+ self.pill.collapse()
+ }
+ .accessibilityAction(named: "Open Captions Window") {
+ MeetingFloatingCaptionsController.shared.show()
+ }
+ }
+
+ private var emptyCaptionStatusText: String {
+ switch self.coordinator.liveTranscript.availability {
+ case .available:
+ return "Listening…"
+ case .unavailable(let reason), .degraded(let reason):
+ return reason
+ }
+ }
+
+ /// Mirrors the dictation overlay's persistent status row without coupling meeting state to the
+ /// dictation overlay. The ZStack keeps the waveform geometrically centered even when the app
+ /// icon and label have different widths.
+ private var meetingStatusFooter: some View {
+ ZStack {
+ MeetingCaptionWaveform(level: self.microphoneLevel, animated: !self.reduceMotion)
+ .frame(width: 90, height: 20)
+
+ HStack {
+ if let meetingAppIcon = self.meetingAppIcon {
+ Image(nsImage: meetingAppIcon)
+ .resizable()
+ .aspectRatio(contentMode: .fit)
+ .frame(width: 18, height: 18)
+ .clipShape(RoundedRectangle(cornerRadius: 4, style: .continuous))
+ } else {
+ Circle()
+ .fill(self.theme.palette.accent.opacity(0.9))
+ .frame(width: 9, height: 9)
+ .frame(width: 18, height: 18)
+ }
+
+ Spacer()
+
+ Text("Meeting")
- .font(.system(size: 10, weight: .semibold))
++ .font(.fluidSystem(size: 10, weight: .semibold))
+ .foregroundStyle(self.theme.palette.accent)
+ .lineLimit(1)
+ .fixedSize(horizontal: true, vertical: false)
+ }
+ }
+ .frame(height: 28)
+ .padding(.horizontal, 14)
+ .padding(.bottom, 7)
+ .accessibilityElement(children: .combine)
+ .accessibilityLabel("Meeting microphone activity")
+ }
+
+ private static func resolveMeetingAppIcon(for application: MeetingApplicationIdentity?) -> NSImage? {
+ if let processID = application?.processID,
+ let icon = NSRunningApplication(processIdentifier: processID)?.icon
+ {
+ return icon
+ }
+ if let bundleIdentifier = application?.bundleIdentifier,
+ let applicationURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier)
+ {
+ return NSWorkspace.shared.icon(forFile: applicationURL.path)
+ }
+ return NSApplication.shared.applicationIconImage
+ }
+
+ /// One rolling stream across the most recent rows. TextKit selects complete wrapped lines;
+ /// this input bound prevents an ever-growing live transcript from retaining excess storage.
+ private func rollingSubtitle(rows: [MeetingLiveBubbleComposer.Row]) -> String {
+ var words: [String] = []
+ var previousSpeaker: MeetingLiveSpeaker?
+ for row in rows.suffix(8) {
+ if previousSpeaker != nil, row.speaker != previousSpeaker {
+ words.append("—")
+ }
+ previousSpeaker = row.speaker
+ words.append(row.text)
+ }
+ return String(words.joined(separator: " ").suffix(MeetingRollingCaptionLayout.maximumInputCharacters))
+ }
+
+ private func stopRecording() {
+ guard !self.isStopping, self.isRecordingActive else { return }
+ self.isStopping = true
+ let coordinator = self.coordinator
+ Task {
+ _ = try? await coordinator.stopAndTranscribe()
+ }
+ }
+
+ private var stopButton: some View {
+ Button {
+ self.stopRecording()
+ } label: {
+ Image(systemName: "stop.fill")
- .font(.system(size: 8, weight: .bold))
++ .font(.fluidSystem(size: 8, weight: .bold))
+ .foregroundStyle(Color.white.opacity(0.92))
+ .frame(width: 18, height: 18)
+ .background(Color.white.opacity(0.12), in: Circle())
+ .overlay(Circle().stroke(Color.white.opacity(0.18), lineWidth: 1))
+ }
+ .buttonStyle(.plain)
+ .disabled(self.isStopping || !self.isRecordingActive)
+ .accessibilityLabel("Stop meeting recording and transcribe")
+ }
+ }
+
+ /// Five bars scaled by the published mic level; center-weighted so it reads as a waveform.
+ private struct MeetingRecordingLevelBars: View {
+ let level: Float
+ let animated: Bool
+
+ @Environment(\.theme) private var theme
+
+ private static let weights: [CGFloat] = [0.45, 0.75, 1.0, 0.75, 0.45]
+
+ var body: some View {
+ FluidOverlayLevelBars(
+ heights: Self.weights.map { max(2.5, CGFloat(self.level) * 11 * $0) },
+ width: 2,
+ spacing: 2.5,
+ cornerRadius: 1,
+ color: self.theme.palette.accent,
+ glowColor: self.theme.palette.accent,
+ glowRadius: 0
+ )
+ .frame(maxHeight: .infinity, alignment: .center)
+ .animation(self.animated ? .easeOut(duration: 0.12) : nil, value: self.level)
+ .accessibilityHidden(true)
+ }
+ }
+
+ /// Wider center-weighted meter for the captions footer, matching the visual rhythm of the
+ /// dictation overlay while remaining driven by the meeting microphone track.
+ private struct MeetingCaptionWaveform: View {
+ let level: Float
+ let animated: Bool
+
+ @Environment(\.theme) private var theme
+
+ private static let weights: [CGFloat] = [0.30, 0.46, 0.66, 0.86, 1.0, 0.86, 0.66, 0.46, 0.30]
+
+ var body: some View {
+ FluidOverlayLevelBars(
+ heights: Self.weights.map { max(4, CGFloat(self.level) * 19 * $0) },
+ width: 3,
+ spacing: 4,
+ cornerRadius: 1.5,
+ color: self.theme.palette.accent,
+ glowColor: self.theme.palette.accent.opacity(0.42),
+ glowRadius: 2
+ )
+ .frame(maxHeight: .infinity, alignment: .center)
+ .animation(self.animated ? .easeOut(duration: 0.12) : nil, value: self.level)
+ .accessibilityHidden(true)
+ }
+ }
diff --cc Sources/Fluid/UI/MeetingTranscriptionView.swift
index 2174e0e9,bac03bc9..e8634ce9
--- a/Sources/Fluid/UI/MeetingTranscriptionView.swift
+++ b/Sources/Fluid/UI/MeetingTranscriptionView.swift
@@@ -9,43 -13,2601 +13,2601 @@@ nonisolated struct MeetingApplicationOp
}
}
+ struct MeetingMicrophoneOption: Identifiable, Equatable {
+ let id: String
+ let identity: MeetingMicrophoneIdentity
+
+ init(identity: MeetingMicrophoneIdentity) {
+ self.identity = identity
+ self.id = identity.captureDeviceID
+ }
+ }
+
+ struct MeetingTranscriptionSetupDraft: Equatable {
+ var mode: MeetingCaptureMode = .onlineCall
+ var title: String = Self.defaultTitle(mode: .onlineCall, applicationDisplayName: nil)
+ var selectedApplicationID: String?
+ var selectedMicrophoneID: String?
+ /// Once true, the default title stops following the selected application/mode.
+ var titleWasEdited = false
+
+ init(settings: SettingsStore = .shared) {
+ let defaults = settings.meetingRecordingDefaults
+ self.mode = defaults.mode
+ self.title = Self.defaultTitle(mode: defaults.mode, applicationDisplayName: nil)
+ self.selectedApplicationID = nil
+ // Left unset here: selectPreferredMicrophone decides once identities load.
+ self.selectedMicrophoneID = nil
+ }
+
+ static func defaultTitle(mode: MeetingCaptureMode, applicationDisplayName: String?) -> String {
+ guard mode == .onlineCall else { return "In-room meeting" }
+ guard let applicationDisplayName, !applicationDisplayName.isEmpty else { return "Meeting" }
+ return "\(applicationDisplayName) call"
+ }
+ }
+
+ struct MeetingSetupReadiness: Equatable {
+ var isCheckingSources: Bool
+ var meetingAudioStatus: String
+ var meetingAudioReady: Bool
+ var microphoneStatus: String
+ var microphoneReady: Bool
+ var modelStatus: String
+ var modelReady: Bool
+ var storageStatus: String
+ var storageReady: Bool
+ var activityStatus: String
+ var activityReady: Bool
+ var showMicrophoneSettingsAction: Bool
+ var showScreenRecordingSettingsAction: Bool
+ var blockingMessage: String?
+
+ static let checking = Self(
+ isCheckingSources: true,
+ meetingAudioStatus: "Checking…",
+ meetingAudioReady: false,
+ microphoneStatus: "Checking…",
+ microphoneReady: false,
+ modelStatus: "Available after recording",
+ modelReady: false,
+ storageStatus: "Checking…",
+ storageReady: false,
+ activityStatus: "Checking…",
+ activityReady: false,
+ showMicrophoneSettingsAction: false,
+ showScreenRecordingSettingsAction: false,
+ blockingMessage: "Checking recording access and sources."
+ )
+ }
+
struct MeetingTranscriptionView: View {
- let asrService: ASRService
- @StateObject private var transcriptionService: MeetingTranscriptionService
- @ObservedObject private var fileHistoryStore = FileTranscriptionHistoryStore.shared
- @ObservedObject private var settings = SettingsStore.shared
- @State private var selectedFileURL: URL?
+ @ObservedObject var coordinator: MeetingSessionCoordinator
+ @ObservedObject var asrService: ASRService
+ let onOpenVoiceEngine: () -> Void
+
@Environment(\.theme) private var theme
- @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @Environment(\.accessibilityReduceMotion) private var accessibilityReduceMotion
+
+ @State private var setupDraft: MeetingTranscriptionSetupDraft
+ @State private var setupDraftBeforeEditing: MeetingTranscriptionSetupDraft
+ @State private var isShowingMeetingSettings: Bool
+ @State private var applications: [MeetingApplicationOption] = []
+ @State private var microphones: [MeetingMicrophoneOption] = []
+ @State private var isRefreshingSources = false
+ @State private var isStarting = false
+ @State private var isStopping = false
+ @State private var isRetrying = false
+ @State private var actionErrorMessage: String?
+ @State private var cachedMicrophoneStatus: AVAuthorizationStatus = .notDetermined
+ @State private var cachedScreenCaptureAccess = false
+ @State private var cachedModelReady = false
+ @State private var cachedStorageStatus = "Checking…"
+ @State private var cachedStorageReady = false
+ @State private var meetingHistory: [MeetingSession] = []
+ @State private var selectedHistorySessionID: MeetingSessionID?
+ @State private var meetingHistoryError: String?
+ @State private var pendingDeleteSessionID: MeetingSessionID?
+ @State private var pendingDeleteAudioSessionID: MeetingSessionID?
+ @State private var draftMeetingAudioRetentionPolicy = SettingsStore.shared.meetingAudioRetentionPolicy
+ @AppStorage("MeetingHistoryInspectorVisible") private var isMeetingHistoryVisible = true
+
+ init(
+ coordinator: MeetingSessionCoordinator,
+ asrService: ASRService,
+ onOpenVoiceEngine: @escaping () -> Void
+ ) {
+ self.coordinator = coordinator
+ self.asrService = asrService
+ self.onOpenVoiceEngine = onOpenVoiceEngine
+
+ let initialDraft = MeetingTranscriptionSetupDraft(settings: .shared)
+ self._setupDraft = State(initialValue: initialDraft)
+ self._setupDraftBeforeEditing = State(initialValue: initialDraft)
+ self._isShowingMeetingSettings = State(initialValue: !SettingsStore.shared.meetingRecordingDefaults.isConfigured)
+ }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ MeetingTranscriptionHeader(
+ state: self.canvasState,
+ isMeetingHistoryVisible: self.isMeetingHistoryVisible,
+ onNewMeeting: self.startNewMeeting,
+ onOpenMeetingSettings: self.openMeetingSettings,
+ onToggleMeetingHistory: {
+ let willShowHistory = !self.isMeetingHistoryVisible
+ withAnimation(self.accessibilityReduceMotion ? nil : .easeInOut(duration: 0.2)) {
+ self.isMeetingHistoryVisible.toggle()
+ }
+ if willShowHistory, self.meetingHistory.isEmpty {
+ Task { await self.loadMeetingHistory() }
+ }
+ }
+ )
+
+ Divider()
+
+ HStack(spacing: 0) {
+ MeetingTranscriptionCanvas(
+ setupDraft: self.$setupDraft,
+ state: self.canvasState,
+ applications: self.applications,
+ microphones: self.microphones,
+ readiness: self.readiness,
+ errorMessage: self.actionErrorMessage,
+ onRefreshSources: self.refreshSourcesFromUserAction,
+ onStart: self.startRecording,
+ onStop: self.stopAndTranscribe,
+ onRetrySession: { self.retryProcessingSession(id: $0.id) },
+ onRevealAudio: self.revealCapturedAudio,
+ onRecordAgain: self.recordAgain,
+ onCopyTranscript: self.copyTranscript,
+ onExportTranscript: self.exportTranscript,
+ onReassignSegment: self.reassignSegment,
+ onNameUnknownSegment: self.nameUnknownSegment,
+ onRenameSpeaker: self.renameSpeaker,
+ onMergeSpeakers: self.mergeSpeakers,
+ onUndoCorrection: self.undoTranscriptCorrection,
+ onRenameSession: self.renameMeetingSession,
+ onAssignSpeakers: self.assignSpeakers,
+ canUndoCorrection: { self.coordinator.canUndoCorrection(sessionID: $0) },
+ isQuiescent: self.coordinator.isQuiescent,
+ onOpenMeetingSettings: self.openMeetingSettings,
+ isRetrying: self.isRetrying,
+ onCloseSelection: self.closeCanvasAction
+ )
+
+ if self.isMeetingHistoryVisible {
+ Divider()
+ MeetingHistoryInspector(
+ sessions: self.meetingHistory,
+ selectedSessionID: Binding(
+ get: { self.selectedHistorySessionID },
+ set: { if self.canBrowseMeetingHistory { self.selectedHistorySessionID = $0 } }
+ ),
+ errorMessage: self.meetingHistoryError,
+ isQuiescent: self.coordinator.isQuiescent,
+ onRefresh: { Task { await self.loadMeetingHistory() } },
+ onRetry: { self.retryProcessingSession(id: $0) },
+ onRevealAudio: self.revealCapturedAudio,
+ onExportAudio: self.exportAudio,
+ onExportTranscript: { self.exportTranscript($0, format: $1, includeEchoes: false) },
+ onDeleteAudioRequest: { self.pendingDeleteAudioSessionID = $0 },
+ onDeleteRequest: { self.pendingDeleteSessionID = $0 },
+ onRecordAgain: self.recordAgain
+ )
+ .frame(width: 290)
+ .transition(.move(edge: .trailing).combined(with: .opacity))
+ }
+ }
+ }
+ .background(self.theme.palette.windowBackground)
+ .clipped()
+ .task {
+ async let sources: Void = self.refreshSources(requestPermissions: false)
+ if self.isMeetingHistoryVisible {
+ await self.loadMeetingHistory()
+ }
+ await sources
+ }
+ .onChange(of: self.setupDraft.mode) { _, _ in
+ Task { await self.refreshSources(requestPermissions: false) }
+ self.regenerateDefaultTitleIfNeeded()
+ }
+ .onChange(of: self.setupDraft.selectedApplicationID) { _, _ in
+ self.regenerateDefaultTitleIfNeeded()
+ }
+ .onChange(of: self.asrService.isAsrReady) { _, isReady in
+ self.cachedModelReady = isReady || self.asrService.modelsExistOnDisk
+ }
+ .onChange(of: self.asrService.modelsExistOnDisk) { _, existsOnDisk in
+ self.cachedModelReady = self.asrService.isAsrReady || existsOnDisk
+ }
+ .onChange(of: self.coordinator.latestCompletedSession?.id) { _, _ in
+ Task { await self.loadMeetingHistory() }
+ }
+ .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
+ Task {
+ async let sources: Void = self.refreshSources(requestPermissions: false)
+ if self.isMeetingHistoryVisible {
+ await self.loadMeetingHistory()
+ }
+ await sources
+ }
+ }
+ .sheet(isPresented: self.$isShowingMeetingSettings) {
+ MeetingRecordingSettingsSheet(
+ draft: self.$setupDraft,
+ retentionPolicy: self.$draftMeetingAudioRetentionPolicy,
+ applications: self.applications,
+ microphones: self.microphones,
+ readiness: self.readiness,
+ isFirstSetup: !SettingsStore.shared.meetingRecordingDefaults.isConfigured,
+ savedApplicationName: Self.savedApplicationName,
+ savedApplicationBundleIdentifier: SettingsStore.shared.meetingRecordingDefaults.applicationBundleIdentifier,
+ onRefreshSources: self.refreshSourcesFromUserAction,
+ onOpenMicrophoneSettings: { Self.openMicrophoneSettings() },
+ onOpenScreenRecordingSettings: { self.openScreenRecordingSettings() },
+ onOpenVoiceEngine: self.onOpenVoiceEngine,
+ onCancel: self.cancelMeetingSettings,
+ onSave: self.saveMeetingSettings
+ )
+ .interactiveDismissDisabled(!SettingsStore.shared.meetingRecordingDefaults.isConfigured)
+ }
+ .alert(
+ "Delete Meeting?",
+ isPresented: Binding(
+ get: { self.pendingDeleteSessionID != nil },
+ set: { if !$0 { self.pendingDeleteSessionID = nil } }
+ )
+ ) {
+ Button("Cancel", role: .cancel) { self.pendingDeleteSessionID = nil }
+ Button("Delete", role: .destructive) {
+ if let id = self.pendingDeleteSessionID { self.deleteSession(id: id) }
+ }
+ } message: {
+ Text("The recording and transcript will be permanently deleted from this Mac.")
+ }
+ .alert(
+ "Delete Audio?",
+ isPresented: Binding(
+ get: { self.pendingDeleteAudioSessionID != nil },
+ set: { if !$0 { self.pendingDeleteAudioSessionID = nil } }
+ )
+ ) {
+ Button("Cancel", role: .cancel) { self.pendingDeleteAudioSessionID = nil }
+ Button("Delete Audio", role: .destructive) {
+ if let id = self.pendingDeleteAudioSessionID { self.deleteAudio(id: id) }
+ }
+ } message: {
+ Text("The transcript stays; the audio files are deleted from this Mac.")
+ }
+ }
+
+ private var canvasState: MeetingTranscriptionCanvasState {
+ if let selectedHistorySession, self.canBrowseMeetingHistory {
+ switch selectedHistorySession.state {
+ case .failed:
+ let message = selectedHistorySession.failures.last?.message ?? "This meeting failed."
+ return .failed(session: selectedHistorySession, message: message)
+ case .interrupted:
+ let message = selectedHistorySession.endedAt != nil && !selectedHistorySession.processingAttempts.isEmpty
+ ? "Transcription was interrupted. Captured audio is ready to retry."
+ : "Recording was interrupted. Captured audio has been preserved on this Mac."
+ return .failed(session: selectedHistorySession, message: message)
+ default:
+ return .result(selectedHistorySession)
+ }
+ }
+
+ switch self.coordinator.state {
+ case .idle:
+ return .setup(isStarting: self.isStarting, recentSession: self.coordinator.latestCompletedSession)
+ case .preparing:
+ return .setup(isStarting: true, recentSession: self.coordinator.latestCompletedSession)
+ case .recording, .recordingDegraded:
+ guard let session = self.coordinator.activeSession else {
+ return .failed(session: nil, message: "The active meeting could not be loaded.")
+ }
+ if self.isStopping {
+ return .stopping(session: session, trackHealth: self.coordinator.trackHealth, liveTranscript: self.coordinator.liveTranscript)
+ }
+ return .recording(session: session, trackHealth: self.coordinator.trackHealth, liveTranscript: self.coordinator.liveTranscript)
+ case .stopping:
+ guard let session = self.coordinator.activeSession else {
+ return .failed(session: nil, message: "The meeting is stopping, but its session could not be loaded.")
+ }
+ return .stopping(session: session, trackHealth: self.coordinator.trackHealth, liveTranscript: self.coordinator.liveTranscript)
+ case let .processing(_, stage):
+ guard let session = self.coordinator.activeSession else {
+ return .failed(session: nil, message: "The meeting is processing, but its session could not be loaded.")
+ }
+ return .processing(session: session, stage: stage)
+ case .completed:
+ guard let session = self.coordinator.latestCompletedSession else {
+ return .failed(session: nil, message: "The completed transcript could not be loaded.")
+ }
+ return .result(session)
+ case .interrupted:
+ let session = self.coordinator.activeSession
+ let message = session?.endedAt != nil && session?.processingAttempts.isEmpty == false
+ ? "Transcription was interrupted. Captured audio is ready to retry."
+ : "Recording was interrupted. Captured audio has been preserved on this Mac."
+ return .failed(
+ session: session,
+ message: message
+ )
+ case let .failed(_, failure):
+ return .failed(session: self.coordinator.activeSession, message: failure.message)
+ }
+ }
+
+ private var selectedHistorySession: MeetingSession? {
+ guard let selectedHistorySessionID else { return nil }
+ return self.meetingHistory.first(where: { $0.id == selectedHistorySessionID })
+ }
+
+ /// Closing a history selection returns to whatever is underneath; closing the just-finished
+ /// meeting's own result/failure returns to the new-meeting screen.
+ private var closeCanvasAction: (() -> Void)? {
+ if self.selectedHistorySessionID != nil {
+ return { self.selectedHistorySessionID = nil }
+ }
+ switch self.coordinator.state {
+ case .completed, .failed, .interrupted:
+ return { self.startNewMeeting() }
+ default:
+ return nil
+ }
+ }
+
+ private var canBrowseMeetingHistory: Bool {
+ switch self.coordinator.state {
+ case .idle, .completed, .interrupted, .failed:
+ return true
+ case .preparing, .recording, .recordingDegraded, .stopping, .processing:
+ return false
+ }
+ }
+
+ private var readiness: MeetingSetupReadiness {
+ let microphoneStatus = self.cachedMicrophoneStatus
+ let microphoneReady = microphoneStatus == .authorized
+ let meetingAudioReady = self.setupDraft.mode == .inRoom || self.cachedScreenCaptureAccess
+ let modelReady = self.cachedModelReady
+ let conflictingActivity = self.asrService.activeExclusiveActivity
+ let activityReady = conflictingActivity == nil
+
+ let microphoneStatusText: String
+ switch microphoneStatus {
+ case .authorized:
+ microphoneStatusText = self.microphones.isEmpty ? "No microphone found" : "Ready"
+ case .notDetermined:
+ microphoneStatusText = "Access required"
+ case .denied:
+ microphoneStatusText = "Access denied"
+ case .restricted:
+ microphoneStatusText = "Access restricted"
+ @unknown default:
+ microphoneStatusText = "Access unavailable"
+ }
+
+ let blockingMessage: String?
+ if self.isRefreshingSources {
+ blockingMessage = "Checking recording access and sources."
+ } else if let conflictingActivity {
+ blockingMessage = "Wait for the active \(conflictingActivity.displayName) to finish."
+ } else if microphoneStatus == .restricted {
+ blockingMessage = "Microphone access is restricted by system policy."
+ } else if !microphoneReady {
+ blockingMessage = "Allow microphone access, then refresh sources."
+ } else if self.microphones.isEmpty {
+ blockingMessage = "Connect a microphone, then refresh sources."
+ } else if self.setupDraft.mode == .onlineCall, !meetingAudioReady {
+ blockingMessage = "Allow Screen & System Audio access, then refresh sources."
+ } else if !self.cachedStorageReady {
+ let trackCount = MeetingPCMStoragePolicy.trackCount(for: self.setupDraft.mode)
+ blockingMessage = "Free at least \(MeetingPCMStoragePolicy.requiredFreeSpaceDescription(trackCount: trackCount)) of storage before recording."
+ } else {
+ blockingMessage = nil
+ }
+
+ return MeetingSetupReadiness(
+ isCheckingSources: self.isRefreshingSources,
+ meetingAudioStatus: meetingAudioReady ? "Ready" : "Access required",
+ meetingAudioReady: meetingAudioReady,
+ microphoneStatus: microphoneStatusText,
+ microphoneReady: microphoneReady && !self.microphones.isEmpty,
+ modelStatus: modelReady ? "Installed · runs after Stop" : "Will prepare after Stop",
+ modelReady: modelReady,
+ storageStatus: self.cachedStorageStatus,
+ storageReady: self.cachedStorageReady,
+ activityStatus: conflictingActivity.map { "Wait for \($0.displayName)" } ?? "Ready",
+ activityReady: activityReady,
+ showMicrophoneSettingsAction: microphoneStatus == .denied,
+ showScreenRecordingSettingsAction: self.setupDraft.mode == .onlineCall && !meetingAudioReady,
+ blockingMessage: blockingMessage
+ )
+ }
+
+ private func refreshSourcesFromUserAction() {
+ Task { await self.refreshSources(requestPermissions: true) }
+ }
+
+ @MainActor
+ private func refreshSources(requestPermissions: Bool) async {
+ guard !self.isRefreshingSources else { return }
+ self.isRefreshingSources = true
+ self.refreshCachedReadiness()
+ defer {
+ self.refreshCachedReadiness()
+ self.isRefreshingSources = false
+ }
+
+ self.actionErrorMessage = nil
+
+ if requestPermissions, AVCaptureDevice.authorizationStatus(for: .audio) == .notDetermined {
+ _ = await Self.requestMicrophoneAccess()
+ }
+
+ if AVCaptureDevice.authorizationStatus(for: .audio) == .authorized {
+ let snapshot = await MeetingCaptureSourceCatalog.microphoneSnapshot()
+ let identities = snapshot.identities
+ self.microphones = identities.map(MeetingMicrophoneOption.init)
+ self.selectPreferredMicrophone(from: identities, systemDefaultUID: snapshot.defaultCoreAudioUID)
+ } else {
+ self.microphones = []
+ self.setupDraft.selectedMicrophoneID = nil
+ }
+
+ guard self.setupDraft.mode == .onlineCall else { return }
+
+ if requestPermissions, !CGPreflightScreenCaptureAccess() {
+ _ = CGRequestScreenCaptureAccess()
+ }
+
+ guard CGPreflightScreenCaptureAccess() else {
+ self.applications = []
+ self.setupDraft.selectedApplicationID = nil
+ return
+ }
+
+ do {
+ let identities = try await MeetingCaptureSourceCatalog.availableApplications()
+ self.applications = identities.map(MeetingApplicationOption.init)
+ self.selectPreferredApplication(from: identities)
+ } catch {
+ self.applications = []
+ self.setupDraft.selectedApplicationID = nil
+ self.actionErrorMessage = error.localizedDescription
+ }
+ }
+
+ /// Keeps the title following the selected app/mode until the user types their own.
+ private func regenerateDefaultTitleIfNeeded() {
+ guard !self.setupDraft.titleWasEdited else { return }
+ let applicationName = self.applications.first(where: { $0.id == self.setupDraft.selectedApplicationID })?.identity.displayName
+ self.setupDraft.title = MeetingTranscriptionSetupDraft.defaultTitle(
+ mode: self.setupDraft.mode,
+ applicationDisplayName: applicationName
+ )
+ }
+
+ private func resetDraftTitleToDefault() {
+ self.setupDraft.titleWasEdited = false
+ self.regenerateDefaultTitleIfNeeded()
+ }
+
+ private func selectPreferredMicrophone(
+ from identities: [MeetingMicrophoneIdentity],
+ systemDefaultUID: String?
+ ) {
+ if let selectedID = setupDraft.selectedMicrophoneID,
+ identities.contains(where: { $0.captureDeviceID == selectedID })
+ {
+ return
+ }
+
+ let defaults = SettingsStore.shared.meetingRecordingDefaults
+ let savedMicrophone = defaults.savedMicrophone(in: identities)
+ let preferredInputUID = SettingsStore.shared.preferredInputDeviceUID
+ // Default preselection follows the system's current input, not the remembered device.
+ let selection = MeetingMicrophonePreselection.select(
+ identities: identities,
+ savedDeviceID: savedMicrophone?.captureDeviceID,
+ savedRole: defaults.microphoneRole,
+ systemDefaultUID: systemDefaultUID,
+ preferredInputUID: preferredInputUID,
+ systemDefaultCaptureID: nil
+ )
+ self.setupDraft.selectedMicrophoneID = selection.deviceID
+ }
+
+ private func selectPreferredApplication(from identities: [MeetingApplicationIdentity]) {
+ let options = identities.map(MeetingApplicationOption.init)
+ if let selectedID = setupDraft.selectedApplicationID,
+ options.contains(where: { $0.id == selectedID })
+ {
+ return
+ }
+
+ let defaults = SettingsStore.shared.meetingRecordingDefaults
+ if defaults.isConfigured {
+ let savedIdentity = defaults.savedApplication(in: identities)
+ self.setupDraft.selectedApplicationID = savedIdentity.map { MeetingApplicationOption(identity: $0).id }
+ return
+ }
+
+ let preferredBundleIdentifiers = [
+ "us.zoom.xos",
+ "com.google.Chrome",
+ "com.microsoft.teams2",
+ ]
+ let preferredIdentity = preferredBundleIdentifiers.lazy.compactMap { bundleIdentifier in
+ identities.first(where: { $0.bundleIdentifier == bundleIdentifier })
+ }.first ?? identities.first
+ self.setupDraft.selectedApplicationID = preferredIdentity.map { MeetingApplicationOption(identity: $0).id }
+ }
+
+ private func startRecording() {
+ guard !self.isStarting else { return }
+ let readiness = self.readiness
+ guard readiness.activityReady,
+ readiness.storageReady,
+ readiness.microphoneReady,
+ self.setupDraft.mode == .inRoom || readiness.meetingAudioReady,
+ let configuration = self.captureConfiguration
+ else {
+ self.actionErrorMessage = readiness.blockingMessage ?? "Finish meeting setup before recording."
+ return
+ }
+ self.isStarting = true
+ self.actionErrorMessage = nil
+
+ Task {
+ defer { self.isStarting = false }
+ do {
+ _ = try await self.coordinator.startRecording(configuration: configuration)
+ } catch {
+ self.actionErrorMessage = error.localizedDescription
+ }
+ }
+ }
+
+ private var captureConfiguration: MeetingCaptureConfiguration? {
+ let title = self.setupDraft.title.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !title.isEmpty,
+ let microphoneOption = self.microphones.first(where: { $0.id == self.setupDraft.selectedMicrophoneID })
+ else {
+ return nil
+ }
+
+ var microphone = microphoneOption.identity
+ microphone.role = .unknown
+
+ let applicationOption = self.applications.first(where: { $0.id == self.setupDraft.selectedApplicationID })
+ if self.setupDraft.mode == .onlineCall, applicationOption == nil { return nil }
+ let application = self.setupDraft.mode == .onlineCall ? applicationOption?.identity : nil
+
+ return MeetingCaptureConfiguration(
+ mode: self.setupDraft.mode,
+ title: title,
+ platform: application.map {
+ MeetingPlatformProfile(identifier: $0.bundleIdentifier, displayName: $0.displayName)
+ },
+ application: application,
+ microphone: microphone
+ )
+ }
+
+ private func stopAndTranscribe() {
+ guard !self.isStopping else { return }
+ self.isStopping = true
+ self.actionErrorMessage = nil
+ // Stop is an explicit "show me my meeting" — a stale sidebar pick must not hijack the outcome.
+ self.selectedHistorySessionID = nil
+ Task {
+ defer { self.isStopping = false }
+ do {
+ _ = try await self.coordinator.stopAndTranscribe()
+ } catch {
+ self.actionErrorMessage = error.localizedDescription
+ }
+ }
+ }
+
+ private func retryProcessingSession(id: MeetingSessionID) {
+ guard !self.isRetrying else { return }
+ self.isRetrying = true
+ self.actionErrorMessage = nil
+ self.selectedHistorySessionID = nil
+ Task {
+ defer { self.isRetrying = false }
+ do {
+ _ = try await self.coordinator.retryProcessing(sessionID: id)
+ } catch {
+ self.actionErrorMessage = error.localizedDescription
+ }
+ await self.loadMeetingHistory()
+ }
+ }
+
+ private func reassignSegment(sessionID: MeetingSessionID, segmentID: MeetingTranscriptSegmentID, to speakerID: SessionSpeakerID) {
+ self.actionErrorMessage = nil
+ Task {
+ do {
+ _ = try await self.coordinator.reassignSegment(sessionID: sessionID, segmentID: segmentID, to: speakerID)
+ } catch {
+ self.actionErrorMessage = error.localizedDescription
+ }
+ await self.loadMeetingHistory()
+ }
+ }
+
+ private func nameUnknownSegment(
+ sessionID: MeetingSessionID,
+ segmentID: MeetingTranscriptSegmentID,
+ displayName: String
+ ) {
+ self.actionErrorMessage = nil
+ Task {
+ do {
+ _ = try await self.coordinator.nameUnknownSegment(
+ sessionID: sessionID,
+ segmentID: segmentID,
+ displayName: displayName
+ )
+ } catch {
+ self.actionErrorMessage = error.localizedDescription
+ }
+ await self.loadMeetingHistory()
+ }
+ }
+
+ private func renameSpeaker(sessionID: MeetingSessionID, speakerID: SessionSpeakerID, to displayName: String) {
+ self.actionErrorMessage = nil
+ Task {
+ do {
+ _ = try await self.coordinator.renameSpeaker(sessionID: sessionID, speakerID: speakerID, to: displayName)
+ } catch {
+ self.actionErrorMessage = error.localizedDescription
+ }
+ await self.loadMeetingHistory()
+ }
+ }
+
+ private func assignSpeakers(sessionID: MeetingSessionID, names: [SessionSpeakerID: String]) async -> String? {
+ self.actionErrorMessage = nil
+ var errorMessage: String?
+ do {
+ _ = try await self.coordinator.renameSpeakers(sessionID: sessionID, names: names)
+ } catch {
+ errorMessage = error.localizedDescription
+ }
+ await self.loadMeetingHistory()
+ return errorMessage
+ }
+
+ private func mergeSpeakers(sessionID: MeetingSessionID, source: SessionSpeakerID, into targetID: SessionSpeakerID) {
+ self.actionErrorMessage = nil
+ Task {
+ do {
+ _ = try await self.coordinator.mergeSpeakers(sessionID: sessionID, source: source, into: targetID)
+ } catch {
+ self.actionErrorMessage = error.localizedDescription
+ }
+ await self.loadMeetingHistory()
+ }
+ }
+
+ private func renameMeetingSession(sessionID: MeetingSessionID, to title: String) {
+ self.actionErrorMessage = nil
+ Task {
+ do {
+ _ = try await self.coordinator.renameSession(sessionID: sessionID, to: title)
+ } catch {
+ self.actionErrorMessage = error.localizedDescription
+ }
+ await self.loadMeetingHistory()
+ }
+ }
+
+ private func undoTranscriptCorrection(sessionID: MeetingSessionID) {
+ self.actionErrorMessage = nil
+ Task {
+ do {
+ _ = try await self.coordinator.undoTranscriptCorrection(sessionID: sessionID)
+ } catch {
+ self.actionErrorMessage = error.localizedDescription
+ }
+ await self.loadMeetingHistory()
+ }
+ }
+
+ private func deleteSession(id: MeetingSessionID) {
+ self.pendingDeleteSessionID = nil
+ self.actionErrorMessage = nil
+ Task {
+ do {
+ try await self.coordinator.deleteSession(id: id)
+ if self.selectedHistorySessionID == id { self.selectedHistorySessionID = nil }
+ } catch {
+ self.actionErrorMessage = error.localizedDescription
+ }
+ await self.loadMeetingHistory()
+ }
+ }
+
+ private func deleteAudio(id: MeetingSessionID) {
+ self.pendingDeleteAudioSessionID = nil
+ self.actionErrorMessage = nil
+ Task {
+ do {
+ _ = try await self.coordinator.deleteAudio(sessionID: id)
+ } catch {
+ self.actionErrorMessage = error.localizedDescription
+ }
+ await self.loadMeetingHistory()
+ }
+ }
+
+ private func recordAgain(_ session: MeetingSession) {
+ guard let configuration = self.recordAgainConfiguration(from: session) else { return }
+ self.actionErrorMessage = nil
+ Task {
+ do {
+ _ = try await self.coordinator.recordAgain(from: session.id, configuration: configuration)
+ self.selectedHistorySessionID = nil
+ self.resetDraftTitleToDefault()
+ await self.loadMeetingHistory()
+ } catch {
+ self.actionErrorMessage = error.localizedDescription
+ }
+ }
+ }
+
+ private func recordAgainConfiguration(from session: MeetingSession) -> MeetingCaptureConfiguration? {
+ guard let microphone = self.resolvedMicrophone(for: session) else {
+ self.actionErrorMessage = "microphone unavailable"
+ return nil
+ }
+ var application: MeetingApplicationIdentity?
+ if session.mode == .onlineCall {
+ guard let bundleIdentifier = session.capturedApplication?.bundleIdentifier,
+ let resolved = self.applications.first(where: { $0.identity.bundleIdentifier == bundleIdentifier })
+ else {
+ self.actionErrorMessage = "app not running"
+ return nil
+ }
+ application = resolved.identity
+ }
+ return MeetingCaptureConfiguration(
+ mode: session.mode,
+ title: session.title,
+ platform: session.platform,
+ application: application,
+ microphone: microphone
+ )
+ }
+
+ private func resolvedMicrophone(for session: MeetingSession) -> MeetingMicrophoneIdentity? {
+ if let coreAudioUID = session.selectedMicrophone.coreAudioUID,
+ let match = self.microphones.first(where: { $0.identity.coreAudioUID == coreAudioUID })
+ {
+ var identity = match.identity
+ identity.role = .unknown
+ return identity
+ }
+ guard let match = self.microphones.first(where: { $0.identity.captureDeviceID == session.selectedMicrophone.captureDeviceID }) else {
+ return nil
+ }
+ var identity = match.identity
+ identity.role = .unknown
+ return identity
+ }
+
+ private func revealCapturedAudio(_ session: MeetingSession) {
+ Task {
+ do {
+ // Reload fresh: the passed-in session may predate a since-completed audio deletion.
+ guard let freshSession = try await MeetingSessionStore.shared.load(id: session.id) else {
+ self.actionErrorMessage = "Captured audio could not be revealed: recording no longer on disk."
+ return
+ }
+ guard freshSession.retention.audioDeletedAt == nil,
+ freshSession.hasFinalizedAudio
+ else {
+ self.actionErrorMessage = "Captured audio could not be revealed: audio for this recording has been deleted."
+ return
+ }
+ guard let directory = try await MeetingSessionStore.shared.existingSessionDirectory(for: freshSession.id) else {
+ self.actionErrorMessage = "Captured audio could not be revealed: recording no longer on disk."
+ return
+ }
+ guard let firstAudioURL = MeetingAudioPresentation.firstPlaybackURL(
+ in: freshSession,
+ directory: directory
+ ) else {
+ self.actionErrorMessage = "Captured audio is still preparing or is no longer available on disk."
+ return
+ }
+ NSWorkspace.shared.activateFileViewerSelecting([firstAudioURL])
+ } catch {
+ self.actionErrorMessage = "Captured audio could not be revealed: \(error.localizedDescription)"
+ }
+ }
+ }
+
+ private func exportAudio(_ session: MeetingSession) {
+ let panel = NSOpenPanel()
+ panel.canChooseDirectories = true
+ panel.canChooseFiles = false
+ panel.canCreateDirectories = true
+ panel.prompt = "Choose"
+ guard panel.runModal() == .OK, let destinationFolder = panel.url else { return }
+
+ Task {
+ do {
+ // Reload fresh: the passed-in session may predate a since-completed audio deletion.
+ guard let freshSession = try await MeetingSessionStore.shared.load(id: session.id) else {
+ self.actionErrorMessage = "Export failed: recording no longer on disk."
+ return
+ }
+ guard freshSession.retention.audioDeletedAt == nil,
+ freshSession.hasFinalizedAudio
+ else {
+ self.actionErrorMessage = "Export failed: audio for this recording has been deleted."
+ return
+ }
+ guard let sourceDirectory = try await MeetingSessionStore.shared.existingSessionDirectory(for: freshSession.id) else {
+ self.actionErrorMessage = "Export failed: recording no longer on disk."
+ return
+ }
+ try Self.stageExport(of: freshSession, from: sourceDirectory, into: destinationFolder)
+ } catch {
+ self.actionErrorMessage = "Export failed: \(error.localizedDescription)"
+ }
+ }
+ }
+
+ private static func stageExport(
+ of session: MeetingSession,
+ from sourceDirectory: URL,
+ into destinationFolder: URL
+ ) throws {
+ let fileManager = FileManager.default
+ let baseName = Self.sanitizedExportName(session.title)
+ let name = Self.uniqueExportName(baseName, in: destinationFolder, fileManager: fileManager)
+ let stagingDirectory = destinationFolder.appendingPathComponent(".\(name).\(UUID().uuidString).export-tmp", isDirectory: true)
+ try fileManager.createDirectory(at: stagingDirectory, withIntermediateDirectories: true)
+
+ do {
+ for track in session.audioTracks {
+ for chunk in track.chunks where chunk.finalizationState == .finalized && chunk.byteCount > 0 {
+ let sourceURL = chunk.fileURL(relativeTo: sourceDirectory)
+ let ext = sourceURL.pathExtension.isEmpty ? "m4a" : sourceURL.pathExtension
+ let fileName = "\(track.kind.rawValue)-\(String(format: "%03d", chunk.sequence)).\(ext)"
+ try fileManager.copyItem(
+ at: sourceURL,
+ to: stagingDirectory.appendingPathComponent(fileName, isDirectory: false)
+ )
+ }
+ }
+ var destinationName = name
+ do {
+ try fileManager.moveItem(at: stagingDirectory, to: destinationFolder.appendingPathComponent(destinationName, isDirectory: true))
+ } catch CocoaError.fileWriteFileExists {
+ // Destination appeared between the uniqueness check and the move; retry once with a fresh name.
+ destinationName = Self.uniqueExportName(baseName, in: destinationFolder, fileManager: fileManager)
+ try fileManager.moveItem(at: stagingDirectory, to: destinationFolder.appendingPathComponent(destinationName, isDirectory: true))
+ }
+ } catch {
+ try? fileManager.removeItem(at: stagingDirectory)
+ throw error
+ }
+ }
+
+ private static func sanitizedExportName(_ title: String) -> String {
+ let allowed = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 _.-")
+ let sanitized = String(title.unicodeScalars.map { allowed.contains($0) ? Character($0) : "-" }.prefix(80))
+ return sanitized.isEmpty ? "Meeting" : sanitized
+ }
+
+ private static func uniqueExportName(_ baseName: String, in folder: URL, fileManager: FileManager) -> String {
+ var candidate = baseName
+ var suffix = 2
+ while fileManager.fileExists(atPath: folder.appendingPathComponent(candidate).path) {
+ candidate = "\(baseName) \(suffix)"
+ suffix += 1
+ }
+ return candidate
+ }
+
+ private func startNewMeeting() {
+ do {
+ try self.coordinator.resetForNewMeeting()
+ self.selectedHistorySessionID = nil
+ self.resetDraftTitleToDefault()
+ self.actionErrorMessage = nil
+ } catch {
+ self.actionErrorMessage = error.localizedDescription
+ }
+ }
+
+ @MainActor
+ private func loadMeetingHistory() async {
+ do {
+ self.meetingHistory = try await MeetingSessionStore.shared.loadAll()
+ self.meetingHistoryError = nil
+ if let selectedHistorySessionID,
+ !self.meetingHistory.contains(where: { $0.id == selectedHistorySessionID })
+ {
+ self.selectedHistorySessionID = nil
+ }
+ } catch {
+ self.meetingHistoryError = "Meeting history could not be loaded."
+ }
+ }
+
+ private static var savedApplicationName: String? {
+ let defaults = SettingsStore.shared.meetingRecordingDefaults
+ guard defaults.isConfigured, let bundleIdentifier = defaults.applicationBundleIdentifier else { return nil }
+ return defaults.applicationDisplayName ?? bundleIdentifier
+ }
+
+ private func openMeetingSettings() {
+ self.setupDraftBeforeEditing = self.setupDraft
+ self.draftMeetingAudioRetentionPolicy = SettingsStore.shared.meetingAudioRetentionPolicy
+ self.isShowingMeetingSettings = true
+ }
+
+ private func cancelMeetingSettings() {
+ self.setupDraft = self.setupDraftBeforeEditing
+ self.draftMeetingAudioRetentionPolicy = SettingsStore.shared.meetingAudioRetentionPolicy
+ self.isShowingMeetingSettings = false
+ Task { await self.refreshSources(requestPermissions: false) }
+ }
+
+ private func saveMeetingSettings() {
+ guard let microphone = self.microphones.first(where: { $0.id == self.setupDraft.selectedMicrophoneID }) else {
+ self.actionErrorMessage = "Choose an available microphone before saving."
+ return
+ }
+
+ // A settings-only change must not require the meeting app to be running:
+ // fall back to the previously saved app; recording re-validates availability anyway.
+ // The fallback never applies while the saved app IS running — a nil selection then
+ // means the user deliberately deselected it.
+ let settings = SettingsStore.shared
+ let previousDefaults = settings.meetingRecordingDefaults
+ let application = self.applications.first(where: { $0.id == self.setupDraft.selectedApplicationID })
+ var applicationBundleIdentifier = application?.identity.bundleIdentifier
+ var applicationDisplayName = application?.identity.displayName
+ if application == nil {
+ let savedIsRunning = previousDefaults.applicationBundleIdentifier.map { saved in
+ self.applications.contains { $0.identity.bundleIdentifier == saved }
+ } ?? false
+ if self.setupDraft.mode == .onlineCall,
+ savedIsRunning || previousDefaults.applicationBundleIdentifier == nil
+ {
+ self.actionErrorMessage = "Choose an available meeting application before saving."
+ return
+ }
+ applicationBundleIdentifier = previousDefaults.applicationBundleIdentifier
+ applicationDisplayName = previousDefaults.applicationDisplayName
+ }
+
+ settings.meetingRecordingDefaults = MeetingRecordingDefaults(
+ isConfigured: true,
+ mode: self.setupDraft.mode,
+ applicationBundleIdentifier: applicationBundleIdentifier,
+ applicationDisplayName: applicationDisplayName,
+ microphoneCaptureDeviceID: microphone.identity.captureDeviceID,
+ microphoneCoreAudioUID: microphone.identity.coreAudioUID,
+ microphoneRole: .unknown
+ )
+
+ let previousRetentionPolicy = settings.meetingAudioRetentionPolicy
+ settings.meetingAudioRetentionPolicy = self.draftMeetingAudioRetentionPolicy
+ if previousRetentionPolicy != self.draftMeetingAudioRetentionPolicy {
+ Task { await self.coordinator.sweepExpiredAudio() }
+ }
+
+ self.setupDraftBeforeEditing = self.setupDraft
+ self.actionErrorMessage = nil
+ self.isShowingMeetingSettings = false
+ }
+
+ private func copyTranscript(_ session: MeetingSession, includeEchoes: Bool) {
+ let text = MeetingTranscriptExporter.text(for: session, includeEchoes: includeEchoes)
+ guard !text.isEmpty else { return }
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(text, forType: .string)
+ }
+
+ private func exportTranscript(_ session: MeetingSession, format: MeetingTranscriptExportFormat, includeEchoes: Bool) {
+ let panel = NSSavePanel()
+ panel.nameFieldStringValue = "\(Self.sanitizedExportName(session.title)).\(format.fileExtension)"
+ panel.message = "Exported transcripts are outside FluidVoice's retention controls and may be indexed or synced by other apps."
+ guard panel.runModal() == .OK, let url = panel.url else { return }
+ self.actionErrorMessage = nil
+ do {
+ let data: Data
+ switch format {
+ case .text: data = Data(MeetingTranscriptExporter.text(for: session, includeEchoes: includeEchoes).utf8)
+ case .json: data = try MeetingTranscriptExporter.json(for: session)
+ }
+ try data.write(to: url, options: .atomic)
+ } catch {
+ self.actionErrorMessage = "Export failed: \(error.localizedDescription)"
+ }
+ }
+
+ private static func requestMicrophoneAccess() async -> Bool {
+ await withCheckedContinuation { continuation in
+ AVCaptureDevice.requestAccess(for: .audio) { granted in
+ continuation.resume(returning: granted)
+ }
+ }
+ }
+
+ private static func openMicrophoneSettings() {
+ guard let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone")
+ else { return }
+ NSWorkspace.shared.open(url)
+ }
+
+ private func openScreenRecordingSettings() {
+ guard let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture")
+ else { return }
+ PermissionDragGuideController.shared.present(
+ instruction: "Drag \(Bundle.main.fluidAppDisplayName) into the Screen & System Audio Recording list as shown",
+ settingsPaneURL: url,
+ isGranted: { CGPreflightScreenCaptureAccess() },
+ onGranted: { [self] in
+ self.refreshCachedReadiness()
+ Task { await self.refreshSources(requestPermissions: false) }
+ }
+ )
+ }
+
+ private func refreshCachedReadiness() {
+ self.cachedMicrophoneStatus = AVCaptureDevice.authorizationStatus(for: .audio)
+ self.cachedScreenCaptureAccess = CGPreflightScreenCaptureAccess()
+ self.cachedModelReady = self.asrService.isAsrReady ||
+ self.asrService.modelsExistOnDisk ||
+ SettingsStore.shared.selectedSpeechModel.isInstalled
+ let storage = Self.storageReadiness(trackCount: MeetingPCMStoragePolicy.trackCount(for: self.setupDraft.mode))
+ self.cachedStorageStatus = storage.status
+ self.cachedStorageReady = storage.ready
+ }
+
+ private static func storageReadiness(trackCount: Int) -> (status: String, ready: Bool) {
+ guard let applicationSupport = FileManager.default.urls(
+ for: .applicationSupportDirectory,
+ in: .userDomainMask
+ ).first,
+ let capacity = try? applicationSupport.resourceValues(
+ forKeys: [.volumeAvailableCapacityForImportantUsageKey]
+ ).volumeAvailableCapacityForImportantUsage
+ else {
+ return ("Storage availability unavailable", false)
+ }
+ let requiredBytes = MeetingPCMStoragePolicy.requiredFreeBytes(trackCount: trackCount)
+ let formatter = ByteCountFormatter()
+ formatter.countStyle = .file
+ return ("\(formatter.string(fromByteCount: capacity)) available", capacity >= requiredBytes)
+ }
+ }
+
+ enum MeetingTranscriptExportFormat {
+ case text
+ case json
+
+ var fileExtension: String {
+ switch self {
+ case .text: return "txt"
+ case .json: return "json"
+ }
+ }
+ }
+
+ enum MeetingTranscriptionCanvasState {
+ case setup(isStarting: Bool, recentSession: MeetingSession?)
+ case recording(
+ session: MeetingSession,
+ trackHealth: [MeetingAudioTrackKind: MeetingTrackHealth],
+ liveTranscript: MeetingLiveTranscriptSnapshot
+ )
+ case stopping(
+ session: MeetingSession,
+ trackHealth: [MeetingAudioTrackKind: MeetingTrackHealth],
+ liveTranscript: MeetingLiveTranscriptSnapshot
+ )
+ case processing(session: MeetingSession, stage: MeetingProcessingStage)
+ case result(MeetingSession)
+ case failed(session: MeetingSession?, message: String)
+ }
+
+ struct MeetingTranscriptionCanvas: View {
+ @Binding var setupDraft: MeetingTranscriptionSetupDraft
+
+ let state: MeetingTranscriptionCanvasState
+ let applications: [MeetingApplicationOption]
+ let microphones: [MeetingMicrophoneOption]
+ let readiness: MeetingSetupReadiness
+ let errorMessage: String?
+ let onRefreshSources: () -> Void
+ let onStart: () -> Void
+ let onStop: () -> Void
+ let onRetrySession: (MeetingSession) -> Void
+ let onRevealAudio: (MeetingSession) -> Void
+ let onRecordAgain: (MeetingSession) -> Void
+ let onCopyTranscript: (MeetingSession, Bool) -> Void
+ let onExportTranscript: (MeetingSession, MeetingTranscriptExportFormat, Bool) -> Void
+ let onReassignSegment: (MeetingSessionID, MeetingTranscriptSegmentID, SessionSpeakerID) -> Void
+ let onNameUnknownSegment: (MeetingSessionID, MeetingTranscriptSegmentID, String) -> Void
+ let onRenameSpeaker: (MeetingSessionID, SessionSpeakerID, String) -> Void
+ let onMergeSpeakers: (MeetingSessionID, SessionSpeakerID, SessionSpeakerID) -> Void
+ let onUndoCorrection: (MeetingSessionID) -> Void
+ let onRenameSession: (MeetingSessionID, String) -> Void
+ let onAssignSpeakers: (MeetingSessionID, [SessionSpeakerID: String]) async -> String?
+ let canUndoCorrection: (MeetingSessionID) -> Bool
+ let isQuiescent: Bool
+ let onOpenMeetingSettings: () -> Void
+ let isRetrying: Bool
+ let onCloseSelection: (() -> Void)?
+
+ @Environment(\.theme) private var theme
+
+ /// Recording renders outside the ScrollView so the live captions card can fill the height;
+ /// its transcript list is its own scroller, and nested scrolling would fight it.
+ private var fillsCanvasHeight: Bool {
+ switch self.state {
+ case .recording, .stopping: true
+ default: false
+ }
+ }
+
+ var body: some View {
+ Group {
+ if self.fillsCanvasHeight {
+ self.canvasContent
+ .frame(maxWidth: 820)
+ .padding(self.theme.metrics.spacing.xxl)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
+ } else {
+ ScrollView {
+ self.canvasContent
+ .frame(maxWidth: 820)
+ .padding(self.theme.metrics.spacing.xxl)
+ .frame(maxWidth: .infinity)
+ }
+ }
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .background(self.theme.palette.windowBackground)
+ }
+
+ @ViewBuilder
+ private var canvasContent: some View {
+ Group {
+ switch self.state {
+ case let .setup(isStarting, recentSession):
+ MeetingSetupCanvas(
+ draft: self.$setupDraft,
+ applications: self.applications,
+ microphones: self.microphones,
+ readiness: self.readiness,
+ isStarting: isStarting,
+ errorMessage: self.errorMessage,
+ recentSession: recentSession,
+ onRefreshSources: self.onRefreshSources,
+ onStart: self.onStart,
+ onOpenMeetingSettings: self.onOpenMeetingSettings
+ )
+ case let .recording(session, trackHealth, liveTranscript):
+ MeetingRecordingCanvas(
+ session: session,
+ trackHealth: trackHealth,
+ liveTranscript: liveTranscript,
+ isStopping: false,
+ onStop: self.onStop
+ )
+ case let .stopping(session, trackHealth, liveTranscript):
+ MeetingRecordingCanvas(
+ session: session,
+ trackHealth: trackHealth,
+ liveTranscript: liveTranscript,
+ isStopping: true,
+ onStop: self.onStop
+ )
+ case let .processing(session, stage):
+ MeetingProcessingCanvas(session: session, stage: stage)
+ case let .result(session):
+ MeetingResultCanvas(
+ session: session,
+ isQuiescent: self.isQuiescent,
+ canUndo: self.canUndoCorrection(session.id),
+ onCopyTranscript: self.onCopyTranscript,
+ onExportTranscript: self.onExportTranscript,
+ onReassignSegment: { segmentID, speakerID in
+ self.onReassignSegment(session.id, segmentID, speakerID)
+ },
+ onNameUnknownSegment: { segmentID, name in
+ self.onNameUnknownSegment(session.id, segmentID, name)
+ },
+ onRenameSpeaker: { speakerID, name in
+ self.onRenameSpeaker(session.id, speakerID, name)
+ },
+ onMergeSpeakers: { source, target in
+ self.onMergeSpeakers(session.id, source, target)
+ },
+ onUndo: { self.onUndoCorrection(session.id) },
+ onRenameSession: { title in self.onRenameSession(session.id, title) },
+ onAssignSpeakers: { names in await self.onAssignSpeakers(session.id, names) },
+ onClose: self.onCloseSelection
+ )
+ case let .failed(session, message):
+ MeetingFailureCanvas(
+ session: session,
+ message: self.errorMessage ?? message,
+ isRetrying: self.isRetrying,
+ onRetrySession: self.onRetrySession,
+ onRevealAudio: self.onRevealAudio,
+ onRecordAgain: self.onRecordAgain,
+ onClose: self.onCloseSelection
+ )
+ }
+ }
+ }
+ }
+
+ private struct MeetingTranscriptionHeader: View {
+ let state: MeetingTranscriptionCanvasState
+ let isMeetingHistoryVisible: Bool
+ let onNewMeeting: () -> Void
+ let onOpenMeetingSettings: () -> Void
+ let onToggleMeetingHistory: () -> Void
+
+ @Environment(\.theme) private var theme
+
+ var body: some View {
+ HStack(spacing: self.theme.metrics.spacing.md) {
+ Image(systemName: "person.2.wave.2.fill")
+ .font(self.theme.typography.titleIcon)
+ .foregroundStyle(self.theme.palette.accent)
+
+ Text("Meeting Transcription")
+ .font(self.theme.typography.title)
+ .foregroundStyle(self.theme.palette.primaryText)
+
+ Spacer()
+
+ HStack(spacing: self.theme.metrics.spacing.xs) {
+ if self.canStartNewMeeting {
+ MeetingHeaderIconButton(
+ systemImage: "plus",
+ label: "New Meeting",
+ action: self.onNewMeeting
+ )
+ .keyboardShortcut("n", modifiers: .command)
+ .accessibilityHint("Clear the current meeting and return to recording setup")
+ }
+
+ MeetingHeaderIconButton(
+ systemImage: "gearshape",
+ label: "Meeting Settings",
+ action: self.onOpenMeetingSettings
+ )
+ .accessibilityHint("Change the saved recording application, microphone, and meeting defaults")
+
+ MeetingHeaderIconButton(
+ systemImage: self.isMeetingHistoryVisible
+ ? "rectangle.righthalf.inset.filled"
+ : "sidebar.right",
+ label: self.isMeetingHistoryVisible ? "Hide meeting history" : "Show meeting history",
+ isSelected: self.isMeetingHistoryVisible,
+ action: self.onToggleMeetingHistory
+ )
+ }
+ }
+ .padding(.horizontal, self.theme.metrics.spacing.xxl)
+ .padding(.vertical, self.theme.metrics.spacing.lg)
+ }
+
+ private var canStartNewMeeting: Bool {
+ switch self.state {
+ case .result, .failed:
+ return true
+ case .setup, .recording, .stopping, .processing:
+ return false
+ }
+ }
+ }
+
+ private struct MeetingHeaderIconButton: View {
+ let systemImage: String
+ let label: String
+ var isSelected = false
+ let action: () -> Void
+
+ @Environment(\.theme) private var theme
+ @State private var isHovered = false
+
+ var body: some View {
+ Button(action: self.action) {
+ Image(systemName: self.systemImage)
- .font(.system(size: 14, weight: .semibold))
++ .font(.fluidSystem(size: 14, weight: .semibold))
+ .foregroundStyle(self.isSelected ? self.theme.palette.accent : self.theme.palette.primaryText)
+ .frame(width: 32, height: 30)
+ .background(self.backgroundColor, in: RoundedRectangle(
+ cornerRadius: self.theme.metrics.corners.md,
+ style: .continuous
+ ))
+ .overlay {
+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.md, style: .continuous)
+ .stroke(self.theme.palette.separator.opacity(0.55), lineWidth: 1)
+ }
+ }
+ .buttonStyle(.plain)
+ .contentShape(RoundedRectangle(cornerRadius: self.theme.metrics.corners.md, style: .continuous))
+ .onHover { self.isHovered = $0 }
+ .help(self.label)
+ .accessibilityLabel(self.label)
+ }
+
+ private var backgroundColor: Color {
+ if self.isSelected {
+ return self.theme.palette.accent.opacity(0.14)
+ }
+ if self.isHovered {
+ return self.theme.palette.contentBackground.opacity(0.9)
+ }
+ return self.theme.palette.contentBackground.opacity(0.55)
+ }
+ }
+
+ private struct MeetingHistoryInspector: View {
+ let sessions: [MeetingSession]
+ @Binding var selectedSessionID: MeetingSessionID?
+ let errorMessage: String?
+ let isQuiescent: Bool
+ let onRefresh: () -> Void
+ let onRetry: (MeetingSessionID) -> Void
+ let onRevealAudio: (MeetingSession) -> Void
+ let onExportAudio: (MeetingSession) -> Void
+ let onExportTranscript: (MeetingSession, MeetingTranscriptExportFormat) -> Void
+ let onDeleteAudioRequest: (MeetingSessionID) -> Void
+ let onDeleteRequest: (MeetingSessionID) -> Void
+ let onRecordAgain: (MeetingSession) -> Void
+
+ @Environment(\.theme) private var theme
+ @State private var searchText = ""
+
+ private var filteredSessions: [MeetingSession] {
+ let query = self.searchText.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !query.isEmpty else { return self.sessions }
+ return self.sessions.filter { session in
+ session.title.localizedCaseInsensitiveContains(query) ||
+ session.capturedApplication?.displayName.localizedCaseInsensitiveContains(query) == true ||
+ session.activeSpeakers.contains(where: { $0.displayName.localizedCaseInsensitiveContains(query) })
+ }
+ }
+
+ /// Sessions arrive newest-first, so a first-seen-order bucket walk keeps groups chronological.
+ private var groupedSessions: [(key: String, sessions: [MeetingSession])] {
+ let calendar = Calendar.current
+ var order: [String] = []
+ var buckets: [String: [MeetingSession]] = [:]
+ for session in self.filteredSessions {
+ let key = Self.dayLabel(for: session.startedAt, calendar: calendar)
+ if buckets[key] == nil {
+ buckets[key] = []
+ order.append(key)
+ }
+ buckets[key]?.append(session)
+ }
+ return order.map { (key: $0, sessions: buckets[$0] ?? []) }
+ }
+
+ private static func dayLabel(for date: Date, calendar: Calendar) -> String {
+ if calendar.isDateInToday(date) { return "Today" }
+ if calendar.isDateInYesterday(date) { return "Yesterday" }
+ return date.formatted(date: .abbreviated, time: .omitted)
+ }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ HStack(spacing: self.theme.metrics.spacing.sm) {
+ Text("Meetings")
+ .font(self.theme.typography.sectionTitle)
+ Text("\(self.sessions.count)")
+ .font(self.theme.typography.badge)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ Spacer()
+ Button(action: self.onRefresh) {
+ Image(systemName: "arrow.clockwise")
+ }
+ .buttonStyle(.borderless)
+ .help("Refresh meeting history")
+ .accessibilityLabel("Refresh meeting history")
+ }
+ .padding(.horizontal, self.theme.metrics.spacing.lg)
+ .padding(.top, self.theme.metrics.spacing.lg)
+ .padding(.bottom, self.theme.metrics.spacing.md)
+
+ TextField("Search meetings", text: self.$searchText)
+ .textFieldStyle(.roundedBorder)
+ .padding(.horizontal, self.theme.metrics.spacing.lg)
+ .padding(.bottom, self.theme.metrics.spacing.md)
+
+ Divider()
+
+ if let errorMessage {
+ ContentUnavailableView(
+ "History unavailable",
+ systemImage: "exclamationmark.triangle",
+ description: Text(errorMessage)
+ )
+ } else if self.filteredSessions.isEmpty {
+ ContentUnavailableView(
+ self.searchText.isEmpty ? "No meetings yet" : "No matching meetings",
+ systemImage: self.searchText.isEmpty ? "person.2.wave.2" : "magnifyingglass",
+ description: Text(self.searchText.isEmpty
+ ? "Completed meetings will appear here."
+ : "Try a different title, app, or speaker.")
+ )
+ } else {
+ // Rows draw their own selection/hover fill (never the saturated system blue),
+ // so a plain ScrollView replaces List here instead of fighting its native highlight.
+ ScrollViewReader { proxy in
+ ScrollView {
+ LazyVStack(alignment: .leading, spacing: 2, pinnedViews: [.sectionHeaders]) {
+ ForEach(self.groupedSessions, id: \.key) { group in
+ Section {
+ ForEach(group.sessions) { session in
+ MeetingHistoryRow(
+ session: session,
+ isSelected: self.selectedSessionID == session.id,
+ isQuiescent: self.isQuiescent,
+ onRetry: { self.onRetry(session.id) },
+ onRecordAgain: { self.onRecordAgain(session) }
+ )
+ .id(session.id)
+ .onTapGesture { self.selectedSessionID = session.id }
+ .contextMenu { self.contextMenu(for: session) }
+ }
+ } header: {
+ Text(group.key)
+ .font(self.theme.typography.captionSmall)
+ .tracking(1.1)
+ .textCase(.uppercase)
+ .foregroundStyle(self.theme.palette.tertiaryText)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, self.theme.metrics.spacing.lg)
+ .padding(.top, self.theme.metrics.spacing.md)
+ .padding(.bottom, self.theme.metrics.spacing.xs)
+ .background(self.theme.palette.sidebarBackground)
+ }
+ }
+ }
+ .padding(.horizontal, self.theme.metrics.spacing.sm)
+ .padding(.bottom, self.theme.metrics.spacing.md)
+ }
+ // Dropping List for a custom highlight also drops its arrow-key traversal.
+ .focusable()
+ .onMoveCommand { direction in
+ guard let moved = self.sessionID(movingFrom: self.selectedSessionID, direction: direction)
+ else { return }
+ self.selectedSessionID = moved
+ withAnimation(.easeOut(duration: 0.12)) { proxy.scrollTo(moved, anchor: .center) }
+ }
+ }
+ }
+ }
+ .background(self.theme.palette.sidebarBackground)
+ }
+
+ private func sessionID(
+ movingFrom current: MeetingSessionID?,
+ direction: MoveCommandDirection
+ ) -> MeetingSessionID? {
+ MeetingHistoryTraversal.sessionID(
+ movingFrom: current,
+ direction: direction,
+ ordered: self.groupedSessions.flatMap(\.sessions).map(\.id)
+ )
+ }
+
+ @ViewBuilder
+ private func contextMenu(for session: MeetingSession) -> some View {
+ if session.hasRetryableAudio, session.state == .failed || session.state == .interrupted {
+ Button("Retry Transcription", systemImage: "arrow.clockwise") {
+ self.onRetry(session.id)
+ }
+ .disabled(!self.isQuiescent)
+ }
+ Button("Reveal Audio", systemImage: "folder") {
+ self.onRevealAudio(session)
+ }
+ Button("Export Audio…", systemImage: "square.and.arrow.up") {
+ self.onExportAudio(session)
+ }
+ .disabled(!session.hasFinalizedAudio)
+ Button("Export Transcript (Text)…", systemImage: "doc.text") {
+ self.onExportTranscript(session, .text)
+ }
+ .disabled(!session.transcriptSegments.contains(where: { !$0.isEcho }))
+ Button("Export Transcript (JSON)…", systemImage: "curlybraces") {
+ self.onExportTranscript(session, .json)
+ }
+ .disabled(session.transcriptSegments.isEmpty)
+ if session.hasFinalizedAudio, session.retention.audioDeletedAt == nil, session.state == .completed {
+ Button("Delete Audio (Keep Transcript)…", systemImage: "waveform.slash") {
+ self.onDeleteAudioRequest(session.id)
+ }
+ .disabled(!self.isQuiescent)
+ }
+ Divider()
+ Button("Delete Meeting…", systemImage: "trash", role: .destructive) {
+ self.onDeleteRequest(session.id)
+ }
+ .disabled(!self.isQuiescent)
+ }
+ }
+
+ nonisolated enum MeetingHistoryTraversal {
+ static func sessionID(
+ movingFrom current: MeetingSessionID?,
+ direction: MoveCommandDirection,
+ ordered: [MeetingSessionID]
+ ) -> MeetingSessionID? {
+ guard !ordered.isEmpty else { return nil }
+ guard let current, let index = ordered.firstIndex(of: current) else { return ordered.first }
+ switch direction {
+ case .up: return index > 0 ? ordered[index - 1] : nil
+ case .down: return index < ordered.count - 1 ? ordered[index + 1] : nil
+ default: return nil
+ }
+ }
+ }
+
+ private struct MeetingHistoryRow: View {
+ let session: MeetingSession
+ let isSelected: Bool
+ let isQuiescent: Bool
+ let onRetry: () -> Void
+ let onRecordAgain: () -> Void
+
+ @Environment(\.theme) private var theme
+ @State private var isHovered = false
+
+ var body: some View {
+ HStack(spacing: self.theme.metrics.spacing.md) {
+ self.tile
+ VStack(alignment: .leading, spacing: 2) {
+ Text(self.session.title)
+ .font(self.theme.typography.bodyStrong)
+ .foregroundStyle(self.theme.palette.primaryText)
+ .lineLimit(1)
+ .truncationMode(.tail)
+ self.secondaryLine
+ }
+ Spacer(minLength: 0)
+ }
+ .padding(.horizontal, self.theme.metrics.spacing.sm)
+ .padding(.vertical, self.theme.metrics.spacing.sm)
+ .background(self.rowBackground, in: RoundedRectangle(cornerRadius: self.theme.metrics.corners.md, style: .continuous))
+ .contentShape(Rectangle())
+ .onHover { self.isHovered = $0 }
+ .accessibilityElement(children: .combine)
+ .accessibilityLabel("\(self.session.title), \(self.statusText), \(self.sourceName)")
+ .accessibilityAddTraits(self.isSelected ? [.isButton, .isSelected] : .isButton)
+ }
+
+ private var tile: some View {
+ Image(systemName: self.tileIcon)
- .font(.system(size: 14, weight: .medium))
++ .font(.fluidSystem(size: 14, weight: .medium))
+ .foregroundStyle(self.tileIconColor)
+ .frame(width: 34, height: 34)
+ .background(self.theme.palette.contentBackground, in: RoundedRectangle(
+ cornerRadius: self.theme.metrics.corners.md,
+ style: .continuous
+ ))
+ .accessibilityHidden(true)
+ }
+
+ @ViewBuilder
+ private var secondaryLine: some View {
+ HStack(spacing: self.theme.metrics.spacing.xs) {
+ ForEach(Array(self.secondaryTextParts.enumerated()), id: \.offset) { index, part in
+ if index > 0 {
+ Text("·").foregroundStyle(self.theme.palette.tertiaryText)
+ }
+ Text(part)
+ }
+ if let actionLabel {
+ Text("·").foregroundStyle(self.theme.palette.tertiaryText)
+ Button(actionLabel, action: self.performAction)
+ .buttonStyle(.plain)
+ .foregroundStyle(self.actionColor)
+ .disabled(!self.isQuiescent)
+ .accessibilityLabel(self.actionAccessibilityLabel ?? actionLabel)
+ }
+ }
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .lineLimit(1)
+ }
+
+ private func performAction() {
+ switch self.session.state {
+ case .interrupted: self.onRetry()
+ case .failed: self.onRecordAgain()
+ default: break
+ }
+ }
+
+ private var timeText: String {
+ self.session.startedAt.formatted(date: .omitted, time: .shortened)
+ }
+
+ private var secondaryTextParts: [String] {
+ switch self.session.state {
+ case .completed:
+ var parts = [self.timeText, Self.durationText(self.session.duration)]
+ if !self.session.activeSpeakers.isEmpty {
+ parts.append("\(self.session.activeSpeakers.count) speakers")
+ }
+ return parts
+ case .interrupted:
+ return [self.timeText, "Interrupted"]
+ case .failed:
+ return [self.timeText, self.session.failures.last?.message ?? "Failed"]
+ case .processing:
+ return [self.timeText, "Processing"]
+ case .recording, .recordingDegraded, .preparing, .stopping:
+ return [self.timeText, "Recording"]
+ }
+ }
+
+ private var actionLabel: String? {
+ switch self.session.state {
+ case .interrupted: return self.session.hasRetryableAudio ? "Retry" : nil
+ case .failed: return "Record again"
+ default: return nil
+ }
+ }
+
+ /// The row shows "Retry" to fit a narrow sidebar; spoken output keeps the full sentence.
+ private var actionAccessibilityLabel: String? {
+ switch self.session.state {
+ case .interrupted: return self.session.hasRetryableAudio ? "Retry transcription" : nil
+ case .failed: return "Record again"
+ default: return nil
+ }
+ }
+
+ private var actionColor: Color {
+ self.session.state == .interrupted ? self.theme.palette.warning : self.theme.palette.accent
+ }
+
+ private var rowBackground: Color {
+ if self.isSelected {
+ return self.theme.palette.accent.opacity(self.theme.metrics.pickerControl.selectedRowOpacity)
+ }
+ if self.isHovered {
+ return self.theme.palette.accent.opacity(self.theme.metrics.pickerControl.selectedRowOpacity * 0.4)
+ }
+ return .clear
+ }
+
+ private var sourceName: String {
+ self.session.capturedApplication?.displayName ?? "In-room"
+ }
+
+ private var statusText: String {
+ switch self.session.state {
+ case .completed: "Completed"
+ case .failed: "Failed"
+ case .interrupted: "Interrupted"
+ case .processing: "Processing"
+ case .recording, .recordingDegraded, .preparing, .stopping: "Recording"
+ }
+ }
+
+ private var tileIcon: String {
+ switch self.session.state {
+ case .interrupted: "exclamationmark.triangle.fill"
+ case .failed: "xmark.circle"
+ default: "doc.text"
+ }
+ }
+
+ private var tileIconColor: Color {
+ switch self.session.state {
+ case .interrupted: self.theme.palette.warning
+ case .failed: Color(nsColor: .systemRed)
+ default: self.theme.palette.secondaryText
+ }
+ }
+
+ private static func durationText(_ duration: TimeInterval) -> String {
+ let totalMinutes = max(0, Int(duration / 60))
+ if totalMinutes >= 60 {
+ return "\(totalMinutes / 60)h \(totalMinutes % 60)m"
+ }
+ return "\(max(1, totalMinutes))m"
+ }
+ }
+
+ private struct MeetingRecordingSettingsSheet: View {
+ @Binding var draft: MeetingTranscriptionSetupDraft
+ @Binding var retentionPolicy: MeetingAudioRetentionPolicy
+ @ObservedObject private var settings = SettingsStore.shared
+ @ObservedObject private var dismissalAdvisor = MeetingAutoDetectDismissalAdvisor.shared
+ @ObservedObject private var appServices = AppServices.shared
+
+ let applications: [MeetingApplicationOption]
+ let microphones: [MeetingMicrophoneOption]
+ let readiness: MeetingSetupReadiness
+ let isFirstSetup: Bool
+ let savedApplicationName: String?
+ let savedApplicationBundleIdentifier: String?
+ let onRefreshSources: () -> Void
+ let onOpenMicrophoneSettings: @MainActor @Sendable () -> Void
+ let onOpenScreenRecordingSettings: @MainActor @Sendable () -> Void
+ let onOpenVoiceEngine: () -> Void
+ let onCancel: () -> Void
+ let onSave: () -> Void
+
+ @Environment(\.theme) private var theme
+
+ private var savedApplicationIsRunning: Bool {
+ guard let savedApplicationBundleIdentifier else { return false }
+ return self.applications.contains { $0.identity.bundleIdentifier == savedApplicationBundleIdentifier }
+ }
+
+ private var usesSavedApplicationFallback: Bool {
+ self.draft.mode == .onlineCall
+ && self.draft.selectedApplicationID == nil
+ && self.savedApplicationName != nil
+ && !self.savedApplicationIsRunning
+ }
+
+ private var canSave: Bool {
+ guard self.draft.selectedMicrophoneID != nil else { return false }
+ return self.draft.mode == .inRoom
+ || self.draft.selectedApplicationID != nil
+ || self.usesSavedApplicationFallback
+ }
+
+ private var separationDescription: String {
+ if !CPUArchitecture.isAppleSilicon {
+ return "Plain transcript on Intel"
+ }
+ return self.readiness.modelReady ? "Automatic after Stop" : "Prepares after Stop"
+ }
+
+ private var saveHelp: String? {
+ guard !self.canSave else { return nil }
+ if let blockingMessage = readiness.blockingMessage {
+ return blockingMessage
+ }
+ if self.draft.selectedMicrophoneID == nil {
+ return "Choose an available microphone to save this setup."
+ }
+ return "Choose an available meeting application to save this setup."
+ }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ HStack(spacing: self.theme.metrics.spacing.md) {
+ Image(systemName: "gearshape.fill")
+ .font(self.theme.typography.titleIcon)
+ .foregroundStyle(self.theme.palette.accent)
+
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.xs) {
+ Text(self.isFirstSetup ? "Set up meeting recording" : "Meeting Settings")
+ .font(self.theme.typography.title)
+ Text("Saved for future meetings until you change it.")
+ .font(self.theme.typography.bodySmall)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+ Spacer()
+ }
+ .padding(.horizontal, self.theme.metrics.spacing.xl)
+ .padding(.vertical, self.theme.metrics.spacing.lg)
+
+ Divider()
+
+ ScrollView {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.lg) {
+ ThemedCard(style: .subtle, padding: 0) {
+ VStack(spacing: 0) {
+ MeetingAdaptiveSetupRow(
+ title: "Meeting type",
+ detail: "Choose the setup you use most often."
+ ) {
+ Picker("Meeting type", selection: self.$draft.mode) {
+ Text("Online call").tag(MeetingCaptureMode.onlineCall)
+ Text("In-room").tag(MeetingCaptureMode.inRoom)
+ }
+ .pickerStyle(.segmented)
+ .labelsHidden()
+ .frame(width: 320, alignment: .trailing)
+ .accessibilityLabel("Default meeting type")
+ }
+
+ if self.draft.mode == .onlineCall {
+ Divider()
+ MeetingAdaptiveSetupRow(
+ title: "Meeting audio",
+ detail: self.usesSavedApplicationFallback
+ ? "\(self.savedApplicationName ?? "Your saved app") is saved but not running — it will be captured next time it's open."
+ : "FluidVoice records audio from this application."
+ ) {
+ Picker("Meeting audio", selection: self.$draft.selectedApplicationID) {
+ Text(self.usesSavedApplicationFallback
+ ? "\(self.savedApplicationName ?? "Saved app") (not running)"
+ : "Choose application…").tag(String?.none)
+ ForEach(self.applications) { option in
+ Text(option.identity.displayName).tag(Optional(option.id))
+ }
+ }
+ .labelsHidden()
+ .frame(width: 320, alignment: .trailing)
+ .accessibilityLabel("Default meeting application")
+ }
+ }
+
+ if self.settings.meetingAutoDetectEnabled,
+ self.appServices.meetingAutoDetectHealth == .zoomWindowTitleUnreadable {
+ MeetingAdaptiveSetupRow(
+ title: "Zoom window access needs repair",
+ detail: "Screen Recording or Accessibility access is preventing FluidVoice from reading Zoom meeting windows. Recording has not started.") {
+ Button("Open Screen Recording Settings") {
+ self.onOpenScreenRecordingSettings()
+ }
+ .fluidButton(.compact, size: .small)
+ }
+ }
+
+ Divider()
+ MeetingAdaptiveSetupRow(
+ title: "Microphone",
+ detail: "Used for your voice and in-room meetings."
+ ) {
+ Picker("Microphone", selection: self.$draft.selectedMicrophoneID) {
+ Text("Choose microphone…").tag(String?.none)
+ ForEach(self.microphones) { option in
+ Text(option.identity.displayName).tag(Optional(option.id))
+ }
+ }
+ .labelsHidden()
+ .frame(width: 320, alignment: .trailing)
+ .accessibilityLabel("Default meeting microphone")
+ }
+
+ Divider()
+ MeetingAdaptiveSetupRow(title: "Language") {
+ Text("English")
+ .font(self.theme.typography.bodyStrong)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+
+ Divider()
+ MeetingAdaptiveSetupRow(title: "Speaker separation") {
+ Text(self.separationDescription)
+ .font(self.theme.typography.bodyStrong)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+
+ Divider()
+ MeetingAdaptiveSetupRow(
+ title: "Keep audio",
+ detail: "Applies to all recordings, including past ones. Audio is deleted only "
+ + "while FluidVoice is running; transcripts are always kept."
+ ) {
+ Picker("Keep audio", selection: self.$retentionPolicy) {
+ ForEach(MeetingAudioRetentionPolicy.allCases, id: \.self) { policy in
+ Text(policy.displayName).tag(policy)
+ }
+ }
+ .labelsHidden()
+ .frame(width: 320, alignment: .trailing)
+ .accessibilityLabel("Audio retention")
+ }
+
+ Divider()
+ MeetingAdaptiveSetupRow(
+ title: "Detect meetings automatically",
+ detail: "Shows a \"Meeting detected\" prompt for Zoom, Teams, and Webex. Never starts recording on its own."
+ ) {
+ Toggle("", isOn: self.$settings.meetingAutoDetectEnabled)
+ .labelsHidden()
+ .toggleStyle(.switch)
+ }
+
+ if self.settings.meetingAutoDetectEnabled {
+ Divider()
+ MeetingAdaptiveSetupRow(
+ title: "Also check browser tabs",
+ detail: "Checks the address of the frontmost browser tab against a fixed list of meeting "
+ + "sites (Google Meet, Zoom, Teams, Whereby, Jitsi). Nothing is stored or sent."
+ ) {
+ Toggle("", isOn: self.$settings.meetingAutoDetectBrowserEnabled)
+ .labelsHidden()
+ .toggleStyle(.switch)
+ }
+ }
+ }
+ }
+
+ if self.dismissalAdvisor.shouldSuggest {
+ ThemedCard(style: .subtle, padding: self.theme.metrics.spacing.md) {
+ HStack(spacing: self.theme.metrics.spacing.md) {
+ Label(
+ "You've dismissed several meeting-detected prompts recently.",
+ systemImage: "bell.slash"
+ )
+ .font(self.theme.typography.bodySmall)
+ Spacer()
+ Button("Turn Off") {
+ self.settings.meetingAutoDetectEnabled = false
+ self.settings.meetingAutoDetectBrowserEnabled = false
+ self.dismissalAdvisor.shouldSuggest = false
+ }
+ .fluidButton(.compact, size: .small)
+ Button("Keep On") {
+ self.dismissalAdvisor.shouldSuggest = false
+ }
+ .fluidButton(.compact, size: .small)
+ }
+ }
+ }
+
+ ViewThatFits(in: .horizontal) {
+ HStack(spacing: self.theme.metrics.spacing.sm) {
+ self.repairActions
+ }
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.sm) {
+ self.repairActions
+ }
+ }
+
+ Label("Recording and transcription stay on this Mac.", systemImage: "lock.fill")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+
+ if let saveHelp {
+ Label(saveHelp, systemImage: "exclamationmark.circle")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.warning)
+ }
+ }
+ .padding(self.theme.metrics.spacing.xl)
+ }
+
+ Divider()
+
+ HStack(spacing: self.theme.metrics.spacing.md) {
+ Button(self.isFirstSetup ? "Not Now" : "Cancel", action: self.onCancel)
+ .fluidButton(.compact, size: .medium)
+ .keyboardShortcut(.cancelAction)
+ Spacer()
+ Button(self.readiness.isCheckingSources ? "Refreshing…" : "Refresh Sources", systemImage: "arrow.clockwise") {
+ self.onRefreshSources()
+ }
+ .fluidButton(.compact, size: .medium)
+ .disabled(self.readiness.isCheckingSources)
+
+ Button(self.isFirstSetup ? "Save Setup" : "Save Changes", action: self.onSave)
+ .fluidButton(.accent, size: .medium)
+ .disabled(!self.canSave)
+ .keyboardShortcut(.defaultAction)
+ }
+ .padding(self.theme.metrics.spacing.lg)
+ }
+ .frame(minWidth: 560, idealWidth: 720, maxWidth: 720)
+ .frame(minHeight: 540, idealHeight: 620)
+ .background(self.theme.palette.windowBackground)
+ }
+
+ @ViewBuilder
+ private var repairActions: some View {
+ if self.readiness.showMicrophoneSettingsAction {
+ Button("Microphone Settings", systemImage: "mic.fill", action: self.onOpenMicrophoneSettings)
+ .fluidButton(.compact, size: .small)
+ }
+ if self.readiness.showScreenRecordingSettingsAction {
+ Button(
+ "Screen Recording Settings",
+ systemImage: "rectangle.inset.filled.and.person.filled",
+ action: self.onOpenScreenRecordingSettings
+ )
+ .fluidButton(.compact, size: .small)
+ }
+ if !self.readiness.modelReady {
+ Button("Voice Engine", systemImage: "waveform", action: self.onOpenVoiceEngine)
+ .fluidButton(.compact, size: .small)
+ }
+ }
+ }
+
+ private struct MeetingSetupCanvas: View {
+ @Binding var draft: MeetingTranscriptionSetupDraft
+
+ let applications: [MeetingApplicationOption]
+ let microphones: [MeetingMicrophoneOption]
+ let readiness: MeetingSetupReadiness
+ let isStarting: Bool
+ let errorMessage: String?
+ let recentSession: MeetingSession?
+ let onRefreshSources: () -> Void
+ let onStart: () -> Void
+ let onOpenMeetingSettings: () -> Void
+
+ @Environment(\.theme) private var theme
+
+ private var requiredSystemsReady: Bool {
+ !self.readiness.isCheckingSources &&
+ self.readiness.microphoneReady &&
+ self.readiness.storageReady &&
+ self.readiness.activityReady &&
+ (self.draft.mode == .inRoom || self.readiness.meetingAudioReady)
+ }
+
+ private var canStart: Bool {
+ guard self.requiredSystemsReady,
+ self.draft.selectedMicrophoneID != nil,
+ !self.draft.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ else {
+ return false
+ }
+ return self.draft.mode == .inRoom || self.draft.selectedApplicationID != nil
+ }
+
+ private var startHelp: String? {
+ if let blockingMessage = readiness.blockingMessage, !self.requiredSystemsReady {
+ return blockingMessage
+ }
+ if self.draft.selectedMicrophoneID == nil {
+ return "Choose a microphone to continue."
+ }
+ if self.draft.mode == .onlineCall, self.draft.selectedApplicationID == nil {
+ return "Choose the application playing meeting audio."
+ }
+ if self.draft.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ return "Add a title for this meeting."
+ }
+ return nil
+ }
+
+ private var modeName: String {
+ self.draft.mode == .onlineCall ? "Online call" : "In-room meeting"
+ }
+
+ private var applicationName: String? {
+ guard self.draft.mode == .onlineCall else { return nil }
+ return self.applications.first(where: { $0.id == self.draft.selectedApplicationID })?.identity.displayName
+ }
+
+ private var microphoneName: String {
+ self.microphones.first(where: { $0.id == self.draft.selectedMicrophoneID })?.identity.displayName
+ ?? "Choose microphone"
+ }
+
+ private var setupSummary: String {
+ [self.applicationName, self.microphoneName]
+ .compactMap { $0 }
+ .joined(separator: " · ")
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.xl) {
+ ThemedCard(style: .subtle, padding: 0) {
+ VStack(spacing: 0) {
+ ViewThatFits(in: .horizontal) {
+ HStack(alignment: .center, spacing: self.theme.metrics.spacing.lg) {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.xs) {
+ Text(self.modeName)
+ .font(self.theme.typography.sectionTitle)
+ .foregroundStyle(self.theme.palette.primaryText)
+ Text(self.setupSummary)
+ .font(self.theme.typography.bodySmall)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ }
+ Spacer(minLength: self.theme.metrics.spacing.lg)
+ Button("Edit setup…", systemImage: "slider.horizontal.3", action: self.onOpenMeetingSettings)
+ .fluidButton(.compact, size: .small)
+ }
+
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.md) {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.xs) {
+ Text(self.modeName)
+ .font(self.theme.typography.sectionTitle)
+ Text(self.setupSummary)
+ .font(self.theme.typography.bodySmall)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+ Button("Edit setup…", systemImage: "slider.horizontal.3", action: self.onOpenMeetingSettings)
+ .fluidButton(.compact, size: .small)
+ }
+ }
+ .padding(.horizontal, self.theme.metrics.spacing.lg)
+ .padding(.vertical, self.theme.metrics.spacing.md)
+ .accessibilityElement(children: .contain)
+
+ Divider()
+
+ MeetingAdaptiveSetupRow(title: "Meeting title") {
+ // A plain $draft.title binding can't tell a user keystroke apart from
+ // the programmatic default-title regeneration, so route edits through here.
+ TextField("Meeting title", text: Binding(
+ get: { self.draft.title },
+ set: { newValue in
+ self.draft.title = newValue
+ self.draft.titleWasEdited = true
+ }
+ ))
+ .textFieldStyle(.roundedBorder)
+ .accessibilityLabel("Meeting title")
+ }
+
+ Divider()
+
+ ViewThatFits(in: .horizontal) {
+ HStack(spacing: self.theme.metrics.spacing.md) {
+ MeetingReadyStatus(
+ isReady: self.canStart,
+ title: self.canStart ? "Ready to record" : "Setup needs attention",
+ detail: self.canStart
+ ? "English · \(self.readiness.storageStatus)"
+ : (self.startHelp ?? "Check the recording setup.")
+ )
+ Spacer(minLength: self.theme.metrics.spacing.md)
+ Button("Refresh", systemImage: "arrow.clockwise", action: self.onRefreshSources)
+ .fluidButton(.compact, size: .small)
+ .disabled(self.readiness.isCheckingSources || self.isStarting)
+ }
+
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.md) {
+ MeetingReadyStatus(
+ isReady: self.canStart,
+ title: self.canStart ? "Ready to record" : "Setup needs attention",
+ detail: self.canStart
+ ? "English · \(self.readiness.storageStatus)"
+ : (self.startHelp ?? "Check the recording setup.")
+ )
+ Button("Refresh", systemImage: "arrow.clockwise", action: self.onRefreshSources)
+ .fluidButton(.compact, size: .small)
+ .disabled(self.readiness.isCheckingSources || self.isStarting)
+ }
+ }
+ .padding(.horizontal, self.theme.metrics.spacing.lg)
+ .padding(.vertical, self.theme.metrics.spacing.md)
+ }
+ }
+
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.sm) {
+ Label("Recording and transcription stay on this Mac.", systemImage: "lock.fill")
+ Label(
+ self.draft.mode == .onlineCall
+ ? "Headphones give the cleanest speaker separation."
+ : "Place the Mac where every speaker can be heard clearly.",
+ systemImage: self.draft.mode == .onlineCall ? "headphones" : "mic.fill"
+ )
+ Label("Make sure everyone knows the meeting is being recorded.", systemImage: "person.2")
+ }
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+
+ if let errorMessage, !errorMessage.isEmpty {
+ Label(errorMessage, systemImage: "exclamationmark.triangle.fill")
+ .font(self.theme.typography.bodySmall)
+ .foregroundStyle(self.theme.palette.warning)
+ .accessibilityLabel("Could not start recording. \(errorMessage)")
+ }
+
+ HStack {
+ Spacer()
+ Button(action: self.onStart) {
+ if self.isStarting {
+ HStack(spacing: self.theme.metrics.spacing.sm) {
+ ProgressView()
+ .controlSize(.small)
+ Text("Starting…")
+ }
+ } else {
+ Label("Start recording", systemImage: "record.circle")
+ }
+ }
+ .fluidButton(.accent, size: .medium)
+ .disabled(!self.canStart || self.isStarting)
+ .keyboardShortcut(.defaultAction)
+ }
+
+ if let recentSession {
+ Divider()
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.sm) {
+ Text("Recent meeting")
+ .font(self.theme.typography.sectionTitle)
+
+ HStack {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.xs) {
+ Text(recentSession.title)
+ .font(self.theme.typography.bodyStrong)
+ Text(recentSession.startedAt.formatted(date: .abbreviated, time: .shortened))
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+ Spacer()
+ Text(Self.durationText(recentSession.duration))
+ .font(self.theme.typography.codeCaption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+ .padding(self.theme.metrics.spacing.md)
+ .background(self.theme.palette.contentBackground, in: RoundedRectangle(
+ cornerRadius: self.theme.metrics.corners.md,
+ style: .continuous
+ ))
+ }
+ }
+ }
+ }
+
+ private static func durationText(_ duration: TimeInterval) -> String {
+ let total = max(0, Int(duration.rounded(.down)))
+ return String(format: "%d:%02d", total / 60, total % 60)
+ }
+ }
+
+ private struct MeetingRecordingCanvas: View {
+ let session: MeetingSession
+ let trackHealth: [MeetingAudioTrackKind: MeetingTrackHealth]
+ let liveTranscript: MeetingLiveTranscriptSnapshot
+ let isStopping: Bool
+ let onStop: () -> Void
+
+ @Environment(\.theme) private var theme
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.xl) {
+ TimelineView(.periodic(from: .now, by: 1)) { context in
+ HStack {
+ Label(
+ self.isStopping ? "Stopping…" : "Recording",
+ systemImage: self.isStopping ? "stop.circle.fill" : "record.circle.fill"
+ )
+ .font(self.theme.typography.sectionTitle)
+ .foregroundStyle(self.isStopping ? self.theme.palette.warning : Color(nsColor: .systemRed))
+
+ Text(Self.durationText(context.date.timeIntervalSince(self.session.startedAt)))
+ .font(self.theme.typography.codeCaption)
+ .foregroundStyle(self.theme.palette.primaryText)
+
+ Spacer()
+
+ Text(self.sourceSummary)
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .lineLimit(1)
+ }
+ .accessibilityElement(children: .combine)
+ .accessibilityLabel(
+ "\(self.isStopping ? "Meeting recording is stopping" : "Meeting recording in progress"), " +
+ "\(Self.durationText(context.date.timeIntervalSince(self.session.startedAt))) elapsed, " +
+ self.sourceSummary
+ )
+ }
+
+ ThemedCard(style: .prominent) {
+ VStack(spacing: self.theme.metrics.spacing.lg) {
+ if self.session.mode == .onlineCall {
+ MeetingTrackHealthRow(
+ title: "Meeting audio",
+ health: self.trackHealth[.applicationAudio] ?? .waiting
+ )
+ }
+ MeetingTrackHealthRow(
+ title: "Microphone",
+ health: self.trackHealth[.microphone] ?? .waiting
+ )
+ }
+ }
+
+ if self.isStopping {
+ Text("Saving captured audio before offline transcription begins…")
+ .font(self.theme.typography.body)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ } else {
+ MeetingLiveTranscriptCard(snapshot: self.liveTranscript)
+ Text("When the meeting ends, stop recording to transcribe it offline.")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+
+ HStack {
+ Spacer()
+
+ Button(action: self.onStop) {
+ if self.isStopping {
+ HStack(spacing: self.theme.metrics.spacing.sm) {
+ ProgressView()
+ .controlSize(.small)
+ Text("Stopping…")
+ }
+ } else {
+ Label("Stop & Transcribe", systemImage: "stop.fill")
+ }
+ }
+ .fluidButton(.destructive, size: .medium)
+ .disabled(self.isStopping)
+ .keyboardShortcut(.defaultAction)
+ }
+ }
+ }
+
+ private var sourceSummary: String {
+ let microphoneName = self.session.selectedMicrophone.displayName
+ guard self.session.mode == .onlineCall else { return microphoneName }
+ let applicationName = self.session.capturedApplication?.displayName ?? "Meeting audio"
+ return "\(applicationName) · \(microphoneName)"
+ }
+
+ private static func durationText(_ duration: TimeInterval) -> String {
+ let total = max(0, Int(duration.rounded(.down)))
+ let hours = total / 3600
+ let minutes = (total % 3600) / 60
+ let seconds = total % 60
+ if hours > 0 {
+ return String(format: "%d:%02d:%02d", hours, minutes, seconds)
+ }
+ return String(format: "%d:%02d", minutes, seconds)
+ }
+ }
+
+ /// Live captions during recording only — rows identify capture source, not a person; the offline
+ /// diarization pipeline replaces this view's content entirely on completion.
+ private struct MeetingLiveTranscriptCard: View {
+ let snapshot: MeetingLiveTranscriptSnapshot
+
+ @Environment(\.theme) private var theme
+
+ var body: some View {
+ ThemedCard(style: .subtle) {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.sm) {
+ HStack {
+ Text("Live captions")
+ .font(self.theme.typography.captionStrong)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ Spacer()
+ if let indicator = self.availabilityIndicator {
+ Label(indicator, systemImage: "exclamationmark.circle")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .labelStyle(.titleAndIcon)
+ }
+ Button {
+ MeetingFloatingCaptionsController.shared.show()
+ } label: {
+ Image(systemName: "rectangle.portrait.and.arrow.right")
- .font(.system(size: 12, weight: .semibold))
++ .font(.fluidSystem(size: 12, weight: .semibold))
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Open floating captions")
+ }
+
+ if self.rows.isEmpty {
+ Text("Listening…")
+ .font(self.theme.typography.bodySmall)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .frame(maxHeight: .infinity, alignment: .top)
+ } else {
+ self.scrollingBubbleList
+ }
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
+ }
+ }
+
+ private var rows: [MeetingLiveBubbleComposer.Row] {
+ MeetingLiveBubbleComposer.rows(for: self.snapshot)
+ }
+
+ private var availabilityIndicator: String? {
+ switch self.snapshot.availability {
+ case .available:
+ return nil
+ case let .unavailable(reason), let .degraded(reason):
+ return reason
+ }
+ }
+
+ private var scrollingBubbleList: some View {
+ MeetingLiveBubbleScrollList(rows: self.rows)
+ .frame(minHeight: 120, maxHeight: .infinity)
+ }
+ }
+
+ private struct MeetingProcessingCanvas: View {
+ let session: MeetingSession
+ let stage: MeetingProcessingStage
+
+ @Environment(\.theme) private var theme
+
+ private let stages: [MeetingProcessingStage] = [
+ .saving,
+ .identifyingSpeakers,
+ .transcribing,
+ .finalizing,
+ ]
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.xl) {
+ HStack(spacing: self.theme.metrics.spacing.md) {
+ ProgressView()
+ .controlSize(.regular)
+ .fixedSize()
+
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.xs) {
+ Text("Transcribing meeting…")
+ .font(self.theme.typography.sectionTitle)
+ .accessibilityAddTraits(.isHeader)
+ Text("You can close this window. Processing will continue.")
+ .font(self.theme.typography.bodySmall)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+ }
+
+ ThemedCard {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.lg) {
+ ForEach(Array(self.stages.enumerated()), id: \.element) { index, stage in
+ HStack(spacing: self.theme.metrics.spacing.md) {
+ Image(systemName: self.icon(for: stage, index: index))
+ .foregroundStyle(self.color(for: stage, index: index))
+ .frame(width: 20)
+ Text(Self.title(for: stage))
+ .font(self.theme.typography.body)
+ Spacer()
+ }
+ .accessibilityElement(children: .combine)
+ .accessibilityLabel("\(Self.title(for: stage)), \(self.accessibilityStatus(for: stage, index: index))")
+ }
+ }
+ }
+
+ Text(self.session.title)
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+ }
+
+ private var activeIndex: Int {
+ self.stages.firstIndex(of: self.stage) ?? 0
+ }
+
+ private func icon(for stage: MeetingProcessingStage, index: Int) -> String {
+ if self.stage == .completed || index < self.activeIndex { return "checkmark.circle.fill" }
+ if stage == self.stage { return "circle.dotted" }
+ return "circle"
+ }
+
+ private func color(for stage: MeetingProcessingStage, index: Int) -> Color {
+ if self.stage == .completed || index < self.activeIndex { return self.theme.palette.success }
+ if stage == self.stage { return self.theme.palette.accent }
+ return self.theme.palette.tertiaryText
+ }
+
+ private func accessibilityStatus(for stage: MeetingProcessingStage, index: Int) -> String {
+ if self.stage == .completed || index < self.activeIndex { return "complete" }
+ if stage == self.stage { return "in progress" }
+ return "waiting"
+ }
+
+ private static func title(for stage: MeetingProcessingStage) -> String {
+ switch stage {
+ case .pending: return "Waiting"
+ case .saving: return "Saving"
+ case .identifyingSpeakers: return "Identifying speakers"
+ case .transcribing: return "Transcribing"
+ case .finalizing: return "Finalizing"
+ case .completed: return "Complete"
+ }
+ }
+ }
+
+ /// Escape also dismisses: viewing a past meeting is a detail view, not a mode.
+ private struct MeetingCloseTranscriptButton: View {
+ let action: () -> Void
+
+ var body: some View {
+ Button("Close", systemImage: "xmark") { self.action() }
+ .labelStyle(.iconOnly)
+ .buttonStyle(.borderless)
+ .keyboardShortcut(.cancelAction)
+ .help("Close this transcript")
+ .accessibilityLabel("Close transcript")
+ }
+ }
+
+ private struct MeetingResultCanvas: View {
+ let session: MeetingSession
+ let isQuiescent: Bool
+ let canUndo: Bool
+ @State private var showsProbableEchoes = false
+ let onCopyTranscript: (MeetingSession, Bool) -> Void
+ let onExportTranscript: (MeetingSession, MeetingTranscriptExportFormat, Bool) -> Void
+ let onReassignSegment: (MeetingTranscriptSegmentID, SessionSpeakerID) -> Void
+ let onNameUnknownSegment: (MeetingTranscriptSegmentID, String) -> Void
+ let onRenameSpeaker: (SessionSpeakerID, String) -> Void
+ let onMergeSpeakers: (SessionSpeakerID, SessionSpeakerID) -> Void
+ let onUndo: () -> Void
+ let onRenameSession: (String) -> Void
+ let onAssignSpeakers: ([SessionSpeakerID: String]) async -> String?
+ let onClose: (() -> Void)?
+
+ @Environment(\.theme) private var theme
+ @State private var pendingRenameSpeaker: MeetingSessionSpeaker?
+ @State private var pendingRenameText = ""
+ @State private var pendingNameUnknownSegmentID: MeetingTranscriptSegmentID?
+ @State private var pendingUnknownSpeakerName = ""
+ @State private var isRenamingSession = false
+ @State private var pendingRenameSessionText = ""
+ @State private var isShowingAssignSpeakers = false
+ @State private var assignSpeakersFocus: SessionSpeakerID?
+
+ /// Naming is reached by clicking a speaker's name, so the sheet opens on the one clicked.
+ private func presentAssignSpeakers(focusing speakerID: SessionSpeakerID?) {
+ guard self.isQuiescent, !self.session.activeSpeakers.isEmpty else { return }
+ self.assignSpeakersFocus = speakerID
+ self.isShowingAssignSpeakers = true
+ }
+
+ private var speakerNames: [SessionSpeakerID: String] {
+ Dictionary(uniqueKeysWithValues: self.session.activeSpeakers.map { ($0.id, $0.displayName) })
+ }
- init(asrService: ASRService) {
- self.asrService = asrService
- _transcriptionService = StateObject(wrappedValue: MeetingTranscriptionService(asrService: asrService))
+ private func chipTint(for speaker: MeetingSessionSpeaker) -> Color? {
+ speaker.isLocalUser ? self.theme.palette.accent : self.speakerTints[speaker.id]
}
- @State private var showingFilePicker = false
- @State private var showingExportDialog = false
- @State private var exportResult: TranscriptionResult?
- @State private var exportFormat: ExportFormat = .text
- @State private var showingCopyConfirmation = false
- @State private var isDropTargeted = false
- @State private var dropErrorMessage: String?
+ private var speakerTints: [SessionSpeakerID: Color] {
+ MeetingSpeakerPalette.tints(for: self.session.activeSpeakers)
+ }
- enum ExportFormat: String, CaseIterable {
- case text = "Text (.txt)"
- case json = "JSON (.json)"
+ private var hasEchoSegments: Bool {
+ self.session.transcriptSegments.contains(where: \.isEcho)
+ }
- var fileExtension: String {
- switch self {
- case .text: return "txt"
- case .json: return "json"
- }
- }
+ /// Single projection so shown and copied never disagree.
+ private func visibleSegments(sorted: [MeetingTranscriptSegment]) -> [MeetingTranscriptSegment] {
+ self.showsProbableEchoes ? sorted : sorted.filter { !$0.isEcho }
}
- private var selectedFileIsVideo: Bool {
- guard let fileExtension = selectedFileURL?.pathExtension.lowercased() else { return false }
- return UTType(filenameExtension: fileExtension)?.conforms(to: .movie) ?? false
+ /// Sorted once with per-row display state — no per-row re-sorting. Compares the resolved
+ /// displayed label (not the raw speaker id) so consecutive nil-speaker rows in different
+ /// attribution states — e.g. `unassigned` then `timingUncertain` — each still show a label.
+ private func rows(
+ for visibleSegments: [MeetingTranscriptSegment]
+ ) -> [(segment: MeetingTranscriptSegment, showsLabel: Bool, isLocal: Bool)] {
+ let speakerNames = self.speakerNames
+ var previousLabelIdentity: String?
+ return visibleSegments.map { segment in
+ let labelIdentity = MeetingTranscriptExporter.speakerLabelIdentity(
+ for: segment,
+ in: self.session,
+ speakerNames: speakerNames
+ )
+ let showsLabel = labelIdentity != previousLabelIdentity
+ previousLabelIdentity = labelIdentity
+ return (segment, showsLabel, self.isLocalSegment(segment))
+ }
}
var body: some View {
@@@ -230,560 -2704,554 +2704,554 @@@
)
}
}
- .padding()
- .background(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .fill(self.theme.palette.cardBackground)
- .overlay(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .stroke(self.theme.palette.cardBorder.opacity(0.5), lineWidth: 1)
- )
- )
+ .frame(maxWidth: 760)
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, self.theme.metrics.spacing.lg)
+ }
- Button(action: {
- if self.transcriptionService.result != nil {
- self.showingFilePicker = true
- } else {
- Task {
- await self.transcribeFile()
- }
- }
- }) {
- Label(
- self.transcriptionService.result == nil ? "Transcribe" : "Transcribe another file",
- systemImage: self.transcriptionService.result == nil ? "waveform" : "plus"
- )
- .frame(maxWidth: .infinity)
- .padding(.vertical, 12)
+ HStack(spacing: self.theme.metrics.spacing.sm) {
+ Button("Copy Transcript", systemImage: "doc.on.doc") {
+ self.onCopyTranscript(self.session, self.showsProbableEchoes)
}
- .buttonStyle(.borderedProminent)
- .disabled(self.transcriptionService.isTranscribing)
+ .fluidButton(.compact, size: .medium)
+ .disabled(visibleSegments.isEmpty)
- } else {
- // File picker button – whole area is tappable; supports drag-and-drop
- Button(action: {
- self.showingFilePicker = true
- }) {
- VStack(spacing: 12) {
- Image(systemName: "arrow.up.doc.fill")
- .font(.fluidSystem(size: 32))
-
- Text("Drag and drop a file here, or click to open")
- .font(.fluidSystem(.headline))
-
- Text(MeetingTranscriptionService.supportedFormatsDescription)
- .font(.fluidSystem(.caption))
- .foregroundColor(.secondary)
- }
- .frame(maxWidth: .infinity)
- .padding(32)
- .contentShape(Rectangle())
+ Menu("Export Transcript", systemImage: "square.and.arrow.up") {
+ Button("Text…") { self.onExportTranscript(self.session, .text, self.showsProbableEchoes) }
+ Button("JSON…") { self.onExportTranscript(self.session, .json, self.showsProbableEchoes) }
}
- .buttonStyle(.plain)
- .background(
- RoundedRectangle(cornerRadius: 12, style: .continuous)
- .fill(self.theme.palette.cardBackground)
- .overlay(
- RoundedRectangle(cornerRadius: 12, style: .continuous)
- .stroke(self.theme.palette.cardBorder.opacity(0.45), lineWidth: 1)
- )
- )
- .overlay(
- RoundedRectangle(cornerRadius: 12)
- .strokeBorder(style: StrokeStyle(lineWidth: 2, dash: [8]))
- .foregroundColor(Color.fluidGreen.opacity(self.isDropTargeted ? 0.7 : 0.3))
- )
+ .fluidButton(.compact, size: .medium)
+ .disabled(visibleSegments.isEmpty)
+
+ Button("Undo", systemImage: "arrow.uturn.backward") {
+ self.onUndo()
+ }
+ .fluidButton(.compact, size: .medium)
+ .keyboardShortcut("z", modifiers: .command)
+ .disabled(!self.canUndo || !self.isQuiescent)
}
}
- .overlay {
- if self.isDropTargeted, !self.transcriptionService.isTranscribing {
- RoundedRectangle(cornerRadius: 12, style: .continuous)
- .strokeBorder(Color.fluidGreen, lineWidth: 2)
- .allowsHitTesting(false)
+ .alert(
+ "Rename Speaker",
+ isPresented: Binding(
+ get: { self.pendingRenameSpeaker != nil },
+ set: { if !$0 { self.pendingRenameSpeaker = nil } }
+ )
+ ) {
+ TextField("Speaker name", text: self.$pendingRenameText)
+ Button("Cancel", role: .cancel) { self.pendingRenameSpeaker = nil }
+ Button("Rename") {
+ if let speaker = self.pendingRenameSpeaker {
+ self.onRenameSpeaker(speaker.id, self.pendingRenameText)
+ }
+ self.pendingRenameSpeaker = nil
}
+ } message: {
+ Text("Enter a new name for this speaker.")
}
- .onDrop(of: [.fileURL], isTargeted: self.$isDropTargeted) { providers in
- self.handleDrop(providers: providers)
- }
- .fileImporter(
- isPresented: self.$showingFilePicker,
- allowedContentTypes: MeetingTranscriptionService.allowedContentTypes,
- allowsMultipleSelection: false
- ) { result in
- switch result {
- case let .success(urls):
- if let url = urls.first {
- self.selectFile(url)
+ .alert(
+ "Name Unknown Speaker",
+ isPresented: Binding(
+ get: { self.pendingNameUnknownSegmentID != nil },
+ set: { if !$0 { self.pendingNameUnknownSegmentID = nil } }
+ )
+ ) {
+ TextField("Speaker name", text: self.$pendingUnknownSpeakerName)
+ Button("Cancel", role: .cancel) { self.pendingNameUnknownSegmentID = nil }
+ Button("Save") {
+ if let segmentID = self.pendingNameUnknownSegmentID {
+ self.onNameUnknownSegment(segmentID, self.pendingUnknownSpeakerName)
}
- case let .failure(error):
- DebugLogger.shared.error("File picker error: \(error)", source: "MeetingTranscriptionView")
+ self.pendingNameUnknownSegmentID = nil
}
+ } message: {
+ Text("This name applies only to this transcript turn.")
}
- }
-
- // MARK: - Progress Card
-
- private var progressCard: some View {
- VStack(spacing: 16) {
- ProgressView(value: self.transcriptionService.progress)
- .progressViewStyle(.linear)
-
- HStack {
- ProgressView()
- .controlSize(.small)
- .fixedSize()
-
- Text(self.transcriptionService.currentStatus)
- .font(.fluidSystem(.subheadline))
- .foregroundColor(.secondary)
- }
+ .alert("Rename Meeting", isPresented: self.$isRenamingSession) {
+ TextField("Meeting title", text: self.$pendingRenameSessionText)
+ Button("Cancel", role: .cancel) {}
+ Button("Rename") { self.onRenameSession(self.pendingRenameSessionText) }
+ } message: {
+ Text("Enter a new title for this meeting.")
+ }
+ // Prevents an echo toggle left on for one meeting from leaking into the next.
+ .onChange(of: self.session.id) { _, _ in
+ self.showsProbableEchoes = false
+ self.isShowingAssignSpeakers = false
+ self.pendingNameUnknownSegmentID = nil
+ }
+ .sheet(isPresented: self.$isShowingAssignSpeakers) {
+ MeetingAssignSpeakersSheet(
+ speakers: self.session.activeSpeakers,
+ quotesBySpeaker: Dictionary(uniqueKeysWithValues: self.session.activeSpeakers.map {
+ ($0.id, MeetingAssignSpeakersQuoteSource.sampleQuotes(for: $0.id, in: self.session.transcriptSegments))
+ }),
+ tints: self.speakerTints,
+ accentColor: self.theme.palette.accent,
+ focusedSpeakerID: self.assignSpeakersFocus,
+ onSave: self.onAssignSpeakers,
+ onCancel: { self.isShowingAssignSpeakers = false }
+ )
}
- .padding()
- .background(
- RoundedRectangle(cornerRadius: 12, style: .continuous)
- .fill(self.theme.palette.cardBackground)
- .overlay(
- RoundedRectangle(cornerRadius: 12, style: .continuous)
- .stroke(self.theme.palette.cardBorder.opacity(0.45), lineWidth: 1)
- )
- )
}
- // MARK: - Results Card
-
- private func resultsCard(result: TranscriptionResult) -> some View {
- VStack(alignment: .leading, spacing: 16) {
- // Header with stats
- HStack {
- VStack(alignment: .leading, spacing: 4) {
- Text("Transcription Complete")
- .font(.fluidSystem(.headline))
-
- HStack(spacing: 16) {
- Label("\(String(format: "%.1f", result.duration))s", systemImage: "clock")
- Label("\(String(format: "%.0f%%", result.confidence * 100))", systemImage: "checkmark.circle")
- Label(
- "\(String(format: "%.1f", result.duration / result.processingTime))x",
- systemImage: "speedometer"
- )
- }
- .font(.fluidSystem(.caption))
- .foregroundColor(.secondary)
- }
-
- Spacer()
-
- // Action buttons
- HStack(spacing: 8) {
- Button(action: {
- self.copyToClipboard(result.text)
- }) {
- Image(systemName: "doc.on.doc")
- }
- .help("Copy to clipboard")
-
- Button(action: {
- self.exportResult = result
- self.showingExportDialog = true
- }) {
- Image(systemName: "square.and.arrow.up")
+ @ViewBuilder
+ private func speakerChipMenu(for speaker: MeetingSessionSpeaker) -> some View {
+ Button("Rename…", systemImage: "pencil") {
+ self.pendingRenameSpeaker = speaker
+ self.pendingRenameText = speaker.displayName
+ }
+ .disabled(!self.isQuiescent)
+ if !speaker.isLocalUser {
+ let eligibleTargets = self.session.activeSpeakers.filter {
+ $0.id != speaker.id && !$0.isLocalUser && $0.trackKind == speaker.trackKind
+ }
+ if !eligibleTargets.isEmpty {
+ Menu("Merge into") {
+ ForEach(eligibleTargets) { target in
+ Button(target.displayName) {
+ self.onMergeSpeakers(speaker.id, target.id)
+ }
}
- .help("Export transcription")
}
- .buttonStyle(.borderless)
+ .disabled(!self.isQuiescent)
}
+ }
+ }
- if let notice = result.speakerLabelingNotice ?? transcriptionService.fallbackNotice {
- Label(notice, systemImage: "exclamationmark.triangle.fill")
- .font(.fluidSystem(.caption))
- .foregroundColor(.secondary)
- }
+ private func displayName(for speaker: MeetingSessionSpeaker) -> String {
+ guard speaker.isLocalUser,
+ speaker.displayName.caseInsensitiveCompare("You") != .orderedSame
+ else {
+ return speaker.displayName
+ }
+ return "\(speaker.displayName) (You)"
+ }
- Divider()
+ // Only explicitly persisted legacy ownership metadata receives the local-user treatment.
+ private func isLocalSegment(_ segment: MeetingTranscriptSegment) -> Bool {
+ guard let speakerID = segment.speakerID,
+ let speaker = self.session.speakers.first(where: { $0.id == speakerID })
+ else { return false }
+ return speaker.isLocalUser
+ }
- // Transcription text
- ScrollView {
- if !result.speakerSegments.isEmpty {
- VStack(alignment: .leading, spacing: 12) {
- ForEach(result.speakerSegments) { segment in
- VStack(alignment: .leading, spacing: 2) {
- HStack(spacing: 6) {
- Text(segment.speaker)
- .font(.fluidSystem(.caption))
- .fontWeight(.semibold)
- .foregroundColor(Color.fluidGreen)
-
- Text(segment.timestampText)
- .font(.fluidSystem(.caption2))
- .foregroundColor(.secondary)
- }
+ @ViewBuilder
+ private var meetingMetadata: some View {
+ Label(
+ self.session.startedAt.formatted(date: .abbreviated, time: .shortened),
+ systemImage: "calendar"
+ )
+ Label(Self.durationText(self.session.duration), systemImage: "clock")
+ Label(self.sourceName, systemImage: self.session.mode == .onlineCall ? "macwindow" : "person.3")
+ Label(self.session.selectedMicrophone.displayName, systemImage: "mic")
+ }
- Text(segment.text)
- .font(.fluidSystem(.body))
- .textSelection(.enabled)
- }
- }
- }
- .frame(maxWidth: .infinity, alignment: .leading)
- .padding()
- } else {
- Text(result.text)
- .font(.fluidSystem(.body))
- .textSelection(.enabled)
- .frame(maxWidth: .infinity, alignment: .leading)
- .padding()
- }
- }
- .frame(maxHeight: 300)
- .background(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .fill(self.theme.palette.contentBackground)
- .overlay(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .stroke(self.theme.palette.cardBorder.opacity(0.45), lineWidth: 1)
- )
- )
+ private var sourceName: String {
+ self.session.capturedApplication?.displayName ?? "In-room meeting"
+ }
+
+ private var statusText: String {
+ switch self.session.state {
+ case .completed: "Completed"
+ case .failed: "Failed"
+ case .interrupted: "Interrupted"
+ case .processing: "Processing"
+ case .recording, .recordingDegraded, .preparing, .stopping: "Recording"
}
- .padding()
- .background(
- RoundedRectangle(cornerRadius: 12, style: .continuous)
- .fill(self.theme.palette.cardBackground)
- .overlay(
- RoundedRectangle(cornerRadius: 12, style: .continuous)
- .stroke(self.theme.palette.cardBorder.opacity(0.45), lineWidth: 1)
- )
- )
}
- // MARK: - Recent Transcriptions Section
+ private var statusIcon: String {
+ switch self.session.state {
+ case .completed: "checkmark.circle.fill"
+ case .failed: "xmark.circle.fill"
+ case .interrupted: "exclamationmark.circle.fill"
+ case .processing: "ellipsis.circle.fill"
+ case .recording, .recordingDegraded, .preparing, .stopping: "record.circle.fill"
+ }
+ }
- private var recentTranscriptionsSection: some View {
- VStack(alignment: .leading, spacing: 16) {
- HStack {
- Text("Recent transcriptions")
- .font(.fluidSystem(.headline))
- Spacer()
- if !self.fileHistoryStore.entries.isEmpty {
- Button("Clear all") {
- self.fileHistoryStore.clearAll()
- }
- .buttonStyle(.plain)
- .foregroundColor(.secondary)
- .font(.fluidSystem(.caption))
- }
- }
+ private var statusColor: Color {
+ switch self.session.state {
+ case .completed: self.theme.palette.success
+ case .failed: Color(nsColor: .systemRed)
+ case .interrupted: self.theme.palette.warning
+ case .processing: self.theme.palette.accent
+ case .recording, .recordingDegraded, .preparing, .stopping: self.theme.palette.warning
+ }
+ }
- VStack(spacing: 8) {
- ForEach(self.fileHistoryStore.entries) { entry in
- VStack(spacing: 0) {
- self.recentEntryRow(entry: entry)
- .id(entry.id)
- if self.fileHistoryStore.selectedEntryID == entry.id {
- Divider()
- .padding(.horizontal, 12)
- self.historyDetailCard(entry: entry)
- .id(MeetingTranscriptionScrollTarget.detail(entry.id))
- .transition(.opacity)
- }
- }
- .background(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .fill(self.theme.palette.cardBackground)
- )
- .overlay(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .stroke(self.theme.palette.cardBorder.opacity(0.45), lineWidth: 1)
- )
- }
- }
+ private static func durationText(_ duration: TimeInterval) -> String {
+ let total = max(0, Int(duration.rounded(.down)))
+ let hours = total / 3600
+ let minutes = (total % 3600) / 60
+ let seconds = total % 60
+ if hours > 0 {
+ return String(format: "%d:%02d:%02d", hours, minutes, seconds)
}
+ return String(format: "%d:%02d", minutes, seconds)
}
+ }
- private func recentEntryRow(entry: FileTranscriptionEntry) -> some View {
- let isSelected = self.fileHistoryStore.selectedEntryID == entry.id
- return Button(action: {
- withAnimation(self.reduceMotion ? nil : .spring(response: 0.3, dampingFraction: 1)) {
- self.fileHistoryStore.selectedEntryID = isSelected ? nil : entry.id
- }
- }) {
- HStack {
- Image(systemName: "doc.text.fill")
- .font(.fluidSystem(.body))
- .foregroundColor(Color.fluidGreen)
- .frame(width: 24)
-
- VStack(alignment: .leading, spacing: 2) {
- Text(entry.fileName)
- .font(.fluidSystem(size: 14, weight: .medium))
- .lineLimit(1)
- Text(entry.relativeTimeString)
- .font(.fluidSystem(.caption))
- .foregroundColor(.secondary)
- Text(entry.previewText)
- .font(.fluidSystem(.caption))
- .foregroundColor(.secondary)
- .lineLimit(1)
- }
+ private struct MeetingFailureCanvas: View {
+ let session: MeetingSession?
+ let message: String
+ let isRetrying: Bool
+ let onRetrySession: (MeetingSession) -> Void
+ let onRevealAudio: (MeetingSession) -> Void
+ let onRecordAgain: (MeetingSession) -> Void
+ let onClose: (() -> Void)?
- Spacer()
+ @Environment(\.theme) private var theme
- Image(systemName: "chevron.right")
- .font(.fluidSystem(.caption).weight(.semibold))
- .foregroundColor(.secondary)
- .rotationEffect(.degrees(isSelected ? 90 : 0))
- .accessibilityHidden(true)
- }
- .padding(12)
- .contentShape(Rectangle())
+ private var hasRecoverableAudio: Bool {
+ self.session?.hasRetryableAudio == true
+ }
+
+ private var title: String {
+ guard let session else { return "Meeting setup failed" }
+ let lastFailureDomain = session.failures.last?.domain
+ if lastFailureDomain == .processing ||
+ (session.state == .interrupted && !session.processingAttempts.isEmpty)
+ {
+ return session.state == .interrupted
+ ? "Meeting transcription was interrupted"
+ : "Meeting transcription failed"
}
- .buttonStyle(.plain)
- .accessibilityValue(isSelected ? "Expanded" : "Collapsed")
- .accessibilityHint(isSelected ? "Collapse transcription" : "Expand transcription")
+ if self.hasRecoverableAudio {
+ return session.state == .interrupted
+ ? "Meeting recording was interrupted"
+ : "Meeting recording failed"
+ }
+ return "Meeting setup failed"
}
- private func historyDetailCard(entry: FileTranscriptionEntry) -> some View {
- let result = entry.toTranscriptionResult()
- return VStack(alignment: .leading, spacing: 16) {
- HStack {
- VStack(alignment: .leading, spacing: 4) {
- Text("Transcript")
- .font(.fluidSystem(.headline))
- HStack(spacing: 16) {
- Label("\(String(format: "%.1f", entry.duration))s", systemImage: "clock")
- Label("\(String(format: "%.0f%%", entry.confidence * 100))", systemImage: "checkmark.circle")
- Label(entry.fullDateString, systemImage: "calendar")
+ var body: some View {
+ ThemedCard(style: .prominent) {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.lg) {
+ HStack(alignment: .firstTextBaseline) {
+ Label(self.title, systemImage: "exclamationmark.triangle.fill")
+ .font(self.theme.typography.sectionTitle)
+ .foregroundStyle(self.theme.palette.warning)
+ .accessibilityAddTraits(.isHeader)
+ Spacer(minLength: 0)
+ if let onClose {
+ MeetingCloseTranscriptButton(action: onClose)
}
- .font(.fluidSystem(.caption))
- .foregroundColor(.secondary)
}
- Spacer()
- HStack(spacing: 8) {
- Button(action: { self.copyToClipboard(entry.text) }) {
- Image(systemName: "doc.on.doc")
- }
- .help("Copy to clipboard")
- Button(action: {
- self.exportResult = result
- self.showingExportDialog = true
- }) {
- Image(systemName: "square.and.arrow.up")
+ Text(self.message)
+ .font(self.theme.typography.body)
+ .textSelection(.enabled)
+ if self.hasRecoverableAudio {
+ Text("The captured audio has been preserved on this Mac.")
+ .font(self.theme.typography.bodySmall)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+ HStack(spacing: self.theme.metrics.spacing.sm) {
+ if let session, self.hasRecoverableAudio {
+ Button("Reveal Audio", systemImage: "folder", action: { self.onRevealAudio(session) })
+ .fluidButton(.compact, size: .medium)
+ Button(action: { self.onRetrySession(session) }) {
+ if self.isRetrying {
+ HStack(spacing: self.theme.metrics.spacing.sm) {
+ ProgressView().controlSize(.small)
+ Text("Retrying…")
+ }
+ } else {
+ Label("Retry Transcription", systemImage: "arrow.clockwise")
+ }
+ }
+ .fluidButton(.accent, size: .medium)
+ .disabled(self.isRetrying)
}
- .help("Export transcription")
- Button(action: {
- self.fileHistoryStore.deleteEntry(id: entry.id)
- }) {
- Image(systemName: "trash")
+ if let session {
+ Button("Record Again", systemImage: "arrow.counterclockwise.circle") {
+ self.onRecordAgain(session)
+ }
+ .fluidButton(.compact, size: .medium)
}
- .help("Remove from history")
}
- .buttonStyle(.borderless)
}
- if let notice = entry.speakerLabelingNotice {
- Label(notice, systemImage: "exclamationmark.triangle.fill")
- .font(.fluidSystem(.caption))
- .foregroundColor(.secondary)
- }
- Divider()
- ScrollView {
- Text(entry.text)
- .font(.fluidSystem(.body))
- .textSelection(.enabled)
- .frame(maxWidth: .infinity, alignment: .leading)
- .padding()
- }
- .frame(maxHeight: 300)
- .background(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .fill(self.theme.palette.contentBackground)
- .overlay(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .stroke(self.theme.palette.cardBorder.opacity(0.45), lineWidth: 1)
- )
- )
}
- .padding()
}
+ }
- // MARK: - Error Card
+ private struct MeetingAdaptiveSetupRow<Content: View>: View {
+ let title: String
+ var detail: String?
+ @ViewBuilder let content: Content
- private func errorCard(error: String) -> some View {
- HStack {
- Image(systemName: "exclamationmark.triangle.fill")
- .foregroundColor(.red)
+ @Environment(\.theme) private var theme
- Text(error)
- .font(.fluidSystem(.subheadline))
+ init(
+ title: String,
+ detail: String? = nil,
+ @ViewBuilder content: () -> Content
+ ) {
+ self.title = title
+ self.detail = detail
+ self.content = content()
+ }
- Spacer()
+ var body: some View {
+ ViewThatFits(in: .horizontal) {
+ HStack(alignment: .center, spacing: self.theme.metrics.spacing.lg) {
+ self.label
+ .frame(width: 164, alignment: .leading)
+ self.content
+ .frame(width: 320, alignment: .leading)
+ Spacer(minLength: 0)
+ }
- Button("Dismiss") {
- self.transcriptionService.reset()
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.sm) {
+ self.label
+ self.content
+ .frame(maxWidth: .infinity, alignment: .leading)
}
- .buttonStyle(.borderless)
}
- .padding()
- .background(
- RoundedRectangle(cornerRadius: 12, style: .continuous)
- .fill(Color.red.opacity(0.12))
- .overlay(
- RoundedRectangle(cornerRadius: 12, style: .continuous)
- .stroke(Color.red.opacity(0.4), lineWidth: 1)
- )
- )
+ .padding(.horizontal, self.theme.metrics.spacing.lg)
+ .padding(.vertical, self.theme.metrics.spacing.md)
}
- // MARK: - Drop Error Card
-
- private func dropErrorCard(message: String) -> some View {
- HStack {
- Image(systemName: "exclamationmark.triangle.fill")
- .foregroundColor(.red)
+ private var label: some View {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.xs) {
+ Text(self.title)
+ .font(self.theme.typography.bodyStrong)
+ .foregroundStyle(self.theme.palette.primaryText)
+ if let detail {
+ Text(detail)
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ }
+ }
- Text(message)
- .font(.fluidSystem(.subheadline))
+ private struct MeetingReadyStatus: View {
+ let isReady: Bool
+ let title: String
+ let detail: String
- Spacer()
+ @Environment(\.theme) private var theme
- Button("Dismiss") {
- self.dropErrorMessage = nil
+ var body: some View {
+ HStack(spacing: self.theme.metrics.spacing.md) {
+ Image(systemName: self.isReady ? "checkmark.circle.fill" : "exclamationmark.circle.fill")
+ .foregroundStyle(self.isReady ? self.theme.palette.success : self.theme.palette.warning)
+ .accessibilityHidden(true)
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.xs) {
+ Text(self.title)
+ .font(self.theme.typography.bodyStrong)
+ .foregroundStyle(self.theme.palette.primaryText)
+ Text(self.detail)
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .fixedSize(horizontal: false, vertical: true)
}
- .buttonStyle(.borderless)
}
- .padding()
- .background(
- RoundedRectangle(cornerRadius: 12, style: .continuous)
- .fill(Color.red.opacity(0.12))
- .overlay(
- RoundedRectangle(cornerRadius: 12, style: .continuous)
- .stroke(Color.red.opacity(0.4), lineWidth: 1)
- )
- )
+ .accessibilityElement(children: .combine)
+ .accessibilityLabel("\(self.title). \(self.detail)")
}
+ }
- // MARK: - Helper Functions
-
- private static let supportedFileExtensions = MeetingTranscriptionService.supportedFileExtensions
+ private struct MeetingTrackHealthRow: View {
+ let title: String
+ let health: MeetingTrackHealth
- private static let dropErrorCopy = MeetingTranscriptionService.dropErrorCopy
+ @Environment(\.theme) private var theme
- private func handleDrop(providers: [NSItemProvider]) -> Bool {
- guard !self.transcriptionService.isTranscribing,
- let provider = providers.first else { return false }
- provider.loadItem(forTypeIdentifier: UTType.fileURL.identifier, options: nil) { item, _ in
- let url: URL? = (item as? URL) ?? (item as? Data).flatMap { URL(dataRepresentation: $0, relativeTo: nil) }
- guard let url = url else { return }
- let ext = url.pathExtension.lowercased()
- guard Self.supportedFileExtensions.contains(ext) else {
- DispatchQueue.main.async {
- self.dropErrorMessage = Self.dropErrorCopy
- DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
- self.dropErrorMessage = nil
- }
- }
- return
- }
- DispatchQueue.main.async {
- self.selectFile(url)
- }
+ private var statusText: String {
+ switch self.health.status {
+ case .waiting: return "Waiting for audio"
+ case .healthy: return "Healthy"
+ case .degraded: return self.health.detail ?? "Audio source degraded"
+ case .unavailable: return self.health.detail ?? "Audio source unavailable"
+ case .stopped: return "Stopped"
}
- return true
}
- private func selectFile(_ url: URL) {
- // A drop may finish loading after transcription has started.
- guard !self.transcriptionService.isTranscribing else { return }
- withAnimation(self.reduceMotion ? nil : .spring(response: 0.3, dampingFraction: 1)) {
- self.selectedFileURL = url
- self.transcriptionService.reset()
- self.dropErrorMessage = nil
- }
+ private var isHealthy: Bool {
+ self.health.status == .healthy
}
- private func transcribeFile() async {
- guard let fileURL = selectedFileURL else { return }
+ var body: some View {
+ HStack(spacing: self.theme.metrics.spacing.md) {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.xs) {
+ Text(self.title)
+ .font(self.theme.typography.bodyStrong)
+ Text(self.statusText)
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .lineLimit(2)
+ }
- do {
- _ = try await self.transcriptionService.transcribeFile(fileURL)
- } catch {
- DebugLogger.shared.error("Transcription error: \(error)", source: "MeetingTranscriptionView")
- }
- }
+ Spacer()
- private func formatFileSize(fileURL: URL) -> String {
- guard let attributes = try? FileManager.default.attributesOfItem(atPath: fileURL.path),
- let fileSize = attributes[.size] as? Int64
- else {
- return "Unknown size"
- }
+ ProgressView(value: min(max(Double(self.health.level), 0), 1))
+ .progressViewStyle(.linear)
+ .frame(width: 150)
+ .accessibilityLabel("\(self.title) level")
- let formatter = ByteCountFormatter()
- formatter.countStyle = .file
- return formatter.string(fromByteCount: fileSize)
+ Label(
+ self.statusText,
+ systemImage: self.isHealthy ? "checkmark.circle.fill" : "exclamationmark.circle.fill"
+ )
+ .labelStyle(.iconOnly)
+ .foregroundStyle(self.isHealthy ? self.theme.palette.success : self.theme.palette.warning)
+ .accessibilityLabel(self.statusText)
+ }
}
+ }
- private func copyToClipboard(_ text: String) {
- ClipboardAudit.record("ui_copy_begin")
- NSPasteboard.general.clearContents()
- NSPasteboard.general.setString(text, forType: .string)
- ClipboardAudit.record("ui_copy_end")
+ private struct MeetingSpeakerChip: View {
+ let title: String
+ let systemImage: String
+ let tint: Color
+ let action: () -> Void
- withAnimation {
- self.showingCopyConfirmation = true
- }
+ @Environment(\.theme) private var theme
+ @Environment(\.isEnabled) private var isEnabled
+ @State private var isHovering = false
- DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
- withAnimation {
- self.showingCopyConfirmation = false
+ var body: some View {
+ Button(action: self.action) {
+ HStack(spacing: 3) {
+ Label(self.title, systemImage: self.systemImage)
+ Image(systemName: "chevron.right")
- .font(.system(size: 9, weight: .semibold))
++ .font(.fluidSystem(size: 9, weight: .semibold))
+ .opacity(self.isHovering ? 1 : 0.45)
}
+ .font(self.theme.typography.badge)
+ .foregroundStyle(self.tint)
+ .padding(.horizontal, self.theme.metrics.spacing.md)
+ .padding(.vertical, self.theme.metrics.spacing.sm)
+ .background(self.tint.opacity(self.isHovering ? 0.20 : 0.12), in: Capsule())
+ .overlay(Capsule().strokeBorder(self.tint.opacity(self.isHovering ? 0.45 : 0.22)))
}
+ .buttonStyle(.plain)
+ .help("Rename this speaker")
+ .accessibilityLabel("Rename \(self.title)")
+ .pointerStyle(self.isEnabled ? .link : nil)
+ .onHover { self.isHovering = self.isEnabled && $0 }
}
}
- // MARK: - Document for Export
-
- struct TranscriptionDocument: FileDocument {
- static var readableContentTypes: [UTType] {
- [.plainText, .json]
- }
+ private struct MeetingTranscriptSegmentRow: View {
+ let segment: MeetingTranscriptSegment
+ let speakerName: String
+ let speakerTint: Color?
+ let onRenameSpeakerTapped: (() -> Void)?
+ let isLocalUser: Bool
+ let showsSpeakerLabel: Bool
+ let reassignTargets: [MeetingSessionSpeaker]
+ let isQuiescent: Bool
+ let onReassign: (SessionSpeakerID) -> Void
- let result: TranscriptionResult
- let format: MeetingTranscriptionView.ExportFormat
- let service: MeetingTranscriptionService
+ @Environment(\.theme) private var theme
+ @State private var isHoveringSpeaker = false
- init(
- result: TranscriptionResult,
- format: MeetingTranscriptionView.ExportFormat,
- service: MeetingTranscriptionService
- ) {
- self.result = result
- self.format = format
- self.service = service
+ var body: some View {
+ Group {
+ if self.isLocalUser {
+ self.localBubble
+ } else {
+ self.remoteMessage
+ }
+ }
+ .opacity(self.segment.isEcho ? 0.6 : 1)
+ .contextMenu {
+ Menu("Reassign to") {
+ ForEach(self.reassignTargets) { target in
+ Button(target.displayName) {
+ self.onReassign(target.id)
+ }
+ }
+ }
+ .disabled(!self.isQuiescent)
+ }
+ .accessibilityElement(children: .combine)
+ .accessibilityLabel(
+ "\(MeetingTranscriptExporter.timestampText(self.segment.start.seconds)), \(self.speakerName), \(self.segment.text)"
+ )
}
- init(configuration: ReadConfiguration) throws {
- throw CocoaError(.fileReadUnknown)
+ /// A wash of the speaker's own tint, faint enough that a wall of turns still reads as text.
+ private var bubbleFill: Color {
+ (self.isLocalUser ? self.theme.palette.accent : self.speakerTint)?.opacity(0.10)
+ ?? self.theme.palette.contentBackground
}
- func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
- let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent("temp.\(self.format.fileExtension)")
-
- switch self.format {
- case .text:
- try self.service.exportToText(self.result, to: tempURL)
- case .json:
- try self.service.exportToJSON(self.result, to: tempURL)
+ private var speakerLabel: some View {
+ let name = Text(self.speakerName)
+ .foregroundColor(self.nameColor)
+ .fontWeight(.semibold)
- .font(.system(size: 14, design: .monospaced))
++ .font(.fluidSystem(size: 14, design: .monospaced))
+
+ return HStack(spacing: 8) {
+ if let onRenameSpeakerTapped = self.onRenameSpeakerTapped {
+ Button(action: onRenameSpeakerTapped) {
+ HStack(spacing: 3) {
+ name
+ // Always shown, not hover-only, so the affordance survives an unfocused window.
+ Image(systemName: "chevron.right")
- .font(.system(size: 10, weight: .semibold))
++ .font(.fluidSystem(size: 10, weight: .semibold))
+ .foregroundColor(self.nameColor)
+ .opacity(self.isHoveringSpeaker ? 1 : 0.45)
+ }
+ }
+ .buttonStyle(.plain)
+ // No .help here: the tooltip lands on top of the turn's first line of text.
+ .accessibilityLabel("Rename \(self.speakerName)")
+ .pointerStyle(.link)
+ .onHover { self.isHoveringSpeaker = $0 }
+ } else {
+ name
+ }
+ Text(MeetingTranscriptExporter.timestampText(self.segment.start.seconds))
- .font(.system(size: 14, design: .monospaced))
++ .font(.fluidSystem(size: 14, design: .monospaced))
+ .foregroundColor(self.theme.palette.tertiaryText)
}
+ }
- let data = try Data(contentsOf: tempURL)
- try? FileManager.default.removeItem(at: tempURL)
-
- return FileWrapper(regularFileWithContents: data)
+ private var nameColor: Color {
+ if self.isLocalUser { return self.theme.palette.accent }
+ return self.speakerTint ?? self.theme.palette.tertiaryText
}
- }
- // MARK: - Preview
+ private var localBubble: some View {
+ VStack(alignment: .trailing, spacing: 6) {
+ if self.showsSpeakerLabel {
+ self.speakerLabel
+ }
+ Text(self.segment.text)
+ .textSelection(.enabled)
+ .meetingBubbleStyle(MeetingBubbleStyle.final(fill: self.bubbleFill, foreground: self.theme.palette.primaryText))
+ if self.segment.isEcho {
+ Text("probable echo")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.tertiaryText)
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .trailing)
+ .padding(.leading, 96)
+ }
- #Preview {
- MeetingTranscriptionView(asrService: ASRService())
- .frame(width: 700, height: 800)
+ private var remoteMessage: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ if self.showsSpeakerLabel {
+ self.speakerLabel
+ }
+ Text(self.segment.text)
+ .textSelection(.enabled)
+ .meetingBubbleStyle(MeetingBubbleStyle.final(fill: self.bubbleFill, foreground: self.theme.palette.primaryText))
+ if self.segment.isEcho {
+ Text("probable echo")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.tertiaryText)
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.trailing, 48)
+ }
}
diff --cc Sources/Fluid/UI/PermissionDragGuide.swift
index 00000000,9a3b3bf3..ffe6f398
mode 000000,100644..100644
--- a/Sources/Fluid/UI/PermissionDragGuide.swift
+++ b/Sources/Fluid/UI/PermissionDragGuide.swift
@@@ -1,0 -1,309 +1,309 @@@
+ import AppKit
+ import SwiftUI
+
+ /// Floating "drag the app into the list" guide shown next to System Settings, generalized from
+ /// the Accessibility onboarding flow so any TCC pane (Screen Recording, etc.) can reuse it.
+ @MainActor
+ final class PermissionDragGuideController {
+ static let shared = PermissionDragGuideController()
+
+ private var panel: NSPanel?
+ private var monitorTask: Task<Void, Never>?
+ private var requestID: UUID?
+
+ private init() {}
+
+ func present(
+ instruction: String,
+ settingsPaneURL: URL,
+ isGranted: @escaping @Sendable () -> Bool,
+ onGranted: @escaping @MainActor () -> Void = {}
+ ) {
+ let requestID = UUID()
+ self.requestID = requestID
+ NSWorkspace.shared.open(settingsPaneURL)
+
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { [weak self] in
+ guard let self, self.requestID == requestID else { return }
+ self.showPanel(instruction: instruction)
+ self.startMonitor(requestID: requestID, isGranted: isGranted, onGranted: onGranted)
+ self.activateSystemSettingsSoon(requestID: requestID)
+ }
+ }
+
+ func dismiss() {
+ self.requestID = nil
+ self.monitorTask?.cancel()
+ self.monitorTask = nil
+ self.panel?.close()
+ self.panel = nil
+ }
+
+ private func showPanel(instruction: String) {
+ let panelWidth: CGFloat = 560
+ let panelHeight: CGFloat = 150
+ let gap: CGFloat = 14
+ let visibleFrame = NSScreen.main?.visibleFrame ?? NSRect(x: 0, y: 0, width: 1440, height: 900)
+
+ let panelX: CGFloat
+ let panelY: CGFloat
+ if let settingsFrame = Self.systemSettingsWindowFrame() {
+ panelX = min(
+ visibleFrame.maxX - panelWidth - 16,
+ max(visibleFrame.minX + 16, settingsFrame.midX - (panelWidth / 2))
+ )
+ panelY = max(visibleFrame.minY + 16, settingsFrame.minY - panelHeight - gap)
+ } else {
+ panelX = visibleFrame.midX - (panelWidth / 2)
+ panelY = visibleFrame.minY + 120
+ }
+
+ let frame = NSRect(x: panelX, y: panelY, width: panelWidth, height: panelHeight)
+ let panel = self.panel ?? NSPanel(
+ contentRect: frame,
+ styleMask: [.borderless, .nonactivatingPanel],
+ backing: .buffered,
+ defer: false
+ )
+ panel.level = .floating
+ panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
+ panel.isOpaque = false
+ panel.backgroundColor = .clear
+ panel.hasShadow = true
+ panel.hidesOnDeactivate = false
+ panel.contentView = NSHostingView(
+ rootView: PermissionDragGuideView(
+ appURL: Self.draggableAppURL,
+ appName: Bundle.main.fluidAppDisplayName,
+ instruction: instruction,
+ onReturnToApp: { [weak self] in self?.returnToApp() },
+ onClose: { [weak self] in self?.dismiss() }
+ )
+ )
+ panel.setFrame(frame, display: true, animate: self.panel != nil)
+ panel.orderFrontRegardless()
+ self.panel = panel
+ }
+
+ private func startMonitor(
+ requestID: UUID,
+ isGranted: @escaping @Sendable () -> Bool,
+ onGranted: @escaping @MainActor () -> Void
+ ) {
+ self.monitorTask?.cancel()
+ self.monitorTask = Task { [weak self] in
+ var missingSettingsCount = 0
+ while !Task.isCancelled {
+ try? await Task.sleep(nanoseconds: 900_000_000)
+ guard let self, await self.requestID == requestID else { return }
+
+ if isGranted() {
+ await MainActor.run {
+ self.dismiss()
+ onGranted()
+ NSApp.activate(ignoringOtherApps: true)
+ }
+ return
+ }
+
+ let settingsFrame = await MainActor.run { Self.systemSettingsWindowFrame() }
+ missingSettingsCount = settingsFrame == nil ? missingSettingsCount + 1 : 0
+ if missingSettingsCount >= 3 {
+ await MainActor.run { self.returnToApp() }
+ return
+ }
+ }
+ }
+ }
+
+ private func returnToApp() {
+ self.dismiss()
+ NSApp.activate(ignoringOtherApps: true)
+ (NSApp.windows.first { $0.isVisible && $0.title == "FluidVoice" } ?? NSApp.keyWindow)?
+ .makeKeyAndOrderFront(nil)
+ }
+
+ private func activateSystemSettingsSoon(requestID: UUID) {
+ for delay in [0.25, 0.85, 1.45] {
+ DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in
+ guard let self, self.requestID == requestID else { return }
+ if let app = NSWorkspace.shared.runningApplications
+ .first(where: { $0.bundleIdentifier == "com.apple.SystemSettings" }) ??
+ NSWorkspace.shared.runningApplications
+ .first(where: { $0.localizedName == "System Settings" })
+ {
+ app.activate(options: [])
+ }
+ }
+ }
+ }
+
+ private static var draggableAppURL: URL {
+ let runningAppURL = Bundle.main.bundleURL
+ if runningAppURL.pathExtension == "app",
+ FileManager.default.fileExists(atPath: runningAppURL.path)
+ {
+ return runningAppURL
+ }
+ let installedURL = URL(fileURLWithPath: "/Applications/FluidVoice.app")
+ if FileManager.default.fileExists(atPath: installedURL.path) {
+ return installedURL
+ }
+ return Bundle.main.bundleURL
+ }
+
+ private static func systemSettingsWindowFrame() -> NSRect? {
+ guard let windowList = CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) as? [[String: Any]] else {
+ return nil
+ }
+ for info in windowList {
+ guard (info[kCGWindowOwnerName as String] as? String) == "System Settings",
+ let bounds = info[kCGWindowBounds as String] as? [String: Any],
+ let x = bounds["X"] as? CGFloat,
+ let y = bounds["Y"] as? CGFloat,
+ let width = bounds["Width"] as? CGFloat,
+ let height = bounds["Height"] as? CGFloat,
+ width > 0,
+ height > 0
+ else { continue }
+
+ for screen in NSScreen.screens {
+ let convertedFrame = NSRect(
+ x: x,
+ y: screen.frame.maxY - y - height,
+ width: width,
+ height: height
+ )
+ if screen.frame.intersects(convertedFrame) {
+ return convertedFrame
+ }
+ }
+ let convertedY = (NSScreen.main?.frame.maxY ?? 0) - y - height
+ return NSRect(x: x, y: convertedY, width: width, height: height)
+ }
+ return nil
+ }
+ }
+
+ private struct PermissionDragGuideView: View {
+ let appURL: URL
+ let appName: String
+ let instruction: String
+ let onReturnToApp: () -> Void
+ let onClose: () -> Void
+
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @State private var isArrowRaised = false
+ @State private var isTokenHovered = false
+
+ private var appIcon: NSImage {
+ NSWorkspace.shared.icon(forFile: self.appURL.path)
+ }
+
+ var body: some View {
+ VStack(spacing: 12) {
+ HStack(spacing: 12) {
+ Image(systemName: "arrow.up")
- .font(.system(size: 30, weight: .bold))
++ .font(.fluidSystem(size: 30, weight: .bold))
+ .foregroundStyle(FluidOnboardingLandingColors.blue)
+ .offset(y: self.reduceMotion ? 0 : (self.isArrowRaised ? -8 : 4))
+ .animation(
+ self.reduceMotion ? nil : .easeInOut(duration: 0.85).repeatForever(autoreverses: true),
+ value: self.isArrowRaised
+ )
+
+ Text(self.instruction)
- .font(.system(size: 15, weight: .semibold))
++ .font(.fluidSystem(size: 15, weight: .semibold))
+ .foregroundStyle(.white.opacity(0.78))
+ .lineLimit(1)
+
+ Spacer()
+
+ Button {
+ self.onClose()
+ } label: {
+ Image(systemName: "xmark")
- .font(.system(size: 11, weight: .bold))
++ .font(.fluidSystem(size: 11, weight: .bold))
+ .foregroundStyle(.white.opacity(0.58))
+ .frame(width: 26, height: 26)
+ .background(Circle().fill(Color.white.opacity(0.075)))
+ .contentShape(Circle())
+ }
+ .buttonStyle(.plain)
+ .focusable(false)
+ .help("Close guide")
+ }
+
+ HStack(spacing: 12) {
+ Button {
+ self.onReturnToApp()
+ } label: {
+ Image(systemName: "chevron.left")
- .font(.system(size: 15, weight: .bold))
++ .font(.fluidSystem(size: 15, weight: .bold))
+ .foregroundStyle(.white.opacity(0.72))
+ .frame(width: 34, height: 34)
+ .background(Circle().fill(Color.white.opacity(0.075)))
+ .contentShape(Circle())
+ }
+ .buttonStyle(.plain)
+ .focusable(false)
+ .help("Return to \(self.appName)")
+
+ Image(nsImage: self.appIcon)
+ .resizable()
+ .frame(width: 34, height: 34)
+ .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
+
+ Text(self.appName)
- .font(.system(size: 16, weight: .semibold))
++ .font(.fluidSystem(size: 16, weight: .semibold))
+ .foregroundStyle(.white.opacity(0.92))
+
+ Spacer()
+
+ Image(systemName: "line.3.horizontal")
- .font(.system(size: 14, weight: .bold))
++ .font(.fluidSystem(size: 14, weight: .bold))
+ .foregroundStyle(.white.opacity(0.38))
+ }
+ .padding(.horizontal, 16)
+ .frame(maxWidth: .infinity)
+ .frame(height: 56)
+ .background(
+ RoundedRectangle(cornerRadius: 10, style: .continuous)
+ .fill(Color.white.opacity(self.isTokenHovered ? 0.095 : 0.055))
+ .overlay(
+ RoundedRectangle(cornerRadius: 10, style: .continuous)
+ .stroke(Color.white.opacity(self.isTokenHovered ? 0.16 : 0.08), lineWidth: 1)
+ )
+ )
+ .contentShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
+ .onHover { isHovered in
+ if self.reduceMotion {
+ self.isTokenHovered = isHovered
+ } else {
+ withAnimation(.easeOut(duration: 0.14)) {
+ self.isTokenHovered = isHovered
+ }
+ }
+ }
+ .onDrag {
+ NSItemProvider(object: self.appURL as NSURL)
+ }
+ .accessibilityLabel("Drag \(self.appName) into the list")
+ }
+ .padding(.horizontal, 20)
+ .padding(.vertical, 16)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .background(
+ RoundedRectangle(cornerRadius: 18, style: .continuous)
+ .fill(Color(red: 0.11, green: 0.11, blue: 0.13).opacity(0.96))
+ .overlay(
+ RoundedRectangle(cornerRadius: 18, style: .continuous)
+ .stroke(Color.white.opacity(0.14), lineWidth: 1)
+ )
+ )
+ .onAppear {
+ guard !self.reduceMotion else { return }
+ self.isArrowRaised = true
+ }
+ }
+ }
diff --cc Sources/Fluid/fluidApp.swift
index 4929fa45,cc232fde..11f17e75
--- a/Sources/Fluid/fluidApp.swift
+++ b/Sources/Fluid/fluidApp.swift
@@@ -15,22 -15,24 +15,25 @@@ struct FluidApp: App
@ObservedObject private var settings = SettingsStore.shared
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
- init() {
- // Use the shared singleton instance
- _appServices = StateObject(wrappedValue: AppServices.shared)
- }
-
var body: some Scene {
WindowGroup(id: "main") {
- AdaptiveAppTheme(accent: self.settings.accentColor) {
- ContentView()
- .environmentObject(self.menuBarManager)
- .environmentObject(self.appServices)
- }
+ #if DEBUG
+ if MeetingExternalReferenceTrialAGate.autorunEnabled(environment: ProcessInfo.processInfo.environment)
+ || MeetingSCKPairedDiagnosticGate.autorunEnabled()
+ || MeetingStage05EvidenceAutorun.requested()
+ || ProcessInfo.processInfo.environment["FLUIDVOICE_MIC_PHASE1"] != nil
+ || ProcessInfo.processInfo.environment["FLUIDVOICE_VPIO_ACOUSTIC"] == "1"
+ {
+ Color.clear
+ } else {
+ self.applicationContent
+ }
+ #else
+ self.applicationContent
+ #endif
}
.defaultSize(width: 1000, height: 700)
+ .windowStyle(.hiddenTitleBar)
.commands {
CommandGroup(replacing: .appSettings) {
Button("Settings...") {