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
feat(meeting): survive display sleep and recover from capture interruptions
Shreeraman A Ke72adb502c88
diff --git a/Fluid.xcodeproj/project.pbxproj b/Fluid.xcodeproj/project.pbxprojindex cdd8e7a2..9bcccdbb 100644--- a/Fluid.xcodeproj/project.pbxproj+++ b/Fluid.xcodeproj/project.pbxproj@@ -27,6 +27,7 @@A62300000000000000000002 /* AudioBufferConverterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A62300000000000000000001 /* AudioBufferConverterTests.swift */; };D1A600000000000000000202 /* SpeakerTurnMergingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1A600000000000000000201 /* SpeakerTurnMergingTests.swift */; };F1BD00000000000000000002 /* StripThinkingTagsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1BD00000000000000000001 /* StripThinkingTagsTests.swift */; };+ D1A600000000000000000204 /* MeetingWindowSelectorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1A600000000000000000203 /* MeetingWindowSelectorTests.swift */; };C0DE63600000000000000002 /* AudioEngineRetirementDrainTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE63600000000000000001 /* AudioEngineRetirementDrainTests.swift */; };DA7100020000000000000002 /* DirectAudioReliabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA7100010000000000000001 /* DirectAudioReliabilityTests.swift */; };DA7200020000000000000002 /* AudioHardwareRecoveryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA7200010000000000000001 /* AudioHardwareRecoveryTests.swift */; };@@ -78,6 +79,7 @@A62300000000000000000001 /* AudioBufferConverterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioBufferConverterTests.swift; sourceTree = "<group>"; };D1A600000000000000000201 /* SpeakerTurnMergingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpeakerTurnMergingTests.swift; sourceTree = "<group>"; };F1BD00000000000000000001 /* StripThinkingTagsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StripThinkingTagsTests.swift; sourceTree = "<group>"; };+ D1A600000000000000000203 /* MeetingWindowSelectorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingWindowSelectorTests.swift; sourceTree = "<group>"; };C0DE63600000000000000001 /* AudioEngineRetirementDrainTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioEngineRetirementDrainTests.swift; sourceTree = "<group>"; };DA7100010000000000000001 /* DirectAudioReliabilityTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectAudioReliabilityTests.swift; sourceTree = "<group>"; };DA7200010000000000000001 /* AudioHardwareRecoveryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioHardwareRecoveryTests.swift; sourceTree = "<group>"; };@@ -177,6 +179,7 @@A62300000000000000000001 /* AudioBufferConverterTests.swift */,D1A600000000000000000201 /* SpeakerTurnMergingTests.swift */,F1BD00000000000000000001 /* StripThinkingTagsTests.swift */,+ D1A600000000000000000203 /* MeetingWindowSelectorTests.swift */,C0DE63600000000000000001 /* AudioEngineRetirementDrainTests.swift */,DA7100010000000000000001 /* DirectAudioReliabilityTests.swift */,DA7200010000000000000001 /* AudioHardwareRecoveryTests.swift */,@@ -361,6 +364,7 @@A62300000000000000000002 /* AudioBufferConverterTests.swift in Sources */,D1A600000000000000000202 /* SpeakerTurnMergingTests.swift in Sources */,F1BD00000000000000000002 /* StripThinkingTagsTests.swift in Sources */,+ D1A600000000000000000204 /* MeetingWindowSelectorTests.swift in Sources */,C0DE63600000000000000002 /* AudioEngineRetirementDrainTests.swift in Sources */,DA7100020000000000000002 /* DirectAudioReliabilityTests.swift in Sources */,DA7200020000000000000002 /* AudioHardwareRecoveryTests.swift in Sources */,diff --git a/MEETING_TRANSCRIPTION_PRD.md b/MEETING_TRANSCRIPTION_PRD.mdindex e8a86454..6e19cdda 100644--- a/MEETING_TRANSCRIPTION_PRD.md+++ b/MEETING_TRANSCRIPTION_PRD.md@@ -158,7 +158,7 @@ Goal: prove the complete path before polishing secondary automation.#### Milestone 1 test and review gate- [ ] **[MUST · M1] M1-TEST-001** Deterministic tests cover legal state transitions, concurrent/repeated Start and Stop, stale-generation callbacks, and exactly one finalization/processing job.-- [ ] **[MUST · M1] M1-TEST-002** A real online-call capture proves separate non-empty application/system and microphone files with timestamps inside one session manifest.+- [ ] **[MUST · M1] M1-TEST-002** A real online-call capture proves separate non-empty application/system and microphone files with timestamps inside one session manifest. Dual-track separation, gap, drift, and skew figures are measured in Appendix A; this item still needs the same proof through the app's own writer and manifest, not only the harness.- [ ] **[MUST · M1] M1-TEST-003** A real in-room capture proves microphone-only recording does not request Screen/System Audio permission solely for that mode.- [ ] **[MUST · M1] M1-TEST-004** Stop proves the complete offline English path: finalized audio → transcription/diarization → timestamped canvas result.- [ ] **[MUST · M1] M1-TEST-005** Apple Silicon fixtures cover remote speaker separation, clean confirmed personal-mic **You**, and ambiguous/leaked microphone speech remaining unknown.@@ -458,6 +458,17 @@ flowchart TD- [ ] **[OPTIONAL · V1] CAP-023** Add timestamp/acoustic duplicate suppression only after evaluation proves it does not remove real overlapping speech.- [ ] **[MUST · V1] CAP-026** Ask whether the selected online-call microphone is personal or shared. Only a confirmed personal mic may support the default **You** attribution.+### 11.5 Capture API and filter scope++Decided 2026-08-10 from measured evidence on macOS 26.5.1; see Appendix A.++- [ ] **[MUST · FOUNDATION] CAP-027 — ScreenCaptureKit is the V1 capture API.** A one-hour dual-track soak recorded zero gaps, zero backwards timestamps, zero format changes, ~14 ppm clock drift, and a constant 87.6 ms inter-track skew. FB13847291 (`EXC_BAD_ACCESS` on long audio-only capture) did not reproduce. Reliability does not justify migrating to Core Audio process taps.+- [ ] **[MUST · FOUNDATION] CAP-028 — Scope the content filter to a window, never a display.** `SCContentFilter(display:...)` terminates with `SCStreamErrorDomain -3815` on any display power transition, including a one-second blackout, and never recovers. `SCContentFilter(desktopIndependentWindow:)` survives the same event with audio delivery uninterrupted, and still scopes audio to the owning application.+- [ ] **[MUST · V1] CAP-029 — Pin the capture window at Start.** Resolve the selected meeting application's main window once when recording begins and hold it for the session. Never follow keyboard focus; the user will switch apps mid-meeting.+- [ ] **[MUST · V1] CAP-030 — Filter the window candidate list.** `SCShareableContent.windows` includes WindowServer backstops, Dock wallpaper surfaces, menubar strips, and untitled entries. Require an owning application, a non-empty title, a minimum size, and `isOnScreen`. Selecting an unowned system window aborts the process.+- [ ] **[MUST · V1] CAP-031 — Hold a display-sleep power assertion while recording.** Take `kIOPMAssertionTypePreventUserIdleDisplaySleep` for the capture duration and release it on stop and on termination. Do not rely on the implicit assertion Core Audio takes; the system revokes it mid-session.+- [ ] **[MUST · V1] CAP-032 — Treat window loss as a first-class capture risk.** Window scoping trades a display dependency for a window dependency. A browser-hosted meeting binds to the browser window, which the user may close or recreate mid-call. This is why REL-015 is mandatory.+---## 12. Offline English transcription pipeline@@ -579,6 +590,12 @@ flowchart TD- First use: the same context with **Set up** and **Not now**.- Include the detected app icon without implying FluidVoice has already begun capture.- [ ] **[MUST · M4] DETECT-015** Provide a keyboard-complete alternative through the FluidVoice menu-bar menu or Meeting tab. The nonactivating HUD may expose pointer and VoiceOver actions without pretending it accepts normal keyboard focus.+- [ ] **[MUST · M4] DETECT-016 — Primary signal is bidirectional per-process audio, and it costs no permission.** Poll `kAudioHardwarePropertyProcessObjectList` for `kAudioProcessPropertyIsRunningInput` and `IsRunningOutput`. A known meeting application holding both concurrently for 10–15 s is a call. Input alone is dictation; output alone is media. Verified permission-free on macOS 26.5.1. Poll rather than listen: the change listeners for these properties are reported not to fire.+- [ ] **[MUST · M4] DETECT-017 — Exclude `com.apple.replayd` and FluidVoice's own bundles from detection.** ScreenCaptureKit microphone capture is attributed to `replayd`, not to the requesting process, so an unguarded detector fires on FluidVoice's own meeting recording.+- [ ] **[MUST · M4] DETECT-018 — Gate the audio signal on process identity.** FluidVoice ships dictation, so an audio-activity signal without an application allowlist will fire on the user's own voice notes. Bidirectionality already excludes that case; do not loosen it without a replacement guard.+- [ ] **[MUST · M4] DETECT-019 — Do not require a calendar match.** Calendar-only detection structurally misses Slack huddles, unscheduled calls, and meetings that start late. A current event with a parsed conferencing URL raises confidence and supplies a default title, but its absence must never veto detection.+- [ ] **[OPTIONAL · M4] DETECT-020 — Handle the muted-mic case as lower confidence.** Participants who join muted produce no input signal. Fall back to a known meeting application with output audio plus a matching window title, camera in use, or an active calendar event, and label the match as weaker rather than folding it into the primary path.+- [ ] **[MUST · M4] DETECT-021 — Prefer Accessibility over Screen Recording for window titles.** `CGWindowListCopyWindowInfo` omits `kCGWindowName` without the Screen Recording grant. `AXUIElement` returns the same information for a cheaper permission.---@@ -641,7 +658,7 @@ flowchart TD- [ ] **[MUST · V1] REL-001** On launch, scan sessions left in recording/stopping/processing states.- [ ] **[MUST · V1] REL-002** Salvage finalized chunks, mark unexpected capture termination as interrupted, and never auto-delete evidence.- [ ] **[MUST · V1] REL-003** Offer **Resume Processing**, **Reveal/Export Audio**, and **Delete** for recoverable sessions.-- [ ] **[MUST · V1] REL-004** Handle force quit, power loss, sleep/wake, selected-app exit/relaunch, permission revocation, and disk exhaustion.+- [ ] **[MUST · V1] REL-004** Handle force quit, power loss, sleep/wake, selected-app exit/relaunch, permission revocation, and disk exhaustion. **Display power transitions are a separate and far more frequent event than system sleep** and must be handled explicitly: idle display sleep, lid close, screen lock, monitor input switch, display unplug, and resolution change, each occurring mid-capture.- [ ] **[MUST · V1] REL-005** Handle microphone unplug/reconnect, Bluetooth route changes, and sample-rate changes without corrupting prior chunks.- [ ] **[MUST · V1] REL-006** Handle waiting room → meeting, breakout room/window, browser refresh, and source subprocess changes without silent loss.- [ ] **[MUST · V1] REL-007** Surface independent last-sample time, level, discontinuity, and failure for each track.@@ -652,6 +669,9 @@ flowchart TD- [ ] **[MUST · V1] REL-012** Start, Stop, menu Stop, Quit, and late ScreenCaptureKit/writer callbacks are idempotent and generation-checked; repeated Stop enters disabled **Stopping…** and creates exactly one finalization/processing job.- [ ] **[MUST · V1] REL-013** Critical-low-disk behavior safely stops and finalizes capture before exhausting the reserve, then notifies the user without deleting audio.- [ ] **[MUST · V1] REL-014** Processing settings/provider changes cannot mutate an in-flight attempt; a deliberate retry creates a new pinned attempt while preserving prior checkpoints/results.+- [ ] **[MUST · V1] REL-015 — Capture interruption is recoverable, not terminal.** `SCStreamDelegate.stream(_:didStopWithError:)` currently ends the session. It must instead rebuild the stream and resume on a new chunk boundary, with bounded retries and honest degraded state. A transient loss costs a chunk boundary, never a meeting.+- [ ] **[MUST · V1] REL-016 — Do not trust the stop callback alone.** Run a buffer-silence watchdog per track and restart proactively on stall. The delegate callback is not guaranteed to fire, and is reported to arrive with an invalid error object in some teardown races.+- [ ] **[MUST · V1] REL-017 — Screen Recording consent can lapse mid-recording.** macOS re-confirms the grant on a roughly monthly cadence, so revocation during an active capture will eventually happen. Treat it as a typed interruption that preserves all finalized audio and explains what to do, not as a generic failure.---@@ -717,6 +737,9 @@ flowchart TD- [ ] **[MUST · V1] TEST-FAIL-004** Window close, tab navigation, and menu-bar-only use do not stop recording.- [ ] **[MUST · V1] TEST-FAIL-005** Permission lifecycle covers first grant, denial, return from System Settings, revocation, regrant, and relaunch for microphone and Screen/System Audio independently.- [ ] **[MUST · V1] TEST-FAIL-006** Duplicate Start/Stop/menu/Quit actions and stale callbacks produce exactly one session, one finalized manifest, and one queued processing job.+- [ ] **[MUST · V1] TEST-FAIL-007 — Display power transitions during capture.** Capture must survive a forced `pmset displaysleepnow`, an idle display sleep, a screen lock, and a monitor input switch. Each is verified by continued buffer delivery on both tracks, not merely by the absence of an error.+- [ ] **[MUST · V1] TEST-FAIL-008 — Capture-window loss during capture.** Close and recreate the captured application's window mid-session. Recording either continues or resumes on a new chunk boundary; all finalized chunks survive.+- [ ] **[MUST · V1] TEST-FAIL-009 — One-hour stability run.** A full-hour dual-track capture reports zero gaps, zero backwards timestamps, zero format changes, and drift within the TEST-BUDGET-002 limits.### 21.4 Speaker and identity matrix@@ -811,6 +834,24 @@ These do not block writing the PRD. They must be resolved before their associate- [ ] **[MUST · V1] RISK-010** Meeting recovery cannot depend on the existing graceful shutdown timeout.- [ ] **[MUST · M4] RISK-011** Active-speaker visuals are brittle across layout changes, sharing, overlap, and minimized windows.- [ ] **[MUST · M3] RISK-012** Incorrect profile enrollment compounds future errors; only confirmed clean speech may update a profile.+- [ ] **[MUST · V1] RISK-013 — A display-scoped ScreenCaptureKit filter dies on any display power transition.** Measured, not theoretical: a one-second display blackout terminates the stream with `-3815` and it never recovers. The user sees the display return and the meeting continue while the transcript has silently stopped. Mitigated by CAP-028 and REL-015.+- [ ] **[MUST · V1] RISK-014 — The two SCK audio outputs are not on one clock.** `.audio` and `.microphone` arrive with different format descriptions (measured 48 kHz stereo versus 48 kHz mono) and independent presentation-timestamp epochs, offset by a per-session constant (measured 87–98 ms). Feeding both into one writer corrupts the container. Use one writer per track and take each track's own first-buffer timestamp as its origin.+- [ ] **[OPTIONAL · SECURITY] RISK-015 — Screen Recording is a heavy consent ask for an audio feature.** The system dialog says FluidVoice can record screen contents, and macOS re-confirms roughly monthly. Core Audio process taps use `NSAudioCaptureUsageDescription` instead, with no periodic re-consent, but require solving per-process audio attribution for multi-process apps such as Chrome, Zoom, and Electron clients. Revisit after the capture layer is stable; not a V1 blocker.++---++## Appendix A — Capture reliability measurements (2026-08-10)++Host: macOS 26.5.1 (25F80), Apple Silicon. Harness mirrored the `1.6.8/meeting-m1` `SCStreamConfiguration` exactly.++| Experiment | Configuration | Result |+|---|---|---|+| 60-minute soak | Display-scoped filter | Terminated at 20:18 with `-3815` when the display slept. Screen lock excluded: lock delay was 300 s and the session stayed unlocked. |+| 60-minute soak | Display-scoped filter, display held awake | Ran the full 3600 s. Zero gaps, zero backwards timestamps, zero format changes, ~14 ppm drift, 30 ms track differential over the hour, constant 87.6 ms skew. FB13847291 did not reproduce. |+| Trigger isolation | Display-scoped filter, forced `displaysleepnow` | Died within one second of display-off and did not recover when the display returned one second later. |+| Filter comparison | Window-scoped filter, forced `displaysleepnow`, three runs | Survived every time. Audio delivery continuous through the blackout. App-track silence 2.8% against an emitting app, 100% against a silent app, confirming audio remains scoped to the owning application. |++Untested, and worth closing before shipping: whether a window-scoped filter survives a deliberate screen lock, and its behavior when the captured window is closed and recreated mid-session.---diff --git a/Sources/Fluid/Services/Meeting/MeetingAudioChunkWriter.swift b/Sources/Fluid/Services/Meeting/MeetingAudioChunkWriter.swiftindex f45c2733..93e4e2e4 100644--- a/Sources/Fluid/Services/Meeting/MeetingAudioChunkWriter.swift+++ b/Sources/Fluid/Services/Meeting/MeetingAudioChunkWriter.swift@@ -61,6 +61,10 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {private var dropReportScheduled = falseprivate var lastHealthEmission = Date.distantPastprivate var lastLevelMeasurement = Date.distantPast+ private var silenceAccumulatedSeconds: Double = 0++ /// Peak amplitude (0...1) below which a buffer counts as silent for watchdog purposes.+ private static let silenceAmplitudeThreshold: Float = 0.0001init(track: MeetingAudioTrack,@@ -176,6 +180,7 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {let gap = CMTimeGetSeconds(presentationTime - activeChunk.end)if elapsed >= self.chunkDuration || backwards || gap > 0.5 {if backwards || gap > 0.5 {+ self.silenceAccumulatedSeconds = 0let kind: MeetingInterruptionKind = backwards ? .clockDiscontinuity : .sourceLostself.activeChunk?.discontinuities.append(MeetingAudioDiscontinuity(kind: kind,@@ -210,9 +215,18 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {self.track.health.lastPresentationTime = Self.mediaTime(presentationTime)let now = Date()self.track.health.lastSampleAt = now++ let peak = Self.peakAmplitude(sampleBuffer)+ if let peak {+ self.silenceAccumulatedSeconds = peak < Self.silenceAmplitudeThreshold+ ? self.silenceAccumulatedSeconds + max(0, CMTimeGetSeconds(duration))+ : 0+ }+ self.track.health.silentForSeconds = self.silenceAccumulatedSeconds+if now.timeIntervalSince(self.lastLevelMeasurement) >= 0.1 {self.lastLevelMeasurement = now- self.track.health.level = Self.normalizedLevel(sampleBuffer)+ self.track.health.level = Self.normalizedLevel(fromPeak: peak ?? 0)}self.track.health.detail = nilself.emitHealthIfNeeded()@@ -476,13 +490,19 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {return hasher.finalize().map { String(format: "%02x", $0) }.joined()}- private static func normalizedLevel(_ sampleBuffer: CMSampleBuffer) -> Float {+ private static func normalizedLevel(fromPeak peak: Float) -> Float {+ guard peak > 0 else { return 0 }+ let decibels = 20 * log10f(min(1, peak))+ return max(0, min(1, (decibels + 60) / 60))+ }++ private static func peakAmplitude(_ sampleBuffer: CMSampleBuffer) -> Float? {guard let formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer),let asbd = CMAudioFormatDescriptionGetStreamBasicDescription(formatDescription)?.pointee,asbd.mFormatID == kAudioFormatLinearPCM,asbd.mBitsPerChannel == 32,asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0- else { return 0 }+ else { return nil }var requiredSize = 0let sizeStatus = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(@@ -495,7 +515,7 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {flags: 0,blockBufferOut: nil)- guard sizeStatus == noErr, requiredSize > 0 else { return 0 }+ guard sizeStatus == noErr, requiredSize > 0 else { return nil }let rawBuffer = UnsafeMutableRawPointer.allocate(byteCount: requiredSize,@@ -514,7 +534,7 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {flags: UInt32(kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment),blockBufferOut: &retainedBlockBuffer)- guard status == noErr else { return 0 }+ guard status == noErr else { return nil }var peak: Float = 0for buffer in UnsafeMutableAudioBufferListPointer(audioBufferList) {@@ -529,8 +549,6 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {index += stride}}- guard peak > 0 else { return 0 }- let decibels = 20 * log10f(min(1, peak))- return max(0, min(1, (decibels + 60) / 60))+ return peak}}diff --git a/Sources/Fluid/Services/Meeting/MeetingCaptureEngine.swift b/Sources/Fluid/Services/Meeting/MeetingCaptureEngine.swiftindex d6acf263..57f77dfd 100644--- a/Sources/Fluid/Services/Meeting/MeetingCaptureEngine.swift+++ b/Sources/Fluid/Services/Meeting/MeetingCaptureEngine.swift@@ -2,6 +2,7 @@ import AppKit@preconcurrency import AVFoundationimport CoreMediaimport Foundation+import IOKit.pwr_mgtimport ScreenCaptureKitnonisolated protocol MeetingCaptureControlling: Sendable {@@ -26,6 +27,8 @@ actor MeetingCaptureEngine: MeetingCaptureControlling {private var activeCapture: ActiveCapture?private var startingSessionID: MeetingSessionID?private var stopTask: Task<MeetingCaptureStopResult, Error>?+ private var displaySleepAssertionID: IOPMAssertionID?+ private var terminating = falsefunc start(session: MeetingSession,@@ -86,12 +89,23 @@ actor MeetingCaptureEngine: MeetingCaptureControlling {throw error}+ // The actor is reentrant across the awaits above; termination may have arrived meanwhile.+ if self.terminating {+ try? await runtime.stop()+ _ = await Self.stopWriters(writers)+ throw MeetingCaptureError.captureStartFailed("The app is shutting down.")+ }+ self.displaySleepAssertionID = Self.acquireDisplaySleepAssertion()self.activeCapture = ActiveCapture(sessionID: session.id,runtime: runtime,writers: writers)- return MeetingCaptureStartResult(tracks: tracks, firstPresentationTime: nil)+ return MeetingCaptureStartResult(+ tracks: tracks,+ firstPresentationTime: nil,+ captureScope: runtime.captureScope+ )}func stop(sessionID: MeetingSessionID) async throws -> MeetingCaptureStopResult {@@ -128,19 +142,42 @@ actor MeetingCaptureEngine: MeetingCaptureControlling {let result = try await task.valueself.activeCapture = nilself.stopTask = nil+ self.releaseDisplaySleepAssertion()return result} catch {self.activeCapture = nilself.stopTask = nil+ self.releaseDisplaySleepAssertion()throw error}}func shutdownForTermination() async {- guard let sessionID = self.activeCapture?.sessionID else { return }+ self.terminating = true+ guard let sessionID = self.activeCapture?.sessionID else {+ self.releaseDisplaySleepAssertion()+ return+ }_ = try? await self.stop(sessionID: sessionID)}+ private func releaseDisplaySleepAssertion() {+ guard let assertionID = self.displaySleepAssertionID else { return }+ self.displaySleepAssertionID = nil+ IOPMAssertionRelease(assertionID)+ }++ private nonisolated static func acquireDisplaySleepAssertion() -> IOPMAssertionID? {+ var assertionID: IOPMAssertionID = 0+ let result = IOPMAssertionCreateWithName(+ kIOPMAssertionTypePreventUserIdleDisplaySleep as CFString,+ IOPMAssertionLevel(kIOPMAssertionLevelOn),+ "FluidVoice meeting recording" as CFString,+ &assertionID+ )+ return result == kIOReturnSuccess ? assertionID : nil+ }+private nonisolated static func stopWriters(_ writers: [MeetingAudioChunkWriter]) async -> [MeetingAudioTrack] {await withTaskGroup(of: MeetingAudioTrack.self, returning: [MeetingAudioTrack].self) { group infor writer in writers {@@ -209,29 +246,93 @@ actor MeetingCaptureEngine: MeetingCaptureControlling {}private nonisolated protocol MeetingCaptureRuntime: AnyObject, Sendable {+ /// The ScreenCaptureKit scope actually in effect. `nil` for runtimes with no SCK stream.+ var captureScope: MeetingCaptureScope? { get }func start() async throwsfunc stop() async throws}+/// A candidate window for `.window`-scoped capture, in a shape independent of ScreenCaptureKit+/// so the selection logic can be unit tested with plain values.+nonisolated struct MeetingWindowCandidate: Sendable, Equatable {+ var windowID: UInt32+ var title: String?+ var frame: CGRect+ var layer: Int+ /// Index within `SCShareableContent.windows`, which is ordered front-to-back.+ var zOrderIndex: Int+}++/// Pure selection logic for Phase 1c window-scoped capture: excludes panels/menubar items+/// (non-zero layer) and slivers (sub-200x100), then ranks titled-frontmost-largest-stablest.+nonisolated enum MeetingWindowSelector {+ static let minimumWidth: CGFloat = 200+ static let minimumHeight: CGFloat = 100++ static func selectWindow(from candidates: [MeetingWindowCandidate]) -> MeetingWindowCandidate? {+ candidates+ .filter { $0.layer == 0 && $0.frame.width >= self.minimumWidth && $0.frame.height >= self.minimumHeight }+ .sorted(by: self.isRanked)+ .first+ }++ /// True when `lhs` should be preferred over `rhs`: non-empty title, then frontmost+ /// (lower z-order), then larger area, then windowID ascending as the stable tiebreak.+ private static func isRanked(_ lhs: MeetingWindowCandidate, _ rhs: MeetingWindowCandidate) -> Bool {+ let lhsHasTitle = lhs.title?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false+ let rhsHasTitle = rhs.title?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false+ if lhsHasTitle != rhsHasTitle { return lhsHasTitle }+ if lhs.zOrderIndex != rhs.zOrderIndex { return lhs.zOrderIndex < rhs.zOrderIndex }+ let lhsArea = lhs.frame.width * lhs.frame.height+ let rhsArea = rhs.frame.width * rhs.frame.height+ if lhsArea != rhsArea { return lhsArea > rhsArea }+ return lhs.windowID < rhs.windowID+ }+}+private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCaptureRuntime, SCStreamOutput, SCStreamDelegate,@unchecked Sendable{- private let stream: SCStream+ private struct BuiltStream {+ let stream: SCStream+ let delegateProxy: ScreenCaptureRuntimeDelegateProxy+ let scope: MeetingCaptureScope+ }++ /// Delays before each of the (up to 3) rebuild attempts following an unexpected stream stop.+ private static let rebuildDelays: [TimeInterval] = [0.5, 1.0, 2.0]++ private let application: MeetingApplicationIdentity+ private let microphone: MeetingMicrophoneIdentityprivate let applicationWriter: MeetingAudioChunkWriterprivate let microphoneWriter: MeetingAudioChunkWriterprivate let eventHandler: @Sendable (MeetingCaptureEvent) -> Voidprivate let stateLock = NSLock()+ private var stream: SCStream+ private var scope: MeetingCaptureScopeprivate var delegateProxy: ScreenCaptureRuntimeDelegateProxy?private var stopping = false- private var unexpectedStopReported = false+ private var rebuilding = false+ private var pendingStream: SCStream?+ private var pendingStreamFailed = false++ var captureScope: MeetingCaptureScope? {+ self.stateLock.withLock { self.scope }+ }private init(stream: SCStream,+ scope: MeetingCaptureScope,+ application: MeetingApplicationIdentity,+ microphone: MeetingMicrophoneIdentity,applicationWriter: MeetingAudioChunkWriter,microphoneWriter: MeetingAudioChunkWriter,eventHandler: @escaping @Sendable (MeetingCaptureEvent) -> Void) {self.stream = stream+ self.scope = scope+ self.application = application+ self.microphone = microphoneself.applicationWriter = applicationWriterself.microphoneWriter = microphoneWriterself.eventHandler = eventHandler@@ -245,30 +346,58 @@ private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCamicrophoneWriter: MeetingAudioChunkWriter,eventHandler: @escaping @Sendable (MeetingCaptureEvent) -> Void) async throws -> ScreenCaptureMeetingRuntime {+ let built = try await Self.buildStream(application: application, microphone: microphone)+ let runtime = ScreenCaptureMeetingRuntime(+ stream: built.stream,+ scope: built.scope,+ application: application,+ microphone: microphone,+ applicationWriter: applicationWriter,+ microphoneWriter: microphoneWriter,+ eventHandler: eventHandler+ )+ built.delegateProxy.owner = runtime+ runtime.delegateProxy = built.delegateProxy+ try runtime.attachOutputs(to: built.stream)+ return runtime+ }++ /// Resolves the shareable content, filter, configuration and stream. Re-invoked both for the+ /// initial `make` and for every rebuild attempt after an unexpected stream stop.+ private static func buildStream(+ application: MeetingApplicationIdentity,+ microphone: MeetingMicrophoneIdentity+ ) async throws -> BuiltStream {let content: SCShareableContentdo {content = try await SCShareableContent.current} catch {throw MeetingCaptureError.screenCapturePermissionDenied(error.localizedDescription)}- guard let runningApplication = content.applications.first(where: { candidate in- if let processID = application.processID {- return candidate.processID == processID- }- return candidate.bundleIdentifier == application.bundleIdentifier+ let byProcessID = application.processID.flatMap { processID in+ content.applications.first(where: { $0.processID == processID })+ }+ // The saved PID goes stale when the app relaunches; the bundle match keeps rebuilds working.+ guard let runningApplication = byProcessID ?? content.applications.first(where: {+ $0.bundleIdentifier == application.bundleIdentifier}) else {throw MeetingCaptureError.applicationUnavailable(application.displayName)}- let display = application.displayID.flatMap { displayID in- content.displays.first(where: { $0.displayID == displayID })- } ?? content.displays.first- guard let display else { throw MeetingCaptureError.noCaptureDisplay }- let filter = SCContentFilter(- display: display,- including: [runningApplication],- exceptingWindows: []- )+ let filter: SCContentFilter+ let scope: MeetingCaptureScope+ if let window = Self.selectWindow(for: runningApplication, in: content) {+ filter = SCContentFilter(desktopIndependentWindow: window)+ scope = .window+ } else {+ let display = application.displayID.flatMap { displayID in+ content.displays.first(where: { $0.displayID == displayID })+ } ?? content.displays.first+ guard let display else { throw MeetingCaptureError.noCaptureDisplay }+ filter = SCContentFilter(display: display, including: [runningApplication], exceptingWindows: [])+ scope = .display+ }+let configuration = SCStreamConfiguration()configuration.width = 2configuration.height = 2@@ -282,18 +411,37 @@ private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCaconfiguration.captureMicrophone = trueconfiguration.microphoneCaptureDeviceID = microphone.captureDeviceID- let placeholder = ScreenCaptureRuntimeDelegateProxy()- let stream = SCStream(filter: filter, configuration: configuration, delegate: placeholder)- let runtime = ScreenCaptureMeetingRuntime(- stream: stream,- applicationWriter: applicationWriter,- microphoneWriter: microphoneWriter,- eventHandler: eventHandler- )- placeholder.owner = runtime- runtime.delegateProxy = placeholder+ let delegateProxy = ScreenCaptureRuntimeDelegateProxy()+ let stream = SCStream(filter: filter, configuration: configuration, delegate: delegateProxy)+ return BuiltStream(stream: stream, delegateProxy: delegateProxy, scope: scope)+ }++ /// Maps the app's own windows to selection candidates and picks one via `MeetingWindowSelector`.+ /// Deliberately does not require `isOnScreen` (unreliable for other-Space/hidden windows).+ /// Window titles are PII and must never be logged or persisted.+ private static func selectWindow(+ for runningApplication: SCRunningApplication,+ in content: SCShareableContent+ ) -> SCWindow? {+ let ownedWindows = content.windows.enumerated().filter { _, window in+ window.owningApplication?.processID == runningApplication.processID+ }+ let candidates = ownedWindows.map { index, window in+ MeetingWindowCandidate(+ windowID: window.windowID,+ title: window.title,+ frame: window.frame,+ layer: window.windowLayer,+ zOrderIndex: index+ )+ }+ guard let winner = MeetingWindowSelector.selectWindow(from: candidates) else { return nil }+ return ownedWindows.first(where: { _, window in window.windowID == winner.windowID })?.element+ }++ private func attachOutputs(to stream: SCStream) throws {try stream.addStreamOutput(- runtime,+ self,type: .audio,sampleHandlerQueue: DispatchQueue(label: "com.fluidvoice.meeting.screencapture.application",@@ -301,19 +449,19 @@ private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCa))try stream.addStreamOutput(- runtime,+ self,type: .microphone,sampleHandlerQueue: DispatchQueue(label: "com.fluidvoice.meeting.screencapture.microphone",qos: .userInteractive))- return runtime}func start() async throws {+ let currentStream = self.stateLock.withLock { self.stream }do {- try await self.stream.startCapture()+ try await currentStream.startCapture()} catch {throw MeetingCaptureError.captureStartFailed(error.localizedDescription)}@@ -321,9 +469,12 @@ private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCafunc stop() async throws {self.markStopping()+ let (currentStream, streamAlreadyDead) = self.stateLock.withLock { (self.stream, self.rebuilding) }+ // Mid-rebuild the current stream already stopped on its own; stopCapture would only time out.+ guard !streamAlreadyDead else { return }let result = await withCheckedContinuation { continuation inlet completion = MeetingOneShotCompletion(continuation)- self.stream.stopCapture { error in+ currentStream.stopCapture { error inif let error {completion.resume(.failure(error.localizedDescription))} else {@@ -340,9 +491,7 @@ private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCa}private func markStopping() {- self.stateLock.lock()- self.stopping = true- self.stateLock.unlock()+ self.stateLock.withLock { self.stopping = true }}func stream(@@ -350,9 +499,7 @@ private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCadidOutputSampleBuffer sampleBuffer: CMSampleBuffer,of outputType: SCStreamOutputType) {- self.stateLock.lock()- let shouldAccept = !self.stopping- self.stateLock.unlock()+ let shouldAccept = self.stateLock.withLock { !self.stopping && stream === self.stream }guard shouldAccept else { return }switch outputType {case .audio:@@ -366,20 +513,91 @@ private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCa}}- func handleStreamStop(error: Error) {- self.stateLock.lock()- let wasStopping = self.stopping- let shouldReport = !wasStopping && !self.unexpectedStopReported- if shouldReport {- self.unexpectedStopReported = true+ func handleStreamStop(_ stoppedStream: SCStream, error: Error) {+ let shouldRebuild = self.stateLock.withLock { () -> Bool in+ if stoppedStream === self.pendingStream {+ self.pendingStreamFailed = true+ return false+ }+ guard !self.stopping, !self.rebuilding, stoppedStream === self.stream else { return false }+ self.rebuilding = true+ return true+ }+ guard shouldRebuild else { return }+ self.eventHandler(.interrupted(kind: .sourceLost, trackID: nil, detail: error.localizedDescription))+ self.runRebuildLoop(triggeringError: error)+ }++ /// Attempts up to `rebuildDelays.count` rebuilds of the stream, checking `stopping` before and+ /// after each delay so a concurrent user-initiated `stop()` aborts the loop promptly. On success+ /// the stream reference is swapped under the lock and writers keep running untouched (they rotate+ /// chunks on the PTS gap on their own). On exhaustion this reports the terminal failure exactly as+ /// the non-recoverable path did before this change.+ private func runRebuildLoop(triggeringError: Error) {+ Task { [weak self] in+ guard let self else { return }+ var lastError = triggeringError+ for delay in Self.rebuildDelays {+ if self.stateLock.withLock({ self.stopping }) { self.finishRebuilding(); return }+ try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))+ if self.stateLock.withLock({ self.stopping }) { self.finishRebuilding(); return }++ do {+ let built = try await Self.buildStream(application: self.application, microphone: self.microphone)+ if self.stateLock.withLock({ self.stopping }) { self.finishRebuilding(); return }+ built.delegateProxy.owner = self+ try self.attachOutputs(to: built.stream)+ self.stateLock.withLock {+ self.pendingStream = built.stream+ self.pendingStreamFailed = false+ }+ try await built.stream.startCapture()++ let swapped = self.stateLock.withLock { () -> Bool in+ defer { self.pendingStream = nil }+ guard !self.stopping, !self.pendingStreamFailed else { return false }+ self.stream = built.stream+ self.scope = built.scope+ self.delegateProxy = built.delegateProxy+ self.rebuilding = false+ return true+ }+ guard swapped else {+ try? await built.stream.stopCapture()+ if self.stateLock.withLock({ self.stopping }) {+ self.finishRebuilding()+ return+ }+ continue+ }+ self.eventHandler(.interrupted(kind: .sourceRecovered, trackID: nil, detail: nil))+ return+ } catch {+ self.stateLock.withLock { self.pendingStream = nil }+ lastError = error+ continue+ }+ }+ self.reportRebuildExhausted(triggeringError: lastError)+ }+ }++ private func finishRebuilding() {+ self.stateLock.withLock { self.rebuilding = false }+ }++ private func reportRebuildExhausted(triggeringError: Error) {+ let shouldReport = self.stateLock.withLock { () -> Bool in+ self.rebuilding = false+ guard !self.stopping else { return false }self.stopping = true+ return true}- self.stateLock.unlock()guard shouldReport else { return }self.eventHandler(.interrupted(kind: .captureStoppedUnexpectedly,trackID: nil,- detail: error.localizedDescription+ detail: triggeringError.localizedDescription))}}@@ -388,13 +606,15 @@ private final nonisolated class ScreenCaptureRuntimeDelegateProxy: NSObject, SCSweak var owner: ScreenCaptureMeetingRuntime?func stream(_ stream: SCStream, didStopWithError error: Error) {- self.owner?.handleStreamStop(error: error)+ self.owner?.handleStreamStop(stream, error: error)}}private final nonisolated class InRoomMicrophoneCaptureRuntime: NSObject, MeetingCaptureRuntime,AVCaptureAudioDataOutputSampleBufferDelegate, @unchecked Sendable{+ var captureScope: MeetingCaptureScope? { nil }+private let session = AVCaptureSession()private let output = AVCaptureAudioDataOutput()private let writer: MeetingAudioChunkWriterdiff --git a/Sources/Fluid/Services/Meeting/MeetingModels.swift b/Sources/Fluid/Services/Meeting/MeetingModels.swiftindex 789a36af..732e4fa3 100644--- a/Sources/Fluid/Services/Meeting/MeetingModels.swift+++ b/Sources/Fluid/Services/Meeting/MeetingModels.swift@@ -288,6 +288,9 @@ nonisolated struct MeetingTrackHealth: Codable, Equatable, Sendable {var level: Floatvar droppedSampleCount: Intvar detail: String?+ /// Seconds of continuous below-threshold audio, derived from PTS durations. Optional so+ /// pre-Phase-1c persisted manifests still decode.+ var silentForSeconds: Double? = nilstatic let waiting = Self(status: .waiting,@@ -645,9 +648,17 @@ nonisolated enum MeetingCaptureEvent: Sendable {case interrupted(kind: MeetingInterruptionKind, trackID: MeetingAudioTrackID?, detail: String?)}+/// The scope ScreenCaptureKit was filtering to for this capture. `nil` when the runtime has no+/// ScreenCaptureKit stream at all (in-room microphone-only capture).+nonisolated enum MeetingCaptureScope: Sendable {+ case display+ case window+}+nonisolated struct MeetingCaptureStartResult: Sendable {var tracks: [MeetingAudioTrack]var firstPresentationTime: MeetingMediaTime?+ var captureScope: MeetingCaptureScope? = nil}nonisolated struct MeetingCaptureStopResult: Sendable {diff --git a/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift b/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swiftindex 1637d959..0d49fe23 100644--- a/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift+++ b/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift@@ -64,12 +64,21 @@ final class MeetingSessionCoordinator: ObservableObject {@Published private(set) var latestCompletedSession: MeetingSession?@Published private(set) var trackHealth: [MeetingAudioTrackKind: MeetingTrackHealth] = [:]+ /// Sustained application-audio silence, in seconds, before the silence watchdog degrades the session.+ private static let silenceWatchdogThresholdSeconds: TimeInterval = 90+ /// How recently the microphone track must have had activity for the watchdog to treat it as "the+ /// user is talking into a silent meeting" rather than "nobody is in the meeting".+ private static let microphoneRecentActivityThresholdSeconds: TimeInterval = 15+private let store: any MeetingSessionStoringprivate let capture: any MeetingCaptureControllingprivate let processing: any MeetingProcessingControllingprivate let audioArbiter: any MeetingAudioActivityArbitratingprivate let preferredMicrophoneUID: @MainActor () -> String?+ private enum DegradeReason { case silence, sourceLoss, sticky }++ private var degradeReason: DegradeReason?private var activityLease: MeetingAudioActivityLease?private var captureGeneration: UUID?private var operationGeneration: UUID?@@ -169,6 +178,7 @@ final class MeetingSessionCoordinator: ObservableObject {self.activityLease = leaselet generation = UUID()self.captureGeneration = generation+ self.degradeReason = nilself.operationGeneration = generationlet timebase = Self.makeTimebase()var session = MeetingSession(configuration: configuration, timebase: timebase)@@ -243,6 +253,7 @@ final class MeetingSessionCoordinator: ObservableObject {? Dictionary(uniqueKeysWithValues: session.audioTracks.map { ($0.kind, $0.health) }): [:]self.captureGeneration = nil+ self.degradeReason = nilself.operationGeneration = nilself.state = .failed(session.id, failure)self.releaseActivityLease()@@ -397,6 +408,7 @@ final class MeetingSessionCoordinator: ObservableObject {private func performShutdownForTermination() async {self.captureGeneration = nil+ self.degradeReason = nilself.operationGeneration = nilself.stopTask?.cancel()self.interruptionTask?.cancel()@@ -472,6 +484,7 @@ final class MeetingSessionCoordinator: ObservableObject {throw CancellationError()}self.captureGeneration = nil+ self.degradeReason = nilSelf.apply(stopResult, to: &session)session.state = .processingsession.processingAttempts.append(Self.pendingProcessingAttempt())@@ -565,11 +578,32 @@ final class MeetingSessionCoordinator: ObservableObject {switch event {case let .trackHealth(trackID, health):guard let index = session.audioTracks.firstIndex(where: { $0.id == trackID }) else { return }+ var health = health+ let kind = session.audioTracks[index].kind+ let watchdogTripped = kind == .applicationAudio && health.status != .degraded+ && (health.silentForSeconds ?? 0) >= Self.silenceWatchdogThresholdSeconds+ && (self.trackHealth[.microphone]?.silentForSeconds).map {+ $0 < Self.microphoneRecentActivityThresholdSeconds+ } == true+ if watchdogTripped {+ health.status = .degraded+ health.detail = "No meeting audio is being captured while your microphone is active."+ }session.audioTracks[index].health = health- self.trackHealth[session.audioTracks[index].kind] = health+ self.trackHealth[kind] = healthif health.status == .degraded {session.state = .recordingDegradedself.state = .recordingDegraded(session.id)+ // Writer-reported degrades stay sticky; only watchdog degrades may self-restore.+ self.degradeReason = watchdogTripped ? (self.degradeReason ?? .silence) : .sticky+ } else if kind == .applicationAudio, session.state == .recordingDegraded,+ self.degradeReason == .silence,+ (health.silentForSeconds ?? 0) < Self.silenceWatchdogThresholdSeconds,+ !session.audioTracks.contains(where: { $0.id != trackID && $0.health.status == .degraded })+ {+ session.state = .recording+ self.state = .recording(session.id)+ self.degradeReason = nil}case let .chunkFinalized(trackID, chunk, format):guard let index = session.audioTracks.firstIndex(where: { $0.id == trackID }) else { return }@@ -596,13 +630,22 @@ final class MeetingSessionCoordinator: ObservableObject {session.updatedAt = Date()self.activeSession = sessionself.captureGeneration = nil+ self.degradeReason = nilself.operationGeneration = nilself.enqueuePersistence(session)self.beginUnexpectedStop(sessionID: session.id)return- } else if session.state == .recording {+ } else if kind == .sourceRecovered, session.state == .recordingDegraded,+ self.degradeReason == .sourceLoss,+ !session.audioTracks.contains(where: { $0.health.status == .degraded })+ {+ session.state = .recording+ self.state = .recording(session.id)+ self.degradeReason = nil+ } else if kind != .sourceRecovered, session.state == .recording {session.state = .recordingDegradedself.state = .recordingDegraded(session.id)+ self.degradeReason = kind == .sourceLost ? (self.degradeReason ?? .sourceLoss) : .sticky}}session.updatedAt = Date()@@ -660,6 +703,7 @@ final class MeetingSessionCoordinator: ObservableObject {guard self.operationGeneration == generation else { return }var session = inputSessionself.captureGeneration = nil+ self.degradeReason = nilself.operationGeneration = nilif let partialResult = Self.partialStopResult(from: error) {Self.apply(partialResult, to: &session)diff --git a/Tests/FluidDictationIntegrationTests/MeetingWindowSelectorTests.swift b/Tests/FluidDictationIntegrationTests/MeetingWindowSelectorTests.swiftnew file mode 100644index 00000000..3cf34115--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/MeetingWindowSelectorTests.swift@@ -0,0 +1,93 @@+@testable import FluidVoice_Debug+import Foundation+import XCTest++final class MeetingWindowSelectorTests: XCTestCase {+ private func candidate(+ _ windowID: UInt32,+ title: String? = nil,+ frame: CGRect = CGRect(x: 0, y: 0, width: 800, height: 600),+ layer: Int = 0,+ zOrderIndex: Int = 0+ ) -> MeetingWindowCandidate {+ MeetingWindowCandidate(windowID: windowID, title: title, frame: frame, layer: layer, zOrderIndex: zOrderIndex)+ }++ func testEmptyCandidateListReturnsNil() {+ XCTAssertNil(MeetingWindowSelector.selectWindow(from: []))+ }++ func testTitledBeatsUntitledRegardlessOfArea() {+ let untitledLarge = self.candidate(1, title: nil, frame: CGRect(x: 0, y: 0, width: 2000, height: 2000), zOrderIndex: 0)+ let titledSmall = self.candidate(2, title: "Standup", frame: CGRect(x: 0, y: 0, width: 300, height: 300), zOrderIndex: 5)+ let winner = MeetingWindowSelector.selectWindow(from: [untitledLarge, titledSmall])+ XCTAssertEqual(winner?.windowID, 2)+ }++ func testFrontmostBeatsLargerButBehindAmongTitled() {+ let frontSmall = self.candidate(1, title: "Meeting", frame: CGRect(x: 0, y: 0, width: 400, height: 300), zOrderIndex: 0)+ let behindLarge = self.candidate(2, title: "Other", frame: CGRect(x: 0, y: 0, width: 2000, height: 1500), zOrderIndex: 3)+ let winner = MeetingWindowSelector.selectWindow(from: [behindLarge, frontSmall])+ XCTAssertEqual(winner?.windowID, 1)+ }++ func testNonZeroLayerIsExcluded() {+ let panel = self.candidate(1, title: "Panel", layer: 25)+ XCTAssertNil(MeetingWindowSelector.selectWindow(from: [panel]))+ }++ func testSubMinimumSizeIsExcluded() {+ let sliver = self.candidate(1, title: "Toolbar", frame: CGRect(x: 0, y: 0, width: 150, height: 60))+ XCTAssertNil(MeetingWindowSelector.selectWindow(from: [sliver]))+ }++ func testDeterministicWindowIDTiebreakOnFullTies() {+ let frame = CGRect(x: 0, y: 0, width: 800, height: 600)+ let a = self.candidate(42, title: "Same", frame: frame, zOrderIndex: 1)+ let b = self.candidate(7, title: "Same", frame: frame, zOrderIndex: 1)+ let winner = MeetingWindowSelector.selectWindow(from: [a, b])+ XCTAssertEqual(winner?.windowID, 7)+ }++ /// Zoom-like fixture: a small floating toolbar (excluded by size), an untitled main window,+ /// and the frontmost titled meeting window. The meeting window should win.+ func testRealisticZoomFixture() {+ let toolbar = self.candidate(+ 1, title: "Zoom Toolbar", frame: CGRect(x: 0, y: 0, width: 180, height: 60), layer: 0, zOrderIndex: 0+ )+ let mainWindow = self.candidate(+ 2, title: nil, frame: CGRect(x: 0, y: 0, width: 1200, height: 800), layer: 0, zOrderIndex: 2+ )+ let meetingWindow = self.candidate(+ 3, title: "Zoom Meeting", frame: CGRect(x: 0, y: 0, width: 1000, height: 700), layer: 0, zOrderIndex: 1+ )+ let winner = MeetingWindowSelector.selectWindow(from: [toolbar, mainWindow, meetingWindow])+ XCTAssertEqual(winner?.windowID, 3)+ }++ func testExactMinimumSizeIsIncludedAndOnePixelUnderIsNot() {+ let atMinimum = candidate(1, title: "Meeting", frame: CGRect(x: 0, y: 0, width: 200, height: 100))+ XCTAssertEqual(MeetingWindowSelector.selectWindow(from: [atMinimum])?.windowID, 1)+ let underWidth = candidate(2, title: "Meeting", frame: CGRect(x: 0, y: 0, width: 199, height: 100))+ let underHeight = candidate(3, title: "Meeting", frame: CGRect(x: 0, y: 0, width: 200, height: 99))+ XCTAssertNil(MeetingWindowSelector.selectWindow(from: [underWidth, underHeight]))+ }++ func testWhitespaceOnlyTitleCountsAsUntitled() {+ let whitespace = candidate(1, title: " \n", frame: CGRect(x: 0, y: 0, width: 2000, height: 1500), zOrderIndex: 0)+ let titled = candidate(2, title: "Meeting", frame: CGRect(x: 0, y: 0, width: 400, height: 300), zOrderIndex: 5)+ XCTAssertEqual(MeetingWindowSelector.selectWindow(from: [whitespace, titled])?.windowID, 2)+ }++ func testLargerAreaBeatsSmallerWindowIDWhenTitleAndZOrderTie() {+ let smallEarlyID = candidate(1, title: "A", frame: CGRect(x: 0, y: 0, width: 400, height: 300), zOrderIndex: 2)+ let largeLateID = candidate(9, title: "B", frame: CGRect(x: 0, y: 0, width: 900, height: 700), zOrderIndex: 2)+ XCTAssertEqual(MeetingWindowSelector.selectWindow(from: [smallEarlyID, largeLateID])?.windowID, 9)+ }++ func testFrontmostBeatsSmallerWindowID() {+ let behindEarlyID = candidate(1, title: "A", frame: CGRect(x: 0, y: 0, width: 800, height: 600), zOrderIndex: 4)+ let frontLateID = candidate(9, title: "B", frame: CGRect(x: 0, y: 0, width: 800, height: 600), zOrderIndex: 1)+ XCTAssertEqual(MeetingWindowSelector.selectWindow(from: [behindEarlyID, frontLateID])?.windowID, 9)+ }+}