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

feat(meeting): strengthen detection and unify recording overlay

Shreeraman A K126fedd13635
diff --git a/Fluid.xcodeproj/project.pbxproj b/Fluid.xcodeproj/project.pbxproj
index 93357428..f3f57f2e 100644
--- a/Fluid.xcodeproj/project.pbxproj
+++ b/Fluid.xcodeproj/project.pbxproj
@@ -29,6 +29,8 @@
F1BD00000000000000000002 /* StripThinkingTagsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1BD00000000000000000001 /* StripThinkingTagsTests.swift */; };
D1A600000000000000000204 /* MeetingWindowSelectorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1A600000000000000000203 /* MeetingWindowSelectorTests.swift */; };
D1A600000000000000000206 /* MeetingRecoveryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1A600000000000000000205 /* MeetingRecoveryTests.swift */; };
+ AD7A00000000000000000002 /* MeetingAutoDetectorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD7A00000000000000000001 /* MeetingAutoDetectorTests.swift */; };
+ A7D000000000000000000002 /* AudioTopologyDiagnosticsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7D000000000000000000001 /* AudioTopologyDiagnosticsTests.swift */; };
7E57C8BE6F444F6A9AC9FCB0 /* MeetingEchoSignalScorerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4AD7433B35340CEB85EA268 /* MeetingEchoSignalScorerTests.swift */; };
E5EC00000000000000000002 /* MeetingEchoVetoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5EC00000000000000000001 /* MeetingEchoVetoTests.swift */; };
E5EC00000000000000000012 /* MeetingFallbackEchoProbeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5EC00000000000000000011 /* MeetingFallbackEchoProbeTests.swift */; };
@@ -52,6 +54,7 @@
7CFA1D0B2F500000C0DEF001 /* TypingServiceTransientPasteboardTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CFA1D0B2F500000C0DEF002 /* TypingServiceTransientPasteboardTests.swift */; };
803000000000000000000002 /* MediaPlaybackServiceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 803000000000000000000001 /* MediaPlaybackServiceTests.swift */; };
0B05F11E000000000000A002 /* SupportedFileExtensionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B05F11E000000000000A001 /* SupportedFileExtensionsTests.swift */; };
+ CD0E00000000000000000002 /* MeetingOverlayModelsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD0E00000000000000000001 /* MeetingOverlayModelsTests.swift */; };
803000000000000000000003 /* MediaRemoteAdapter in Frameworks */ = {isa = PBXBuildFile; productRef = 803000000000000000000004 /* MediaRemoteAdapter */; };
B51800000000000000000002 /* SpokenSendTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B51800000000000000000001 /* SpokenSendTests.swift */; };
B51900000000000000000002 /* PrivateAIProviderPromptFormatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B51900000000000000000001 /* PrivateAIProviderPromptFormatTests.swift */; };
@@ -99,6 +102,8 @@
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>"; };
D1A600000000000000000205 /* MeetingRecoveryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingRecoveryTests.swift; sourceTree = "<group>"; };
+ AD7A00000000000000000001 /* MeetingAutoDetectorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingAutoDetectorTests.swift; sourceTree = "<group>"; };
+ A7D000000000000000000001 /* AudioTopologyDiagnosticsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioTopologyDiagnosticsTests.swift; sourceTree = "<group>"; };
B4AD7433B35340CEB85EA268 /* MeetingEchoSignalScorerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingEchoSignalScorerTests.swift; sourceTree = "<group>"; };
E5EC00000000000000000001 /* MeetingEchoVetoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingEchoVetoTests.swift; sourceTree = "<group>"; };
E5EC00000000000000000011 /* MeetingFallbackEchoProbeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingFallbackEchoProbeTests.swift; sourceTree = "<group>"; };
@@ -133,6 +138,7 @@
7CFA1D0B2F500000C0DEF002 /* TypingServiceTransientPasteboardTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TypingServiceTransientPasteboardTests.swift; sourceTree = "<group>"; };
803000000000000000000001 /* MediaPlaybackServiceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MediaPlaybackServiceTests.swift; sourceTree = "<group>"; };
0B05F11E000000000000A001 /* SupportedFileExtensionsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SupportedFileExtensionsTests.swift; sourceTree = "<group>"; };
+ CD0E00000000000000000001 /* MeetingOverlayModelsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingOverlayModelsTests.swift; sourceTree = "<group>"; };
7CDB0A2A2F3C4D5600FB7CAD /* AudioFixtureLoader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioFixtureLoader.swift; sourceTree = "<group>"; };
7CDB0A2B2F3C4D5600FB7CAD /* dictation_fixture.wav */ = {isa = PBXFileReference; lastKnownFileType = audio.wav; path = dictation_fixture.wav; sourceTree = "<group>"; };
7CDB0A2C2F3C4D5600FB7CAD /* XCTest.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = XCTest.framework; path = Platforms/MacOSX.platform/Developer/Library/Frameworks/XCTest.framework; sourceTree = DEVELOPER_DIR; };
@@ -217,6 +223,8 @@
F1BD00000000000000000001 /* StripThinkingTagsTests.swift */,
D1A600000000000000000203 /* MeetingWindowSelectorTests.swift */,
D1A600000000000000000205 /* MeetingRecoveryTests.swift */,
+ AD7A00000000000000000001 /* MeetingAutoDetectorTests.swift */,
+ A7D000000000000000000001 /* AudioTopologyDiagnosticsTests.swift */,
B4AD7433B35340CEB85EA268 /* MeetingEchoSignalScorerTests.swift */,
E5EC00000000000000000001 /* MeetingEchoVetoTests.swift */,
E5EC00000000000000000011 /* MeetingFallbackEchoProbeTests.swift */,
@@ -245,6 +253,7 @@
C0DE63700000000000000001 /* WhisperLanguageSelectionTests.swift */,
CACEC0010000000000000001 /* KeychainServiceCacheTests.swift */,
0B05F11E000000000000A001 /* SupportedFileExtensionsTests.swift */,
+ CD0E00000000000000000001 /* MeetingOverlayModelsTests.swift */,
);
path = FluidDictationIntegrationTests;
sourceTree = "<group>";
@@ -420,6 +429,8 @@
F1BD00000000000000000002 /* StripThinkingTagsTests.swift in Sources */,
D1A600000000000000000204 /* MeetingWindowSelectorTests.swift in Sources */,
D1A600000000000000000206 /* MeetingRecoveryTests.swift in Sources */,
+ AD7A00000000000000000002 /* MeetingAutoDetectorTests.swift in Sources */,
+ A7D000000000000000000002 /* AudioTopologyDiagnosticsTests.swift in Sources */,
7E57C8BE6F444F6A9AC9FCB0 /* MeetingEchoSignalScorerTests.swift in Sources */,
E5EC00000000000000000002 /* MeetingEchoVetoTests.swift in Sources */,
E5EC00000000000000000012 /* MeetingFallbackEchoProbeTests.swift in Sources */,
@@ -447,6 +458,7 @@
C0DE63700000000000000002 /* WhisperLanguageSelectionTests.swift in Sources */,
CACEC0010000000000000002 /* KeychainServiceCacheTests.swift in Sources */,
0B05F11E000000000000A002 /* SupportedFileExtensionsTests.swift in Sources */,
+ CD0E00000000000000000002 /* MeetingOverlayModelsTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
diff --git a/MEETING_AUDIO_PHASE0_RUNBOOK.md b/MEETING_AUDIO_PHASE0_RUNBOOK.md
new file mode 100644
index 00000000..6220cfad
--- /dev/null
+++ b/MEETING_AUDIO_PHASE0_RUNBOOK.md
@@ -0,0 +1,70 @@
+# Meeting Audio Freeze — Phase 0 Evidence Runbook
+
+This runbook classifies the meeting-start freeze before any production behavior is changed. Diagnostics are DEBUG-only and opt-in. They record numeric Core Audio topology events; they do not record audio, device names, meeting titles, window titles, URLs, or transcripts.
+
+## Acceptance rule
+
+A hypothesis may advance to a fix only when all three artifacts agree on the same blocking boundary:
+
+1. the durable `stall-*.jsonl` snapshot identifies the last completed and first incomplete operation;
+2. `sample` shows the main-thread waiter and the owning AVFoundation/Core Audio stack;
+3. the condition matrix changes the reproduction rate in the predicted direction.
+
+Absence of a stall is not proof of safety. Run each condition at least 20 start/stop cycles, and compare against the pre-rebase revision on the same Mac, OS, microphone, output route, and meeting application.
+
+## Launch
+
+Use the installed, consistently signed Debug app. Do not run an ad-hoc build product because that changes macOS privacy identity.
+
+```sh
+mkdir -p /tmp/fluidvoice-audio-evidence
+FLUIDVOICE_AUDIO_TOPOLOGY_DIAGNOSTICS=1 \
+FLUIDVOICE_AUDIO_TOPOLOGY_TRACE_DIRECTORY=/tmp/fluidvoice-audio-evidence \
+FLUIDVOICE_AUDIO_TOPOLOGY_STALL_SECONDS=2 \
+"/Applications/FluidVoice Debug.app/Contents/MacOS/FluidVoice Debug"
+```
+
+The watchdog runs independently of the main thread. After two seconds without a main-runloop heartbeat it immediately writes and `fsync`s:
+
+- `fluidvoice-audio-topology-stall-<pid>-<sequence>.jsonl`
+- `fluidvoice-audio-topology-<pid>.stall`
+
+The normal trace is drained at utility QoS without `fsync`; only a stall snapshot is durability-critical.
+
+## Capture a process sample
+
+Keep the frozen process alive. In another terminal:
+
+```sh
+tools/capture_audio_topology_stall.sh /tmp/fluidvoice-audio-evidence
+```
+
+The script reads the newest marker, validates its PID, and immediately runs Apple's `sample` tool. If `sample` cannot attach, run it from an administrator terminal. For an unresolved kernel/daemon interaction, capture a sysdiagnose immediately afterward with Control-Option-Command-Shift-Period and note its timestamp. Do not attach sysdiagnose archives to the repository; they may contain unrelated private system data.
+
+## Controlled condition matrix
+
+Keep every uncontrolled variable fixed. Record successes, freezes, and failures separately.
+
+| ID | Revision | App path | Purpose |
+|---|---|---|---|
+| A | pre-rebase | real coordinator | Historical control |
+| B | current | isolated microphone capture | VPIO + AVAudioEngine baseline on its actor |
+| C | current | B + retained AVFoundation discovery/default lookup | AVFoundation catalog interaction |
+| D | current | B + physical-input liveness listeners only | Listener scope interaction |
+| E | current | B + all-input liveness listeners | Rebase-introduced ledger interaction |
+| F | current | full signed app + real `MeetingSessionCoordinator` | Production ordering after observer, ASR, detector, and UI readiness |
+| G | current | B executed on MainActor | Executor sensitivity; never substitute for B |
+
+For C, measure discovery, default lookup, and authorization timing independently rather than treating them as one toggle. For D/E, keep listener registration active through capture quiescence. Condition F begins only after the existing UI gate has opened and the log contains `Audio subsystems initialized`; it must not use a mock coordinator.
+
+## Interpreting the boundary
+
+- Incomplete `vpioEnableBegin`: VPIO creation/configuration is the active boundary.
+- VPIO completed but `engineStartBegin` is incomplete: AVAudioEngine start is the active boundary.
+- Incomplete listener add/remove or HAL query before the stall: topology listener interaction is implicated.
+- Heartbeat stalled with all phases closed: look outside the instrumented topology transition; do not force-fit a Core Audio conclusion.
+- A callback marker proves delivery only. All HAL work is separately bracketed so callback arrival is never confused with callback-side querying.
+
+## Promotion gate
+
+Do not ship a fix from a single reproduction. Require at least one clear discriminating A/B result, a matching process sample, and repeated-cycle evidence. Preserve the raw trace, sample, OS/build identifiers, selected input/output transport class, condition ID, and exact commit hashes in a separate evidence folder.
diff --git a/MEETING_AUDIO_START_FREEZE_RCA.md b/MEETING_AUDIO_START_FREEZE_RCA.md
new file mode 100644
index 00000000..6cffa468
--- /dev/null
+++ b/MEETING_AUDIO_START_FREEZE_RCA.md
@@ -0,0 +1,775 @@
+# Meeting transcription start freeze — root cause analysis
+
+**Incident:** BUG-001
+**Date:** 2026-08-25
+**Severity:** P0 / meeting capture unavailable
+**Status:** Narrow production mitigation implemented and validated; long-run and queue-ownership hardening remain
+**Affected build:** FluidVoice Debug 1.6.9 (20), macOS 26.5.1 (25F80)
+
+## 1. Executive summary
+
+FluidVoice reproducibly freezes while meeting capture enables `AVAudioEngine` voice processing and
+Core Audio publishes/tears down virtual aggregate devices. In both incidents, the main thread remained
+parked in AVFoundation's device-liveness listener while removing HAL property listeners; concurrently,
+HAL's device-teardown notification queue remained parked in `dispatch_sync`.
+
+The samples prove a permanent two-thread wait during the same topology transition. They are strongly
+consistent with a circular wait, but they do **not** expose HAL's synchronous target queue or the
+complete wait-for graph. Phase 0 eliminated the meeting microphone catalog as a sufficient cause,
+then isolated the rebase-introduced broad `DeviceIsAlive` ledger as the strongest empirical inducing
+condition. With the normal AVFoundation catalog restored, excluding only aggregate-transport inputs
+from that ledger passed normal dictation and three meeting start/stop cycles. This supports a narrow
+production mitigation, but it is not a statistical proof that the full private HAL deadlock class is
+closed.
+
+The investigation did prove two FluidVoice hazards around that transition:
+
+1. several FluidVoice Core Audio owners register, add, or remove device listeners on the main queue;
+ and
+2. the current “exclusive activity” lease excludes another transcription job but does not quiesce the
+ prepared dictation backend, drain route recovery, suspend topology-driven reconciliation, or own
+ meeting backend switches. It is logical exclusivity without audio-hardware exclusivity.
+
+The production mitigation therefore excludes only aggregate transports from
+`AudioHardwareObserver`'s broad ledger. Physical, Bluetooth, USB, virtual, and unknown transports are
+unchanged; system/default-device listeners, full liveness refreshes, and ASR's selected-device listener
+remain active. Moving Core Audio listener lifecycle ownership off main remains mandatory hardening and
+the correct long-term seam, but is not required to ship this evidence-scoped mitigation.
+
+The rebase history materially sharpens the leading hypothesis. The pre-rebase meeting branch already
+contained the VPIO meeting path, but did not contain the newer multi-device dictation availability
+observer. Rebasing onto `origin/main` introduced per-input `DeviceIsAlive` listeners that are added and
+removed on `DispatchQueue.main` during device-list churn. VPIO deliberately creates and destroys
+temporary aggregate devices, so this new observer is exercised at exactly the incident boundary. Its
+remove call is the closest FluidVoice-owned structural match to the frozen AVFoundation/Core Audio
+stack. This is now the highest-priority **rebase-introduced FluidVoice suspect**, but not the leading
+incident hypothesis: AVFoundation+VPIO remains co-equal because the sampled waiter is AVFoundation's
+own listener. The pre/post-rebase and mechanism-isolation rows must reproduce the difference.
+
+## 2. User impact
+
+- Starting meeting transcription beachballs the entire application.
+- No stop, cancel, or fallback action remains available because the main thread is blocked.
+- Restarting restores the app but starting meeting transcription can reproduce the freeze.
+- No evidence indicates transcript or recording corruption because capture never reaches its committed
+ recording state; this must still be verified during the eventual recovery-path tests.
+
+## 3. Incident evidence
+
+### 3.1 Reproduction 1
+
+- App PID: `13288`
+- Meeting start: `06:41:49.076`
+- Aggregate devices appeared by `06:41:49.422`:
+ - `CADefaultDeviceAggregate-13288-0`
+ - `VPAUAggregateAudioDevice-0xa37144040`
+- The prepared direct dictation capture invalidated on `stream_configuration`, `virtual_format`, and
+ `physical_format`, then scheduled route-recovery generations 11–13.
+- Meeting microphone and application models finished warming, after which logging stopped.
+
+### 3.2 Reproduction 2
+
+- App PID: `46188`
+- Meeting start: `06:57:15.100`
+- Aggregate devices appeared by `06:57:15.406`:
+ - `CADefaultDeviceAggregate-46188-0`
+ - `VPAUAggregateAudioDevice-0xaab760040`
+- The prepared direct dictation capture again invalidated on the same three format properties and
+ scheduled route-recovery generations 1–3.
+- Meeting microphone and application models finished warming, after which logging stopped.
+
+The second incident followed a clean app restart and reproduced the same stack and event order.
+
+### 3.3 Identical main-thread stack in both incidents
+
+```text
+com.apple.main-thread
+ __DeviceIsAliveListener_block_invoke AVFCapture
+ -[AVCaptureHALDevice _refreshConnectionID:KVONotify:]
+ -[AVCaptureHALDevice _removePropertyListeners]
+ AudioObjectRemovePropertyListener_mac_imp CoreAudio
+ HALObject::RemovePropertyListener
+ CADeprecated::CAGuard::WaitFor
+ _pthread_cond_wait
+```
+
+### 3.4 Concurrent HAL notification stack in both incidents
+
+```text
+HALC_ProxyNotification Call Listener Queue
+ HALC_ProxyNotifications::CallListener
+ HALC_ShellPlugIn::ProxyObject_PropertiesChanged
+ HALSystem::AudioObjectsPublishedAndDied
+ HALSystem::ObjectsPublishedAndDied
+ HALDevice::Teardown
+ HALObject::PropertiesChanged
+ _dispatch_sync_f_slow
+ __DISPATCH_WAIT_FOR_QUEUE__
+```
+
+This proves two permanently parked threads during device teardown/listener removal and is strongly
+consistent with a circular wait. It does not reveal HAL's synchronous target queue, prove the complete
+wait-for cycle, or identify any FluidVoice callback as a participant.
+
+### 3.5 Rebase/regression timeline
+
+- The meeting branch's pre-rebase tip was `d5b998a` on 2026-08-19 12:00 PDT. It already contained the
+ VPIO meeting commits, including Phase 3 from 2026-08-17 and later route-following work.
+- The recorded rebase began on 2026-08-19 12:50 PDT by checking out `origin/main` at `6f0684e`; it
+ completed at `1f9af82`, followed by reconciliation commit `a029a69`.
+- The old meeting branch and rebased upstream share base `8d140fc` from 2026-08-05. Therefore
+ `8d140fc..6f0684e` is the relevant upstream delta introduced underneath the meeting work.
+- That upstream delta changed approximately 1,400 lines across `ASRService.swift`,
+ `AudioDeviceService.swift`, and `DirectCoreAudioInput.swift` and contains a concentrated series of
+ microphone-priority, liveness, prewarm-handoff, and Bluetooth recovery changes.
+- The user reports meeting start did not freeze before the rebase. Its denominator, exact installed
+ revision, macOS version, and route are currently unknown, so it establishes a regression lead—not a
+ negative experimental result. Both revisions must be exercised in the same harness and hardware/OS
+ configuration.
+- Reconciliation commit `a029a69` changed only file-transcription code and tests, not ASR, Core Audio,
+ or meeting capture. It remains part of the post-rebase comparison revision but is not a direct audio
+ source-change candidate.
+
+### 3.6 Candidate commit analysis
+
+| Confidence | Commit | Change introduced by rebased upstream | Relevance to this freeze |
+| --- | --- | --- | --- |
+| Medium-high / unconfirmed rebase-introduced suspect | `2dce5cd` — `fix microphone priority routing` | Adds `DeviceIsAlive` listeners on main to **every enumerated input**, with no virtual/aggregate exclusion. A device-list callback reconciles the ledger and removes vanished-device listeners on main. The large commit also changes selection and recovery. | VPIO creates/removes transient inputs; both freezes end in device-liveness listener removal during teardown. This is the closest new FluidVoice source-level match, but the sampled waiter is AVFoundation-owned. |
+| Medium / co-dependent amplifier | `03a0cfd` — `fix cache microphone liveness off main` | Moves the first query off main, but makes availability callbacks enumerate and query liveness for every input during topology churn, retains listener add/remove/delivery on main, and adds liveness-driven ASR recovery. | Adds HAL property reads and recovery reactions at the incident boundary. It is not a complete listener-lifecycle mitigation. |
+| Medium / co-dependent amplifier | `3e04401` — `fix isolate microphone availability updates` | Adds a separate availability tick and a `ContentView` reaction that refreshes input liveness and reconciles microphone selection on availability/default-input changes. | Adds another churn-driven HAL enumeration/reconciliation consumer. It depends on the availability events introduced by `2dce5cd`, so tests must isolate both the listener ledger and its consumers. |
+| Low–medium | `9417cfc`, `405e033`, `77f3573`, `d3f9461`, `9d27956`, `c9eece6`, `7d780f4`, `3789b79` | Expands and hardens Bluetooth/device route-recovery behavior. | Can increase work scheduled after VPIO topology changes. Logs show recovery requests, but not that recovery execution entered the captured wait. |
+| Low / negative control | direct Core Audio prewarm and its lifecycle controller | Already existed before common base `8d140fc`; it was not introduced by the rebase. | Still overlaps meeting start and must be quiesced architecturally, but timing alone no longer makes it the leading regression trigger. |
+
+The pre-rebase tip contains none of `inputAvailabilityListenerTokens`,
+`listInputDevicesRefreshingLiveness`, or `cachedInputLivenessByUID`; the post-rebase revision contains
+all three. Older global ASR/default-device listeners **and** ASR's main-queue per-device
+`DeviceIsAlive` listener for the single monitored microphone existed before the rebase. The regression
+claim is therefore narrow: the newly introduced **all-input reconciliation that can attach listeners
+to transient virtual/aggregate devices**, plus its new recovery reactions, is suspect—not the general
+existence of `DeviceIsAlive` on main and not every Core Audio or multi-device change.
+
+### 3.7 Phase 0 shipped-path isolation results
+
+All rows used the same bundle ID, Team ID, designated requirement, installed `/Applications` path,
+diagnostics, and current meeting path. The flags are DEBUG-only and are not production fixes.
+
+| Row | Variable changed | Result | Interpretation |
+| --- | --- | --- | --- |
+| Baseline | Current microphone catalog and full all-input liveness ledger | Frozen | Reproduced the incident with the two-thread wait above. |
+| Catalog isolation | Replaced AVFoundation microphone discovery/default lookup with the Core Audio catalog; retained the ledger | Frozen | AVFoundation catalog removal is not sufficient. The trace contains no discovery/default events before VPIO, yet the identical wait remains. |
+| Ledger isolation | Held catalog isolation constant; omitted only `AudioHardwareObserver`'s rebase-introduced all-input `DeviceIsAlive` ledger | Normal dictation and three meeting cycles passed | Strongly supports the ledger as an inducing participant, but removes more behavior than a production fix should. |
+| Transient-input isolation | Restored physical-device ledger listeners; excluded aggregate, virtual, and unknown transports | Normal dictation and three meeting cycles passed | Narrows the inducing surface to transient-style transports while preserving physical multi-device behavior. |
+| Aggregate-only isolation | Restored the normal AVFoundation catalog and retained all non-aggregate transports; excluded only aggregate transports from the broad ledger | Normal dictation and three meeting cycles passed | This is the narrowest passing production-shaped row and the basis of the shipped policy. |
+
+The successful traces completed microphone authorization, VPIO enable, input binding, engine prepare,
+and engine start. The frozen rows attached the broad `DeviceIsAlive` ledger to persistent inputs and
+then to VPIO aggregate inputs. The aggregate-only trace excluded those aggregate attachments while
+retaining physical attachments, the normal catalog, and the active meeting detector. That detector's
+separate `DeviceIsRunningSomewhere` ledger remained active—including on aggregate IDs—and the run still
+passed; this is evidence that the observed failure is selector/ownership-path specific, not that every
+main-queue Core Audio listener is sufficient to freeze. A scoped run executed 185 tests with zero
+failures and one expected opt-in hardware skip. The Release configuration also compiled successfully.
+
+Adversarial review of the production diff found the predicate, token-removal ordering, Release
+reachability, and dictation-preservation boundary sound. Kimi K3 approved. Claude Opus requested the
+evidence wording and detector configuration be made explicit; both are addressed above. Review also
+agreed that dedicated off-main listener lifecycle ownership remains mandatory follow-up hardening.
+Three clean cycles justify this narrow mitigation after a reproducible incident and controlled A/B,
+but do not satisfy the 2,995-cycle statistical gate defined later in this document.
+
+## 4. What is proven, inferred, and still unknown
+
+### Proven
+
+- `MeetingSessionCoordinator` acquires `.meeting` through `AudioActivityArbiter`, but the lease only
+ updates ASR state fields. It performs no audio-backend handoff
+ (`MeetingSessionCoordinator.swift:31-67`, `ASRService.swift:246-264`).
+- Startup leaves a prepared direct Core Audio dictation backend and its format listeners alive
+ (`ASRService.swift:1471-1510`, `DirectCoreAudioInput.swift:1207-1354`).
+- Neither idle prewarm nor route recovery is suppressed by the active meeting lease
+ (`ASRService.swift:880-1007`, `ASRService.swift:3368-3613`).
+- Meeting capture calls `input.setVoiceProcessingEnabled(true)`, the observed boundary that creates VPIO audio
+ topology, while the prepared dictation backend is still present
+ (`MeetingMicrophoneCapture.swift:637-692`).
+- VPIO topology changes invalidated the prepared dictation capture in both incidents and caused three
+ ASR route-recovery requests.
+- Multiple FluidVoice services independently add and remove Core Audio listener blocks on
+ `DispatchQueue.main`. At the initial VPIO boundary, the active sets include
+ `AudioHardwareObserver`, ASR device monitoring, and meeting auto-detection. Meeting microphone and
+ output-route monitoring use the same unsafe pattern elsewhere, but are installed only after VPIO
+ microphone startup and therefore cannot trigger this initial-start incident.
+- The online-meeting configuration enumerates microphones through
+ `AVCaptureDevice.DiscoverySession` before VPIO begins
+ (`MeetingCaptureEngine.swift:1257-1284`).
+- The installed build predates the meeting-overlay changes. Relevant microphone/VPIO/ASR code has no
+ current working-tree diff, so the overlay implementation is excluded from the causal path.
+- Runtime logs prove `MeetingAutoDetector` was active in the second incident build even though its
+ source is currently untracked. Repository `HEAD` alone is not evidence of installed-build contents.
+
+### Strongly inferred
+
+- Aggregate-device publication/death causes HAL to deliver a main-queue device event. AVFoundation's
+ liveness handler removes its HAL listeners while HAL teardown synchronously waits for listener
+ delivery. This is the leading wait-cycle hypothesis, not a proven closed graph.
+- Main-queue listener concentration and concurrent ASR invalidation/recovery enlarge the hazardous
+ topology window. They are architectural contributors even if one Apple-internal AVFoundation
+ listener is the immediate deadlock participant.
+- Ephemeral AVFoundation discovery before VPIO causes AVFoundation to materialize audio-device
+ objects whose lifecycle overlaps the VPIO aggregate-device transition.
+- AVFoundation may retain HAL device objects/listeners after the local discovery session is released;
+ the captured AVFCapture stack makes this plausible, but only the ephemeral-versus-retained Phase 0
+ rows can establish the lifetime.
+- The rebased `2dce5cd` per-input listener ledger is the highest-priority new FluidVoice regression
+ suspect, co-equal with the pre-existing AVFoundation/VPIO hypothesis rather than ranked above it.
+ Its main-queue removal of `DeviceIsAlive` listeners is activated by the same transient VPIO device
+ churn seen in both incidents and was absent from the pre-rebase meeting branch.
+- The later liveness/priority recovery work can widen or repeat the hazardous topology window, but the
+ logs do not yet show it beginning a rebuild before the freeze.
+
+### Not yet proven
+
+- The exact dispatch queue targeted by `HALObject::PropertiesChanged` in the private Core Audio frame.
+- Whether AVFoundation discovery plus VPIO alone reproduces the deadlock in a minimal process.
+- Whether removing idle direct prewarm alone changes reproduction frequency. That experiment would
+ isolate an amplifier, not establish a sufficient production fix.
+- Whether this is a macOS 26.5.1 framework regression. FluidVoice must remove its unsafe concurrency
+ regardless; a minimal reproduction and sysdiagnose should be submitted to Apple if it persists.
+- Whether a scheduled ASR route-recovery task began executing before the deadlock. The logs prove
+ three requests were created and that direct-listener invalidation/drain ran; they do not prove the
+ debounced recovery reached its rebuild phase before the main thread stopped.
+- Whether an older recovery request was still sleeping or executing when reproduction 1 began. Its
+ generations 11–13 show prior route events but not the state of generation 10 at meeting start.
+- Absence of later app log lines is not proof that background work never began: user-facing logging
+ commonly hops through main-actor state, which was already blocked.
+- Whether `d5b998a` remains non-hanging under the same macOS, device route, permissions, and repeated
+ cycle count, and whether adding `2dce5cd` alone makes it hang.
+- Whether the necessary additional participant is the new FluidVoice listener ledger, pre-existing
+ AVFoundation device materialization, or their combination. The sampled `DeviceIsAlive` callback is
+ AVFoundation-owned, and the pre-rebase meeting path already used discovery and authorization APIs.
+
+## 5. Observed sequence and competing causal hypotheses
+
+```text
+Startup
+ -> ASR prepares DirectCoreAudio input and installs format listeners
+ -> global ASR, hardware, and meeting-detection listeners remain active
+
+User starts online meeting transcription
+ -> configuration enumerates AVCaptureDevice microphones
+ -> logical .meeting lease is acquired, but audio hardware is not handed off
+ -> meeting enables AVAudioEngine voice processing
+ -> Core Audio publishes VPIO/default aggregate devices and tears transitional devices down
+
+Observed concurrent reactions
+ -> direct dictation input receives three format invalidations
+ -> ASR invalidates its prepared backend and schedules idle route recovery
+ -> device observers enumerate devices and add/remove per-device listeners
+ -> AVFoundation receives device-liveness changes for its HAL device objects
+
+Permanent wait
+ -> main queue: AVFoundation removes a HAL listener and waits in Core Audio
+ -> HAL notification queue: device teardown waits in dispatch_sync
+ -> neither advances across either sample; the UI freezes permanently
+```
+
+Three hypotheses fit that sequence and must be isolated:
+
+1. **AVFoundation/VPIO:** AVFoundation audio-device materialization alone leaves a main-queue liveness
+ listener that deadlocks with VPIO aggregate teardown. If reproduced, removing AVFoundation catalog
+ work from the VPIO path is curative; FluidVoice listener/coordinator work is defense-in-depth.
+2. **FluidVoice main-queue listeners:** HAL is synchronously targeting main because a FluidVoice
+ registration is delivered there while main is already inside listener removal. The closest source
+ match is `AudioHardwareObserver.replaceInputAvailabilityListeners`, which removes and adds
+ `DeviceIsAlive` listeners from main during device-list reconciliation. This exact per-input path was
+ introduced by upstream commit `2dce5cd` and was absent before the rebase. Auto-detection performs
+ the same class of main-queue per-device reconciliation for `DeviceIsRunningSomewhere`.
+3. **Prepared dictation overlap:** direct prewarm or recovery is necessary to create the teardown
+ ordering. The direct backend already uses dedicated queues and completed its recorded listener
+ drain, so current evidence makes it an ownership violation and likely amplifier—not the leading
+ immediate participant.
+
+## 6. Root-cause statement
+
+### Confirmed incident mechanism
+
+VPIO aggregate-device publication/teardown overlaps an AVFoundation device-liveness callback on main.
+The callback blocks removing HAL listeners while HAL teardown blocks in a synchronous dispatch. The
+unresolved target queue prevents claiming the exact closed wait graph.
+
+### Proven architectural root hazard
+
+FluidVoice has no single owner for process-wide audio-topology transitions, and it delivers/removes
+multiple Core Audio listeners on main. Its exclusive-activity model arbitrates user operations but not
+hardware lifecycle. Consequently, listener reconciliation, dictation prewarm/recovery, AVFoundation
+device materialization, and meeting VPIO transitions are permitted to overlap. Phase 0 must determine
+which of these permitted overlaps closes this incident's wait cycle.
+
+### Highest-priority rebase-introduced FluidVoice suspect
+
+The strongest new-FluidVoice-source regression explanation is the interaction introduced by rebasing the
+reportedly non-freezing meeting VPIO path onto the new multi-device dictation observer from
+`2dce5cd`:
+
+```text
+VPIO publishes/destroys aggregate input devices
+ -> system device-list listener fires on main
+ -> FluidVoice enumerates the new list off-main
+ -> FluidVoice returns to main and removes DeviceIsAlive listeners for vanished devices
+ -> removal overlaps HAL/AVFoundation teardown at the captured freeze boundary
+```
+
+This explains the timing and source-level operation without claiming the unobserved final wait edge.
+It does not outrank the AVFoundation-retention hypothesis by direct stack evidence: the captured
+callback is AVFoundation-owned, and AVFoundation discovery existed pre-rebase. The new ledger may be
+the missing sync-edge participant, a timing amplifier, or incidental; only the isolation rows decide.
+The proper fix is not to special-case VPIO device names or add delay; it is to establish off-main,
+stable listener ownership and suppress reconciliation during topology transitions. The diagnostic
+matrix below must first establish whether that slice alone removes the incident.
+
+### Contributing conditions
+
+1. Core Audio listener ownership is duplicated across at least five services. Three pre-existing
+ listener owners are active at the initial VPIO boundary; the later-installed meeting listeners are
+ additional architectural debt, not the temporal trigger for these two incidents.
+2. Many listeners use the main queue directly; some callbacks query Core Audio or add/remove listeners
+ from that same delivery queue. `AudioDeviceService.swift:621-658` is the closest FluidVoice-owned
+ structural match to the captured removal wait.
+3. Route recovery does not respect `.meeting` exclusivity.
+4. Meeting auto-detection continues monitoring FluidVoice's own audio-device changes during capture.
+5. Microphone selection combines two identity systems—Core Audio UID and
+ `AVCaptureDevice.uniqueID`—and eagerly invokes AVFoundation even for the VPIO primary path.
+6. Configuration is resolved before the meeting lease, then the microphone is enumerated again inside
+ the VPIO transition.
+7. `MeetingMicrophoneCapture.start` calls `AVCaptureDevice.authorizationStatus(for:)` immediately
+ before VPIO, despite an existing source comment that this API activates AVFCapture/Core Audio.
+
+## 7. Rejected patch fixes
+
+The following may alter timing but do not establish safe ownership:
+
+- adding a sleep/debounce before or after `setVoiceProcessingEnabled(true)`;
+- retrying meeting start after a timeout;
+- adding only `guard activeExclusiveActivity != .meeting` to one recovery call;
+- disabling only startup prewarm;
+- moving only the listener seen in the current stack off main;
+- catching the VPIO error or falling back after a deadline—the main thread cannot execute fallback
+ once deadlocked;
+- killing and restarting the app automatically;
+- permanently disabling voice processing without evaluating the capture-quality contract.
+
+These are rejected because other listeners and topology owners would remain able to recreate the same
+class of race.
+
+## 8. Required invariants
+
+The final architecture is complete only when these invariants are enforced in code and tests. The
+Phase 0 decision matrix determines which subset is curative for BUG-001 and therefore must land first.
+
+1. **Single topology writer:** exactly one coordinator owns prepare/start/stop/destroy operations for
+ dictation Core Audio, meeting VPIO, and recovery transitions.
+2. **True handoff:** `{dictation prepared/running/recovering}` and
+ `{meeting preparing/recording/switching/stopping}` never overlap. Meeting admission while dictation
+ is active is rejected without preempting or discarding the current utterance; the user may retry
+ after dictation completes.
+3. **Transition suppression:** hardware events received during meeting start, stop, or backend switch
+ are coalesced as a dirty snapshot; they cannot start recovery, prewarm, or listener reconfiguration.
+4. **No FluidVoice HAL work on main callbacks:** FluidVoice Core Audio callbacks do constant-time event
+ capture only. They do not query Core Audio, add/remove listeners, mutate observable UI state, or
+ synchronously cross queues. FluidVoice cannot enforce this inside AVFoundation, so AVFoundation
+ materialization must not overlap VPIO transitions.
+5. **Stable listener ownership:** every listener has one owner, a retained registration record, and the
+ exact same dedicated serial queue argument for matching add/remove. Neither removal nor draining
+ executes from that listener's delivery queue; both are owned by a separate control executor.
+6. **Backend-specific identity and lifetime:** the VPIO path uses a previously selected Core Audio UID.
+ It does not create an AVFoundation discovery session during topology transition. Before SCK→VPIO,
+ FluidVoice releases every app-owned AVCapture session/device/discovery object and observes the
+ topology/listener barrier. If Phase 0 proves AVFoundation retains hazardous process-global objects,
+ SCK→VPIO upgrade is prohibited in that process; the meeting remains on SCK.
+7. **Ordered restoration:** meeting stop fully retires VPIO and waits for topology quiescence before one
+ reconciled dictation prewarm. It never replays every event received during the meeting.
+8. **UI isolation:** MainActor receives immutable topology snapshots and state changes only; it never
+ owns Core Audio listener delivery.
+9. **Backend switches are transitions:** VPIO→SCK downgrade and SCK→VPIO upgrade remain meeting-owned
+ but pass through the same quiescence, listener, identity, and rollback rules as initial start/stop.
+10. **Service reset has one owner:** Core Audio service restart during any transition cannot trigger
+ independent re-registration in ASR, device monitoring, or meeting capture.
+11. **Quarantined failure:** if a HAL call wedges or teardown cannot be proven complete, the state is
+ `failedQuarantined`, not stable. No capture, listener reinstallation, or prewarm begins until an
+ explicit audio-service reset or app restart establishes a new generation.
+12. **Frozen-main distinction:** `failedQuarantined` is an in-process state only while the main heartbeat
+ remains alive. An off-main watchdog that observes a dead main loop persists a privacy-safe marker
+ and VPIO-disable flag for the next launch; it never attempts in-process audio recovery.
+
+## 9. Proposed architecture
+
+### 9.1 `AudioTopologyCoordinator`
+
+After Phase 0 identifies the curative slice, introduce one process-wide actor with an explicit state
+machine for every topology-changing backend operation:
+
+```text
+stableDictationIdle
+ <-> stableDictationActive
+ -> handingOffToMeeting
+ -> meetingStarting(vpio | sck)
+ -> meetingActive(vpio | sck)
+ -> switchingMeetingBackend(vpioToSCK | sckToVPIO)
+ -> meetingActive(vpio | sck)
+ -> handingBackToDictation
+ -> stableDictationIdle
+
+Any state -> rollingBack -> stableDictationIdle | failedQuarantined
+```
+
+It owns transition generations and leases. A lease is granted only after the previous owner is fully
+quiescent; it is not a Boolean permission flag. In-room SCK microphone capture and online fallback,
+downgrade, and upgrade legs are included because they materialize backend-specific audio devices.
+`stableDictationActive` rejects meeting admission; it does not preempt the current utterance.
+
+### 9.2 Asynchronous meeting handoff
+
+`beginMeetingCapture` must:
+
+1. close the gate to new ASR prewarm/recovery;
+2. reuse `ASRService.cancelAudioRouteRecoveryAndWait()` to cancel and await sleeping or active route
+ recovery rather than creating a second barrier;
+3. stop/invalidate the prepared direct input, remove its listeners on their registered queue, drain
+ callbacks, and retire any dictation `AVAudioEngine` off the main actor;
+4. suspend/coalesce `AudioHardwareObserver`, detector, and legacy listener reconciliation so no
+ per-device listener add/remove can occur during the transition;
+5. snapshot microphone authorization, selected Core Audio UID, and output-route facts before the
+ transition without `AVCaptureDevice.DiscoverySession`, `.default`, or `.authorizationStatus` in the
+ VPIO window;
+6. grant the meeting topology lease;
+7. create/start VPIO on the coordinator's audio-control executor;
+8. commit `meetingActive(.vpio)` only after first microphone PCM and application capture are healthy.
+
+If any step fails, rollback runs on the control executor—never main and never a listener queue. Every
+step has an observed completion boundary. A deadline reports failure but cannot declare topology safe;
+if teardown does not complete, enter `failedQuarantined` and keep all new audio work closed.
+
+### 9.3 Ordered handback
+
+`endMeetingCapture` must:
+
+1. stop sample acceptance;
+2. stop application capture and VPIO;
+3. remove and drain meeting listeners and release the engine on the audio-control executor;
+4. wait until observed topology generations are quiet;
+5. take one current device snapshot and reconcile selection;
+6. reopen ASR event handling and optionally prewarm dictation exactly once.
+
+A bounded deadline may report a failed transition, but it must not permit two owners to proceed. A
+dictation hotkey pressed during handback waits for the same barrier or returns a bounded unavailable
+result; it never starts a competing backend.
+
+### 9.4 `AudioHardwareEventHub`
+
+Replace service-local Core Audio listener management with one registration ledger and coalescing hub.
+The hub is justified by the need for one dirty-generation boundary during transitions; a generic
+broadcast framework is not required:
+
+- one dedicated serial listener queue, never `DispatchQueue.main`;
+- one registration ledger for system devices/defaults/service restart and necessary per-device facts;
+- callbacks capture property addresses and IDs, then enqueue a coalesced event to the topology actor;
+- UI, detector, microphone-selection, and health services subscribe to immutable snapshots;
+- auto-detection suppresses or tags FluidVoice-owned capture transitions so it does not react to its
+ own VPIO devices as evidence of an external meeting.
+
+No listener callback may query additional “necessary per-device facts”; those are read later by the
+control executor after the callback returns. I/O-thread properties that Apple documents as synchronously
+delivered permit atomic/statistics updates only.
+
+### 9.5 Separate microphone selection from backend binding
+
+Replace the configuration's eager dual-framework lookup with:
+
+- a stable selected microphone value based on Core Audio UID plus display metadata;
+- a VPIO binder that resolves the current Core Audio object ID under the topology lease;
+- an AVFoundation/SCK resolver invoked only when starting an AVCapture or SCK-microphone backend;
+- lazy fallback resolution only after VPIO is fully torn down and topology is quiet.
+
+The online VPIO configuration/catalog path must not call `AVCaptureDevice.DiscoverySession`,
+`AVCaptureDevice.default`, or `AVCaptureDevice.authorizationStatus` near the transition. Authorization
+is resolved before handoff. If SCK fallback is needed, resolve its required unique ID only after VPIO
+teardown is observed complete. Production code does not infer “no aggregate was published” from elapsed
+time; it requires a topology-generation observation. Without that observation, fallback follows the
+same teardown/quarantine path. Before any SCK→VPIO upgrade, release app-owned AVFoundation objects and
+pass the same barrier; if retained AVFoundation state is proven hazardous, do not upgrade in-process.
+
+For ScreenCaptureKit, Apple's SDK header states that `microphoneCaptureDeviceID` is an
+`AVCaptureDevice.uniqueID`; that requirement belongs in the SCK adapter, not the shared product model.
+
+## 10. Proof plan before production rollout
+
+### Phase 0 — isolate and instrument
+
+Before production changes, capture one full spindump dispatch-queue section from the frozen app and a
+sysdiagnose/Core Audio log window where possible. Resolve HAL's `dispatch_sync` target queue. Build a
+minimal signed harness and measure the baseline failure rate for these conditions:
+
+1. VPIO only;
+2. main-thread AVFoundation discovery/default lookup followed by VPIO, with ephemeral and retained
+ discovery-session variants;
+3. direct Core Audio prewarm with its existing off-main listeners followed by VPIO and no AVFoundation
+ catalog (negative control for the prewarm hypothesis);
+4. FluidVoice-equivalent main-queue Devices/`DeviceIsAlive` listeners followed by VPIO;
+5. AVFoundation discovery plus FluidVoice main-queue listeners followed by VPIO;
+6. all current FluidVoice conditions together.
+
+Record main-runloop heartbeat, topology generation, listener owner/queue, VPIO begin/end, and route
+recovery scheduled/begin/end separately. Run on macOS 26.5.1 and one other supported OS. For every
+stall capture a spindump/sysdiagnose; for every non-stall record the denominator. Choose cycle counts
+from the observed baseline. The targeted curative harness gate is a per-start residual hang probability
+of at most 0.1% at 95% confidence: with zero failures, this requires at least 2,995 independent cycles.
+
+#### Phase 0B — isolate the rebase regression
+
+Use the same signed diagnostic harness, macOS build, microphone/output route, and meeting-start cycle
+for every row. Do not replace the installed production-style debug app with a differently signed
+historical build; preserve its privacy grants and run historical variants as isolated harnesses.
+
+1. `d5b998a` pre-rebase meeting implementation on its original audio base;
+2. `a029a69` post-rebase implementation before later working-tree overlay/detector changes;
+3. a synthetic old-base build containing only the `2dce5cd` per-input availability listener ledger,
+ without the remainder of that 2,390-line selection/recovery commit;
+4. an integration build with full `2dce5cd`, followed by one through `03a0cfd`, then one through
+ `3e04401`; replay the real intervening commits in order rather than blind cherry-picks that silently
+ resolve conflicts. These are diagnostic states, not claims about shipped revisions;
+5. current path with only the `AudioHardwareObserver` per-input listener ledger omitted while the
+ `3e04401` default-input/availability consumer remains active;
+6. current path with the per-input listener ledger retained while only the `3e04401` availability-tick
+ consumer is held inactive;
+7. current path with the same listener coverage and consumers retained, but delivery on a dedicated
+ serial listener queue and
+ add/remove owned by a separate control executor;
+8. current path with per-input listeners intact but topology-driven route recovery/prewarm scheduling
+ suppressed, separating the immediate listener trigger from the recovery amplifier;
+9. current path with the `2dce5cd` ledger retained but AVFoundation discovery/default/authorization
+ removed from the VPIO transition, separating AVFoundation materialization from the new ledger;
+10. current path with the ledger retained for physical inputs but transient virtual/aggregate inputs
+ excluded, while the older ASR monitored-device `DeviceIsAlive` listener remains active as the
+ pre-rebase baseline.
+
+Rows 1–4 must use an explicitly identical meeting-detector configuration. Prefer two matched blocks:
+detector absent, then the incident-equivalent detector present. A negative detector-absent run is not
+binding for the incident configuration because the second frozen build had the detector's main-queue
+per-device listener owner active even though that source is absent from the historical commit objects.
+
+For each add/remove record registration ID, owner, object ID, selector, delivery queue, control queue,
+generation, transport/virtual classification, and monotonic timestamp. Do not record device names.
+Correlate FluidVoice token object IDs with the object IDs published and torn down by VPIO; without that
+match, do not claim the ledger participated in the incident. Record route-recovery `scheduled`, `began`,
+and `ended` separately so a queued request is not mistaken for an executing rebuild.
+
+Start with randomized, interleaved blocks of 100 cycles per row to reduce ordering, thermal, and audio-
+daemon state bias. Any captured matching freeze rules a row in. Zero failures is only preliminary;
+before declaring a suspected condition unnecessary or a fix curative, run at least 2,995 independent
+cycles for that row, matching the 0.1%/95% gate above. Record the user's approximate historical
+pre-rebase start count if recoverable, but never combine it with controlled harness denominators.
+
+Interpretation:
+
+- Rows 1 versus 2 establish whether the rebase reproduces the regression under controlled conditions.
+- If row 1 reproduces the same freeze, the rebase-regression claim is falsified: `2dce5cd` cannot be an
+ inducing requirement, though later changes may still amplify a pre-existing AVFoundation/VPIO race.
+- Row 3 becoming positive identifies the listener ledger as sufficient in the synthetic harness. Row
+ 4 shows whether the complete commit series changes that result and prevents misattributing another
+ part of the large `2dce5cd` commit to the ledger.
+- Rows 5 and 6 independently distinguish the listener ledger from its UI/reconciliation consumer;
+ neither is interpreted by removing both variables at once.
+- Row 7 becoming negative proves queue/lifecycle ownership is the curative slice rather than merely
+ deleting multi-device availability support.
+- Row 8 affects an amplifier only if the listener rows remain positive while recovery suppression
+ changes the failure rate.
+- Row 9 distinguishes AVFoundation materialization from the ledger on the real integration path.
+- Row 10 tests the unique new mechanism—all-input listener attachment to transient objects—without
+ removing physical multi-device availability or the older single monitored-device baseline.
+- A positive minimal AVFoundation-discovery+VPIO row with no FluidVoice per-input ledger falsifies the
+ ledger as an inducing requirement, even if it remains an amplifier.
+- If row 2 is positive but rows 3–4 are negative, automate `git bisect` across the remaining upstream
+ audio commits using the harness; do not nominate a commit from log messages alone.
+
+Decision gate:
+
+- If condition 1 hangs, quarantine/disable VPIO on the affected OS and use the supported SCK path while
+ filing the minimal reproduction with Apple. Application-side coordination is not the curative fix.
+- If condition 2 hangs but 1 does not, identity/AVFoundation isolation is a curative slice.
+- If condition 4/5 hangs but 1 does not, listener migration and transition suspension are a curative
+ slice. They begin by retargeting the implicated existing owners and moving add/remove to a separate
+ control executor; they do not wait for the hub.
+- Compare condition 3 with condition 1. If prewarm adds hangs or materially worsens the measured rate,
+ async dictation quiescence is a curative slice.
+- If only condition 6 hangs, add combinations until the smallest sufficient trigger is identified.
+- If multiple isolation rows hang independently, Phase 1 is the union of every positive row's curative
+ slices. Re-run every positive row and their combination after each slice; a lower rate is not a pass.
+- If no harness row reproduces, do not guess a curative fix or enable VPIO broadly. Escalate to the
+ instrumented in-app path/device matrix, ship the two proven hazard repairs (off-main listener
+ discipline and transition suppression) behind the VPIO kill switch as defense-in-depth, and keep
+ VPIO disabled on the affected OS until the shipped-path gate is met.
+
+### Phase 1 — curative slice selected by Phase 0
+
+Implement only the smallest change that Phase 0 proves removes the trigger: AVFoundation isolation,
+off-main listener ownership, or dictation quiescence. Re-run the same isolation condition before
+combining architectural changes. Keep a kill switch for the VPIO path so rollback does not require a
+new build; never use the switch to bypass incomplete teardown. This phase may retarget existing listener
+owners directly and must not wait for the hub/ledger architecture.
+
+### Phase 2 — listener discipline and transition suspension
+
+Move all FluidVoice Core Audio listener delivery off main, prohibit add/remove from the delivery queue,
+and suspend per-device reconciliation across start/stop/switch. Migrate one complete owner at a time;
+never leave an owner half hub/half legacy. Both listener add and remove paths get runtime diagnostics.
+
+### Phase 3 — real topology ownership and handoff
+
+Add the coordinator state machine and dependency protocols. Make meeting acquisition async: suppress
+events, reuse the existing cancel/drain barrier, retire prewarm, then start VPIO. Cover start, stop,
+VPIO↔SCK backend switches, service restart, cancellation, and quarantined failure. Reverse the sequence
+before exactly one dictation reconciliation/prewarm.
+
+### Phase 4 — identity/backend separation
+
+If not already selected as Phase 1, remove AVFoundation discovery/default/authorization calls from the
+online VPIO transition. Resolve AVFoundation IDs only inside in-room or SCK adapters after topology
+handoff. Test device replacement where an object ID changes but the Core Audio UID remains stable.
+
+### Phase 5 — system validation and rollout
+
+- statistically justified automated start/stop cycles with idle prewarm and detector enabled;
+- input/output matrix: built-in, USB, Bluetooth, and mismatched input/output routes;
+- device disconnect, default-route change, sleep/wake, and audio-service restart during every state;
+- Zoom desktop, Google Meet in Chrome, and Teams desktop while application audio is active;
+- main-runloop stall budget and zero overlap assertions from signposts;
+- two-hour meeting soak followed by successful dictation handback;
+- fallback and rollback verification with no permission/signing changes.
+- forced VPIO→SCK downgrade and dwell-based SCK→VPIO upgrade under Bluetooth/output-route changes;
+- hotkey input during post-meeting handback and `failedQuarantined` behavior;
+- own VPIO activity produces no meeting-detection prompt;
+- listener ledger count returns to baseline after selected-microphone unplug and service restart.
+- a privacy-safe off-main main-runloop watchdog is active at meeting start/stop/switch boundaries and
+ persists only phase/generation/timing plus a next-launch VPIO-disable marker; it records no audio,
+ transcript, meeting title, device name, or application/window title.
+
+## 11. Acceptance criteria
+
+- No main-thread hang on any shipped capture path. A VPIO-only harness hang is an acceptable diagnostic
+ outcome only when VPIO is disabled on that affected OS and the shipped SCK path passes its gates.
+- Every Phase 0-positive targeted harness row has zero failures in at least 2,995 independent post-fix
+ cycles, bounding per-start hang probability to at most 0.1% at 95% confidence; the real-device matrix
+ additionally has zero hangs in at least 100 cycles per representative route.
+- Runtime instrumentation reports no FluidVoice Core Audio listener add **or remove** using
+ `DispatchQueue.main`, and no removal from its listener's delivery queue.
+- No ASR prewarm or route-recovery start while the topology coordinator is meeting-owned.
+- At most one coalesced dictation reconciliation after meeting handback.
+- Meeting start or backend switch either commits healthy capture or returns a bounded error after
+ fully observed rollback; incomplete teardown enters `failedQuarantined` and does not reopen audio.
+- Dictation behavior before and after a meeting passes its existing integration tests and real-device
+ smoke matrix.
+- Instrumentation proves zero overlap among dictation prepared/running/recovering and meeting
+ preparing/recording/switching/stopping states using matched interval signposts checked by tests.
+- The production off-main heartbeat records a next-launch quarantine marker when main stalls during an
+ audio transition and never attempts recovery from the frozen process.
+
+## 12. Apple documentation basis
+
+- [`AudioObjectAddPropertyListenerBlock`](https://developer.apple.com/documentation/coreaudio/audioobjectaddpropertylistenerblock%28_%3A_%3A_%3A_%3A%29)
+ retains the supplied dispatch queue until matching removal and documents asynchronous delivery except
+ for I/O-context properties.
+- [`AudioObjectRemovePropertyListenerBlock`](https://developer.apple.com/documentation/coreaudio/audioobjectremovepropertylistenerblock%28_%3A_%3A_%3A_%3A%29)
+ requires the queue on which the listener was dispatched, supporting an explicit registration ledger.
+- [`setVoiceProcessingEnabled`](https://developer.apple.com/documentation/avfaudio/avaudioionode/setvoiceprocessingenabled%28_%3A%29)
+ is the supported AVAudio I/O-node boundary for enabling voice processing.
+- [`AVCaptureDevice.DiscoverySession`](https://developer.apple.com/documentation/avfoundation/avcapturedevice/discoverysession)
+ materializes the currently available capture devices and can monitor device-list changes.
+- [`SCStreamConfiguration`](https://developer.apple.com/documentation/screencapturekit/scstreamconfiguration)
+ supports microphone capture. The installed SDK's `SCStream.h` specifies that
+ `microphoneCaptureDeviceID` is an `AVCaptureDevice.uniqueID`.
+
+## 13. Review status
+
+Initial independent verdicts were all **REVISE**:
+
+- Fireworks Kimi K3 through OpenCode: `REVISE`;
+- xAI Grok 4.6: the Orchestrate route failed before producing analysis; a direct Grok 4.6 continuation
+ then returned `REVISE` without modifying files;
+- Claude Opus 5 through Orchestrate: `REVISE`.
+
+### Consensus accepted
+
+- Two parked stacks are consistent with, but do not prove, a closed circular wait. Resolve HAL's sync
+ target before naming the final cycle.
+- Direct prewarm invalidation and scheduled recovery prove an ownership gap, not participation in the
+ observed wait. The direct lifecycle's dedicated listener/control queues are a pattern to preserve.
+- FluidVoice's per-device listener add/remove on main is the strongest app-owned participant hypothesis
+ and must be isolated before building a coordinator around an assumed cause.
+- AVFoundation identity/materialization can be the whole trigger; the VPIO path must be tested without
+ it, and authorization lookup inside `MeetingMicrophoneCapture.start` must leave the transition.
+- Phase order must follow the isolation result. “Coordinator first” was removed.
+- Backend switches, service restart, incomplete rollback, Bluetooth behavior, detector self-activity,
+ and post-meeting hotkeys require explicit topology states and tests.
+
+### Review disagreements resolved
+
+- One review inferred that auto-detection was absent because its source is untracked and absent from
+ repository `HEAD`. That inference is rejected: the second incident's installed-app log explicitly
+ records `MeetingAutoDetector detector-started` before the freeze. It remains an active incident-build
+ listener owner. The installed build predating the later overlay work does not imply it predates the
+ detector work.
+- Reviewers differed on whether a global hub/coordinator is oversized. This revision makes the curative
+ BUG-001 slice evidence-dependent and narrows the hub to a registration ledger plus transition-event
+ coalescer. The full topology state machine remains required for the already-existing VPIO↔SCK switch
+ paths, but it is not allowed to delay the Phase 0-proven curative change.
+
+### Final gate and closure
+
+The first post-revision gate returned Kimi `APPROVE`, Opus `APPROVE` with five blocking clarifications,
+and Grok `REVISE`. The final clarifications are incorporated:
+
+- AVFoundation object/listener retention moved from proven to inferred;
+- the decision gate now handles multiple positive rows and zero reproduction;
+- the Phase 1 listener slice explicitly does not wait for a hub;
+- SCK→VPIO requires app-owned AVFoundation release plus an observed barrier and can be prohibited
+ in-process when retained framework state is hazardous;
+- `stableDictationActive`, next-launch quarantine for a dead main loop, a production off-main watchdog,
+ and numerical statistical gates are defined.
+
+Grok's final closure review returned **APPROVE** with no remaining implementation blockers. Final
+review state: **Kimi APPROVE, Opus APPROVE, Grok APPROVE**.
+
+### Rebase-regression addendum review
+
+The later rebase analysis initially returned **REVISE** from both Kimi K3 and Grok 4.6. Their accepted
+corrections demote `2dce5cd` from a claimed trigger to an unconfirmed rebase-introduced suspect, keep
+AVFoundation+VPIO co-equal, add `3e04401`, split the ledger from its consumer, control detector state,
+require token-to-dying-object correlation, add transient-device exclusion, and define statistical and
+falsification gates. Claude Opus was not rerun for this addendum because the current repository
+disclosure policy/tool gate permits relevant source and diffs only to Kimi and Grok; the previous Opus
+approval applies to the base RCA, not this addendum.
+
+After those corrections, the final rebase-addendum gate returned **Kimi APPROVE** and
+**Grok APPROVE**, with no remaining regression-analysis blockers.
+
+### Production mitigation closure
+
+Subsequent Phase 0 rows isolated aggregate membership in `AudioHardwareObserver`'s broad
+`DeviceIsAlive` ledger as the narrowest passing condition. The production implementation now filters
+only `kAudioDeviceTransportTypeAggregate` before both the ledger's removal set and add loop. It is
+unconditional in Debug and Release; diagnostic flags are not required. Non-aggregate monitoring,
+system/default-device listeners, liveness queries, and ASR's selected-device listener remain unchanged.
+
+Final validation completed:
+
+- normal dictation and three meeting start/stop cycles passed on the production-shaped A/B build;
+- 185 scoped meeting/dictation/diagnostic tests passed, with one expected opt-in hardware skip;
+- the Release configuration and canonical Apple-signed Debug build both compiled successfully;
+- Kimi K3 and Grok 4.6 approved the scoped production policy; Claude Opus's requested evidence wording
+ and detector-provenance corrections are incorporated here; and
+- the installed `/Applications/FluidVoice Debug.app` retained the same bundle ID, Team ID, Apple
+ Development identity, and designated requirement, and passed strict deep signature verification.
+
+This closes the reproducible incident with an evidence-scoped mitigation. It does **not** close the
+entire private HAL deadlock class or satisfy the 2,995-cycle statistical reliability gate. Dedicated
+off-main Core Audio listener lifecycle ownership, live USB/Bluetooth/iPhone hot-plug acceptance, and
+the long-run reliability gate remain explicit follow-up work.
diff --git a/MEETING_CALENDAR_INTEGRATION_PLAN.md b/MEETING_CALENDAR_INTEGRATION_PLAN.md
new file mode 100644
index 00000000..f07e9588
--- /dev/null
+++ b/MEETING_CALENDAR_INTEGRATION_PLAN.md
@@ -0,0 +1,496 @@
+# Local Calendar Meeting Reminder Plan
+
+**Status:** Deferred / ready for implementation planning
+**Last revised:** 2026-08-22
+**Product direction:** Local-first EventKit integration with FluidVoice in-app reminders first. System notifications are a later phase after dogfooding.
+
+## 1. Objective
+
+Add an optional local calendar integration that reads meeting events already available through macOS Calendar and reminds the user through FluidVoice's existing in-app notification surfaces.
+
+The first release does not use OAuth, a sync backend, meeting bots, automatic recording, or macOS system notifications. Calendar data is context for reminders and later post-confirmation metadata; it is never evidence that independently creates or confirms a live meeting episode.
+
+### Initial user flow
+
+1. The user enables **Calendar meeting reminders** in Meeting Settings.
+2. FluidVoice explains why macOS labels the permission as Full Access even though FluidVoice performs no calendar writes.
+3. FluidVoice activates its Settings window and requests EventKit access.
+4. The user selects calendars. Nothing is selected automatically.
+5. FluidVoice fetches eligible meetings from those calendars.
+6. At approximately one minute before an eligible meeting, FluidVoice shows its nonactivating reminder HUD.
+7. The reminder offers:
+ - **Join** — revalidate and open the conference URL.
+ - **Prepare** — open Meeting setup with an ephemeral title seed; never start recording.
+ - **Not now** — suppress only that occurrence.
+8. After 20 seconds, an unhandled HUD collapses into an actionable Upcoming Meetings section in the existing FluidVoice menu.
+
+## 2. Non-negotiable invariants
+
+1. Calendar access is optional and off by default.
+2. FluidVoice never writes through EventKit.
+3. Calendar data never creates or confirms a `MeetingAutoDetector` episode.
+4. Calendar data never changes live-detection thresholds or confidence.
+5. No calendar path calls recording or capture-configuration APIs.
+6. Exact PID/window capture targeting remains unchanged.
+7. Denied, revoked, unavailable, stale, or malformed calendar data cannot reduce existing live-detection behavior.
+8. EventKit objects remain inside one serialized provider and never escape into the application.
+9. Calendar event payloads are not cached on disk in v1.
+10. Titles, notes, locations, raw URLs, meeting codes, passcodes, and attendees never enter logs or analytics.
+11. No new status item is introduced; reminders use the existing FluidVoice HUD and menu.
+12. No meeting-related `UNUserNotificationCenter` permission, category, or request is introduced before the in-app dogfood gate passes.
+
+## 3. Apple platform constraints
+
+- EventKit has no read-only authorization. Reading events requires `requestFullAccessToEvents()` and `NSCalendarsFullAccessUsageDescription`, even when application code never writes.
+- Sandboxed macOS apps require the calendar entitlement. FluidVoice is currently not sandboxed, so the entitlement should not be added until App Sandbox is actually enabled.
+- `events(matching:)` is synchronous and must not run on the main actor.
+- `EKEventStoreChanged` means previously fetched objects may be stale. Refetch the current range and replace the complete snapshot set.
+- Do not automatically call `EKEventStore.reset()` for store-change notifications. Apple documents `reset()` as reverting unsaved state and invalidating store-created objects; notification guidance requires a refetch.
+- Event and calendar identifiers can change after synchronization or account removal/re-add. They are hints, not permanent primary keys.
+- A predicate with `nil` calendars searches every calendar. FluidVoice must skip the fetch entirely when zero selected identifiers resolve to calendars.
+
+Primary references:
+
+- [Accessing the Event Store](https://developer.apple.com/documentation/eventkit/accessing-the-event-store)
+- [Retrieving Events and Reminders](https://developer.apple.com/documentation/eventkit/retrieving-events-and-reminders)
+- [Updating with Notifications](https://developer.apple.com/documentation/eventkit/updating-with-notifications)
+- [`EKEventStore.reset()`](https://developer.apple.com/documentation/eventkit/ekeventstore/reset%28%29)
+- [`calendarItemIdentifier`](https://developer.apple.com/documentation/eventkit/ekcalendaritem/calendaritemidentifier)
+
+## 4. V1 product policy
+
+### Eligible meeting
+
+An event is eligible when all of the following are true:
+
+- It belongs to a resolved, user-selected calendar.
+- It is timed and not all-day.
+- It is not canceled.
+- Its duration is between 5 minutes and 8 hours.
+- A directly validated conferencing HTTPS URL is found in `event.url`, location, or notes.
+- The current user has not explicitly declined, when that state can be reduced to a transient Boolean without retaining the roster.
+
+Tentative events remain eligible. Attendees, organizer, busy/free state, and attendee count are not required.
+
+### Reminder window
+
+- Opens at `start - 60 seconds`.
+- Closes at `start + 2 minutes`.
+- The actionable menu entry remains available until `event end + 2 minutes`.
+- Ending a recording after the event start never triggers a catch-up HUD; the event remains menu-only.
+
+### Calendar selection
+
+- Permission grant selects zero calendars.
+- The picker appears immediately after grant.
+- Missing or re-added calendar identifiers remain visibly unresolved.
+- FluidVoice never silently substitutes all calendars.
+- If the resolved selection is empty, no predicate is constructed and no event fetch occurs.
+
+### Sensitive UI
+
+The floating HUD uses generic copy by default, such as **Meeting starts in 1 minute**, with time and provider icon. It does not render the raw event title, reducing accidental disclosure during screen sharing.
+
+The event title may appear in the explicit Upcoming Meetings UI/menu and Prepare flow. It becomes ordinary persisted meeting metadata only after the user explicitly starts or saves a meeting.
+
+## 5. Target architecture
+
+```text
+EventKitCalendarProvider
+ |
+ v
+LocalCalendarEventSnapshot[]
+ |
+ +--> CalendarConferenceLinkParser
+ |
+ v
+CalendarReminderReconciler
+ |
+ +--> CalendarPromptCoordinator --> existing FluidVoice HUD
+ |
+ +--> UpcomingMeetingsModel -----> existing FluidVoice menu/settings UI
+ |
+ `--> CalendarMeetingCorrelator (later, post-confirmation only)
+```
+
+### Proposed responsibilities
+
+#### `EventKitCalendarProvider`
+
+- Own exactly one long-lived `EKEventStore`.
+- Serialize every store operation.
+- Request permission on the main actor.
+- Run event predicates off-main.
+- Convert EventKit objects immediately into immutable `Sendable` snapshots.
+- Check authorization before and after a fetch.
+- Discard a result if authorization changed during the fetch.
+- Replace snapshots wholesale rather than merging framework objects.
+
+#### `LocalCalendarEventSnapshot`
+
+V1 fields:
+
+- Volatile local/external identity hints.
+- Selected calendar identifier.
+- Sensitive, non-`Codable` title value with redacted textual description.
+- Start and end dates.
+- All-day and canceled flags.
+- Transient `isCurrentUserDeclined` Boolean.
+- Normalized provider and meeting identity.
+- Ephemeral actionable URL.
+
+No attendee, organizer, notes, location, or raw URL persistence.
+
+#### `CalendarConferenceLinkParser`
+
+- Pure and independently testable.
+- Scan `event.url`, location, then notes; continue past non-meeting URLs.
+- Bound the number of notes bytes inspected.
+- Extract bounded HTML `href` candidates where necessary.
+- Accept direct provider HTTPS URLs only in v1.
+- Reject redirect wrappers, userinfo, non-HTTPS schemes, non-ASCII hosts, malformed hosts, and incorrect subdomain boundaries.
+- Share a data-driven provider host table with live detection while keeping invite and strict in-call policies separate.
+- Preserve existing `MeetingInCallURLMatcher` results exactly.
+
+#### `CalendarReminderReconciler`
+
+Derive reminder state rather than incrementally mutating independent timers:
+
+```text
+snapshots
+ -> eligible occurrences
+ -> desired HUD/menu state
+ -> reconcile against presented/terminal aliases
+```
+
+- Use an injected clock.
+- Use one rescheduled wall-clock timer for the next reminder boundary, expiry, or fetch horizon.
+- Revalidate selection, snapshot, URL, recording state, expiry, and suppression immediately before presentation or action.
+- Inspect only existing materialization-safe activity properties; never instantiate the lazy meeting coordinator merely to check recording state.
+
+#### Source-neutral prompt coordinator
+
+Semantic identity is typed:
+
+```swift
+enum MeetingPromptIdentity {
+ case live(LiveEpisodeID)
+ case calendar(CalendarOccurrenceKey)
+}
+```
+
+An independent internal presentation token retains async race/cancellation protection.
+
+Calendar and live prompts have separate typed action closures. A calendar code path must be unable to call detector dismissal, timeout, adoption, or start methods.
+
+The coordinator treats both a visible live prompt and the detector's hidden suppression-retrying prompt as live occupancy.
+
+Priority:
+
+1. Active recording.
+2. Visible or pending live prompt.
+3. Calendar reminder.
+
+Outcomes:
+
+- `acted`
+- `dismissed`
+- `displaced`
+- `collapsed`
+- `expired`
+
+## 6. Reminder presentation behavior
+
+### Calendar HUD
+
+- Calendar bypasses bundle/frontmost matching because the meeting application may not yet be running.
+- It yields to active recording and active dictation/command overlays.
+- It is visible for `min(20 seconds, expiresAt - now)`.
+- Hover and accessibility interaction pause the visible countdown without extending the absolute eligibility deadline.
+- Accessibility announcements use generic provider/time copy rather than the sensitive title.
+- After 20 seconds it collapses into the existing FluidVoice menu.
+
+### Displacement
+
+- Live prompt arrives before calendar becomes visible: no presented alias; calendar may requeue until expiry.
+- Live prompt arrives after calendar becomes visible: write/retain the presented alias, collapse calendar to menu, and do not re-show its HUD.
+- Calendar presentation never traverses the detector's existing replacement-timeout callback path.
+
+### Wake and restart
+
+- Wake/restart inside the eligibility window with no presented alias: show the HUD.
+- Wake/restart after presentation: restore the menu entry, not the HUD.
+- Wake after expiry: no HUD.
+- If the HMAC secret is temporarily unavailable, fail closed for HUD presentation until it becomes readable; do not generate a replacement secret or rewrite aliases.
+
+### Multiple meetings
+
+- At most one calendar HUD is visible.
+- Choose among newly eligible, unpresented occurrences by `(startDate, occurrenceAlias)`.
+- If several become eligible in one reconciliation, show one HUD and put the others directly in the menu to avoid a burst.
+- Meetings whose windows open later remain independently eligible for their own HUD.
+
+### Existing menu
+
+- Add an independent Upcoming Meetings section; do not reuse or instantiate meeting-session UI state to populate it.
+- Derive entries lazily when the menu opens from current snapshots and opaque reminder state.
+- Entries expose Join, Prepare, and Not now using the same revalidation pipeline as the HUD.
+
+## 7. Identity and persistence
+
+Use HMAC-SHA256 with a per-install secret stored as `AfterFirstUnlockThisDeviceOnly` and cached once per process.
+
+```text
+primary alias = HMAC(
+ selectedCalendarID
+ + external/server identifier
+ + original occurrence date or start
+ + scheduled UTC start
+)
+
+fallback alias = HMAC(
+ selectedCalendarID
+ + normalized conference identity
+ + scheduled UTC start
+)
+```
+
+Including scheduled start deliberately re-arms a rescheduled meeting.
+
+Rules:
+
+- Generate the secret only on definitive item-not-found.
+- On any other Keychain error, enter fail-closed reminder mode.
+- Never use raw identifiers as persistent fallback keys.
+- Never delete or rewrite stored aliases merely because the secret could not be read.
+- Persist a presented alias only once the HUD is actually visible.
+- Join, Prepare, and Not now create terminal occurrence state.
+- Prune aliases after `event end + 2 minutes + 7 days`.
+
+## 8. Refresh and lifecycle
+
+Fetch range:
+
+```text
+now - 5 minutes ... now + 48 hours
+```
+
+All refresh triggers feed one coalescing coordinator:
+
+- UI-ready startup.
+- Permission or selection change.
+- Debounced `EKEventStoreChanged`.
+- Application activation.
+- Wake/session activation.
+- Timezone or system-clock change.
+- `lastSuccessfulFetch + 6 hours`.
+
+The six-hour horizon boundary prevents a continuously running Mac from missing meetings that were outside the previous 48-hour fetch range. It is scheduled through the same one-shot timer, not an independent polling loop.
+
+On an EventKit change notification:
+
+1. Treat existing EventKit objects as stale.
+2. Refetch the full current range.
+3. Convert to new value snapshots.
+4. Atomically replace the old snapshot set.
+5. Reconcile reminder state.
+
+## 9. Prepare and Join actions
+
+### Prepare
+
+Navigation needs an atomic, memory-only seed:
+
+```swift
+case meetingTranscription(seed: EphemeralMeetingSetupSeed?)
+```
+
+- Apply only when setup is pristine.
+- Never overwrite a visible dirty draft.
+- Never write the seed to `SettingsStore`.
+- Clear it at event end or after consumption.
+- Calendar invokes navigation only; it never invokes recording APIs.
+
+### Join
+
+- Refetch/reconcile current state as necessary.
+- Confirm the calendar remains selected.
+- Confirm the event remains eligible.
+- Reparse and revalidate the URL.
+- Open only the validated in-memory URL after the user's click.
+- On failure, keep the reminder/menu available with a content-free error; never open a fallback URL.
+
+## 10. Phased implementation
+
+### Phase 0 — Contract and build prerequisites
+
+- Amend the PRD requirements described above.
+- Add the calendar usage description.
+- Add educational permission UI and activated-window flow.
+- Lock privacy and persistence rules.
+
+**Gate:** no EventKit API is reachable without the usage string and explicit user action.
+
+### Phase 1A — Source-neutral HUD
+
+- Introduce typed semantic identity and source-specific callbacks.
+- Preserve live prompt behavior exactly.
+- Treat visible and suppression-retrying live prompts as occupancy.
+- Move detector-invariance Cartesian tests into this phase.
+
+**Gate:** existing live tests retain identical results; calendar identities cannot reach detector APIs.
+
+### Phase 1B — Calendar HUD policy
+
+- Add calendar payload, priority, displacement, collapse, fullscreen-safe generic copy, and in-memory reminder state behind the feature flag.
+- Do not introduce EventKit persistence keys here.
+
+**Gate:** fake calendar requests cannot mutate detector state or start recording.
+
+### Phase 1C — EventKit provider and parser
+
+- Add permission/status provider, calendar selection, bounded fetch, snapshots, conference parser, refresh coordinator, and HMAC secret service.
+
+**Gate:** empty resolved selections perform zero event fetches; malicious parser corpus passes; revocation clears UI and snapshots.
+
+### Phase 2 — Upcoming Meetings UI
+
+- Show selected/unresolved calendars, eligible/ineligible events, reasons, last refresh time, and repair actions.
+- Add the actionable Upcoming Meetings status-menu section.
+
+**Gate:** users can diagnose permission, selection, freshness, and parser eligibility before reminders are enabled.
+
+### Phase 3 — In-app reminder reconciler
+
+- Add deterministic scheduler, one-shot timer, durable opaque aliases, wake/restart behavior, and HUD/menu coordination.
+
+**Gate:** automated timing/churn suite and real-meeting dogfood criteria below pass.
+
+### Phase 4 — Post-confirmation calendar correlation
+
+Only after reminder dogfood:
+
+- Consume an already-confirmed live candidate plus snapshots.
+- Strong match: normalized conference identity.
+- Medium match: provider, time overlap, and captured application.
+- Title-only or ambiguous: no enrichment.
+- Never change detector confidence or exact capture target.
+
+### Phase 5 — System local notifications
+
+Only after Phase 3:
+
+- Request notification permission separately.
+- Add deterministic opaque request identifiers.
+- Use minimal lock-screen content.
+- Add Join and Prepare actions.
+- Reconcile pending/delivered requests.
+- Refetch and revalidate on action.
+- Select exactly one surface: FluidVoice HUD or system notification.
+
+### Phase 6 — Attendee-assisted naming
+
+Separate explicit opt-in:
+
+- Fetch roster only for an unambiguous matched event.
+- Reduce and discard raw participant data.
+- Require confirmation for every proposed name.
+- No cross-meeting voice identity.
+
+## 11. Test strategy
+
+### Detector isolation
+
+Run the Cartesian product of calendar actions against live states:
+
+- No live prompt.
+- Visible live prompt.
+- Suppression-retrying live prompt.
+- Live prompt starting.
+- Active recording.
+- Dictation/command overlay.
+
+Assert detector episode, consumption, bundle suppression, and dismissal-counter state is identical to the calendar-absent baseline.
+
+### Permission and EventKit
+
+- Feature disabled creates no event store and no TCC prompt.
+- Grant followed by zero selection performs no event fetch.
+- Denial and restriction.
+- Revocation before, during, and after a fetch.
+- Account/calendar removal and re-add.
+- Empty and unresolved calendar selection.
+- Store-change storms and stale-generation cancellation.
+- Manual signed Debug and Release TCC matrix.
+
+### Scheduler
+
+- Reminder boundary and expiry.
+- 20-second collapse.
+- Wake before and after presentation.
+- Restart inside and outside eligibility.
+- DST fold/gap.
+- Timezone and clock change.
+- Six-hour fetch horizon.
+- Edit, delete, cancel, reschedule, recurring detach, and identifier churn.
+- Overlap, equal-start ties, back-to-back events, and several newly due events.
+- Recording ends before and after event start.
+- Keychain locked, unavailable, item-not-found, and transient error.
+
+### URL security
+
+- Non-HTTPS and custom schemes.
+- Userinfo.
+- Non-ASCII and malformed hosts.
+- Dot-boundary attacks.
+- Redirect wrappers.
+- HTML notes and scan-size limits.
+- Multiple source fields where an earlier value is not a meeting URL.
+- Join-time revalidation and stale-link failure.
+
+### Privacy
+
+Run a fixture calendar containing distinctive titles, attendee names, notes, URLs, codes, and passcodes. Capture:
+
+- Logs.
+- Analytics payloads.
+- UserDefaults.
+- Keychain values.
+- Meeting setup state before explicit start/save.
+
+Assert that only selected calendar identifiers, opaque aliases, provider enums, and content-free counters persist or leave the calendar subsystem.
+
+## 12. Phase 3 dogfood gate
+
+Use at least 20 real eligible meetings.
+
+- At least 95% of first HUD presentations occur within ±5 seconds of the first schedulable moment.
+- Zero calendar-caused detector-state mutations.
+- Zero duplicate HUDs in one process lifecycle.
+- Zero wake bursts.
+- Zero wrong Join targets.
+- Zero raw calendar content in logs, analytics, or persistence.
+- Correct reminders after reschedule and recurring detach.
+- Fetch latency and energy impact recorded using content-free metrics.
+
+Do not begin system-notification work until this gate passes.
+
+## 13. Suggested first implementation slice
+
+Start only with Phase 0 and Phase 1A:
+
+1. Amend the PRD and add the usage description.
+2. Add educational permission UI scaffolding without calling EventKit yet.
+3. Introduce source-neutral prompt identity and callbacks.
+4. Preserve live behavior.
+5. Add the detector-invariance interleaving suite.
+
+Do not combine this slice with EventKit fetching or reminder scheduling. Keeping the first change narrow makes any live-detection regression attributable to the HUD refactor.
+
+## 14. Deferred product choices
+
+- Whether users may opt into showing meeting titles in the floating HUD.
+- Whether redirect wrappers are common enough in real EventKit data to justify bounded offline unwrapping.
+- Whether the six-hour horizon should change after energy measurements.
+- Whether overlapping meetings eventually need a chooser rather than menu-only secondary entries.
+- Whether system notifications should replace or complement the in-app HUD when FluidVoice is running.
diff --git a/MEETING_DETECTION_NOTIFICATION_DESIGN.md b/MEETING_DETECTION_NOTIFICATION_DESIGN.md
new file mode 100644
index 00000000..e5ef26da
--- /dev/null
+++ b/MEETING_DETECTION_NOTIFICATION_DESIGN.md
@@ -0,0 +1,612 @@
+# Meeting Detection and Notification Design
+
+Status: proposed
+Scope: calendar-independent runtime detection, in-app reminder, and meeting-end assistance
+Product posture: local-first, privacy-first, user-initiated recording
+
+## 1. Outcome
+
+FluidVoice should recognize a likely live call quickly enough to prevent a missed transcript, while treating every detection as a suggestion rather than permission to record.
+
+The system must:
+
+- notify only when independent, current signals identify the same application or browser meeting;
+- never begin recording without an explicit user action;
+- revalidate the meeting and exact capture target when the user acts;
+- withdraw a stale reminder when the evidence disappears;
+- identify likely meeting end conservatively without automatically stopping by default;
+- keep raw URLs, window titles, audio, and detection history on the device;
+- remain useful when optional permissions or newer CoreAudio attribution APIs are unavailable.
+
+Calendar events may enrich a candidate later, but are neither required nor authoritative for this design.
+
+## 2. Current implementation
+
+The current detector already has several strong properties:
+
+- Recording is prompt-only and requires an explicit click.
+- Native applications and browser meetings use separate tiers.
+- A native confirmation requires audio plus a qualifying application window.
+- Browser confirmation requires audio plus a fixed meeting-domain/path match.
+- Browser URL values and native window titles are not logged.
+- Exact application and, when known, window identifiers are passed to capture.
+- The detector remains separate from the lazily created recording coordinator.
+- Busy recording or dictation state suppresses new reminders.
+- Prompts deduplicate within an episode and explicit dismissals suppress repeats.
+- Sleep, screen lock, and user switching clear transient state.
+- The prompt supports VoiceOver announcements, Reduce Motion, keyboard actions, hover pause, and no auto-start.
+
+The implementation is currently a two-second polling state machine on the main actor. It combines:
+
+1. known running applications;
+2. device-wide microphone start/stop edges;
+3. per-application CoreAudio input or output activity on macOS 14.4 and later;
+4. native application window presence;
+5. a frontmost browser tab URL for supported meeting sites;
+6. capture readiness and existing FluidVoice activity.
+
+## 3. Root gaps
+
+These are correctness gaps in the signal model, not UI polish issues.
+
+### G1. Device activity is per device, but consumed as global activity
+
+The device listener emits an edge whenever any monitored input device changes. Its consumer treats each inactive edge as if all microphones became inactive. With two microphones, a loopback device, an aggregate device, or a device transition, one device stopping can incorrectly end evidence while another remains active.
+
+Required correction: maintain a set of currently active input device IDs and publish only aggregate transitions from zero to nonzero and nonzero to zero. Explicitly classify or exclude FluidVoice-created loopback devices.
+
+### G2. Process input and output are collapsed
+
+The process provider returns one Boolean when either application input or output is active. These signals mean different things:
+
+- input activity means the application owns a microphone path;
+- output activity may mean remote participants, a ringtone, media preview, or ordinary application sound.
+
+Required correction: expose input and output independently, with bundle identifier, CoreAudio process object, PID when resolvable, observation time, and source quality.
+
+### G3. Process attribution can use stale foreground history
+
+Device-wide evidence requires a recent foreground event, but process-attributed evidence only requires that the application has been foreground at least once during its lifetime. An application activated hours earlier can therefore satisfy this gate.
+
+Required correction: every foreground-dependent rule must have an explicit freshness window. Direct microphone ownership can reduce the need for foreground evidence, but must not silently turn an old timestamp into current intent.
+
+### G4. Confirmation is instantaneous
+
+Once audio and window/URL evidence coincide, the detector immediately creates an episode. A ringtone, pre-join test, transient microphone probe, or one polling sample can therefore produce a reminder. The queued/visible reminder is not promptly cancelled when those signals disappear.
+
+Required correction: add positive stability, negative hysteresis, and cancellation while stabilizing or prompting.
+
+### G5. Start validates readiness, not current meeting identity
+
+At click time, `canStart` checks that the episode is unconsumed and FluidVoice is ready. It does not require fresh live evidence. A user can act on a stale reminder after the call has ended or the browser has navigated away.
+
+Required correction: perform a fresh, bounded revalidation of the candidate, exact application, browser meeting locator when applicable, and capture source immediately before recording.
+
+### G6. Native window evidence has uneven specificity
+
+The Zoom path recognizes meeting-specific titles, but any layer-zero Teams or Webex window qualifies. Persistent home windows can combine with unrelated output activity and old activation history.
+
+Required correction: application-specific evidence policies. When a reliable meeting-window marker is unavailable, require stronger process ownership, current activation, and longer stability.
+
+### G7. Browser detection observes only the frontmost tab
+
+This avoids scanning private browser state broadly, but it misses a background or minimized call and can lose identity when the user presents from another tab. Browser process audio cannot identify which tab owns audio.
+
+Required correction: retain the last verified meeting locator ephemerally and refresh it opportunistically. Treat a different foreground tab as loss of visible correlation, not immediate proof that the call ended. Do not broaden to full-history or all-tab collection.
+
+### G8. Detector health is too narrow
+
+Only unreadable Zoom titles are surfaced. Process attribution availability, device-listener health, browser URL access, Accessibility timeouts, permission degradation, and stale polling are not represented coherently.
+
+Required correction: publish a capability snapshot and operational health state, separate from candidate confidence.
+
+### G9. Notification outcomes do not match user intent precisely
+
+“Not now” suppresses the whole application for 30 minutes, while timeout suppresses only the current episode. There is no direct permanent per-application control, pause control, explanation of why the reminder appeared, or persistent place to recover an auto-dismissed action.
+
+Required correction: model episode dismissal, time snooze, and source exclusion as different product actions.
+
+## 4. Design principles
+
+1. **Explicit rules before opaque scoring.** Use a small evidence-policy matrix whose outcomes can be explained and tested. A confidence band is an output, not an uninspectable weighted score.
+2. **Current evidence only.** Every fact has an observation time, freshness limit, source, and health quality.
+3. **Stable identity.** Evidence must refer to the same canonical application family and candidate locator.
+4. **Positive stability and negative hysteresis.** Starting a suggestion needs sustained evidence; losing it needs a shorter cancellation window before recording and a longer safety window during recording.
+5. **Asymmetric safety.** Prompt false positives damage trust; automatic recording is forbidden. Meeting-end false positives can lose content, so end detection only nudges by default.
+6. **Graceful degradation.** Missing optional permissions lower the available confidence; they do not masquerade as a healthy detector.
+7. **Minimal observation.** Read only the processes and windows already in the fixed registry. Reduce browser URLs immediately to an allowed provider plus opaque meeting locator.
+8. **One episode, one interruption.** A dismissal or timeout suppresses the current episode until it genuinely ends.
+
+## 4.1 User controls and sensitive contexts
+
+Detector accuracy is not consent to interrupt. A technically correct meeting match may still be a conversation the user never wants to transcribe.
+
+Launch controls are therefore part of the notification safety boundary, not later personalization:
+
+- **Suggestion mode:** `Passive` or `Floating reminder`. New installations default to Passive. Existing installations preserve their current explicit detector preference. A passive meeting indicator can explain the feature and offer to enable floating reminders, but it never changes the mode automatically.
+- **Pause all suggestions:** one hour, until tomorrow, or indefinitely from the menu bar and Meeting settings.
+- **Application exclusions:** never suggest for a selected native application or browser.
+- **Provider exclusions:** never suggest for a selected browser meeting provider without excluding the whole browser.
+- **Suggest only when I use my microphone:** optional stricter mode for users who do not want muted/listen-only calls suggested.
+- **End reminders:** independently enabled or disabled; default on only while FluidVoice is actively recording.
+
+Private browser windows are excluded by default. A browser adapter may participate only if it can reliably identify private-window state and fail closed. If that distinction is not reliable for a browser/version, browser meeting suggestions are unavailable for that adapter rather than inspecting the window optimistically.
+
+Only the active macOS login session is observed. Lock, fast-user-switch, logout, or sleep clears transient candidates and private locator digests. FluidVoice does not infer who is physically operating a shared Mac; the reminder always says that nothing is recording and requires an action in the active session.
+
+The first successful capture started from a suggestion shows a concise, one-time local reminder that the user is responsible for following participant-consent and organization rules. Managed organization policy can make that reminder recurring or disable suggested capture, but cannot enable automatic recording.
+
+## 5. Architecture
+
+```text
+Workspace events CoreAudio process observations
+Device aggregate Window / browser correlation
+ \ /
+ MeetingSignalMonitor (background actor)
+ |
+ timestamped facts
+ |
+ MeetingEvidenceReducer (pure)
+ |
+ MeetingCandidateStore
+ |
+ PromptPolicy
+ |
+ InAppMeetingReminderCoordinator
+ |
+ explicit Start -> fresh revalidation
+ |
+ MeetingSessionCoordinator
+```
+
+### 5.1 MeetingSignalMonitor
+
+This component owns observation and health, off the main actor.
+
+It publishes immutable snapshots:
+
+```swift
+struct MeetingSignalSnapshot: Sendable {
+ let observedAt: DetectorInstant
+ let applications: [ApplicationAudioObservation]
+ let aggregateInput: AggregateInputObservation
+ let windows: [ObservedMeetingWindow]
+ let browserCorrelations: [BrowserMeetingCorrelation]
+ let capabilities: DetectionCapabilities
+ let generation: UInt64
+}
+```
+
+`DetectorInstant` wraps `ContinuousClock.Instant`. Sleep advances this clock so every pre-sleep fact fails freshness checks after wake; `SuspendingClock` is forbidden in detector policy.
+
+Properties:
+
+- Process input and output are separate facts.
+- Snapshots have a monotonic generation and timestamp; stale async AX results are discarded.
+- CoreAudio enumeration runs off-main.
+- A device edge requests an immediate process refresh, rate-limited to avoid storms.
+- Normal cadence is one second while a candidate is stabilizing or recording, one second while relevant apps are running unless a proven process-audio push signal supplies equivalent latency, and thirty seconds only when push listeners are healthy and no relevant application is running.
+- A watchdog marks the monitor degraded after five missed expected observations.
+- Device changes temporarily lower confidence instead of creating false start/end edges.
+
+### 5.2 Canonical identities
+
+Do not key candidates only by PID and window number. Both can be reused.
+
+```text
+application family = canonical supported application or browser
+process identity = PID + launch timestamp when available
+meeting locator = native window token or provider + one-way in-memory locator digest
+episode identity = application family + process identity + meeting locator generation
+```
+
+The digest is session-random and is never persisted. Raw URLs and titles never enter logs, analytics, or notification copy.
+
+### 5.3 MeetingEvidenceReducer
+
+The reducer is a pure state machine. It accepts snapshots and user outcomes and emits candidate transitions. This makes timing deterministic in tests.
+
+Candidate states:
+
+```text
+idle
+ -> observing
+ -> stabilizing
+ -> confirmed
+ -> reminderPresented
+ -> accepted | dismissed | timedOut
+ -> ending
+ -> ended
+```
+
+Rules:
+
+- `observing`: at least one relevant signal exists.
+- `stabilizing`: a valid application-specific evidence combination exists.
+- `confirmed`: the same combination remains valid for its stability threshold.
+- `reminderPresented`: PromptPolicy authorizes an interruption.
+- `accepted`: the user requested capture and fresh revalidation passed.
+- `dismissed` or `timedOut`: no more reminders for this episode.
+- `ending`: required evidence weakened; negative grace is running.
+- `ended`: application exited, meeting locator disappeared and audio ceased, or the absence threshold elapsed.
+
+Any loss of the required combination during `stabilizing` returns to `observing`. Before capture, a confirmed or visible reminder is invalidated after three seconds without a valid combination. During capture, signal loss never automatically stops the recording by default.
+
+### 5.4 Evidence policy matrix
+
+| Context | Required evidence | Stability | Result |
+|---|---|---:|---|
+| Native, meeting-specific window | same app has input or output activity + meeting window | 4 s | high-confidence reminder |
+| Native, generic persistent window | same app owns input; recent activation is supporting evidence | 6 s | high-confidence reminder |
+| Native, generic persistent window, muted | same app has sustained output + recent activation + app-specific call marker | 8 s | high-confidence reminder |
+| Browser | browser input or output + currently verified supported meeting locator | 5 s | high-confidence reminder |
+| Browser, locator temporarily unreadable after verification | same browser audio continues and locator was verified recently | no new reminder; preserve existing candidate for 15 s | continuity only |
+| Legacy/degraded OS attribution | aggregate mic + recent foreground + qualifying window/URL | 8 s | medium confidence, passive in-app status only initially |
+| Audio only | any | — | no reminder |
+| Window/URL only | any | — | no reminder |
+| Generic browser mic with no supported meeting locator | any | — | no reminder |
+
+The exact thresholds are launch defaults, not remote feature flags. They may be adjusted only through a versioned local policy after trace evaluation.
+
+“Recent activation” means no more than 30 seconds old and is supporting evidence only. A direct same-process input owner does not require the app to remain frontmost; background calls must work.
+
+### 5.5 Capability and health model
+
+```swift
+struct DetectionCapabilities: Sendable, Equatable {
+ let processInputAttribution: Availability
+ let processOutputAttribution: Availability
+ let aggregateInputActivity: Availability
+ let nativeWindowIdentity: Availability
+ let browserMeetingCorrelation: Availability
+ let capturePermission: CapturePermissionState
+ let monitorHealth: MonitorHealth
+}
+```
+
+Availability is `available`, `permissionRequired`, `unsupported`, or `temporarilyDegraded`. Health is not evidence. The UI can explain why detection is limited without accidentally increasing confidence.
+
+## 6. Fresh start revalidation
+
+Clicking “Start transcript” executes the cancellable start transaction defined in Phase 4 of `MEETING_DETECTOR_PHASED_IMPLEMENTATION_PLAN.md`. That transaction owns the authoritative ordering, deadline, target-liveness race, and acceptance semantics.
+
+Failure leaves the user in control:
+
+- Evidence ended: “The call no longer appears active.”
+- Target changed or ambiguous: open source selection with the detected application preselected.
+- Permission missing: show the exact missing capability and a direct repair action.
+- FluidVoice busy: keep the current work untouched and explain that another audio task is active.
+
+No episode is consumed before capture succeeds. Repeated clicks are single-flight.
+
+## 7. In-app notification design
+
+### 7.1 Presentation policy
+
+The first user-facing phase uses only FluidVoice-owned surfaces. A high-confidence candidate always receives passive menu-bar status and receives a floating reminder only when the user has enabled Floating-reminder mode.
+
+It must:
+
+- use the display containing the detected meeting application when known, otherwise the active display;
+- never activate FluidVoice or steal keyboard focus;
+- remain keyboard and VoiceOver accessible;
+- respect Reduce Motion and avoid appearing over another application’s full-screen presentation;
+- keep a recoverable “Meeting suggestion” action in the menu bar while the transient panel is hidden;
+- withdraw within three seconds when pre-capture evidence becomes invalid;
+- show only once per episode.
+
+The menu-bar state is a first-class surface, not a fallback implementation detail:
+
+- Passive mode shows a neutral meeting-suggestion indicator without animation or sound.
+- Floating-reminder mode shows the same indicator whenever the panel is visible, suppressed, or timed out.
+- The menu item reads “Possible meeting in Zoom — Start transcript” and exposes the same source and privacy status to VoiceOver.
+- It persists until the episode ends, the user selects Not now, the source becomes excluded, or capture begins. Short correlation gaps use the episode’s end grace rather than removing it immediately.
+- A dot/badge may be enabled later; sound is default-off and outside the initial release.
+
+Recommended copy:
+
+```text
+Meeting may have started
+Zoom is using call audio. Nothing is being recorded.
+
+[Not now] [Start transcript]
+```
+
+Use “Call may have started” for call-oriented applications when the registry knows that distinction. Do not display a URL, window title, participant, or calendar subject in the calendar-free reminder.
+
+The panel remains available for 30 seconds; hover or keyboard interaction pauses the countdown. Panel timeout suppresses another floating interruption for that episode but preserves the passive menu-bar action until the episode ends. Timeout is therefore distinct from an active decline even though neither causes another panel.
+
+### 7.2 Actions are distinct
+
+- **Start transcript:** fresh revalidation followed by user-initiated capture.
+- **Not now:** actively decline and suppress this episode until it ends; remove its passive menu-bar action.
+- **Snooze 10 minutes:** hide the current panel, preserve only its passive menu-bar recovery, and prohibit another floating reminder for that episode. Other candidates may be detected but remain passive until the snooze expires. Expiry never re-presents an existing episode; only a different episode that becomes stable after expiry may show a panel.
+- **Don’t suggest for this app:** optional overflow action; persist a reversible local source exclusion.
+- **Why this appeared:** opens a local explanation using coarse evidence labels such as “meeting window” and “call audio,” never raw observed values.
+- **Pause suggestions:** menu-bar control with one hour, until tomorrow, and indefinite choices.
+
+Automatic timeout suppresses further floating interruptions for the episode but does not remove passive menu-bar recovery and does not count as negative feedback. An explicit “Not now” may contribute to a local suggestion to mute that source after repeated occurrences, but FluidVoice must not change settings automatically.
+
+### 7.3 Setup reminders
+
+A confirmed meeting can expose that capture is unavailable, but permission status determines whether FluidVoice may interrupt:
+
+- `notDetermined`: one contextual setup reminder may appear. If the user chooses Not now, persist that setup-reminder decline and do not ask again until a manual meeting-capture or settings action.
+- `denied`: passive settings/menu-bar status only. After the user declines a repair action, do not prompt again until they manually revisit meeting capture or re-enable setup reminders.
+- `restricted`: passive explanation only, with no misleading System Settings action.
+- `unsupported` or temporarily unavailable: passive explanation and retry status only.
+
+The auto-detected online-call path does not offer microphone-only capture when application/system audio permission is missing. A mic-only transcript would omit remote participants and violate the promise of a meeting transcript. If a separate mic-only mode is introduced later, it requires explicit source copy and its own product design.
+
+When a contextual setup reminder is allowed, it should name one repair action rather than sending the user to a generic setup screen:
+
+```text
+Meeting may have started
+Allow Screen Recording to capture Zoom audio. Nothing is being recorded.
+
+[Not now] [Open System Settings]
+```
+
+Show at most once per episode. Returning from System Settings triggers a fresh capability check. If permission remains absent, keep passive status and offer “Try again” in settings; never loop or immediately reopen System Settings. Detection settings must show the same capability state persistently.
+
+### 7.4 Interruption suppression and passive recovery
+
+Full-screen presentation, user-configured quiet mode, dictation, active recording, and another prompt can suppress the floating panel. macOS does not provide arbitrary applications a general Focus-state API, so FluidVoice must not claim to read Focus state; later system notifications inherit the operating system’s Focus delivery behavior. Suppression never produces a second toast explaining the first suppression. Instead, the menu-bar indicator changes to the neutral “possible meeting” state and remains accessible for the episode.
+
+Source exclusions produce no candidate indicator because the user explicitly requested silence. A diagnostics/settings row may show that a source is excluded without revealing a live meeting. Busy FluidVoice activity may show “Meeting suggestion available after current task” passively, but must never stop or replace the current task.
+
+### 7.5 Simultaneous-candidate arbitration
+
+Only one floating panel is allowed. Rank eligible candidates deterministically by:
+
+1. high confidence over medium confidence;
+2. exact same-process microphone input ownership;
+3. meeting-specific locator over generic application evidence;
+4. capture readiness;
+5. most recent transition into a stable candidate.
+
+Do not replace a visible panel or an in-progress Start transaction. Other valid candidates appear as menu-bar choices under “Other possible meetings.” If the user selects one, source selection clearly names each viable application before capture. Accepting one candidate suppresses interruptions while FluidVoice is busy but does not end or merge distinct episodes; they remain passive and may become actionable after the recording ends if still live.
+
+### 7.6 Browser observation contract
+
+Before browser detection is enabled, show this user-facing disclosure:
+
+> FluidVoice checks the current page only in supported browsers to recognize supported meeting sites. Matching happens on this Mac. It does not scan history or all tabs, and it does not store page addresses or titles. Private windows are excluded.
+
+Initial adapters are Chrome, Safari, Arc, Edge, Brave, and their supported meeting PWAs. Each browser/version must pass fixtures for current-page access and private-window exclusion. If Accessibility or page access is unavailable, that adapter reports degraded/unavailable and produces no browser reminder. The session-random meeting-locator digest is regenerated at launch and never appears in exported traces, so it cannot link meetings across sessions.
+
+### 7.7 System notifications later
+
+System notifications are a later phase behind a separate “System meeting notifications” setting, default off. Passive suggestion mode never escalates to a system notification unless the user independently enables this setting. When enabled, system delivery is considered only when FluidVoice is not visible or the floating reminder cannot be presented. Copy remains generic, and actions route through the same fresh revalidation transaction. System notifications never bypass source exclusions, episode suppression, pause, operating-system Focus delivery, or the no-auto-start rule.
+
+## 8. Meeting-end assistance
+
+Start and end use different policies.
+
+Before capture:
+
+- invalidate the reminder after three seconds without a valid start combination;
+- end the episode after 30 seconds of both missing application audio and missing meeting locator, or immediately when the process exits;
+- tolerate short browser correlation loss and device transitions.
+
+During capture:
+
+- never stop solely because the microphone is muted, the window is minimized, or one audio direction stops;
+- treat recent transcript output, application audio, a verified meeting locator, an alive exact capture target, or a qualifying native call marker as continuation evidence;
+- after 60 seconds in which none of the continuation-evidence signals above is present, show one non-modal, non-focus-stealing “Still recording?” nudge positioned away from detected presentation controls;
+- offer “Stop recording” and “Keep recording,” and state that stopping will finalize the local transcript;
+- choosing “Keep recording” suppresses every further end nudge for that recording, including after later source fluctuations;
+- default to no automatic stop.
+
+A future automatic-stop preference may be designed separately, with an explicit opt-in and substantially longer absence window. It is outside this phase.
+
+## 9. Privacy and local diagnostics
+
+### 9.1 Data handling invariants
+
+- Raw URLs and window titles are processed in memory and immediately reduced to provider, allowed-path classification, and ephemeral locator digest.
+- No participant names, content, titles, raw process paths, device names, audio, or transcript text enter detection diagnostics.
+- Candidate history is memory-only by default. Explicitly enrolled dogfood diagnostics may persist only the redacted bounded trace described below.
+- Persisted operational state is limited to user-facing preferences: suggestion mode, pause, source exclusions, end-nudge preference, setup-reminder dismissal, and consent acknowledgment.
+- No detector telemetry leaves the device without a separate, explicit opt-in design.
+
+### 9.2 Local decision trace
+
+Add a bounded, redacted circular buffer suitable for testing and support export:
+
+```text
+time delta | candidate token | transition | evidence classes | policy result | health
+```
+
+Example evidence classes are `processInput`, `processOutput`, `meetingWindow`, `meetingURL`, `recentActivation`, and `aggregateMicFallback`. Tokens are random per launch. Raw bundle identifiers, PIDs, device identifiers, locator digests, URLs, paths, and titles are never written into the trace buffer; redaction happens at write time, not at export.
+
+The in-memory default buffer holds at most 5,000 transitions and clears at launch. Explicitly enrolled dogfood diagnostics may retain the same redacted records for at most seven days. Users can inspect detector health, export the redacted trace explicitly, or select “Clear detection diagnostics.” Export never includes the session locator digest. A test gate verifies that detector operation and trace review make no network requests.
+
+Dogfood enrollment is explicit. Enrolled builds provide a local review inbox containing coarse candidate time, registry application label, outcome, and evidence classes. Review data remains on device unless the user exports it.
+
+Local aggregate counters may include:
+
+- candidates created, confirmed, cancelled during stability, and ended;
+- reminders shown, suppressed, timed out, dismissed, and accepted;
+- time from first valid combination to reminder and from reminder to capture;
+- start revalidation failures by coarse reason;
+- end nudges accepted or rejected;
+- capability and monitor degradation counts.
+
+## 10. Product decisions
+
+This design resolves the following defaults:
+
+| Decision | Default |
+|---|---|
+| Automatic recording | Never |
+| New-install suggestion mode | Passive menu-bar status; user enables floating reminders |
+| Existing-install suggestion mode | Preserve the user’s current detector setting |
+| High-confidence candidate | Menu-bar status, plus floating reminder when enabled |
+| Medium-confidence candidate | Menu-bar status only during initial rollout |
+| Explicit “Not now” | Suppress current episode |
+| Timeout | No second panel; preserve passive recovery; no negative-feedback count |
+| Permanent source exclusion | Explicit, reversible local setting |
+| Private browser windows | Excluded; unsupported adapter fails closed |
+| Missing denied/restricted permission | Passive status only; no recurring repair prompt |
+| Likely meeting end | Ask once; never auto-stop by default |
+| End nudge preference | Independent toggle; default on during active recording |
+| Consent reminder | One-time on first suggestion-started capture; policy may require recurring |
+| Raw URL/title retention | None |
+| External detector telemetry | None |
+| System notification | Later, separate explicit opt-in; default off even in Passive mode |
+
+One-hour/until-tomorrow pause, application exclusions, and browser-provider exclusions ship with the first strengthened reminder release. Browser-profile-specific exclusions and organization-policy management remain later extensions.
+
+## 11. Phased implementation rationale
+
+The authoritative phase numbering, work packages, and gates are in `MEETING_DETECTOR_PHASED_IMPLEMENTATION_PLAN.md`. This section is retained only as the original rollout rationale; references to implementation phases must use the detailed plan.
+
+### Rationale A — Correct signal semantics
+
+- Aggregate device state across all input devices.
+- Exclude known FluidVoice loopback devices.
+- Split process input and output observations.
+- Add observation generations, health, and a watchdog.
+- Move CoreAudio enumeration off-main.
+- Add freshness to every timestamp-dependent rule.
+- Build deterministic trace-replay tests.
+
+Exit gate: multi-device and stale-attribution tests pass; observation does not block the main actor; no product behavior is broadened.
+
+### Rationale B — Candidate reducer in shadow mode
+
+- Implement the pure evidence reducer and application-specific policies.
+- Run old and new decisions side by side locally without showing additional reminders.
+- Make redacted trace export available in debug builds.
+- Dogfood native applications first, then opt-in browsers.
+
+Exit gate: the labelled-evaluation sample and confidence-bound requirements in Section 13.1 pass for each supported application family, no duplicate episode reminders occur, and p90 confirmation remains under ten seconds for high-confidence joins.
+
+### Rationale C — Strengthened in-app reminder
+
+- Route visible reminders through the new candidate/prompt policy.
+- Add positive stability, live invalidation, current-episode dismissal, menu-bar recovery, and fresh start revalidation.
+- Add exact capability repair CTAs.
+- Add Passive/Floating mode, global pause, application/provider exclusions, and end-nudge preference.
+- Add deterministic simultaneous-candidate arbitration and the private-browser fail-closed contract.
+- Retain no-auto-start.
+
+Exit gate: zero starts after failed live revalidation; stale reminders withdraw within three seconds; exclusions and pause act immediately; menu-bar recovery and source identification pass task-based usability tests; median unwanted reminders no more than one per active user per week during dogfood.
+
+### Rationale D — Explanation and coverage
+
+- Add local “Why this appeared?” evidence explanation.
+- Expand application-specific policies only with trace fixtures and precision evidence.
+- Handle browser/native handoff, reconnects, waiting rooms, breakout transitions, and simultaneous candidate applications.
+
+Exit gate: each added source meets the same per-source precision target; exclusions take effect immediately and survive restart.
+
+### Rationale E — System notifications
+
+- Request notification permission contextually and only after user opt-in.
+- Add a separate System meeting notifications preference; never infer it from Passive/Floating suggestion mode.
+- Use system notifications only when the in-app surface is unavailable.
+- Reuse the same episode suppression, actions, privacy copy, and start revalidation.
+
+“In-app surface unavailable” means no eligible floating panel was presented because the panel was suppressed by presentation policy, or a passive menu-bar action remained unactivated for the configured system-notification delay. FluidVoice does not claim to know whether the user visually noticed the menu item. It never means source exclusion, explicit Not now, pause, denied permission, or an invalid candidate. When the system surface is selected, the floating panel is cancelled so the two surfaces never duplicate.
+
+Exit gate: system and in-app surfaces never duplicate; Focus and permission states degrade to menu-bar recovery; notification opt-out does not disable detection.
+
+## 12. Test strategy
+
+### Reducer and invariants
+
+- Audio-only and window-only never confirm.
+- A candidate cannot confirm before its stability interval.
+- Loss during stability cancels without a reminder.
+- Every reminder maps to one live episode.
+- Dismiss, timeout, and exclusion have distinct persistence semantics.
+- No recording begins without explicit action and successful fresh revalidation.
+- A consumed episode cannot re-prompt until it ends.
+- Monotonic generation rejects stale async observations.
+
+### Signal fixtures
+
+- Two microphones where only one stops.
+- Aggregate and loopback device appearance/disappearance.
+- Input active without output; output active without input.
+- Ringtone or notification audio in a persistent meeting application window.
+- Stale foreground activation followed by unrelated output.
+- Muted join with remote output.
+- Waiting room, pre-join device test, reconnect, and breakout transition.
+- Browser meeting moved to background or minimized.
+- Browser navigates away before and after reminder presentation.
+- Application PID and window ID reuse.
+- Same-count replacement of one active application by another.
+- Detector startup during an already-running meeting.
+- Sleep, wake, lock, fast user switch, audio service restart, and device change.
+- Two simultaneous meeting candidates with deterministic prompt arbitration.
+
+### Notification fixtures
+
+- Full-screen presentation suppresses interruption but preserves menu-bar recovery.
+- Dictation overlay and active recording suppress new reminders.
+- Incoming candidates cannot replace a Start transaction.
+- VoiceOver can discover status and invoke both primary actions.
+- Keyboard navigation never focuses the underlying application unexpectedly.
+- Reduce Motion and increased contrast render correctly.
+- Setup reminder deep-links to the correct capability.
+- Denied and restricted permissions never produce recurring contextual repair prompts.
+- Passive mode, timeout, full-screen suppression, and user-configured quiet mode preserve accessible menu-bar recovery.
+- Application/provider exclusions, private-window exclusion, and global pause produce no live candidate indicator.
+- Simultaneous candidates remain separately selectable and accepting one does not merge their episodes.
+- Evidence loss silently withdraws visible and pending reminders.
+
+## 13. Launch metrics and stop conditions
+
+Metrics are calculated locally during dogfood unless users explicitly export a diagnostic report.
+
+### 13.1 Labelled evaluation protocol
+
+Dogfood users review a local periodic digest rather than receiving an extra interruption after every reminder. Each sampled episode can be labelled `meeting`, `not a meeting`, or `unsure`. The digest samples across every outcome: panel shown, Not now, timeout, passive recovery opened, capture started, candidate suppressed by presentation policy, and eligible shadow candidate not shown. Silence and `unsure` are never counted as confirmation.
+
+Report separate denominators and label-response rates for each outcome. Prompt precision is `labelled meeting / (labelled meeting + labelled not a meeting)` among reminders actually shown; passive and shadow precision are reported separately. Manual online-call recordings with no eligible suggestion are counted as missed-opportunity proxies, not automatically as detector false negatives.
+
+An application family may enter explicit opt-in V2 dogfood after the preliminary gate in the implementation plan. Default-on rollout uses the larger sample and confidence-bound gate defined there. Expansion decisions use per-family results, never only an aggregate average. Unreachable sample volume keeps a family opt-in; it never relaxes the gate automatically.
+
+An active user-week for burden metrics is a local calendar week in which FluidVoice ran on at least three days and observed at least one eligible candidate. This avoids diluting interruption burden with inactive installations.
+
+Launch targets:
+
+- Prompt precision: meet the labelled-evaluation gate above for every supported application family.
+- Prompt burden: median no more than one unwanted reminder per active user per week.
+- Detection latency: p90 under ten seconds from a valid high-confidence combination.
+- Stale reminder latency: at most three seconds after pre-capture evidence becomes invalid.
+- Duplicate rate: zero duplicate reminders within one episode.
+- Start safety: 100% of starts have explicit action, live revalidation, and an exact viable capture target.
+- Accidental auto-starts: zero by construction.
+- Main-thread impact: no synchronous CoreAudio enumeration or unbounded AX work on the main actor.
+- Missed-value proxy: track manual online-call recordings lacking a prior eligible suggestion, segmented by source, without weakening the precision gate.
+- Trust: track local suggestion disablement, pause, and source exclusion shortly after a reminder.
+- Permission burden: no repeat contextual setup prompt after denied/restricted status or an explicit repair dismissal.
+- User comprehension: in moderated task tests, at least 95% of participants correctly identify whether recording started, which source is captured, how to stop, and why the suggestion appeared.
+- Accessibility: keyboard and VoiceOver users can discover passive status and complete Start, Not now, source choice, Keep recording, and Stop recording without focus loss.
+- Privacy: automated integration tests observe no detector or diagnostics network traffic and exported traces contain no raw URL, title, path, participant, device name, or cross-session token.
+
+Stop rollout and return to shadow mode for an application family if:
+
+- labelled precision falls below 85%;
+- unwanted reminders exceed two per active user per week at the 75th percentile;
+- any recording starts after failed or stale revalidation;
+- a privacy invariant is violated;
+- monitor degradation produces repeated or unwithdrawn reminders.
+
+## 14. Recommended implementation slice
+
+The first implementation should not add application coverage or system notifications. It should deliver one coherent vertical slice:
+
+1. correct aggregate device state;
+2. structured per-process input/output observations off-main;
+3. pure candidate reducer with four- or six-second stability;
+4. visible reminder cancellation on evidence loss;
+5. current-episode “Not now” semantics;
+6. fresh start revalidation;
+7. redacted local trace and deterministic tests.
+
+This slice fixes the detector’s root semantics and makes the existing in-app reminder trustworthy. Coverage, personalization, calendar enrichment, and system delivery can then build on a stable episode model rather than adding exceptions to the current Boolean pipeline.
diff --git a/MEETING_DETECTOR_PHASE0_PROBE_REPORT.md b/MEETING_DETECTOR_PHASE0_PROBE_REPORT.md
new file mode 100644
index 00000000..25209369
--- /dev/null
+++ b/MEETING_DETECTOR_PHASE0_PROBE_REPORT.md
@@ -0,0 +1,98 @@
+# Meeting Detector — Phase 0 Probe: Local Evidence Report
+
+- Date: 2026-08-23
+- Environment: macOS 26.5.1 (build 25F80), arm64, Xcode 26.6 (build 17F113)
+- App deployment target: macOS 15
+
+## Scope
+
+DEBUG-only feasibility probe plus DEBUG AppDelegate env hook. No production detector or notification behavior; no browser, Accessibility, Apple Events, TCC, or network access; no listeners or observers; no project membership change; no commit.
+
+## Trigger
+
+`FLUIDVOICE_MEETING_PROBE_DURATION_SECONDS` valid only for integer values in `5...300`; absent or invalid values are a no-op. Probe runs at most once per process (lock-guarded check-and-set gate).
+
+## Implementation Evidence
+
+- One utility-QoS serial sampling queue; a separate control queue is the sole owner of file handle, deadline timer, terminal reason, record count, output path, and in-flight flag.
+- Exact GCD monotonic deadline timer; `ContinuousClock` records monotonic offsets, and any in-flight sample past the deadline yields `deadlineExceeded`.
+- Dynamically sized, bounded HAL process/device list reads: size query then data read with one bounded retry on churn; layout validation (`size % stride == 0`, `<= 4096` objects, `<= 65536` stream-config bytes, `<= 4096` buffers).
+- Independent input/output process selector reads (`kAudioProcessPropertyIsRunningInput` / `...Output`) with closed states (`active`/`inactive`/`readError`/`unsupported`).
+- Low-level input-device reads (stream configuration, transport, running-somewhere, UID) without device names.
+- Per-run salted device token: SHA-256 over 16-byte random salt + device UID, truncated to 128 bits; unlinkable across runs.
+- Full non-desktop CG window list (`optionAll`, `excludeDesktopElements`) captured off-main inside `autoreleasepool`; only success flag, count, and latency retained — no window metadata persisted.
+- Closed Codable schema: key sets for start/sample/terminal/process/device records validated at setup before any sampling; schema mismatch aborts with `validationFailure`.
+- Output: one UUID-named JSONL file under the macOS temp directory, created with `0600` POSIX permissions; path prefix-validated against the temp dir.
+- Release builds contain none of this code: entire file is wrapped in `#if DEBUG`, and the AppDelegate call site is `#if DEBUG`-guarded.
+
+## Verification
+
+| Check | Result |
+| --- | --- |
+| Debug build | Succeeded |
+| Release build | Succeeded |
+| Release scan for env key and probe-specific symbols | Absent |
+| Debug scan for env key and probe-specific symbols | Present |
+| Existing `MeetingAutoDetectorTests` | 48 passed, 0 failed |
+| Run 1 (5 s) | start + 5 samples + terminal; terminal reason `completed` at exactly 5000 ms; JSON parse/schema passed; forbidden raw field/value scan: no matches; file mode `0600`; window enumeration success, latency <= 4 ms |
+| Run 2 (5 s) | start + 5 samples + terminal; terminal reason `completed` at exactly 5000 ms; JSON parse/schema passed; forbidden raw field/value scan: no matches; file mode `0600`; window enumeration success, latency <= 4 ms |
+| Leaks run (15 s) | start + 14 samples + terminal; `completed` at 15001 ms; forbidden scan: no matches; file mode `0600`; window latency <= 5 ms |
+| Active Zoom call run (60 s, 2026-08-25) | start + 56 samples + terminal; `completed` at 60001 ms; all HAL list reads `ok`; classification failures: 0; every sample contained one Zoom audio-process object at `active`/`active` plus an inactive helper object; built-in input reported `running`; file mode `0600`; forbidden raw field/value scan: no matches; window enumeration succeeded in every sample, latency <= 8 ms |
+| Follow-up run (15 s, 2026-08-25) | start + 14 samples + terminal; `completed` at 15001 ms; the same Zoom and device states persisted; file mode `0600`; forbidden raw field/value scan: no matches; window enumeration succeeded in every sample, latency <= 8 ms. The operator's leave action was not explicitly confirmed, so this run is not counted as call-ended evidence. |
+| Confirmed joined run (90 s, 2026-08-25) | start + 86 samples + terminal; `completed` at 90001 ms; every sample contained a Zoom audio-process object at `active`/`active`, with built-in input `running`; file mode `0600`; forbidden raw field/value scan: no matches. The leave confirmation arrived near/after the deadline, so this run is counted only as joined-state evidence. |
+| Confirmed post-leave run (20 s, 2026-08-25) | start + 19 samples + terminal; `completed` at 20001 ms; the operator had explicitly confirmed leaving while keeping Zoom open; every sample contained only Zoom `inactive`/`inactive`, with built-in input `notRunning`; all HAL list reads `ok`; classification failures: 0; file mode `0600`; forbidden raw field/value scan: no matches; window enumeration succeeded in every sample, latency <= 5 ms. |
+| Token unlinkability | 2 unique device tokens in each run, 0 shared across runs |
+| Stack-filtered `leaks` pass | App-wide scan reported framework/XPC allocations, but no leak stack matched the probe, session, CF-string reader, or window-capture symbols |
+| Code review — initial plan | REVISE (required deadline/CF/buffer/privacy/evidence corrections) |
+| Code review — revised plan | APPROVE |
+| Code review — final code | APPROVE |
+| Code review — post-fix | APPROVE |
+
+Review attribution: Grok 4.6 attempts stalled/timed out without edits or verdict and are explicitly not counted as approval; Kimi K3 provided the explicit approvals.
+
+## Observed Facts
+
+- CoreAudio process enumeration recognized the `selfProcess` and `zoom` coarse families. Both input and output selector reads succeeded independently but observed `inactive`/`inactive` in this short non-active-call run. Duplicate family entries can represent primary/helper audio process objects; no raw mapping leaked.
+- Two input devices were stable within each run by token, both `notRunning`; transports `builtIn` and `other`; classification failures: 0.
+- Full CG window list succeeded in all samples with <= 4 ms query latency.
+
+### Active-call observation — 2026-08-25
+
+- With an operator-confirmed active Zoom meeting, one Zoom audio-process object reported `active` input and `active` output in every 1-second sample. A second Zoom helper object remained `inactive`/`inactive`; family-level aggregation must therefore tolerate multiple process objects.
+- The built-in input device reported `running` for the whole active-call run. The other input-capable device remained `notRunning`.
+- The operator explicitly acknowledged entering a muted interval, but neither the active Zoom process state nor the built-in device state changed. These signals establish call activity, not Zoom's UI mute state.
+- No call-ended transition was observed before either probe deadline. Because the requested leave action was not explicitly acknowledged, this is ambiguous coordination evidence and cannot establish persistence after leaving.
+- A subsequent controlled cycle removed that ambiguity: the joined run showed Zoom `active`/`active` and built-in input `running`; a fresh probe launched only after explicit leave confirmation showed Zoom `inactive`/`inactive` and built-in input `notRunning` in all 19 samples while Zoom remained open.
+- Active-versus-post-leave state separation is therefore validated at 1-second cadence. Exact leave-transition latency is not yet measured because the acknowledgement landed near the first probe's deadline and the definitive post-leave evidence came from a fresh process.
+- The live runs remained metadata-only: no audio, titles, participant data, raw bundle identifiers, raw device identifiers, paths, or URLs were written.
+
+## Phase-0 Questions — Status
+
+1. Process selector API path and independent input/output reads: **supported**. Active Zoom call and post-leave state separation: **VALIDATED AT 1-SECOND CADENCE**. UI mute-state detection from these signals: **NOT SUPPORTED BY THE OBSERVED EVIDENCE**. Same-process join/leave transition latency remains **NOT YET VALIDATED**.
+2. Known primary/helper family mapping works without paths for observed Zoom processes. Other families: **NOT YET EMPIRICALLY VALIDATED**.
+3. Input-capable devices stable within a run and unlinkable across runs. External switching, aggregate/removal, and any app-owned loopback: **NOT YET VALIDATED**.
+4. HAL enumeration and full window snapshot completed off-main in two bounded runs. Rapid switching and sleep/wake stress: **NOT YET VALIDATED**.
+
+## Residual Gates Before Phase 1
+
+- Same-probe join and explicitly acknowledged leave/relaunch transitions plus application playback at 1 s / 2 s / 5 s sampling cadences. Mute/unmute should be treated as a negative-control test unless a separate local signal is justified.
+- External input switching, aggregate-device concurrency, device removal, zero-device/headless runs where feasible; identify whether an app-owned loopback exists.
+- Rapid app switching and user-coordinated sleep/wake.
+- Separate, explicitly consented browser privacy/TCC spike.
+- Lock `DetectorInstant` `ContinuousClock` choice, self-observation exclusion, and actor single-flight contracts after evidence.
+
+## Verdict
+
+First execution slice **IMPLEMENTED AND CODE-APPROVED**, but the full Phase 0 exit gate remains **OPEN**. Phase 1 must not start yet. No heuristics added.
+
+## Artifacts
+
+- Probe source: `Sources/Fluid/Services/Meeting/MeetingDetectorFeasibilityProbe.swift`
+- DEBUG hook: `Sources/Fluid/AppDelegate.swift` (`applicationDidFinishLaunching`, `#if DEBUG` block)
+- Existing detector tests: `Tests/FluidDictationIntegrationTests/MeetingAutoDetectorTests.swift`
+- This report: `MEETING_DETECTOR_PHASE0_PROBE_REPORT.md`
+- Raw JSONL outputs: UUID-named files, inspected in the macOS temp directory (exact names and device tokens intentionally not recorded here). They remain only in temp, may be purged by the OS at any time, and are not copied into the repo.
+
+## Rollback
+
+Remove the DEBUG AppDelegate hook and the new probe/report files only. Existing user detector work is unrelated and must not be reverted.
diff --git a/MEETING_DETECTOR_PHASED_IMPLEMENTATION_PLAN.md b/MEETING_DETECTOR_PHASED_IMPLEMENTATION_PLAN.md
new file mode 100644
index 00000000..3b21bc3e
--- /dev/null
+++ b/MEETING_DETECTOR_PHASED_IMPLEMENTATION_PLAN.md
@@ -0,0 +1,932 @@
+# Meeting Detector Phased Implementation Plan
+
+Status: proposed after implementation grounding; pending adversarial PE review
+Parent design: `MEETING_DETECTION_NOTIFICATION_DESIGN.md`
+Scope: calendar-independent detector, in-app notification lifecycle, and safe meeting-end assistance
+Delivery rule: no automatic recording; no system notifications until the in-app path passes dogfood gates
+
+## 1. Objective
+
+Replace the current mixed signal/state/UI pipeline with a trustworthy detector that:
+
+- observes microphone devices and application audio correctly;
+- combines only fresh, same-target evidence;
+- requires positive stability before suggesting capture;
+- models one durable episode instead of emitting isolated prompts;
+- withdraws stale reminders and revalidates immediately before recording;
+- supports passive menu-bar recovery and explicit user controls;
+- fails closed when browser privacy state or required evidence is unreadable;
+- keeps all detection and evaluation data local by default.
+
+This plan changes architecture before expanding application coverage. Calendar integration and automatic recording remain out of scope.
+
+## 2. Verified baseline
+
+### 2.1 Current data flow
+
+```text
+NSWorkspace / CoreAudio / CGWindow / Accessibility
+ ↓
+ MeetingAutoDetector @MainActor
+ records + evidence + episodes + policy + polling
+ ↓
+ MeetingDetectionPromptController @MainActor
+ ↓
+ AppServices start transaction
+ ↓
+ MeetingSessionCoordinator
+```
+
+Current implementation files:
+
+- `Sources/Fluid/Services/Meeting/MeetingAutoDetectSignals.swift`
+- `Sources/Fluid/Services/Meeting/MeetingAutoDetector.swift`
+- `Sources/Fluid/Services/Meeting/MeetingAppRegistry.swift`
+- `Sources/Fluid/UI/MeetingDetectionPrompt.swift`
+- `Sources/Fluid/Services/AppServices.swift`
+- `Sources/Fluid/Services/MenuBarManager.swift`
+- `Sources/Fluid/Persistence/SettingsStore.swift`
+- `Sources/Fluid/UI/MeetingTranscriptionView.swift`
+- `Tests/FluidDictationIntegrationTests/MeetingAutoDetectorTests.swift`
+
+The application target uses a file-system-synchronized source group. Test files still require explicit Xcode project membership.
+
+### 2.2 Baseline verification
+
+Focused command:
+
+```sh
+xcodebuild test \
+ -project Fluid.xcodeproj \
+ -scheme Fluid \
+ -configuration Debug \
+ -destination 'platform=macOS' \
+ -only-testing:FluidDictationIntegrationTests/MeetingAutoDetectorTests \
+ CODE_SIGNING_ALLOWED=NO
+```
+
+Verified result on 2026-08-22: 48 tests, 0 failures.
+
+### 2.3 Worktree constraint
+
+The detector sources, prompt, tests, and design documents are currently untracked while related application wiring is modified in an already-dirty worktree. Those changes are the working baseline and must not be staged, committed, reset, or cleaned as part of implementation without an explicit user request.
+
+Before the first edit of every phase:
+
+1. record `git status --short --untracked-files=all` and a complete target-file inventory;
+2. after one scoped filesystem approval, copy only the phase’s target files into a stable local development archive outside the repository and outside purgeable temporary storage;
+3. record SHA-256 hashes plus the pre-phase list of files that do not yet exist;
+4. record `project.pbxproj` changes as a targeted patch only; never restore that already-dirty file wholesale;
+5. after the phase, review tracked diffs, the targeted project patch, every created file, and full contents of untracked target files;
+6. never touch unrelated media, render scripts, or meeting work.
+
+Runtime rollback uses an injected detector policy mode. File rollback is a targeted, reviewed reversal using the stable archive and created-file manifest, never a bulk restore or destructive Git command. Persisted settings migrations must remain readable by the previous runtime mode.
+
+## 3. Non-negotiable invariants
+
+Every phase must preserve these:
+
+1. No recording without an explicit user action.
+2. No raw browser URL, window title, participant data, device name, or transcript text in logs or diagnostics.
+3. Audio-only, window-only, and generic-browser-only evidence never trigger a floating reminder.
+4. Busy dictation, file transcription, or meeting capture is never interrupted or replaced.
+5. A candidate and capture target belong to the same canonical application family.
+6. Start is single-flight and succeeds only after fresh evidence and capture readiness pass.
+7. Loss of one signal never automatically stops an active recording.
+8. Lock, sleep, fast-user-switch, and monitor restart clear or demote transient authority.
+9. Existing manual meeting capture and transcription behavior remains unchanged.
+10. Each phase has an independent disable/rollback path and passes focused tests before the next begins.
+11. FluidVoice process audio is never eligible meeting evidence. When FluidVoice holds any exclusive audio lease, aggregate-input fallback loses start/end authority; device-level aggregation cannot distinguish ownership and must not be treated as self-excluded.
+
+## 4. Locked technical decisions
+
+### 4.1 Time model
+
+Live detector ordering uses `DetectorInstant`, a wrapper over `ContinuousClock.Instant`, not `Date`. `ContinuousClock` advances across system sleep, so every pre-sleep fact expires after wake. `SuspendingClock` is forbidden. Reducer events carry detector instants supplied by an injected clock. Wall time is used only for persisted user preferences such as “pause until tomorrow.”
+
+This prevents clock changes, timezone changes, and wake correction from creating false freshness or end decisions.
+
+### 4.2 Signal identity
+
+Process audio observations are not attached directly to a UI process PID. They first map to a canonical application family because helper processes may own audio for a different main application process.
+
+```swift
+struct ApplicationAudioObservation {
+ let audioObjectID: AudioObjectID
+ let processID: pid_t?
+ let observedBundleIdentifier: String
+ let canonicalFamily: MeetingApplicationFamily
+ let inputActive: Bool
+ let outputActive: Bool
+ let observedAt: DetectorInstant
+}
+```
+
+The registry owns helper-to-family mapping. Window and browser correlation then resolve the main UI process and exact capture target.
+
+### 4.3 Snapshot and generation model
+
+`MeetingSignalMonitor` is the sole producer of immutable snapshots from Phase 2 onward. Every refresh has a monotonic generation minted inside the actor. Async results carry the generation that requested them and are dropped if superseded.
+
+Generation prevents stale async writes; freshness thresholds still apply within accepted snapshots. Neither replaces the other.
+
+HAL listeners run on one dedicated serial queue and yield ordered events through an `AsyncStream` consumed by the monitor actor; callbacks never create unordered unstructured tasks. The actor permits at most one refresh pass in flight. Concurrent requests coalesce, with a pending-priority bit requesting the next pass. Blocking provider work runs in cancellable child tasks and returns values to the actor; no provider mutates monitor state.
+
+A priority snapshot request races its deadline outside the actor. It may use a completed snapshot only when its relevant facts are no more than one second old. Otherwise it returns `deadlineExceeded` and revalidation fails closed. It never waits indefinitely behind a suspended actor refresh.
+
+### 4.4 Reducer boundary
+
+`MeetingEvidenceReducer` is pure:
+
+```text
+old state + timestamped event + policy → new state + effects
+```
+
+It does not call CoreAudio, Accessibility, `NSWorkspace`, settings, logging, or capture readiness. Effects such as `candidateConfirmed`, `reminderInvalidated`, and `episodeEnded` are handled outside the reducer.
+
+Capture readiness is notification policy, not meeting identity. A confirmed meeting can exist while capture needs setup.
+
+### 4.5 Rollout modes
+
+Use an internal injected mode, not a remote flag:
+
+- `legacy`: current detector is authoritative;
+- `shadow`: legacy is authoritative, new reducer records redacted decisions only;
+- `nativeV2Dogfood`: new reducer is authoritative only for explicitly enrolled users and validated native families; other users remain legacy;
+- `browserShadow`: native V2 remains authoritative where enabled while V2 browser adapters record counterfactual decisions only;
+- `v2`: new reducer is authoritative for every validated adapter.
+
+Policy mode selects the decision engine; the per-family/per-adapter support matrix independently selects eligibility. Both must permit a candidate. Production defaults change only at explicit phase exit gates. The legacy path remains for one dogfood release after default-on native cutover and is never deleted while its only durable copy is untracked.
+
+### 4.6 Document precedence
+
+Where this plan and `MEETING_DETECTION_NOTIFICATION_DESIGN.md` state different implementation values, this plan governs. Amend the design in the same change so both documents state the same value.
+
+## 5. Dependency graph
+
+```text
+Phase 0: feasibility probes + contracts
+ ↓
+Phase 1: correct signal semantics
+ ↓
+Phase 2: monitor snapshots + pure reducer
+ ↓
+Phase 3: shadow evaluation + local diagnostics
+ ↓
+Phase 4: native cutover + fresh start revalidation
+ ↓
+Phase 5: notification lifecycle + controls
+ ↓
+Phase 6: browser privacy adapters
+ ↓
+Phase 7: end assistance + legacy removal
+ ↓
+Phase 8: optional system notifications
+```
+
+Phase 6 may be delayed without blocking the native detector. Phase 8 is a separate release decision.
+
+## 6. Phase 0 — Feasibility probes and contracts
+
+### Goal
+
+Validate public API assumptions before rewriting production state. Produce evidence, not product behavior.
+
+### Work packages
+
+#### P0.1 CoreAudio process probe
+
+Build a debug-only probe that samples the CoreAudio process object list and records redacted transitions for:
+
+- input and output selectors independently;
+- primary meeting application and helper-process bundle mapping;
+- process object/PID stability across join, mute, unmute, leave, relaunch, and application audio playback;
+- observation latency at one-, two-, and five-second polling cadences;
+- unavailable selector/error behavior.
+
+No process path or user data may be logged.
+
+#### P0.2 Device aggregation probe
+
+Observe built-in input, external input, device switching, aggregate devices, and device removal. Verify:
+
+- stable device IDs during one run;
+- aggregate zero→nonzero and nonzero→zero semantics;
+- one device stopping does not emit global inactive while another remains active;
+- loopback devices can be excluded by stable UID or owned-device metadata, never display-name matching.
+
+#### P0.3 Background-call probe
+
+Move only probe queries for process objects and window snapshots to a utility executor. Exercise rapid app switching, sleep/wake, and repeated refresh to confirm no deadlock, crash, or main-thread dependency.
+
+#### P0.4 Browser privacy spike
+
+For each intended browser adapter, determine whether a private window can be identified reliably through supported local state. The probe report must name the mechanism and permission boundary for that adapter:
+
+- bounded Accessibility attributes that require existing Accessibility access;
+- Apple Events only where a documented browser dictionary exposes the needed state and the user explicitly authorizes the resulting Automation TCC prompt;
+- no process-argument scraping, private API, title-string guessing, or UI-language matching.
+
+Return `supported`, `permissionMissing`, or `unsupported`; do not collapse permission denial into an unsupported browser. Test normal/private windows, multiple profiles, PWAs, and minimized windows. A validated browser/version still performs a runtime capability assertion at launch. Unknown/new versions and unknown private state fail closed until revalidated.
+
+Automation probes change real TCC state and are excluded from the first execution slice. They run only in a separately announced, user-consented probe. Fail criterion: if private state cannot be distinguished reliably, that adapter is marked unsupported for V2 notifications. Do not weaken the privacy contract.
+
+#### P0.5 Contract types
+
+Add or draft the core value types and protocols with no production wiring:
+
+- `DetectorInstant` and `MeetingDetectionClock`;
+- `MeetingApplicationFamily` and helper mapping;
+- `ApplicationAudioObservation`;
+- `AggregateInputObservation`;
+- `DetectionCapabilities` and `MonitorHealth`;
+- `MeetingSignalSnapshot`;
+- `MeetingDetectionPolicyMode`.
+
+### Files
+
+Prefer new debug/test files plus narrowly scoped types in `MeetingAutoDetectSignals.swift` and `MeetingAppRegistry.swift`. Do not change confirmation or notification behavior.
+
+### Tests
+
+- selector error/unsupported mapping;
+- canonical helper-family mapping;
+- monotonic clock fixture;
+- capability state mapping;
+- probe output redaction;
+- no network dependency.
+
+### Exit gate
+
+- Input/output selectors behave independently on the supported deployment target.
+- Off-main HAL and window queries complete a repeated stress probe without UI stalls or deadlock.
+- Device aggregation and loopback exclusion have stable identifiers.
+- Every browser has an explicit supported/unsupported privacy result.
+- The supported application deployment target is macOS 15.0; pre-14.4 behavior is not a product path. Availability guards remain defensive and report unsupported health rather than broad fallback.
+- Existing 48 detector tests remain green.
+
+If any native API assumption fails, revise the evidence matrix before Phase 1; do not add heuristics to hide the failure.
+
+### Rollback
+
+Phase 0 is additive and unreachable in Release. Disable the debug affordance and reverse only the probe/type additions using the phase manifest. TCC changes are not rolled back by file restoration, which is why Automation probing is a separate user-consented action with its state recorded in the report.
+
+## 7. Phase 1 — Correct signal semantics
+
+### Goal
+
+Fix observation truth while preserving the current authoritative detector behavior.
+
+### Work packages
+
+#### P1.1 Aggregate microphone state
+
+Replace per-device Boolean edges with snapshots or edges containing device identity. `CoreAudioMicActivitySignal` maintains the active eligible-device set and emits only aggregate transitions.
+
+Device list changes perform a resync before emitting. Sleep/wake and service restart reset authority until the resync completes.
+
+#### P1.2 Structured process audio
+
+Replace `AudioProcessActivityProviding.isAudioActive(...) -> Bool` with a structured observation API returning input/output separately, source health, generation, and observation time.
+
+The provider reports every relevant family in one process-list pass rather than enumerating the process list once per candidate PID.
+
+FluidVoice and its helper processes are excluded before canonical-family mapping. Aggregate device state remains observable, but the compatibility adapter cannot use it as meeting evidence while `DetectionActivityGate` reports any FluidVoice audio activity.
+
+#### P1.3 Fresh foreground facts
+
+All activation evidence receives an explicit expiry. Remove the `lastFrontmostAt != nil` shortcut for process audio. Direct same-family input ownership may confirm in the later reducer without requiring foreground state; weaker fallback rules require recent activation.
+
+#### P1.4 Move blocking reads off-main
+
+CoreAudio process enumeration and CG window snapshots execute outside `@MainActor`. Main-actor bridges deliver immutable values only. Keep HAL listener callbacks minimal and never synchronously wait on the main actor.
+
+### Files
+
+- `MeetingAutoDetectSignals.swift`
+- `MeetingAppRegistry.swift`
+- `MeetingAutoDetector.swift` as a compatibility adapter
+- `MeetingAutoDetectorTests.swift`
+
+### Tests first
+
+- device A active + device B stops → aggregate remains active;
+- last active device stops → exactly one aggregate inactive edge;
+- device added/removed during activity;
+- excluded loopback never changes aggregate state;
+- input-only, output-only, both, and neither observations;
+- helper process maps to the correct canonical family;
+- stale activation cannot satisfy an attribution gate;
+- one process enumeration serves multiple candidates;
+- generation rejects an old completion after resync.
+
+### Exit gate
+
+- Existing visible prompt outcomes remain unchanged for the old fixtures.
+- New multi-device and directionality tests pass.
+- Thread sanitizer/debug stress shows no cross-actor violation in the signal path.
+- No synchronous CoreAudio enumeration or full window snapshot runs on the main actor.
+- Focused suite and full application build pass.
+
+### Rollback
+
+Switch policy mode to `legacy` using the compatibility adapter. Reverse Phase 1 signal changes through the reviewed stable archive/targeted patch if the compatibility layer itself is faulty.
+
+## 8. Phase 2 — Snapshot monitor and pure episode reducer
+
+### Goal
+
+Create the V2 state machine without changing which path shows reminders.
+
+### Work packages
+
+#### P2.1 `MeetingSignalMonitor`
+
+Create a background actor that owns:
+
+- relevant running-app state;
+- adaptive polling cadence;
+- immediate rate-limited refresh after aggregate device edges;
+- process audio observations;
+- native window and browser correlation requests;
+- capability health and watchdog state;
+- snapshot generation.
+
+Cadence defaults:
+
+- one second while stabilizing or recording;
+- one second while any relevant application is running, unless a proven process-audio push signal supplies equivalent latency;
+- thirty seconds only when push listeners are healthy and no relevant application is running.
+
+Relevant-application launch, process-audio edge when available, aggregate-device edge, service restart, and wake request an immediate rate-limited refresh. Detection latency is measured from the first observable valid combination; the probe report also records the worst unobserved interval.
+
+Cadence is injected and testable. It is not a collection of inline sleep literals.
+
+#### P2.2 Canonical candidate identity
+
+Use:
+
+```text
+family + process launch identity + ephemeral meeting locator + locator generation
+```
+
+PID/window-number reuse cannot reuse an ended episode. Browser locators become session-random digests before entering state.
+
+#### P2.3 Pure reducer
+
+Implement candidate states:
+
+```text
+idle → observing → stabilizing → confirmed → presented
+ ↓ ↓
+ ending ← accepted/dismissed/timedOut
+ ↓
+ ended
+```
+
+Encode application-family policies as data. Do not scatter family-specific branches through the reducer.
+
+Initial policies:
+
+- meeting-specific native window + same-family input/output: 4 seconds;
+- generic persistent native window + same-family input: 6 seconds;
+- generic persistent window + output + recent activation + call marker: 8 seconds;
+- fallback aggregate mic + recent activation + qualifying marker: 8 seconds, medium/passive only;
+- audio-only, marker-only, or generic browser audio: never confirm.
+
+Pre-capture evidence loss invalidates a confirmed/presented effect after three seconds. Episode end uses a longer independent absence policy.
+
+#### P2.4 Effect adapter
+
+Reducer effects are translated into callbacks by a thin coordinator. In `shadow` mode, visible callbacks are discarded and only redacted comparisons are recorded.
+
+At Phase 2 wiring, the legacy detector stops owning independent CoreAudio/window polling. A compatibility adapter derives its legacy Boolean/window inputs from `MeetingSignalMonitor` snapshots. Shadow mode therefore compares decision engines over one observation stream rather than running two sensor stacks.
+
+### New files
+
+- `MeetingSignalMonitor.swift`
+- `MeetingEvidenceReducer.swift`
+- `MeetingCandidateModels.swift`
+- `MeetingDetectionPolicy.swift`
+- `MeetingDetectionTrace.swift`
+- `MeetingEvidenceReducerTests.swift`
+
+Update the Xcode test target for every new test file.
+
+### Tests
+
+- table-driven policy cases for every evidence combination;
+- stability boundary at threshold minus/at/plus one tick;
+- signal flap resets stability;
+- negative grace cancels a visible reminder effect;
+- duplicate snapshots and out-of-order generations are idempotent;
+- PID/window reuse creates a new identity only after end;
+- back-to-back same-window meetings rearm;
+- two candidates remain independent;
+- lock/wake/service restart demotes authority;
+- property test: no event sequence emits `startRecording`;
+- property test: at most one present effect per episode;
+- trace events contain only allowed enums/tokens.
+
+### Exit gate
+
+- Reducer tests are deterministic with no sleeps.
+- Legacy and V2 paths run together with only legacy producing UI.
+- Every V2 decision has a redacted reason code.
+- The new path adds no measurable main-thread polling work.
+- Existing detector and capture tests remain green.
+
+### Rollback
+
+Set mode to `legacy` while keeping the shared monitor and compatibility adapter. If the monitor itself is faulty, disable the detector globally and reverse only Phase 2-created files plus targeted compatibility wiring using the phase manifest; do not restart the removed dual poller as an emergency path.
+
+## 9. Phase 3 — Shadow dogfood and local evaluation
+
+### Goal
+
+Measure V2 precision and disagreements before making it authoritative.
+
+### Work packages
+
+#### P3.1 Redacted comparison trace
+
+Record, in memory by default:
+
+- candidate token;
+- registry family category;
+- evidence classes;
+- legacy/V2 decision and transition;
+- suppression reason;
+- capability/health class;
+- monotonic time delta.
+
+Never store raw URL/path, title, bundle path, device name, PID in export, or meeting locator digest.
+
+#### P3.2 Debug diagnostics
+
+Add a debug-only local view to:
+
+- inspect detector health;
+- see legacy/V2 disagreement counts;
+- label sampled episodes `meeting`, `not a meeting`, or `unsure`;
+- clear local diagnostics;
+- explicitly export a redacted report.
+
+Production history remains memory-only and clears at launch. Seven-day persistence is allowed only after explicit dogfood enrollment.
+
+Dogfood persistence uses an application-support subdirectory protected by the current user account, bounded by seven days and 5,000 redacted transitions. Disabling enrollment deletes it immediately. Export is an explicit copy action; raw identifiers never enter the stored buffer, so export has no second redaction boundary.
+
+#### P3.3 Replay corpus
+
+Convert redacted labelled transitions into deterministic, content-free fixtures. Include:
+
+- join muted/unmuted;
+- ringtone and ordinary app playback;
+- waiting room and pre-join test;
+- persistent home window;
+- background call;
+- device switch;
+- sleep/wake;
+- two simultaneous applications;
+- process or audio-service restart;
+- app relaunch and ID reuse.
+
+### Files
+
+- `MeetingDetectionTrace.swift`
+- new debug diagnostics view/model
+- `MeetingEvidenceReducerTests.swift`
+- fixture resources and loader
+- narrowly scoped settings for dogfood enrollment only
+
+### Preliminary opt-in cutover gate
+
+Per native application family:
+
+- at least 30 labelled V2 counterfactual confirms from the local digest;
+- at least 15 labelled V2 non-confirm/passive candidates;
+- at least 80% requested-label response rate;
+- observed counterfactual precision at least 90%;
+- no start-safety, duplicate, privacy, or stale-generation violation;
+- p90 confirmation under ten seconds;
+- all named replay families pass.
+
+This gate permits only explicit `nativeV2Dogfood`; it does not change production defaults. Labels apply to V2 counterfactual confirms whether or not the legacy path displayed a prompt. Silence and `unsure` are excluded and label-response rate is reported.
+
+### Default-on rollout gate
+
+Per family: at least 150 labelled V2 counterfactual confirms, 75 labelled non-confirm candidates, 70% response, observed precision at least 92%, and 95% Wilson lower bound at least 86%. If volume is unreachable, the family remains opt-in; time alone never relaxes the gate.
+
+If either gate is not met, revise policy data and replay tests, then repeat shadow evaluation. Do not cut over on aggregate accuracy alone.
+
+### Rollback
+
+Disable dogfood enrollment and clear the redacted store. Shadow decisions stop, legacy remains authoritative, and no user-facing setting migration has occurred.
+
+## 10. Phase 4 — Native V2 cutover and fresh start revalidation
+
+### Goal
+
+Make V2 authoritative only for explicitly enrolled dogfood users and validated native families, with a minimal passive/floating choice before any V2 interruption.
+
+### Work packages
+
+#### P4.1 Family-scoped cutover
+
+`nativeV2Dogfood` routes only validated native families through V2 for enrolled users. Enrollment explicitly chooses Passive or Floating; Passive is the default. Add an immediately available Pause control before enabling Floating. Unsupported or degraded families stay silent rather than falling back to broad Boolean logic. Non-enrolled users remain legacy until the default-on gate passes.
+
+Phase 4 includes the minimum passive surface by extending the existing `MenuBarManager`: one neutral possible-meeting item, Start, Not now, and Pause. It does not create a second status item. Phase 5 adds migration, exclusions, multi-candidate menus, explanations, and full presentation policy.
+
+#### P4.2 Prompt invalidation
+
+Reducer `reminderInvalidated` effects call the existing `MeetingDetectionPromptController.invalidateEpisode`. Visible and suppression-pending reminders withdraw within three seconds of invalid evidence.
+
+#### P4.3 Fresh revalidation transaction
+
+Extend the existing `AppServices.startAutoDetectedRecording` seam as a cancellable race between episode liveness, deadline, and capture start:
+
+1. freeze episode and reject duplicate taps;
+2. request a priority snapshot with a two-second deadline;
+3. require a current start-eligible policy for the same episode identity;
+4. resolve the exact live application/window target;
+5. recheck capture permissions, storage, and FluidVoice activity;
+6. create capture configuration;
+7. recheck episode and target once more;
+8. start capture while subscribing to episode/target invalidation;
+9. if the target dies before the capture engine reports a live exact source, cancel/stop startup, discard any empty provisional session, leave the episode unconsumed, and show “The call no longer appears active”;
+10. mark accepted only after the exact source reports success and the episode remains eligible.
+
+The priority refresh API is cooperatively cancellable. Deadline expiry returns `deadlineExceeded` and fails closed; it never falls back to an arbitrarily old cached snapshot.
+
+If evidence ended, close the reminder with “The call no longer appears active.” If the exact target is ambiguous, open source selection with candidates preselected. Never silently fall back to another application.
+
+#### P4.4 Episode outcomes
+
+Change semantics:
+
+- explicit Not now: suppress current episode until end;
+- timeout: prevent another floating panel but retain passive eligibility for Phase 5;
+- capture failure: do not consume the episode;
+- successful capture: accept the episode and suppress other interruptions while busy.
+
+Remove the current bundle-wide 30-minute dismissal from the authoritative V2 path. Preserve it only inside legacy mode until legacy deletion.
+
+#### P4.5 First-capture consent reminder
+
+Before the first capture started from a suggestion, show the one-time local participant-consent/organization-policy reminder. Persist acknowledgment separately from detector mode. Cancellation leaves the episode live and does not start capture.
+
+### Files
+
+- `MeetingAutoDetector.swift` or its new coordinator replacement
+- `MeetingDetectionPrompt.swift`
+- `AppServices.swift`
+- `MenuBarManager.swift` for the minimum passive dogfood surface
+- dogfood-only suggestion-mode/Pause settings
+- reducer/effect models
+- detector and AppServices-focused tests
+
+### Tests
+
+- signal loss during visible reminder invalidates it;
+- signal loss during fullscreen suppression invalidates pending state;
+- fresh snapshot timeout fails closed;
+- target changes before click;
+- target disappears during configuration;
+- capture failure permits retry while episode remains live;
+- repeated click is single-flight;
+- Not now and timeout differ;
+- busy activity remains untouched;
+- native family cutover cannot activate an unvalidated family.
+
+### Exit gate
+
+- Zero capture starts after stale/failed revalidation.
+- 100% of starts use the exact validated target.
+- Stale visible/pending reminder withdrawal is at most three seconds.
+- Existing manual capture tests pass unchanged.
+- Runtime rollback to `legacy` is verified in a debug build.
+- Explicit dogfood users can choose Passive before V2 activation and Pause immediately.
+- Unwanted floating reminders remain at or below one per active enrolled user-week median and two at the 75th percentile.
+- Any privacy, accidental-start, exact-target, duplicate, or stale-reminder stop condition returns the affected family to `shadow`.
+
+### Rollback
+
+Set enrolled users back to `shadow`; non-enrolled users were never cut over. Passive/Floating choice, Pause, and consent acknowledgment remain backward-readable but have no authority in legacy. Cancel any V2 prompt or pending start before changing mode.
+
+## 11. Phase 5 — Notification lifecycle, passive recovery, and controls
+
+### Goal
+
+Complete the user-facing in-app notification policy without system notifications.
+
+### Work packages
+
+#### P5.1 Settings migration
+
+Add typed settings for:
+
+- suggestion mode: `passive` or `floating`;
+- pause-until;
+- excluded native families;
+- excluded browser providers;
+- “suggest only when my microphone is active”;
+- end-nudge preference;
+- setup-reminder dismissal by capability.
+
+Migration:
+
+- existing install with detector explicitly enabled → `floating`;
+- existing install with detector disabled → preserve disabled state;
+- new install → `passive`;
+- browser remains separate opt-in;
+- migration has an idempotent version marker and tests for absent/corrupt/old values.
+
+#### P5.2 Reuse `MenuBarManager`
+
+Extend the existing `NSStatusItem`; do not create a second status item.
+
+Add a meeting suggestion presentation separate from active recording presentation:
+
+- neutral icon/accessibility status;
+- primary possible-meeting item with Start action;
+- other candidates submenu;
+- Not now, Pause, and source-exclusion actions;
+- passive action persists until episode end, explicit Not now, exclusion, or capture start;
+- active recording status remains higher priority than suggestions.
+
+#### P5.3 Floating reminder policy
+
+- shown only in floating mode for high-confidence candidates;
+- never steals focus;
+- one visible panel at a time;
+- 30-second panel timeout preserves passive menu recovery;
+- hover/keyboard interaction pauses timer;
+- fullscreen other app, quiet mode, dictation overlay, or busy activity suppresses panel but preserves passive recovery;
+- evidence loss removes both surfaces after the end grace;
+- setup reminders follow `notDetermined`/`denied`/`restricted` semantics and never nag after explicit decline.
+- place the panel on the display containing the detected application/window when resolvable, otherwise the active display;
+- Snooze 10 minutes hides the current panel, preserves passive recovery, prohibits another panel for that episode, and keeps other candidates passive until expiry;
+- “Why this appeared” shows only coarse evidence classes from the already-redacted decision record.
+
+#### P5.4 Arbitration
+
+Rank one floating candidate by:
+
+1. confidence band;
+2. same-process input ownership;
+3. meeting-specific locator;
+4. capture readiness;
+5. most recent stable transition.
+
+Other candidates remain separately selectable in the menu. Accepting one never merges or ends another episode.
+
+### Files
+
+- `SettingsStore.swift`
+- `MeetingTranscriptionView.swift`
+- `MenuBarManager.swift`
+- `MeetingDetectionPrompt.swift`
+- `AppServices.swift`
+- new notification policy/controller tests
+
+### Tests
+
+- every settings migration path;
+- Pause expiry never re-presents an existing episode;
+- timeout keeps passive action; Not now removes it;
+- exclusions take effect immediately and persist;
+- active recording overrides suggestion icon/menu state;
+- simultaneous candidate ranking and selection;
+- fullscreen/quiet/busy suppression preserves passive state;
+- permission dismissal is sticky until manual setup action;
+- Snooze expiry never re-presents the existing episode;
+- Why-this-appeared contains no raw observed values;
+- multi-display placement follows the detected target with active-display fallback;
+- menu actions and labels are keyboard/VoiceOver accessible;
+- Reduce Motion path;
+- one status item only.
+
+### Exit gate
+
+- Task tests confirm users can identify recording state, capture source, Start, Not now, and Stop.
+- No duplicate in-app surfaces for one episode.
+- Median unwanted floating reminders is at most one per active dogfood user-week.
+- Source exclusions and Pause are immediately effective.
+- No permission-repair repeat after denial or explicit decline.
+- Existing menu-bar recording/processing states remain correct.
+
+### Rollback
+
+Disable V2 user-facing delivery and return enrolled users to `shadow`. New settings use backward-compatible defaults and remain inert in legacy. Remove suggestion menu items/panel state through targeted wiring reversal without replacing the existing `NSStatusItem` or reverting unrelated `MenuBarManager` work.
+
+## 12. Phase 6 — Browser adapters and privacy cutover
+
+### Goal
+
+Move browser detection to V2 only for adapters that pass the Phase 0 privacy spike.
+
+### Work packages
+
+#### P6.1 Adapter interface
+
+Each adapter returns only:
+
+- supported provider enum;
+- allowed meeting-locator classification;
+- session-random locator digest;
+- private-window status;
+- health/availability;
+- observation generation and time.
+
+Raw URL/title values stay inside the adapter call and are discarded immediately.
+
+#### P6.2 Fail-closed support matrix
+
+An adapter is enabled only when it can:
+
+- read the current page within a bounded deadline;
+- distinguish private state reliably;
+- match the allowed provider/path locally;
+- reject landing, post-call, media, and unrelated pages;
+- avoid all-tab/history scanning;
+- pass supported browser-version fixtures.
+
+Unknown private state equals unavailable, not normal browsing.
+
+#### P6.3 Browser policy
+
+- browser process input/output + verified current locator: five-second high-confidence candidate;
+- temporary locator loss after verification: continuity for 15 seconds, never a new prompt;
+- generic browser microphone ownership: no reminder;
+- background/minimized behavior is supported only where the adapter retains a verified locator without broader tab collection;
+- browser/native handoff ends or links episodes through explicit policy, never string similarity.
+
+Every adapter begins in `browserShadow` while native V2 behavior remains unchanged. The local digest labels V2 browser counterfactual confirms directly; it does not infer truth from a legacy prompt. Only an adapter that passes the browser-specific preliminary and default-on gates advances to `v2` eligibility.
+
+### Files
+
+- `MeetingAutoDetectSignals.swift` split into adapter files if needed
+- `MeetingAppRegistry.swift`
+- new browser adapter/protocol files
+- reducer policy tables
+- browser fixture tests
+- settings disclosure and provider exclusions
+
+### Exit gate
+
+Each browser/provider combination independently meets the Phase 3 precision and privacy gates. Failed adapters remain disabled without blocking native V2.
+
+### Rollback
+
+Set the affected adapter to unsupported and clear its ephemeral locator state. Native V2 remains unchanged. Persisted provider exclusions remain inert and backward-compatible; no raw browser state exists to migrate or restore.
+
+## 13. Phase 7 — End assistance, health UX, and legacy removal
+
+### Goal
+
+Finish the detector lifecycle and remove temporary architecture after a stable rollback window.
+
+### Work packages
+
+#### P7.1 Conservative end assistance
+
+While recording, continuation evidence includes any of:
+
+- recent transcript output;
+- exact capture target alive;
+- same-family process input/output;
+- verified meeting locator;
+- qualifying native call marker.
+
+After 60 seconds in which none of the above continuation signals is present—any one signal suffices—show one non-modal “Still recording?” nudge with:
+
+- Stop recording;
+- Keep recording.
+
+State explicitly that stopping finalizes the local transcript. Keep recording suppresses further end nudges for that recording. No automatic stop.
+
+#### P7.2 Health UX
+
+Expose coarse capability states in Meeting settings:
+
+- process attribution unavailable;
+- monitor temporarily degraded;
+- native window identity unavailable;
+- browser adapter unavailable/private-state unsupported;
+- capture permission missing.
+
+Health never appears as evidence and never exposes observed content.
+
+#### P7.3 Remove legacy path
+
+After one stable dogfood release with no rollback:
+
+- require the legacy implementation to have a user-authorized durable archive or Git commit before deletion; if it remains untracked-only, legacy deletion is blocked and the code stays in place;
+
+- remove `legacy`/dual-decision code;
+- remove legacy bundle-wide suppression;
+- delete obsolete CandidateRecord/attemptConfirm state;
+- keep replay fixtures as regression tests;
+- retain a global detector disable switch as the operational kill path.
+
+### Exit gate
+
+- end nudge never auto-stops;
+- recent transcript or transient mute prevents a premature nudge;
+- Keep recording is sticky for that recording;
+- degraded health is visible and actionable without prompting;
+- full suite passes after legacy deletion;
+- no dead legacy settings or migration paths remain.
+
+### Rollback
+
+End-assistance and health UI are independently disableable. Legacy removal has no runtime rollback and therefore occurs only after its durable-recovery precondition and a fresh user-authorized execution plan. Without that authorization, Phase 7 closes with legacy disabled but retained.
+
+## 14. Phase 8 — Optional system notifications
+
+This is deliberately outside initial detector completion.
+
+Proceed only after Phase 5 notification burden and trust gates pass. Add a separate `System meeting notifications` preference, default off. Passive mode alone never opts a user into system delivery.
+
+Reuse the authoritative episode, suppression, exclusion, and fresh-revalidation paths. The system and floating surfaces are mutually exclusive for one episode. Operating-system Focus behavior is inherited rather than inferred by FluidVoice.
+
+### Rollback
+
+Disable the separate system-notification preference, cancel pending detector notification requests by episode identifier, and retain in-app passive recovery. Notification permission state is operating-system state and is never treated as rolled back by code.
+
+## 15. Cross-phase verification
+
+### Per implementation slice
+
+1. Run new unit tests for the slice.
+2. Run `MeetingAutoDetectorTests`.
+3. Run detector/reducer trace replays.
+4. Build the application with code signing disabled.
+5. Run `git diff --check` for tracked files and inspect full untracked target files.
+6. Run a fresh adversarial code review before moving to the next phase.
+
+### Phase gates
+
+After Phases 1, 2, 4, 5, and 7:
+
+- run the entire `FluidDictationIntegrationTests` target;
+- compile detector changes with complete strict-concurrency checking and treat new warnings in changed files as failures;
+- run a reentrancy/single-flight stress harness plus Thread Sanitizer; Thread Sanitizer alone does not prove actor isolation or prevent logical reentrancy;
+- check CPU/wakeups in idle, relevant-app-running, stabilizing, and recording states;
+- verify no detector network activity;
+- inspect exported trace for forbidden fields;
+- dogfood at least one native join muted, join unmuted, ordinary application playback, dismiss, timeout, capture start, and meeting leave.
+
+### Main performance gates
+
+- no synchronous HAL process enumeration or full window scan on main;
+- no unbounded Accessibility traversal;
+- no more than one relevant process-list enumeration per monitor refresh;
+- no polling faster than one second;
+- watchdog detects five missed expected refreshes;
+- detector main-actor signposts remain below 4 ms p95 and 16 ms maximum in a 30-minute stress run;
+- with no relevant app, average detector CPU delta stays below 0.2 percentage point and attributable wakeups below six per minute versus detector-disabled baseline;
+- with a relevant app but no candidate, average CPU delta stays below 0.5 percentage point and attributable wakeups below two per second;
+- while stabilizing, average CPU delta stays below 1 percentage point and attributable wakeups below four per second.
+
+Measure with Instruments Time Profiler/Points of Interest and Energy Log, using identical feature-disabled and feature-enabled runs. If hardware noise makes an absolute gate inconclusive, repeat the paired run; do not replace measurement with subjective UI observation.
+
+These budgets are provisional until Phase 0 records paired baselines on the development Mac. Phase 0 may tighten or relax a number only by recording the raw baseline, measurement variance, and an explicit reviewed replacement before Phase 1 begins.
+
+## 16. PE execution protocol
+
+Every phase follows the same cycle:
+
+1. **Analyze:** re-read the phase targets, current diffs, prior phase evidence, and relevant replay fixtures.
+2. **Plan:** produce a file/symbol-level implementation checklist and explicit invariants.
+3. **Adversarial plan review:** fresh-context PE reviewer plus an external non-Claude review through `orchestrate`; rank findings by severity.
+4. **Revise and lock:** resolve every blocker and major finding in the checklist before code.
+5. **Execute:** delegate bounded implementation packages through the configured orchestration tier; the primary agent retains architecture and review responsibility.
+6. **Verify:** focused tests, build, replay/stress checks, and privacy checks.
+7. **Adversarial code review:** fresh-context review of the phase diff for duplication, magic constants, actor violations, stale-event loopholes, missing tests, privacy leaks, and behavior broadening.
+8. **Fix and re-review:** a phase does not close on a `REVISE` verdict.
+
+No phase is committed or pushed unless the user explicitly requests it.
+
+## 17. Recommended first execution boundary
+
+Begin with one additive Phase 0 slice only. Do not combine it with Phase 1 and do not request browser Automation permission.
+
+The slice:
+
+1. records the full worktree inventory and focused 48-test baseline;
+2. adds one debug-only, Release-unreachable probe source under the file-system-synchronized application group, requiring no `project.pbxproj` edit;
+3. performs process input/output and aggregate-device observation through one shared off-main CoreAudio pass;
+4. emits append-only redacted JSONL containing reason enums, family categories, salted device-token hashes, and monotonic deltas—never names, PIDs, titles, paths, or URLs;
+5. registers no listener that survives probe completion;
+6. exercises app switching and sleep/wake stress;
+7. records observed behavior and residual uncertainty in a local probe report.
+
+The first deliverable answers:
+
+1. Are process input/output selectors independently reliable on the supported macOS target?
+2. Can audio helper processes be mapped to the correct application family without process-path heuristics?
+3. Can every active input device and FluidVoice-owned loopback be identified stably?
+4. Are HAL process enumeration and full window snapshots safe off-main under stress?
+
+Browser privacy/TCC probing and production contract types are explicitly deferred until the first four answers, clock choice, self-observation rule, and actor single-flight contract have been reviewed. Only then may the remaining Phase 0 work and Phase 1 contracts be locked. This prevents the reducer and notification policy from being built on assumed sensor semantics.
diff --git a/MEETING_M3_SPEAKER_IDENTITY.md b/MEETING_M3_SPEAKER_IDENTITY.md
index 7b99777c..63e7d6a5 100644
--- a/MEETING_M3_SPEAKER_IDENTITY.md
+++ b/MEETING_M3_SPEAKER_IDENTITY.md
@@ -12,7 +12,7 @@ participant roster the tool obtains by joining the call.
| Attribution method | Products |
|---|---|
-| Roster / attendee names from joining the call as a bot or participant | Fathom, Granola, Sembly (default), Zoom, Google Meet, most of Fireflies |
+| Roster / attendee names from joining the call as a bot or participant | Bot-based meeting assistants, Zoom, Google Meet |
| Manual labelling only; naming by voice explicitly not offered | **Rev** ("supports speaker diarization but does not support speaker identification"), Descript |
| True persistent voiceprints | Microsoft Teams Voice & Face Enrollment, Sembly Voice ID, Fireflies, Circleback, Read.ai |
diff --git a/MEETING_OVERLAY_IMPLEMENTATION_PLAN.md b/MEETING_OVERLAY_IMPLEMENTATION_PLAN.md
new file mode 100644
index 00000000..78734cf3
--- /dev/null
+++ b/MEETING_OVERLAY_IMPLEMENTATION_PLAN.md
@@ -0,0 +1,457 @@
+# Meeting overlay visual unification — implementation plan
+
+Status: **implemented through the code-hardening gates on 2026-08-25. Unsigned test build succeeds,
+14 focused meeting/dictation overlay tests pass, and the final adversarial implementation review is
+APPROVE. Remaining release gates are manual visual/interaction testing, the VoiceOver checklist,
+multi-display/full-screen/screen-share checks, and the two-hour soak.**
+
+## 1. Product decision
+
+FluidVoice keeps dictation and meeting overlays independent at the lifecycle and settings layers,
+but both use the same visual primitives. Meeting recording exposes two presentation choices:
+
+- **Pill** — a persistent 84×32 recording control suitable for a long meeting.
+- **Captions** — a fixed-size rolling subtitle strip, initially 480×132.
+
+The saved meeting preference is independent from the dictation overlay size. A user can therefore
+use Compact/Small for dictation and Pill for meetings. Clicking the meeting Pill temporarily expands
+to Captions; collapsing returns to Pill. A preference change applies at the **next meeting start**;
+it never overrides temporary presentation choices in an active meeting.
+
+The on-demand resizable full captions window remains a separate destination. It is not a third
+meeting-overlay preference.
+
+## 2. Goals and acceptance criteria
+
+### Product
+
+- Pill and Captions use the established dictation overlay as the canonical visual recipe: same black
+ surface, border vocabulary, shadow, waveform vocabulary, and spacing scale. Meeting-specific
+ differences are limited to content and long-duration motion.
+- Meeting and dictation preferences are stored independently.
+- The visible Pill remains exactly 84×32 and unobtrusive for the entire meeting; its panel is larger
+ only to reserve transparent shadow/hit-test insets. Stop remains immediately available.
+- Pill ↔ Captions morphs in place without opening a second panel, jumping screens, or losing the
+ user-positioned anchor.
+- Captions update without resizing the panel for each partial transcript update.
+- Meeting recording lifecycle, stop behavior, degraded states, and full captions remain unchanged.
+
+### Accessibility and platform behavior
+
+- VoiceOver exposes recording state, expand/collapse, Stop, and caption content without duplicate
+ announcements for rapidly changing partial text.
+- Reduce Motion removes the spring/large geometry interpolation and uses an immediate resize plus a
+ short cross-fade, or no animation when cross-fade preference also requires it.
+- Controls retain usable hit regions even though the visible Pill is 84×32.
+- The panel remains non-activating, movable, visible across Spaces/full-screen apps, and clamped to
+ the active display after display changes.
+- Screen-share exclusion is **not** an acceptance guarantee. Apple now documents
+ `NSWindow.SharingType.none` as a legacy constant macOS no longer uses. Keep it only as best-effort
+ compatibility if it produces no warning, and test popular meeting apps manually. The small Pill is
+ the dependable mitigation when a whole display is shared.
+
+### Engineering
+
+- Shared primitives have no dependency on `NotchContentState`, `MeetingSessionCoordinator`, or a
+ singleton settings store.
+- Dictation behavior and dimensions do not change as an incidental result of extraction.
+- Meeting presentation is modeled explicitly; it is not another Boolean layered onto `isExpanded`.
+- Presentation initializes only on the transition into a new recording, never on degraded/recovered
+ state publishes inside the same recording.
+- All setting decoding is backward-compatible, including backup import from older builds.
+
+## 3. Current architecture and constraints
+
+### Established dictation overlay
+
+- `BottomOverlayView.swift` owns dictation layout presets (`pill`, `small`, `medium`, `large`), its
+ black surface, border, shadow, waveform rendering, and content.
+- `BottomWaveformView` cannot be reused directly because it reads `NotchContentState.shared` and
+ owns dictation-specific processing/release animation.
+- `BottomOverlayWindowController` cannot host meetings because its lifecycle, hit-testing, menus,
+ target app state, and dismissal behavior are dictation-specific.
+
+### New meeting overlay from this iteration
+
+- `MeetingRecordingPillController` owns one persistent `NSPanel`, saved placement, display clamping,
+ and the current 84×32 ↔ 480×132 resize.
+- `MeetingRecordingPillContent` owns recording level, Stop, rolling subtitle composition, and the
+ current matched-geometry transition.
+- `MeetingFloatingPanelFactory` supplies the correct non-activating, floating, movable panel behavior.
+- `MeetingLiveBubbleComposer` and `MeetingLiveBubbleScrollList` already separate caption composition
+ from the panel presentation and should remain the caption data/view foundations.
+
+### Important constraints
+
+- AppKit owns the outer panel frame and is the only geometry animation clock. The current AppKit cubic
+ resize and independent SwiftUI spring are a confirmed race that the new design must remove.
+- The meeting overlay can remain visible for hours. Do not copy the dictation Pill's continuous
+ 30-fps rotating border into the persistent meeting surface. Share its static visual recipe, while
+ audio bars update only when levels change.
+- Captions can update many times per second. Their fixed panel dimensions must not cause fitting-size
+ recalculation or AppKit frame animation on transcript changes.
+- The repository currently has no view/controller tests for meeting overlay presentation.
+- The cached panel root currently snapshots theme construction and has no explicit live view model;
+ presentation, appearance, and accessibility state need an observable bridge that survives meetings.
+
+## 4. Target architecture
+
+```text
+Shared visual layer (stateless)
+├── FluidOverlaySurface
+├── FluidOverlaySurfaceStyle
+├── FluidOverlayShadowMetrics
+├── FluidOverlayLevelBars
+└── FluidOverlayMotionCurve
+
+Dictation feature (existing lifecycle)
+├── BottomOverlayWindowController
+├── BottomOverlayView
+└── Dictation waveform/state adapter
+
+Meeting feature (independent lifecycle)
+├── MeetingRecordingOverlayController
+├── MeetingOverlayViewModel
+├── MeetingOverlayPreference: pill | captions
+├── MeetingOverlayPresentation: pill | captions
+├── MeetingOverlayGeometry
+├── MeetingOverlayPresentationReducer
+├── MeetingRecordingOverlayContent
+└── Meeting level/transcript/state adapter
+```
+
+### Shared primitives
+
+Create `Sources/Fluid/UI/FluidOverlayPrimitives.swift` containing only stateless visual types:
+
+- `FluidOverlaySurfaceStyle`: fill, border gradient/opacities, line width, corner radius, shadow.
+- `FluidOverlaySurface`: renders the background from a supplied style and shape.
+- `FluidOverlayLevelBars`: renders supplied normalized bar heights/level using supplied metrics.
+- `FluidOverlayShadowMetrics`: visible and hit-test shadow extents.
+- `FluidOverlayMotionCurve`: one duration and cubic curve representable as AppKit timing and, where
+ needed for opacity only, SwiftUI timing. Geometry never uses a SwiftUI spring.
+
+Do not put feature sizes into the shared visual layer. Dictation retains its current layout presets;
+meeting retains 84×32 and 480×132 constants. Sharing appearance must not imply that unrelated
+features need identical dimensions.
+
+The canonical compact recipe is the dictation Pill's black fill, white border gradient, radius, and
+shadow. The meeting Pill uses the same static recipe; it does **not** copy the dictation Pill's
+continuous rotating-border timeline because a meeting may last hours. Captions use the established
+larger dictation surface recipe. Recording accent appears in content, not a feature-specific border.
+
+### Meeting state
+
+Add two distinct concepts:
+
+```swift
+enum MeetingOverlayPreference: String, Codable, CaseIterable {
+ case pill
+ case captions
+}
+
+enum MeetingOverlayPresentation: Equatable {
+ case pill
+ case captions
+}
+```
+
+`MeetingOverlayPreference` is persisted. `MeetingOverlayPresentation` is session UI state. On the
+non-visible → recording edge, the controller initializes presentation from the saved preference. A
+tap or collapse only changes presentation. A settings or backup-restore change during a recording is
+saved for the next recording and does not mutate the active presentation.
+
+Use an enum even though there are two cases; this prevents contradictory `isExpanded`, preferred,
+floating-window-visible, and recording-state Booleans as the feature grows.
+
+### Observable state bridge
+
+Create one `@MainActor MeetingOverlayViewModel: ObservableObject` and inject it into the cached panel
+root once. It owns current presentation, recording/session identity, appearance inputs, Reduce Motion,
+and the precomposed caption string. The controller mutates this model; the root never snapshots a
+preference or accent value at panel creation.
+
+Initialize presentation only when a new recording becomes visible. `recording ↔ recordingDegraded`
+must preserve the user's temporary Pill/Captions choice.
+
+### Geometry and position
+
+Add pure `MeetingOverlayGeometry` before controller work. Inputs are current visible-content frame,
+target visible size, transparent outer insets, and screen visible frames. Output is a clamped panel
+frame plus the visible-content frame inside it.
+
+The 84×32 and 480×132 values describe the **visible surface**, not the `NSPanel` frame. The panel adds
+transparent insets for shadow and larger control hit regions. A meeting-specific hosting view rejects
+hits in transparent shadow-only regions, matching the established dictation approach.
+
+Do not persist a size-dependent window origin. Persist a presentation-independent anchor derived from
+the visible surface (center X and bottom Y, with display identity when available), then derive either
+presentation frame from it. Preserve `"MeetingRecordingPill"` long enough to migrate the existing
+autosaved frame once; renaming Swift types must not lose the user's position.
+
+Expose `currentOverlayFrame` for every visible presentation. Replace `expandedPanelFrame` and the
+detection nudge's hard-coded 84×32 fallback so caption-window and nudge placement use the real frame.
+
+### Morph ownership
+
+Keep Pill and Captions in the same `NSPanel` and SwiftUI root. Use one transition coordinator:
+
+1. Resolve target presentation and pre-clamped target frame from the pure geometry layer.
+2. Increment a presentation generation token; stale animation completions become no-ops.
+3. Let AppKit animate the outer frame with the single cubic timing curve.
+4. Disable independent SwiftUI geometry animation. Lay out the persistent surface and controls from
+ actual hosting-view bounds so they follow AppKit interpolation on every frame.
+5. Keep both content layers in one root. Derive caption opacity/clip progress from actual width rather
+ than elapsed time, making panel bounds the single source of morph progress.
+6. With Reduce Motion, set the frame directly and use only the system-preferred cross-fade, or no
+ transition when cross-fade isn't preferred.
+
+Stop remains interactive throughout. Repeated clicks resolve to the latest target; the generation
+token drops stale completion handlers.
+
+Reduce Motion has one source of truth in the observable view model and updates from the macOS display
+accessibility-change notification. Controller and view must not read unrelated snapshots.
+
+## 5. Phased implementation
+
+### Phase 0 — Characterization and safety net
+
+Purpose: lock down established dictation behavior before extracting shared visuals.
+
+- Record current dimensions, surface colors/opacities, corner radii, shadow, waveform metrics, panel
+ position, and Pill hit-testing as explicit values or focused tests.
+- First add pure `MeetingOverlayGeometry` and `MeetingOverlayPresentationReducer` seams; the controller
+ continues using old behavior until these seams are characterized.
+- Test Pill ↔ Captions frames, shadow-padded panel bounds, pre-animation clamping, display removal,
+ anchor migration, and center preservation where space allows.
+- Test new-recording edges, preference/restore changes during recording, temporary expand/collapse,
+ degraded/recovered state, recording stop, and rapid toggles.
+- Capture manual baseline screenshots for dictation Pill and current meeting Pill in light/dark theme.
+- Record the canonical dictation surface values and intentional long-duration meeting deltas.
+
+Exit gate: baseline build/tests are green and expected visual metrics are recorded. No production
+appearance changes.
+
+### Phase 1 — Extract shared visual primitives
+
+Purpose: establish one visual language without merging feature controllers.
+
+- Extract the dictation overlay's static Pill surface recipe, border, shadow, and low-level bar
+ rendering into `FluidOverlayPrimitives.swift`.
+- Adapt `BottomOverlayView` and `BottomWaveformView` to consume the primitives while preserving its
+ state adapter, processing shimmer, dimensions, and public behavior.
+- Replace duplicated meeting surface and bar rendering with the same primitives, configured for the
+ meeting dimensions. Keep recording semantics inside content, not the outer surface recipe.
+- Add meeting hosting-view insets/hit-testing so the visible 84×32 surface has unclipped shadow and a
+ usable Stop hit area without intercepting clicks in transparent padding.
+- Keep the meeting panel factory and dictation window controller separate.
+
+Exit gate: pixel/visual comparison shows no unintended dictation change; dictation overlay tests,
+build, and manual record/process/dismiss cycle pass. Meeting recording/Stop still works.
+
+### Phase 2 — Independent meeting preference
+
+Purpose: let users select Pill or Captions independently of dictation size.
+
+- Add `MeetingOverlayPreference` to `SettingsStore`, defaulting to `.pill`.
+- Rename the established Settings > Overlay row to “Dictation overlay size” and add an independent
+ “Meeting overlay” picker there with Pill and Captions. Persist immediately like other overlay
+ preferences, avoiding one-off Cancel/Save semantics inside the meeting setup sheet.
+- Add the field to `SettingsBackupPayload` as optional so older backups decode, and restore only when
+ present. Keep the backup schema major version unchanged because the addition is backward-compatible.
+- Rename the controller/content from `MeetingRecordingPill*` to `MeetingRecordingOverlay*` once in
+ this phase so names match the two supported presentations. Update detection-prompt anchors.
+- Add the observable view model and initialize only on a new-recording edge. Preference/restore
+ changes during an active meeting apply next meeting.
+- Migrate the saved frame to the presentation-independent anchor; keep the legacy autosave key stable
+ during migration.
+- Replace `expandedPanelFrame` with `currentOverlayFrame` and update captions-window/nudge anchors.
+
+Exit gate: dictation and meeting selections survive relaunch independently; old settings and old
+backup fixtures restore to Pill; changing/restoring preference mid-meeting doesn't disturb the active
+presentation; existing position survives rename/migration.
+
+### Phase 3 — Robust Pill ↔ Captions morph
+
+Purpose: preserve the fluid expansion while making transition behavior deterministic.
+
+- Connect the controller to the Phase 0 geometry/reducer seams and fixed visible presentation sizes.
+- Replace `isExpanded` with `MeetingOverlayPresentation` and centralize transitions in the controller.
+- Keep one surface identity and remove the competing SwiftUI geometry spring. Controls and captions
+ lay out/fade from actual panel bounds.
+- Coalesce rapid toggles and protect against recording ending, panel hiding, display changes, or full
+ captions opening during a transition.
+- Captions preference starts expanded; Pill preference starts compact. Manual expand/collapse remains
+ temporary and does not rewrite the preference.
+- Preserve the current transition into the full resizable captions window, but source it only from a
+ stable completed Captions frame; opening it mid-transition first resolves the overlay state.
+- Subscribe to/coalesce transcript composition only while Captions is presented (target 5–10 UI
+ updates/second). Pill mode must not repeatedly compose rolling caption rows.
+
+Exit gate: no jumps, clipping, orphan panels, or stale `isExpanded` state under normal and rapid
+interaction; Reduce Motion path passes; Stop is usable in both modes and during/after transitions.
+
+### Phase 4 — Accessibility, longevity, and platform validation
+
+Purpose: validate a control that may remain onscreen for hours.
+
+- Provide explicit accessibility actions for Show Captions, Hide Captions, Open Captions Window,
+ and Stop Meeting Recording.
+- Keep partial captions from repeatedly taking VoiceOver focus; finalized content remains reachable
+ in the full captions view.
+- Use a named manual VoiceOver checklist; ordinary XCTest cannot verify SwiftUI accessibility
+ modifiers reliably.
+- Verify hit regions, keyboard/menu-bar fallback for Stop, high contrast, Reduce Transparency,
+ Differentiate Without Color, and Reduce Motion.
+- Run a 2-hour soak: observe CPU/GPU wakeups, memory growth, panel ordering, transcript update cost,
+ and behavior across sleep/wake and monitor changes.
+- Manually test Zoom, Google Meet in Chrome, Teams, Webex, and macOS full-display/window sharing. Log
+ whether the overlay appears in each sharing mode; do not claim reliable exclusion based on
+ `sharingType = .none`.
+
+Exit gate: no sustained timeline redraw loop; Pill redraws are bounded by audio-level/state updates;
+caption UI publishes no faster than the chosen coalescing rate; memory stays bounded; no focus theft;
+VoiceOver checklist passes; screen-sharing behavior is documented.
+
+## 6. Expected files
+
+### Add
+
+- `Sources/Fluid/UI/FluidOverlayPrimitives.swift`
+- `Tests/FluidDictationIntegrationTests/MeetingOverlayPresentationTests.swift`
+
+### Modify
+
+- `Sources/Fluid/Views/BottomOverlayView.swift`
+- `Sources/Fluid/UI/MeetingRecordingPill.swift` (renamed after Phase 1 safety gate)
+- `Sources/Fluid/UI/MeetingFloatingCaptionsPanel.swift`
+- `Sources/Fluid/UI/MeetingDetectionPrompt.swift`
+- `Sources/Fluid/UI/SettingsView.swift`
+- `Sources/Fluid/Persistence/SettingsStore.swift`
+- `Sources/Fluid/Persistence/BackupService.swift`
+- existing settings/backup tests as appropriate
+- Xcode project references if the project does not discover new files automatically
+
+Do not mix detector behavior, calendar integration, notification redesign, or dictation-during-
+meeting audio arbitration into this change.
+
+## 7. Test strategy
+
+### Automated
+
+- Presentation reducer/state transitions, including rapid/reentrant requests.
+- Frame calculation and clamping on one/multiple displays and near every screen edge.
+- Preference default, persistence, invalid raw-value fallback, and independence from dictation size.
+- Backup decode with the new field absent; round-trip with Pill and Captions.
+- Caption rolling-text composition remains deterministic.
+- Observable propagation of presentation, appearance, accessibility, and new-recording edges.
+- Existing meeting live-transcription and dictation integration tests stay green.
+
+### Manual visual/interaction matrix
+
+For Pill and Captions, test:
+
+- light/dark appearance and each accent color;
+- normal motion and Reduce Motion;
+- recording, degraded microphone, stopping, and recording-ended states;
+- click expand, collapse, full captions, Stop, dragging, and rapid toggles;
+- bottom/side screen placement, Dock/menu-bar changes, multiple monitors, full-screen Spaces;
+- live partial captions at high update frequency;
+- dictation overlays before and after the primitive extraction;
+- major meeting apps' window-share and display-share modes.
+
+### Commands during implementation
+
+- Run focused overlay/settings tests after each phase.
+- Run `swift test` after state/settings work.
+- Run the signed app build and manual meeting test after Phases 1, 3, and 4.
+- Reinstall only through the repository's stable-signing workflow; never replace the installed app
+ with an ad-hoc or identity-mismatched build.
+
+## 8. Risks and mitigations
+
+| Risk | Mitigation |
+|---|---|
+| Shared extraction regresses dictation | Characterize first; extract stateless rendering only; visual baseline gate |
+| AppKit and SwiftUI animations fight | AppKit frame is the only geometry clock; SwiftUI derives layout/progress from actual bounds |
+| Cached panel freezes settings/theme | Inject one persistent observable view model and mutate it explicitly |
+| Captions cause resize/layout thrash | Fixed presentation dimensions; transcript updates never request panel fitting size |
+| Persistent animation wastes battery | No copied 30-fps glossy-border timeline; event-driven audio level updates; soak test |
+| Preference and temporary state diverge | Separate persisted preference from session presentation; reducer tests |
+| Stop becomes hard to hit in 84×32 | Preserve visible control and expand its invisible hit region; menu-bar fallback |
+| Older backups fail decoding | Optional backup field with Pill fallback and fixture test |
+| Screen-share privacy claim is false | Treat legacy sharing flag as best effort; test and document; rely on compact footprint |
+| Rename breaks position/anchors | Migrate to a size-independent anchor, freeze the legacy key, expose current-frame semantics |
+| Degrade/recover resets presentation | Initialize only on a new-recording edge, covered by reducer tests |
+
+## 9. Rollout and rollback
+
+- Land phases as reviewable slices; do not combine the primitive extraction and animation rewrite in
+ one unreviewable change.
+- Default everyone to Pill so the new preference does not unexpectedly occupy more screen space.
+- Keep the old meeting rendering available behind a temporary debug switch through Phase 3 if visual
+ comparison reveals regressions; remove the switch before release.
+- Rollback is presentation-only: meeting recording and transcript capture must not depend on the
+ overlay being visible or on either preference value.
+
+## 10. Research basis
+
+- Apple documents
+ [`matchedGeometryEffect`](https://developer.apple.com/documentation/swiftui/view/matchedgeometryeffect%28id%3Ain%3Aproperties%3Aanchor%3Aissource%3A%29)
+ as synchronizing inserted/removed view geometry in one SwiftUI transaction and warns that its source
+ must be unambiguous; it doesn't synchronize an independent AppKit animation context.
+- Apple says
+ [`accessibilityReduceMotion`](https://developer.apple.com/documentation/swiftui/environmentvalues/accessibilityreducemotion)
+ should avoid large animations, especially depth-like movement.
+- Apple's [motion guidance](https://developer.apple.com/design/human-interface-guidelines/motion)
+ recommends purposeful, brief motion and avoiding unnecessary motion for frequent actions.
+- AppKit's
+ [`nonactivatingPanel`](https://developer.apple.com/documentation/appkit/nswindow/stylemask-swift.struct/nonactivatingpanel)
+ avoids activating the owning app, while
+ [`fullScreenAuxiliary`](https://developer.apple.com/documentation/appkit/nswindow/collectionbehavior-swift.struct/fullscreenauxiliary)
+ allows the panel alongside a full-screen window.
+- Apple now labels
+ [`NSWindow.SharingType.none`](https://developer.apple.com/documentation/appkit/nswindow/sharingtype-swift.enum)
+ a legacy constant macOS no longer uses. ScreenCaptureKit
+ [exclusion filters](https://developer.apple.com/documentation/screencapturekit/sccontentfilter/init%28display%3Aexcludingwindows%3A%29)
+ apply only when FluidVoice owns that capture filter; they can't control another application's
+ display-share filter.
+
+## 11. Adversarial review findings and resolutions
+
+Both independent reviewers returned **REVISE** on the initial draft.
+
+### Agreement
+
+- The AppKit resize and SwiftUI spring were unsynchronized; synchronization was asserted, not designed.
+- Persisted preference and temporary presentation needed explicit, tested semantics.
+- The autosaved size-dependent origin and stale `expandedPanelFrame` contract were unsafe once
+ Captions could be the resting presentation.
+- Shared visuals needed a canonical recipe rather than an unspecified “same family.”
+- Long-lived Pill performance needed to address transcript/coordinator redraws, not only the rotating
+ border animation.
+
+### Differences and decision
+
+- Opus recommended AppKit as the sole geometry driver; Kimi proposed matching cubic curves across
+ AppKit and SwiftUI. This plan takes the stricter single-driver approach: AppKit bounds drive SwiftUI
+ layout and morph progress. A shared cubic curve remains only for AppKit geometry and opacity.
+- Opus recommended an observable live-state bridge. Kimi emphasized ambiguous active-meeting setting
+ changes. The revised plan adds the bridge but applies preferences only at the next recording edge.
+- Kimi challenged putting a draft preference inside a Save/Cancel sheet. The setting now lives in the
+ established global Overlay settings and persists immediately.
+- Kimi caught that 84×32 couldn't simultaneously be the full panel frame, preserve shadow, and offer
+ larger hit targets. It is now explicitly the visible-surface size with transparent panel insets.
+
+Neither reviewer recommended merging dictation and meeting lifecycle controllers. Both accepted
+shared stateless primitives plus independent feature state as the correct boundary.
+
+## 12. PE-cycle status
+
+1. Analyse — complete.
+2. Plan — complete.
+3. Adversarial review — complete through Orchestrate: Opus 5 and Kimi K3; both initial verdicts
+ `REVISE`.
+4. Revise/lock — reviewer findings incorporated; awaiting user approval.
+5. Implement — explicitly out of scope until the plan is approved.
+6. Post-implementation review — required after each phase and at completion.
diff --git a/MEETING_TRANSCRIPTION_PRD.md b/MEETING_TRANSCRIPTION_PRD.md
index 4cc0925e..a4f22966 100644
--- a/MEETING_TRANSCRIPTION_PRD.md
+++ b/MEETING_TRANSCRIPTION_PRD.md
@@ -39,7 +39,8 @@ Checkboxes should be checked only when the requirement and its acceptance criter
- [Menu-bar lifecycle](#16-menu-bar-lifecycle-and-notifications)
- [Privacy and retention](#17-permissions-consent-privacy-and-retention)
- [Acceptance gates](#21-acceptance-and-release-gates)
-- [Open decisions](#22-open-decisions-for-alignment)
+- [Follow-up bugs](#22-follow-up-bugs)
+- [Open decisions](#23-open-decisions-for-alignment)
---
@@ -816,7 +817,23 @@ Decided 2026-08-10 from measured evidence on macOS 26.5.1; see Appendix A.
---
-## 22. Open decisions for alignment
+## 22. Follow-up bugs
+
+- [ ] **[P0 · CAPTURE] BUG-001 — Meeting transcription can freeze during voice-processing startup.**
+ - Formal analysis and evidence plan: [`MEETING_AUDIO_START_FREEZE_RCA.md`](MEETING_AUDIO_START_FREEZE_RCA.md).
+ - Reproduced twice on 2026-08-25. During VPIO aggregate-device teardown, main remained parked in an
+ AVFoundation listener-removal wait while HAL remained parked in synchronous notification dispatch.
+ The exact closing queue edge is not yet proven.
+ - Fix boundary: first isolate AVFoundation materialization, FluidVoice main-queue listeners, and idle
+ dictation prewarm. Ship every independently proven curative slice, then complete async topology
+ ownership for start, stop, recovery, and VPIO↔SCK switching.
+ - Verification: instrumented isolation matrix, no listener add/remove on main or its delivery queue,
+ zero topology-owner overlap, and zero failures in at least 2,995 targeted post-fix cycles. A timeout,
+ retry, forced restart, or timing-only guard is not an acceptable fix.
+
+---
+
+## 23. Open decisions for alignment
These do not block writing the PRD. They must be resolved before their associated milestone begins.
@@ -858,7 +875,7 @@ These do not block writing the PRD. They must be resolved before their associate
---
-## 23. Highest-risk implementation traps
+## 24. Highest-risk implementation traps
- [ ] **[MUST · FOUNDATION] RISK-001** ScreenCaptureKit microphone identifiers may not equal the current Core Audio device UID.
- [ ] **[MUST · FOUNDATION] RISK-002** The current diarization wrapper discards the embeddings needed for remembered identity.
@@ -898,7 +915,7 @@ Both follow-ups closed 2026-08-10 on the implemented branch:
---
-## 24. Primary references
+## 25. Primary references
- Apple ScreenCaptureKit: <https://developer.apple.com/documentation/screencapturekit>
- Apple `SCContentFilter`: <https://developer.apple.com/documentation/screencapturekit/sccontentfilter>
diff --git a/README.md b/README.md
index f649d4a7..1185951b 100644
--- a/README.md
+++ b/README.md
@@ -212,8 +212,8 @@ fallback:
./build.sh unsigned
```
-Unsigned builds are tied to a specific executable version and may require Accessibility
-permission to be removed and granted again after rebuilding.
+Unsigned builds are tied to a specific executable version and may require Accessibility,
+Screen Recording, and microphone permissions to be removed and granted again after rebuilding.
---
diff --git a/Sources/CoreAudioCaptureSupport/CoreAudioCaptureSupport.c b/Sources/CoreAudioCaptureSupport/CoreAudioCaptureSupport.c
index d75ac226..4d7ac7a6 100644
--- a/Sources/CoreAudioCaptureSupport/CoreAudioCaptureSupport.c
+++ b/Sources/CoreAudioCaptureSupport/CoreAudioCaptureSupport.c
@@ -11,6 +11,7 @@
// realtime producer strictly allocation-free.
#define FV_RING_CAPACITY 64u
#define FV_MAX_FRAMES_PER_PACKET 8192u
+#define FV_AUDIO_TOPOLOGY_TRACE_CAPACITY 2048u
typedef struct {
float samples[FV_MAX_FRAMES_PER_PACKET];
@@ -37,6 +38,220 @@ typedef struct {
FVPacketSlot slots[FV_RING_CAPACITY];
} FVCapture;
+typedef struct {
+ _Atomic uint64_t publishedSequence;
+ _Atomic uint64_t sequence;
+ _Atomic uint64_t continuousTime;
+ _Atomic uint64_t generation;
+ _Atomic uint32_t event;
+ _Atomic uint32_t owner;
+ _Atomic uint32_t objectID;
+ _Atomic uint32_t selector;
+ _Atomic uint32_t scope;
+ _Atomic uint32_t element;
+ _Atomic uint32_t queueRole;
+ _Atomic uint32_t phase;
+ _Atomic uint32_t transport;
+ _Atomic int32_t status;
+} FVAudioTopologyTraceSlot;
+
+static _Atomic bool fvAudioTopologyTraceEnabled = false;
+static _Atomic uint64_t fvAudioTopologyTraceSequence = 0;
+static _Atomic uint64_t fvAudioTopologyMainHeartbeat = 0;
+static FVAudioTopologyTraceSlot
+ fvAudioTopologyTraceSlots[FV_AUDIO_TOPOLOGY_TRACE_CAPACITY];
+
+void fv_audio_topology_trace_set_enabled(bool enabled) {
+ atomic_store_explicit(
+ &fvAudioTopologyTraceEnabled,
+ enabled,
+ memory_order_release
+ );
+}
+
+bool fv_audio_topology_trace_is_enabled(void) {
+ return atomic_load_explicit(
+ &fvAudioTopologyTraceEnabled,
+ memory_order_acquire
+ );
+}
+
+uint64_t fv_audio_topology_trace_record(
+ uint32_t event,
+ uint32_t owner,
+ AudioObjectID objectID,
+ AudioObjectPropertySelector selector,
+ AudioObjectPropertyScope scope,
+ AudioObjectPropertyElement element,
+ uint32_t queueRole,
+ uint32_t phase,
+ uint32_t transport,
+ int32_t status,
+ uint64_t generation
+) {
+ if (!atomic_load_explicit(
+ &fvAudioTopologyTraceEnabled,
+ memory_order_relaxed
+ )) {
+ return 0;
+ }
+
+ const uint64_t sequence = atomic_fetch_add_explicit(
+ &fvAudioTopologyTraceSequence,
+ 1,
+ memory_order_relaxed
+ ) + 1;
+ FVAudioTopologyTraceSlot *slot =
+ &fvAudioTopologyTraceSlots[(sequence - 1) % FV_AUDIO_TOPOLOGY_TRACE_CAPACITY];
+
+ // Zero marks the slot as being mutated. A reader that races this write
+ // discards the copy after its second acquire load.
+ atomic_store_explicit(&slot->publishedSequence, 0, memory_order_release);
+ atomic_store_explicit(&slot->sequence, sequence, memory_order_relaxed);
+ atomic_store_explicit(&slot->continuousTime, mach_continuous_time(), memory_order_relaxed);
+ atomic_store_explicit(&slot->generation, generation, memory_order_relaxed);
+ atomic_store_explicit(&slot->event, event, memory_order_relaxed);
+ atomic_store_explicit(&slot->owner, owner, memory_order_relaxed);
+ atomic_store_explicit(&slot->objectID, objectID, memory_order_relaxed);
+ atomic_store_explicit(&slot->selector, selector, memory_order_relaxed);
+ atomic_store_explicit(&slot->scope, scope, memory_order_relaxed);
+ atomic_store_explicit(&slot->element, element, memory_order_relaxed);
+ atomic_store_explicit(&slot->queueRole, queueRole, memory_order_relaxed);
+ atomic_store_explicit(&slot->phase, phase, memory_order_relaxed);
+ atomic_store_explicit(&slot->transport, transport, memory_order_relaxed);
+ atomic_store_explicit(&slot->status, status, memory_order_relaxed);
+ atomic_store_explicit(
+ &slot->publishedSequence,
+ sequence,
+ memory_order_release
+ );
+ return sequence;
+}
+
+uint32_t fv_audio_topology_trace_snapshot(
+ uint64_t afterSequence,
+ FVAudioTopologyTraceEvent *events,
+ uint32_t capacity,
+ uint64_t *latestSequence
+) {
+ const uint64_t latest = atomic_load_explicit(
+ &fvAudioTopologyTraceSequence,
+ memory_order_acquire
+ );
+ if (latestSequence != NULL) {
+ *latestSequence = latest;
+ }
+ if (events == NULL || capacity == 0 || latest <= afterSequence) {
+ return 0;
+ }
+
+ const uint64_t oldestAvailable =
+ latest > FV_AUDIO_TOPOLOGY_TRACE_CAPACITY
+ ? latest - FV_AUDIO_TOPOLOGY_TRACE_CAPACITY + 1
+ : 1;
+ uint64_t sequence = afterSequence + 1;
+ if (sequence < oldestAvailable) {
+ sequence = oldestAvailable;
+ }
+
+ uint32_t copied = 0;
+ for (; sequence <= latest && copied < capacity; ++sequence) {
+ FVAudioTopologyTraceSlot *slot =
+ &fvAudioTopologyTraceSlots[(sequence - 1) % FV_AUDIO_TOPOLOGY_TRACE_CAPACITY];
+ const uint64_t publishedBefore = atomic_load_explicit(
+ &slot->publishedSequence,
+ memory_order_acquire
+ );
+ if (publishedBefore != sequence) {
+ continue;
+ }
+ const FVAudioTopologyTraceEvent candidate = {
+ .sequence = atomic_load_explicit(&slot->sequence, memory_order_relaxed),
+ .continuousTime = atomic_load_explicit(&slot->continuousTime, memory_order_relaxed),
+ .generation = atomic_load_explicit(&slot->generation, memory_order_relaxed),
+ .event = atomic_load_explicit(&slot->event, memory_order_relaxed),
+ .owner = atomic_load_explicit(&slot->owner, memory_order_relaxed),
+ .objectID = atomic_load_explicit(&slot->objectID, memory_order_relaxed),
+ .selector = atomic_load_explicit(&slot->selector, memory_order_relaxed),
+ .scope = atomic_load_explicit(&slot->scope, memory_order_relaxed),
+ .element = atomic_load_explicit(&slot->element, memory_order_relaxed),
+ .queueRole = atomic_load_explicit(&slot->queueRole, memory_order_relaxed),
+ .phase = atomic_load_explicit(&slot->phase, memory_order_relaxed),
+ .transport = atomic_load_explicit(&slot->transport, memory_order_relaxed),
+ .status = atomic_load_explicit(&slot->status, memory_order_relaxed),
+ };
+ atomic_thread_fence(memory_order_acquire);
+ const uint64_t publishedAfter = atomic_load_explicit(
+ &slot->publishedSequence,
+ memory_order_acquire
+ );
+ if (publishedAfter != sequence || candidate.sequence != sequence) {
+ continue;
+ }
+ events[copied++] = candidate;
+ }
+ return copied;
+}
+
+uint32_t fv_audio_topology_trace_capacity(void) {
+ return FV_AUDIO_TOPOLOGY_TRACE_CAPACITY;
+}
+
+uint64_t fv_audio_topology_trace_latest_sequence(void) {
+ return atomic_load_explicit(
+ &fvAudioTopologyTraceSequence,
+ memory_order_acquire
+ );
+}
+
+void fv_audio_topology_trace_main_heartbeat(void) {
+ if (!atomic_load_explicit(
+ &fvAudioTopologyTraceEnabled,
+ memory_order_relaxed
+ )) {
+ return;
+ }
+ atomic_store_explicit(
+ &fvAudioTopologyMainHeartbeat,
+ mach_continuous_time(),
+ memory_order_release
+ );
+}
+
+uint64_t fv_audio_topology_trace_last_main_heartbeat(void) {
+ return atomic_load_explicit(
+ &fvAudioTopologyMainHeartbeat,
+ memory_order_acquire
+ );
+}
+
+void fv_audio_topology_trace_reset(void) {
+ atomic_store_explicit(&fvAudioTopologyTraceEnabled, false, memory_order_release);
+ atomic_store_explicit(&fvAudioTopologyTraceSequence, 0, memory_order_release);
+ atomic_store_explicit(&fvAudioTopologyMainHeartbeat, 0, memory_order_release);
+ for (uint32_t index = 0; index < FV_AUDIO_TOPOLOGY_TRACE_CAPACITY; ++index) {
+ atomic_store_explicit(
+ &fvAudioTopologyTraceSlots[index].publishedSequence,
+ 0,
+ memory_order_release
+ );
+ FVAudioTopologyTraceSlot *slot = &fvAudioTopologyTraceSlots[index];
+ atomic_store_explicit(&slot->sequence, 0, memory_order_relaxed);
+ atomic_store_explicit(&slot->continuousTime, 0, memory_order_relaxed);
+ atomic_store_explicit(&slot->generation, 0, memory_order_relaxed);
+ atomic_store_explicit(&slot->event, 0, memory_order_relaxed);
+ atomic_store_explicit(&slot->owner, 0, memory_order_relaxed);
+ atomic_store_explicit(&slot->objectID, 0, memory_order_relaxed);
+ atomic_store_explicit(&slot->selector, 0, memory_order_relaxed);
+ atomic_store_explicit(&slot->scope, 0, memory_order_relaxed);
+ atomic_store_explicit(&slot->element, 0, memory_order_relaxed);
+ atomic_store_explicit(&slot->queueRole, 0, memory_order_relaxed);
+ atomic_store_explicit(&slot->phase, 0, memory_order_relaxed);
+ atomic_store_explicit(&slot->transport, 0, memory_order_relaxed);
+ atomic_store_explicit(&slot->status, 0, memory_order_relaxed);
+ }
+}
+
static OSStatus fv_get_input_stream_format(
AudioObjectID deviceID,
AudioStreamID *streamID,
diff --git a/Sources/CoreAudioCaptureSupport/include/CoreAudioCaptureSupport.h b/Sources/CoreAudioCaptureSupport/include/CoreAudioCaptureSupport.h
index e9e1fc7f..066d0b5c 100644
--- a/Sources/CoreAudioCaptureSupport/include/CoreAudioCaptureSupport.h
+++ b/Sources/CoreAudioCaptureSupport/include/CoreAudioCaptureSupport.h
@@ -65,6 +65,66 @@ double fv_core_audio_capture_sample_rate(FVCoreAudioCaptureRef capture);
uint32_t fv_core_audio_capture_buffer_frame_size(FVCoreAudioCaptureRef capture);
uint64_t fv_core_audio_capture_dropped_packet_count(FVCoreAudioCaptureRef capture);
+// MARK: - Audio topology diagnostics
+
+/// Fixed-size, numeric-only event captured without allocation, locks, dispatch,
+/// file I/O, environment reads, or Core Audio calls. String rendering happens
+/// later on a diagnostics drain queue.
+typedef struct {
+ uint64_t sequence;
+ uint64_t continuousTime;
+ uint64_t generation;
+ uint32_t event;
+ uint32_t owner;
+ AudioObjectID objectID;
+ AudioObjectPropertySelector selector;
+ AudioObjectPropertyScope scope;
+ AudioObjectPropertyElement element;
+ uint32_t queueRole;
+ uint32_t phase;
+ uint32_t transport;
+ int32_t status;
+} FVAudioTopologyTraceEvent;
+
+void fv_audio_topology_trace_set_enabled(bool enabled);
+bool fv_audio_topology_trace_is_enabled(void);
+
+/// Captures one event and returns its monotonically increasing sequence, or 0
+/// when tracing is disabled.
+uint64_t fv_audio_topology_trace_record(
+ uint32_t event,
+ uint32_t owner,
+ AudioObjectID objectID,
+ AudioObjectPropertySelector selector,
+ AudioObjectPropertyScope scope,
+ AudioObjectPropertyElement element,
+ uint32_t queueRole,
+ uint32_t phase,
+ uint32_t transport,
+ int32_t status,
+ uint64_t generation
+);
+
+/// Copies fully published events newer than afterSequence in sequence order.
+/// Overwritten or concurrently mutating slots are skipped. latestSequence is
+/// the highest sequence reserved when the snapshot began.
+uint32_t fv_audio_topology_trace_snapshot(
+ uint64_t afterSequence,
+ FVAudioTopologyTraceEvent *events,
+ uint32_t capacity,
+ uint64_t *latestSequence
+);
+
+uint32_t fv_audio_topology_trace_capacity(void);
+uint64_t fv_audio_topology_trace_latest_sequence(void);
+
+/// Main-runloop heartbeat; both functions are atomic and non-blocking.
+void fv_audio_topology_trace_main_heartbeat(void);
+uint64_t fv_audio_topology_trace_last_main_heartbeat(void);
+
+/// Test-only in intent. Call only while no producers are active.
+void fv_audio_topology_trace_reset(void);
+
#ifdef __cplusplus
}
#endif
diff --git a/Sources/Fluid/AppDelegate.swift b/Sources/Fluid/AppDelegate.swift
index c5fbd1a9..dd5b9720 100644
--- a/Sources/Fluid/AppDelegate.swift
+++ b/Sources/Fluid/AppDelegate.swift
@@ -24,10 +24,18 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele
}
func applicationDidFinishLaunching(_ notification: Notification) {
+ #if DEBUG
+ // Must precede every Core Audio observer. Disabled unless explicitly
+ // requested through the Phase 0 diagnostics environment.
+ AudioTopologyDiagnostics.shared.startIfRequested()
+ #endif
// Bring up file logging + crash handlers immediately during launch.
_ = FileLogger.shared
TypingService.startKeyboardLayoutTracking()
_ = TranscriptionHistoryStore.shared
+ #if DEBUG
+ MeetingDetectorFeasibilityProbe.startIfRequested()
+ #endif
// Must be read during the launch callback - the current Apple Event identifies
// login-item launches (used to optionally start silently, see issue #369).
self.wasLaunchedAsLoginItem = Self.detectLoginItemLaunch()
@@ -60,6 +68,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele
// Login Items can launch hidden; reveal the real SwiftUI window so ContentView startup runs.
self.openMainWindowOnLaunch()
+ self.scheduleMeetingAutoDetectorStart()
// Note: App UI is designed with dark color scheme in mind
// All gradients and effects are optimized for dark mode
@@ -91,6 +100,9 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele
// Clean up the update check timer
self.updateCheckTimer?.invalidate()
self.updateCheckTimer = nil
+ #if DEBUG
+ AudioTopologyDiagnostics.shared.stop()
+ #endif
}
/// Short deadline: the index is rebuilt from its source stores, so a timeout
@@ -264,6 +276,13 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele
}
}
+ private func scheduleMeetingAutoDetectorStart() {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
+ Task { @MainActor in
+ _ = AppServices.shared.meetingAutoDetector
+ }
+ }
+ }
/// Realize the main window invisibly so ContentView's startup runs, then order it out.
/// Used for login-item launches when "Show window when launched at login" is off.
@discardableResult
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swift
index 431aec8f..32ca4fb0 100644
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@ -1086,6 +1086,8 @@ struct ContentView: View {
self.navigateToApp(.aiEnhancements)
case .history:
self.navigateToApp(.history)
+ case .meetingTranscription:
+ self.navigateToApp(.meetingTools)
}
}
@@ -4371,7 +4373,6 @@ struct ContentView: View {
},
rewriteModeCallback: {
guard !self.presentExclusiveActivityBlockIfNeeded() else { return }
- guard !self.showPrivateAIEditModeUnavailableIfNeeded() else { return }
self.captureRecordingContext()
diff --git a/Sources/Fluid/Persistence/BackupService.swift b/Sources/Fluid/Persistence/BackupService.swift
index 0dfdd165..0fe5f1f9 100644
--- a/Sources/Fluid/Persistence/BackupService.swift
+++ b/Sources/Fluid/Persistence/BackupService.swift
@@ -84,6 +84,7 @@ struct SettingsBackupPayload: Codable, Equatable {
let overlayPosition: SettingsStore.OverlayPosition
let overlayBottomOffset: Double
let overlaySize: SettingsStore.OverlaySize
+ let meetingOverlayPreference: MeetingOverlayPreference?
let transcriptionPreviewCharLimit: Int
let userTypingWPM: Int
let saveTranscriptionHistory: Bool
diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swift
index 866db0b7..57eef338 100644
--- a/Sources/Fluid/Persistence/SettingsStore.swift
+++ b/Sources/Fluid/Persistence/SettingsStore.swift
@@ -1954,6 +1954,28 @@ final class SettingsStore: ObservableObject {
}
}
+ /// Tier 1 native (Zoom/Teams/Webex) meeting auto-detection (default: ON).
+ var meetingAutoDetectEnabled: Bool {
+ get {
+ let value = self.defaults.object(forKey: Keys.meetingAutoDetectEnabled)
+ if value == nil { return true }
+ return self.defaults.bool(forKey: Keys.meetingAutoDetectEnabled)
+ }
+ set {
+ objectWillChange.send()
+ self.defaults.set(newValue, forKey: Keys.meetingAutoDetectEnabled)
+ }
+ }
+
+ /// Tier 2 browser-tab meeting auto-detection (default: OFF — reads the frontmost tab's URL).
+ var meetingAutoDetectBrowserEnabled: Bool {
+ get { self.defaults.bool(forKey: Keys.meetingAutoDetectBrowserEnabled) }
+ set {
+ objectWillChange.send()
+ self.defaults.set(newValue, forKey: Keys.meetingAutoDetectBrowserEnabled)
+ }
+ }
+
var preferredOutputDeviceUID: String? {
get { self.defaults.string(forKey: Keys.preferredOutputDeviceUID) }
set { self.defaults.set(newValue, forKey: Keys.preferredOutputDeviceUID) }
@@ -2232,6 +2254,21 @@ final class SettingsStore: ObservableObject {
}
}
+ 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 {
@@ -3347,6 +3384,7 @@ final class SettingsStore: ObservableObject {
overlayPosition: self.overlayPosition,
overlayBottomOffset: self.overlayBottomOffset,
overlaySize: self.overlaySize,
+ meetingOverlayPreference: self.meetingOverlayPreference,
transcriptionPreviewCharLimit: self.transcriptionPreviewCharLimit,
userTypingWPM: self.userTypingWPM,
saveTranscriptionHistory: self.saveTranscriptionHistory,
@@ -3504,6 +3542,9 @@ final class SettingsStore: ObservableObject {
self.overlayPosition = payload.overlayPosition
self.overlayBottomOffset = payload.overlayBottomOffset
self.overlaySize = payload.overlaySize
+ if let meetingOverlayPreference = payload.meetingOverlayPreference {
+ self.meetingOverlayPreference = meetingOverlayPreference
+ }
self.transcriptionPreviewCharLimit = payload.transcriptionPreviewCharLimit
self.userTypingWPM = payload.userTypingWPM
self.saveTranscriptionHistory = payload.saveTranscriptionHistory
@@ -5463,6 +5504,8 @@ private extension SettingsStore {
static let preferredOutputDeviceUID = "PreferredOutputDeviceUID"
static let meetingRecordingDefaults = "MeetingRecordingDefaults"
static let meetingAudioRetentionPolicy = "MeetingAudioRetentionPolicy"
+ static let meetingAutoDetectEnabled = "MeetingAutoDetectEnabled"
+ static let meetingAutoDetectBrowserEnabled = "MeetingAutoDetectBrowserEnabled"
static let microphoneSelectionMode = "MicrophoneSelectionMode"
// Keep the original persisted key so existing installs migrate in place.
static let microphoneSelectionMigrationVersion = "AppOnlyMicrophoneSelectionMigrationVersion"
@@ -5587,6 +5630,7 @@ private extension SettingsStore {
static let overlayBottomOffset = "OverlayBottomOffset"
static let overlayBottomOffsetMigratedTo50 = "OverlayBottomOffsetMigratedTo50"
static let overlaySize = "OverlaySize"
+ static let meetingOverlayPreference = "MeetingOverlayPreference"
static let transcriptionPreviewCharLimit = "TranscriptionPreviewCharLimit"
/// Media Playback Control
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index ee83e987..4e42f73d 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -1945,7 +1945,7 @@ final class ASRService: ObservableObject {
let initialInputSnapshot = await withCheckedContinuation { continuation in
DispatchQueue.global(qos: .userInitiated).async {
- let devices = AudioDevice.listInputDevicesRefreshingLiveness()
+ let devices = AudioDevice.listInputDevicesRefreshingLiveness(diagnosticsOwner: .asrService)
let defaultInputUID = AudioDevice.getDefaultInputDevice()?.uid
continuation.resume(returning: (devices, defaultInputUID))
}
@@ -2819,7 +2819,7 @@ final class ASRService: ObservableObject {
let snapshot = await withCheckedContinuation { continuation in
DispatchQueue.global(qos: .userInitiated).async {
- let devices = AudioDevice.listInputDevicesRefreshingLiveness()
+ let devices = AudioDevice.listInputDevicesRefreshingLiveness(diagnosticsOwner: .asrService)
let defaultInputUID = AudioDevice.getDefaultInputDevice()?.uid
continuation.resume(returning: (devices, defaultInputUID))
}
@@ -4113,6 +4113,15 @@ final class ASRService: ObservableObject {
reconcilesInputSelection: reconcilesInputAfterRecovery
)
self.pendingAudioRouteRecovery = request
+ #if DEBUG
+ AudioTopologyDiagnostics.record(
+ .recoveryScheduled,
+ owner: .asrDeviceList,
+ queueRole: .mainControl,
+ phase: .recovery,
+ generation: request.generation
+ )
+ #endif
self.audioLevelSubject.send(0.0)
if self.isRunning || self.isStarting {
@@ -4159,6 +4168,15 @@ final class ASRService: ObservableObject {
/// rebuild that yielded while AVAudioEngine was deallocating.
private func cancelAudioRouteRecoveryAndWait() async {
self.audioRouteRecoveryGeneration &+= 1
+ #if DEBUG
+ AudioTopologyDiagnostics.record(
+ .recoveryCancel,
+ owner: .asrDeviceList,
+ queueRole: .mainControl,
+ phase: .recovery,
+ generation: self.audioRouteRecoveryGeneration
+ )
+ #endif
self.pendingAudioRouteRecovery = nil
let task = self.audioRouteRecoveryTask
task?.cancel()
@@ -4202,6 +4220,15 @@ final class ASRService: ObservableObject {
guard self.isRecoveringAudioRoute == false else { return }
self.isRecoveringAudioRoute = true
+ #if DEBUG
+ AudioTopologyDiagnostics.record(
+ .recoveryBegin,
+ owner: .asrDeviceList,
+ queueRole: .mainControl,
+ phase: .recovery,
+ generation: request.generation
+ )
+ #endif
defer {
self.finishAudioRouteRecovery(request)
}
@@ -4228,6 +4255,16 @@ final class ASRService: ObservableObject {
}
private func finishAudioRouteRecovery(_ completedRequest: AudioRouteRecoveryRequest) {
+ #if DEBUG
+ AudioTopologyDiagnostics.record(
+ .recoveryEnd,
+ owner: .asrDeviceList,
+ queueRole: .mainControl,
+ phase: .recovery,
+ status: Task.isCancelled ? -1 : noErr,
+ generation: completedRequest.generation
+ )
+ #endif
self.isRecoveringAudioRoute = false
guard let pendingRequest = self.pendingAudioRouteRecovery else {
@@ -4663,17 +4700,26 @@ final class ASRService: ObservableObject {
if self.defaultInputListenerInstalled == false {
let inputToken: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.callback, owner: .asrDefaultInput, objectID: AudioObjectID(kAudioObjectSystemObject), selector: kAudioHardwarePropertyDefaultInputDevice, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainDelivery)
+ #endif
// Defer to next runloop pass — CoreAudio may hold an internal lock during
// this callback, and our handler makes synchronous CoreAudio queries that
// would deadlock waiting for the same lock.
DispatchQueue.main.async { self?.handleDefaultInputChanged() }
}
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .asrDefaultInput, objectID: AudioObjectID(kAudioObjectSystemObject), selector: inputAddress.mSelector, scope: inputAddress.mScope, element: inputAddress.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
let inputStatus = AudioObjectAddPropertyListenerBlock(
AudioObjectID(kAudioObjectSystemObject),
&inputAddress,
DispatchQueue.main,
inputToken
)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .asrDefaultInput, objectID: AudioObjectID(kAudioObjectSystemObject), selector: inputAddress.mSelector, scope: inputAddress.mScope, element: inputAddress.mElement, queueRole: .mainControl, phase: .listener, status: inputStatus)
+ #endif
if inputStatus == noErr {
self.defaultInputListenerInstalled = true
@@ -4686,14 +4732,23 @@ final class ASRService: ObservableObject {
if self.defaultOutputListenerToken == nil {
let outputToken: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.callback, owner: .asrDefaultOutput, objectID: AudioObjectID(kAudioObjectSystemObject), selector: kAudioHardwarePropertyDefaultOutputDevice, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainDelivery)
+ #endif
DispatchQueue.main.async { self?.handleDefaultOutputChanged() }
}
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .asrDefaultOutput, objectID: AudioObjectID(kAudioObjectSystemObject), selector: outputAddress.mSelector, scope: outputAddress.mScope, element: outputAddress.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
let outputStatus = AudioObjectAddPropertyListenerBlock(
AudioObjectID(kAudioObjectSystemObject),
&outputAddress,
DispatchQueue.main,
outputToken
)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .asrDefaultOutput, objectID: AudioObjectID(kAudioObjectSystemObject), selector: outputAddress.mSelector, scope: outputAddress.mScope, element: outputAddress.mElement, queueRole: .mainControl, phase: .listener, status: outputStatus)
+ #endif
if outputStatus == noErr {
self.defaultOutputListenerToken = outputToken
@@ -4725,17 +4780,26 @@ final class ASRService: ObservableObject {
let controller = self.directAudioLifecycleController
let token: AudioObjectPropertyListenerBlock = { [weak self, weak controller] _, _ in
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.callback, owner: .asrDeviceList, objectID: AudioObjectID(kAudioObjectSystemObject), selector: kAudioHardwarePropertyDevices, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .dedicatedDelivery)
+ #endif
// Mark freshness immediately, even if the UI is busy. This only
// updates an in-memory revision; HAL queries remain outside callbacks.
controller?.noteHardwareTopologyChanged()
DispatchQueue.main.async { self?.handleDeviceListChanged() }
}
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .asrDeviceList, objectID: AudioObjectID(kAudioObjectSystemObject), selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
let status = AudioObjectAddPropertyListenerBlock(
AudioObjectID(kAudioObjectSystemObject),
&address,
self.deviceListListenerQueue,
token
)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .asrDeviceList, objectID: AudioObjectID(kAudioObjectSystemObject), selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener, status: status)
+ #endif
if status == noErr {
self.deviceListListenerInstalled = true
@@ -4760,14 +4824,23 @@ final class ASRService: ObservableObject {
)
let token: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.callback, owner: .asrMonitoredInput, objectID: deviceID, selector: kAudioDevicePropertyDeviceIsAlive, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainDelivery)
+ #endif
DispatchQueue.main.async { self?.handleDeviceAvailabilityChanged(deviceID: deviceID) }
}
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .asrMonitoredInput, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
let status = AudioObjectAddPropertyListenerBlock(
deviceID,
&address,
DispatchQueue.main,
token
)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .asrMonitoredInput, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener, status: status)
+ #endif
if status == noErr {
self.monitoredDeviceID = deviceID
@@ -4791,7 +4864,13 @@ final class ASRService: ObservableObject {
)
if let token = self.monitoredDeviceIsAliveListenerToken {
- _ = AudioObjectRemovePropertyListenerBlock(deviceID, &address, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .asrMonitoredInput, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
+ let status = AudioObjectRemovePropertyListenerBlock(deviceID, &address, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .asrMonitoredInput, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener, status: status)
+ #endif
}
self.monitoredDeviceID = nil
self.monitoredDeviceIsAliveListenerToken = nil
@@ -4805,7 +4884,7 @@ final class ASRService: ObservableObject {
// Perform CoreAudio queries off the main thread — during a device topology change
// the HAL may still be settling, and synchronous queries on main can deadlock.
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
- let currentDevices = AudioDevice.listInputDevicesRefreshingLiveness()
+ let currentDevices = AudioDevice.listInputDevicesRefreshingLiveness(diagnosticsOwner: .asrService)
let defaultInputUID = AudioDevice.getDefaultInputDevice()?.uid
DispatchQueue.main.async { [weak self] in
diff --git a/Sources/Fluid/Services/AppNavigationRouter.swift b/Sources/Fluid/Services/AppNavigationRouter.swift
index bd131303..9d667a74 100644
--- a/Sources/Fluid/Services/AppNavigationRouter.swift
+++ b/Sources/Fluid/Services/AppNavigationRouter.swift
@@ -3,6 +3,7 @@ import Foundation
enum AppNavigationDestination {
case aiEnhancements
case history
+ case meetingTranscription
}
@MainActor
diff --git a/Sources/Fluid/Services/AppServices.swift b/Sources/Fluid/Services/AppServices.swift
index 779120e1..13013e26 100644
--- a/Sources/Fluid/Services/AppServices.swift
+++ b/Sources/Fluid/Services/AppServices.swift
@@ -31,13 +31,16 @@ final class AppServices: ObservableObject {
/// Flag indicating the UI has completed its initial render.
/// Heavy operations should wait until this is true.
@Published private(set) var isUIReady: Bool = false
+ @Published private(set) var meetingAutoDetectHealth: MeetingAutoDetector.Health?
/// Call this once the main UI has finished its initial layout.
/// This signals that it's safe to start heavy services.
func signalUIReady() {
- guard !self.isUIReady else { return }
- DebugLogger.shared.info("🚦 UI Ready signal received - services can now initialize", source: "AppServices")
- self.isUIReady = true
+ if !self.isUIReady {
+ DebugLogger.shared.info("🚦 UI Ready signal received - services can now initialize", source: "AppServices")
+ self.isUIReady = true
+ }
+ _ = self.meetingAutoDetector
}
// MARK: - Lazy Services
@@ -120,6 +123,16 @@ final class AppServices: ObservableObject {
)
self._meetingSessionCoordinator = coordinator
self.setupMeetingCoordinatorForwarding()
+ // The auto-detected episode itself stays consumed until the meeting's own evidence ends
+ // (window/URL gone ≥60s) — not merely because our recording stopped — so only the nudge
+ // needs to be dismissed here.
+ coordinator.$state
+ .receive(on: DispatchQueue.main)
+ .sink { state in
+ guard !MeetingFloatingCaptionsController.isVisible(for: state) else { return }
+ MeetingStillRecordingNudgeController.shared.hide()
+ }
+ .store(in: &self.cancellables)
Task { @MainActor in
MeetingRecordingPillController.shared.activate(coordinator: coordinator)
await coordinator.ensureRestored()
@@ -128,6 +141,93 @@ final class AppServices: ObservableObject {
return coordinator
}
+ /// Standalone — activated once, independently of `meetingSessionCoordinator`'s lazy getter.
+ private var _meetingAutoDetector: MeetingAutoDetector?
+ var meetingAutoDetector: MeetingAutoDetector {
+ if let existing = self._meetingAutoDetector {
+ return existing
+ }
+ let detector = MeetingAutoDetector(
+ workspaceEvents: WorkspaceEventsMonitor(),
+ micActivity: CoreAudioMicActivitySignal(),
+ audioProcessActivity: CoreAudioProcessActivityProvider(),
+ windowSnapshotProvider: CGWindowSnapshotProvider(),
+ browserTabReader: AXBrowserTabReader(),
+ activityGate: LiveDetectionActivityGate(),
+ clock: SystemClock(),
+ isNativeDetectionEnabled: { SettingsStore.shared.meetingAutoDetectEnabled },
+ isBrowserDetectionEnabled: {
+ SettingsStore.shared.meetingAutoDetectEnabled && SettingsStore.shared.meetingAutoDetectBrowserEnabled
+ }
+ )
+ self._meetingAutoDetector = detector
+ self.wireMeetingAutoDetector(detector)
+ detector.start()
+ DebugLogger.shared.info("detector-started", source: "MeetingAutoDetector")
+ return detector
+ }
+
+ private func wireMeetingAutoDetector(_ detector: MeetingAutoDetector) {
+ detector.onPromptRequested = { request in
+ MeetingDetectionPromptController.shared.present(request)
+ }
+ detector.onHealthChanged = { [weak self] health in
+ self?.meetingAutoDetectHealth = health
+ }
+ detector.onStillRecordingNudge = {
+ MeetingStillRecordingNudgeController.shared.present()
+ }
+ detector.onSuggestDisablingAutoDetect = {
+ MeetingAutoDetectDismissalAdvisor.shared.shouldSuggest = true
+ }
+ detector.onEpisodeInvalidated = { episodeID in
+ MeetingDetectionPromptController.shared.invalidateEpisode(episodeID)
+ }
+ MeetingDetectionPromptController.shared.onStart = { [weak self] episodeID in
+ guard let self else { throw MeetingAutoDetector.StartError.cannotStart }
+ try await self.startAutoDetectedRecording(episodeID: episodeID)
+ }
+ MeetingDetectionPromptController.shared.onSetup = { [weak self] episodeID in
+ // Setup is intentionally navigation-only: it must never materialize a recording.
+ self?._meetingAutoDetector?.timeoutDismissed(episodeID: episodeID)
+ AppNavigationRouter.shared.request(.meetingTranscription)
+ }
+ MeetingDetectionPromptController.shared.onDismiss = { [weak self] episodeID in
+ self?._meetingAutoDetector?.dismissTapped(episodeID: episodeID, at: Date())
+ }
+ MeetingDetectionPromptController.shared.onTimeout = { [weak self] episodeID in
+ self?._meetingAutoDetector?.timeoutDismissed(episodeID: episodeID)
+ }
+ MeetingStillRecordingNudgeController.shared.onStop = { [weak self] in
+ guard let self else { return }
+ Task { @MainActor in _ = try? await self.meetingSessionCoordinator.stopAndTranscribe() }
+ }
+ }
+
+ private func startAutoDetectedRecording(episodeID: UUID) async throws {
+ guard let detector = self._meetingAutoDetector,
+ let target = detector.resolvedTarget(for: episodeID),
+ detector.canStart(episodeID: episodeID)
+ else {
+ throw MeetingAutoDetector.StartError.cannotStart
+ }
+ let coordinator = self.meetingSessionCoordinator
+ let configuration = try await coordinator.defaultConfiguration(
+ mode: .onlineCall,
+ title: MeetingTranscriptionSetupDraft.defaultTitle(mode: .onlineCall, applicationDisplayName: nil),
+ preferredBundleIdentifier: target.bundleIdentifier,
+ preferredWindowID: target.windowID,
+ requirePreferredApplication: true
+ )
+ try Task.checkCancellation()
+ guard detector.canStart(episodeID: episodeID) else {
+ throw MeetingAutoDetector.StartError.cannotStart
+ }
+ _ = try await coordinator.startRecording(configuration: configuration)
+ detector.adoptStartedEpisode(episodeID: episodeID)
+ AppNavigationRouter.shared.request(.meetingTranscription)
+ }
+
/// Read-only meeting check that does not initialize the meeting stack.
var hasActiveMeetingSessionActivity: Bool {
guard let coordinator = self._meetingSessionCoordinator else { return false }
@@ -143,6 +243,10 @@ final class AppServices: ObservableObject {
self._asr?.activeExclusiveActivity == .fileTranscription
}
+ /// Read-only checks for MeetingAutoDetector: never force either lazy service into existence.
+ var isMeetingSessionCoordinatorMaterialized: Bool { self._meetingSessionCoordinator != nil }
+ var activeExclusiveActivityIfASRMaterialized: ASRExclusiveActivity? { self._asr?.activeExclusiveActivity }
+
/// Legacy UI guard; ASRService is the atomic source of truth for acquisition.
var hasActiveMeetingActivity: Bool {
self.hasActiveMeetingSessionActivity || self._asr?.activeExclusiveActivity == .meeting
@@ -200,11 +304,14 @@ final class AppServices: ObservableObject {
// Access the properties to trigger lazy initialization
_ = self.audioObserver
_ = self.asr
+ _ = self.meetingAutoDetector
DebugLogger.shared.info("✅ All services initialized", source: "AppServices")
}
func shutdownForTermination() async {
+ self._meetingAutoDetector?.stop()
+ self._meetingAutoDetector = nil
if let meetingSessionCoordinator = self._meetingSessionCoordinator {
await meetingSessionCoordinator.shutdownForTermination()
self._meetingSessionCoordinator = nil
diff --git a/Sources/Fluid/Services/AudioDeviceService.swift b/Sources/Fluid/Services/AudioDeviceService.swift
index 5224e840..6147d665 100644
--- a/Sources/Fluid/Services/AudioDeviceService.swift
+++ b/Sources/Fluid/Services/AudioDeviceService.swift
@@ -14,6 +14,20 @@ import IOKit.pwr_mgt
// MARK: - Audio Device Manager
nonisolated enum AudioDevice {
+ enum LivenessDiagnosticsOwner: Sendable {
+ case audioHardwareObserver
+ case asrService
+
+ #if DEBUG
+ var traceOwner: AudioTopologyTraceOwner {
+ switch self {
+ case .audioHardwareObserver: .audioHardwareObserver
+ case .asrService: .asrDeviceList
+ }
+ }
+ #endif
+ }
+
struct Device: Identifiable, Hashable, Sendable {
static let externalMicrophoneDataSourceID: UInt32 = 0x656d6963 // 'emic'
@@ -175,13 +189,15 @@ nonisolated enum AudioDevice {
/// Refreshes the HAL liveness snapshot. Call only from an existing background
/// hardware-refresh path; UI and capture selection consume the cached value.
- static func listInputDevicesRefreshingLiveness() -> [Device] {
+ static func listInputDevicesRefreshingLiveness(
+ diagnosticsOwner: LivenessDiagnosticsOwner = .audioHardwareObserver
+ ) -> [Device] {
let devices = self.listInputDevices()
let liveness = Dictionary(
uniqueKeysWithValues: devices.map { device in
(
InputLivenessKey(id: device.id, uid: device.uid),
- self.queryInputDeviceLiveness(device.id)
+ self.queryInputDeviceLiveness(device.id, diagnosticsOwner: diagnosticsOwner)
)
}
)
@@ -202,8 +218,11 @@ nonisolated enum AudioDevice {
/// Refreshes one monitored device without blocking the listener's main queue.
/// Callers must invoke this from a background hardware-refresh path.
- static func refreshInputDeviceLiveness(deviceID: AudioObjectID) -> Bool {
- let isAlive = self.queryInputDeviceLiveness(deviceID)
+ static func refreshInputDeviceLiveness(
+ deviceID: AudioObjectID,
+ diagnosticsOwner: LivenessDiagnosticsOwner = .audioHardwareObserver
+ ) -> Bool {
+ let isAlive = self.queryInputDeviceLiveness(deviceID, diagnosticsOwner: diagnosticsOwner)
self.inputLivenessCache.update(deviceID: deviceID, isAlive: isAlive)
return isAlive
}
@@ -252,7 +271,10 @@ nonisolated enum AudioDevice {
/// Core Audio may continue enumerating an input after it has stopped being usable.
/// Fail open when HAL cannot answer so unusual and virtual devices still work.
- private static func queryInputDeviceLiveness(_ deviceID: AudioObjectID) -> Bool {
+ private static func queryInputDeviceLiveness(
+ _ deviceID: AudioObjectID,
+ diagnosticsOwner: LivenessDiagnosticsOwner
+ ) -> Bool {
var address = AudioObjectPropertyAddress(
mSelector: kAudioDevicePropertyDeviceIsAlive,
mScope: kAudioObjectPropertyScopeGlobal,
@@ -260,6 +282,18 @@ nonisolated enum AudioDevice {
)
var value: UInt32 = 1
var dataSize = UInt32(MemoryLayout<UInt32>.size)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(
+ .halQueryBegin,
+ owner: diagnosticsOwner.traceOwner,
+ objectID: deviceID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener
+ )
+ #endif
let status = AudioObjectGetPropertyData(
deviceID,
&address,
@@ -268,6 +302,19 @@ nonisolated enum AudioDevice {
&dataSize,
&value
)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(
+ .halQueryEnd,
+ owner: diagnosticsOwner.traceOwner,
+ objectID: deviceID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: status
+ )
+ #endif
return status != noErr || value != 0
}
@@ -437,6 +484,44 @@ extension Notification.Name {
// MARK: - Audio Hardware Observer
+/// Production policy for `AudioHardwareObserver`'s broad per-input `DeviceIsAlive` ledger only.
+/// An aggregate device is a Core Audio *composition* of other (physical and/or virtual) devices,
+/// and VPIO capture creates and tears down transient aggregates repeatedly across meeting/dictation
+/// start and stop. In a production-shaped controlled run, excluding only aggregate membership from
+/// this observer's broad liveness ledger passed normal dictation and three meeting cycles while the
+/// normal AVFoundation catalog and all other transports remained active. This is the narrowest
+/// empirically validated mitigation for the strongest isolated inducing condition; it is not proof
+/// of Apple's complete private HAL wait graph. Excluding aggregate-transport inputs from the broad
+/// ledger removes that duplicate observation during teardown; every other transport
+/// (physical, virtual, or unknown) keeps its current liveness monitoring unchanged. This is
+/// unconditional production behavior — no environment flag gates it — and must stay reachable
+/// from Release builds.
+nonisolated enum AggregateInputLivenessLedgerPolicy {
+ static func permitsBroadLedgerMembership(transportType: UInt32) -> Bool {
+ transportType != kAudioDeviceTransportTypeAggregate
+ }
+}
+
+#if DEBUG
+ /// Prior Phase-0 diagnostic switch, broader than the production aggregate exclusion above
+ /// (it also drops virtual and unknown transports). Kept for future isolation experiments;
+ /// it is not part of the shipped policy and stays opt-in behind an environment flag. It
+ /// deliberately classifies from the already captured off-main device snapshot, so the
+ /// experiment does not add a Core Audio query during reconciliation.
+ nonisolated enum InputLivenessLedgerIsolationPolicy {
+ static func permitsListenerForTransientIsolation(transportType: UInt32) -> Bool {
+ switch transportType {
+ case kAudioDeviceTransportTypeAggregate,
+ kAudioDeviceTransportTypeVirtual,
+ kAudioDeviceTransportTypeUnknown:
+ false
+ default:
+ true
+ }
+ }
+ }
+#endif
+
final class AudioHardwareObserver: ObservableObject {
/// Incremented every time CoreAudio reports a hardware/default-device change.
/// Using a simple `@Published` value avoids putting `AnyPublisher`/`SubscriptionView` generics into
@@ -523,30 +608,99 @@ final class AudioHardwareObserver: ObservableObject {
let sys = AudioObjectID(kAudioObjectSystemObject)
let devicesToken: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
+ #if DEBUG
+ AudioTopologyDiagnostics.record(
+ .callback,
+ owner: .audioHardwareObserver,
+ objectID: sys,
+ selector: kAudioHardwarePropertyDevices,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .mainDelivery,
+ generation: self?.inputAvailabilityRefreshGeneration ?? 0
+ )
+ #endif
self?.changeTick &+= 1
self?.refreshInputAvailabilityListeners()
}
let defaultInToken: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
+ #if DEBUG
+ AudioTopologyDiagnostics.record(
+ .callback,
+ owner: .audioHardwareObserver,
+ objectID: sys,
+ selector: kAudioHardwarePropertyDefaultInputDevice,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .mainDelivery,
+ generation: self?.inputAvailabilityRefreshGeneration ?? 0
+ )
+ #endif
self?.inputAvailabilityTick &+= 1
}
let defaultOutToken: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
+ #if DEBUG
+ AudioTopologyDiagnostics.record(
+ .callback,
+ owner: .audioHardwareObserver,
+ objectID: sys,
+ selector: kAudioHardwarePropertyDefaultOutputDevice,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .mainDelivery,
+ generation: self?.inputAvailabilityRefreshGeneration ?? 0
+ )
+ #endif
self?.changeTick &+= 1
}
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .audioHardwareObserver, objectID: sys, selector: addrDevices.mSelector, scope: addrDevices.mScope, element: addrDevices.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
let devicesStatus = AudioObjectAddPropertyListenerBlock(sys, &addrDevices, queue, devicesToken)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .audioHardwareObserver, objectID: sys, selector: addrDevices.mSelector, scope: addrDevices.mScope, element: addrDevices.mElement, queueRole: .mainControl, phase: .listener, status: devicesStatus)
+ AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .audioHardwareObserver, objectID: sys, selector: addrDefaultIn.mSelector, scope: addrDefaultIn.mScope, element: addrDefaultIn.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
let defaultInStatus = AudioObjectAddPropertyListenerBlock(sys, &addrDefaultIn, queue, defaultInToken)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .audioHardwareObserver, objectID: sys, selector: addrDefaultIn.mSelector, scope: addrDefaultIn.mScope, element: addrDefaultIn.mElement, queueRole: .mainControl, phase: .listener, status: defaultInStatus)
+ AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .audioHardwareObserver, objectID: sys, selector: addrDefaultOut.mSelector, scope: addrDefaultOut.mScope, element: addrDefaultOut.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
let defaultOutStatus = AudioObjectAddPropertyListenerBlock(sys, &addrDefaultOut, queue, defaultOutToken)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .audioHardwareObserver, objectID: sys, selector: addrDefaultOut.mSelector, scope: addrDefaultOut.mScope, element: addrDefaultOut.mElement, queueRole: .mainControl, phase: .listener, status: defaultOutStatus)
+ AudioTopologyDiagnostics.record(.readiness, owner: .audioHardwareObserver, queueRole: .mainControl, status: (devicesStatus == noErr && defaultInStatus == noErr && defaultOutStatus == noErr) ? noErr : -1)
+ #endif
guard devicesStatus == noErr, defaultInStatus == noErr, defaultOutStatus == noErr else {
// Best-effort cleanup for any partial installs.
if devicesStatus == noErr {
- _ = AudioObjectRemovePropertyListenerBlock(sys, &addrDevices, queue, devicesToken)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .audioHardwareObserver, objectID: sys, selector: addrDevices.mSelector, scope: addrDevices.mScope, element: addrDevices.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
+ let status = AudioObjectRemovePropertyListenerBlock(sys, &addrDevices, queue, devicesToken)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .audioHardwareObserver, objectID: sys, selector: addrDevices.mSelector, scope: addrDevices.mScope, element: addrDevices.mElement, queueRole: .mainControl, phase: .listener, status: status)
+ #endif
}
if defaultInStatus == noErr {
- _ = AudioObjectRemovePropertyListenerBlock(sys, &addrDefaultIn, queue, defaultInToken)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .audioHardwareObserver, objectID: sys, selector: addrDefaultIn.mSelector, scope: addrDefaultIn.mScope, element: addrDefaultIn.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
+ let status = AudioObjectRemovePropertyListenerBlock(sys, &addrDefaultIn, queue, defaultInToken)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .audioHardwareObserver, objectID: sys, selector: addrDefaultIn.mSelector, scope: addrDefaultIn.mScope, element: addrDefaultIn.mElement, queueRole: .mainControl, phase: .listener, status: status)
+ #endif
}
if defaultOutStatus == noErr {
- _ = AudioObjectRemovePropertyListenerBlock(sys, &addrDefaultOut, queue, defaultOutToken)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .audioHardwareObserver, objectID: sys, selector: addrDefaultOut.mSelector, scope: addrDefaultOut.mScope, element: addrDefaultOut.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
+ let status = AudioObjectRemovePropertyListenerBlock(sys, &addrDefaultOut, queue, defaultOutToken)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .audioHardwareObserver, objectID: sys, selector: addrDefaultOut.mSelector, scope: addrDefaultOut.mScope, element: addrDefaultOut.mElement, queueRole: .mainControl, phase: .listener, status: status)
+ #endif
}
self.devicesListenerToken = nil
self.defaultInputListenerToken = nil
@@ -585,13 +739,31 @@ final class AudioHardwareObserver: ObservableObject {
if self.installed {
if let token = self.devicesListenerToken {
- _ = AudioObjectRemovePropertyListenerBlock(sys, &addrDevices, queue, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .audioHardwareObserver, objectID: sys, selector: addrDevices.mSelector, scope: addrDevices.mScope, element: addrDevices.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
+ let status = AudioObjectRemovePropertyListenerBlock(sys, &addrDevices, queue, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .audioHardwareObserver, objectID: sys, selector: addrDevices.mSelector, scope: addrDevices.mScope, element: addrDevices.mElement, queueRole: .mainControl, phase: .listener, status: status)
+ #endif
}
if let token = self.defaultInputListenerToken {
- _ = AudioObjectRemovePropertyListenerBlock(sys, &addrDefaultIn, queue, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .audioHardwareObserver, objectID: sys, selector: addrDefaultIn.mSelector, scope: addrDefaultIn.mScope, element: addrDefaultIn.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
+ let status = AudioObjectRemovePropertyListenerBlock(sys, &addrDefaultIn, queue, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .audioHardwareObserver, objectID: sys, selector: addrDefaultIn.mSelector, scope: addrDefaultIn.mScope, element: addrDefaultIn.mElement, queueRole: .mainControl, phase: .listener, status: status)
+ #endif
}
if let token = self.defaultOutputListenerToken {
- _ = AudioObjectRemovePropertyListenerBlock(sys, &addrDefaultOut, queue, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .audioHardwareObserver, objectID: sys, selector: addrDefaultOut.mSelector, scope: addrDefaultOut.mScope, element: addrDefaultOut.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
+ let status = AudioObjectRemovePropertyListenerBlock(sys, &addrDefaultOut, queue, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .audioHardwareObserver, objectID: sys, selector: addrDefaultOut.mSelector, scope: addrDefaultOut.mScope, element: addrDefaultOut.mElement, queueRole: .mainControl, phase: .listener, status: status)
+ #endif
}
self.removeInputAvailabilityListeners()
}
@@ -608,7 +780,26 @@ final class AudioHardwareObserver: ObservableObject {
self.inputAvailabilityRefreshGeneration &+= 1
let generation = self.inputAvailabilityRefreshGeneration
DispatchQueue.global(qos: .utility).async { [weak self] in
+ #if DEBUG
+ AudioTopologyDiagnostics.record(
+ .enumerationBegin,
+ owner: .audioHardwareObserver,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ generation: generation
+ )
+ #endif
let devices = AudioDevice.listInputDevicesRefreshingLiveness()
+ #if DEBUG
+ AudioTopologyDiagnostics.record(
+ .enumerationEnd,
+ owner: .audioHardwareObserver,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: noErr,
+ generation: generation
+ )
+ #endif
DispatchQueue.main.async { [weak self] in
guard let self,
self.inputAvailabilityRefreshGeneration == generation
@@ -620,17 +811,122 @@ final class AudioHardwareObserver: ObservableObject {
private func replaceInputAvailabilityListeners(with devices: [AudioDevice.Device]) {
guard self.installed else { return }
- let currentIDs = Set(devices.map(\.id))
+ #if DEBUG
+ // Phase-0 isolation for the rebase-introduced all-input liveness ledger. The flag is
+ // deliberately scoped to this observer: default-device monitoring, ASR's existing
+ // selected-device listener, and dictation capture remain active.
+ if ProcessInfo.processInfo.environment["FLUIDVOICE_OMIT_INPUT_LIVENESS_LEDGER_ISOLATION"] == "1" {
+ AudioTopologyDiagnostics.record(
+ .isolationActive,
+ owner: .audioHardwareObserver,
+ queueRole: .mainControl,
+ phase: .listener,
+ generation: self.inputAvailabilityRefreshGeneration
+ )
+ self.removeInputAvailabilityListeners()
+ return
+ }
+ #endif
+ #if DEBUG
+ AudioTopologyDiagnostics.record(
+ .replaceBegin,
+ owner: .audioHardwareObserver,
+ queueRole: .mainControl,
+ phase: .listener,
+ generation: self.inputAvailabilityRefreshGeneration
+ )
+ for device in devices {
+ AudioTopologyDiagnostics.record(
+ .topologySnapshot,
+ owner: .audioHardwareObserver,
+ objectID: device.id,
+ queueRole: .mainControl,
+ phase: .listener,
+ transport: AudioTopologyDiagnostics.transportClassification(device.transportType),
+ generation: self.inputAvailabilityRefreshGeneration
+ )
+ }
+ #endif
+ // Production policy: never register this observer's broad per-input DeviceIsAlive
+ // ledger for aggregate-transport inputs. See AggregateInputLivenessLedgerPolicy for the
+ // evidence and scope. Unconditional — no environment flag required — and applies in Release too.
+ let productionScopedDevices = devices.filter {
+ let permitted = AggregateInputLivenessLedgerPolicy.permitsBroadLedgerMembership(
+ transportType: $0.transportType
+ )
+ #if DEBUG
+ if permitted == false {
+ AudioTopologyDiagnostics.record(
+ .policyExcluded,
+ owner: .audioHardwareObserver,
+ objectID: $0.id,
+ queueRole: .mainControl,
+ phase: .listener,
+ transport: AudioTopologyDiagnostics.transportClassification($0.transportType),
+ generation: self.inputAvailabilityRefreshGeneration
+ )
+ }
+ #endif
+ return permitted
+ }
+
+ #if DEBUG
+ // Opt-in diagnostic isolation on top of the production policy above, for future
+ // experiments only; see InputLivenessLedgerIsolationPolicy.
+ let excludesTransientInputs = ProcessInfo.processInfo.environment[
+ "FLUIDVOICE_EXCLUDE_TRANSIENT_INPUT_LIVENESS_ISOLATION"
+ ] == "1"
+ let listenerDevices = excludesTransientInputs
+ ? productionScopedDevices.filter {
+ let permitted = InputLivenessLedgerIsolationPolicy.permitsListenerForTransientIsolation(
+ transportType: $0.transportType
+ )
+ if permitted == false {
+ AudioTopologyDiagnostics.record(
+ .isolationActive,
+ owner: .audioHardwareObserver,
+ objectID: $0.id,
+ queueRole: .mainControl,
+ phase: .listener,
+ transport: AudioTopologyDiagnostics.transportClassification($0.transportType),
+ generation: self.inputAvailabilityRefreshGeneration
+ )
+ }
+ return permitted
+ }
+ : productionScopedDevices
+ #else
+ let listenerDevices = productionScopedDevices
+ #endif
+ let currentIDs = Set(listenerDevices.map(\.id))
for (deviceID, token) in self.inputAvailabilityListenerTokens where currentIDs.contains(deviceID) == false {
var address = Self.inputAvailabilityAddress
- _ = AudioObjectRemovePropertyListenerBlock(deviceID, &address, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .audioHardwareObserver, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener, generation: self.inputAvailabilityRefreshGeneration)
+ #endif
+ let status = AudioObjectRemovePropertyListenerBlock(deviceID, &address, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .audioHardwareObserver, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener, status: status, generation: self.inputAvailabilityRefreshGeneration)
+ #endif
self.inputAvailabilityListenerTokens.removeValue(forKey: deviceID)
}
- for device in devices where self.inputAvailabilityListenerTokens[device.id] == nil {
+ for device in listenerDevices where self.inputAvailabilityListenerTokens[device.id] == nil {
let deviceID = device.id
var address = Self.inputAvailabilityAddress
let token: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
+ #if DEBUG
+ AudioTopologyDiagnostics.record(
+ .callback,
+ owner: .audioHardwareObserver,
+ objectID: deviceID,
+ selector: kAudioDevicePropertyDeviceIsAlive,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .mainDelivery,
+ generation: self?.inputAvailabilityRefreshGeneration ?? 0
+ )
+ #endif
// Never query Core Audio synchronously from its property callback.
// Refresh the cached snapshot off-main before observers resolve priority.
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
@@ -646,22 +942,44 @@ final class AudioHardwareObserver: ObservableObject {
}
}
}
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .audioHardwareObserver, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener, transport: AudioTopologyDiagnostics.transportClassification(device.transportType), generation: self.inputAvailabilityRefreshGeneration)
+ #endif
let status = AudioObjectAddPropertyListenerBlock(
deviceID,
&address,
DispatchQueue.main,
token
)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .audioHardwareObserver, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener, transport: AudioTopologyDiagnostics.transportClassification(device.transportType), status: status, generation: self.inputAvailabilityRefreshGeneration)
+ #endif
if status == noErr {
self.inputAvailabilityListenerTokens[deviceID] = token
}
}
+ #if DEBUG
+ AudioTopologyDiagnostics.record(
+ .replaceEnd,
+ owner: .audioHardwareObserver,
+ queueRole: .mainControl,
+ phase: .listener,
+ status: noErr,
+ generation: self.inputAvailabilityRefreshGeneration
+ )
+ #endif
}
private func removeInputAvailabilityListeners() {
for (deviceID, token) in self.inputAvailabilityListenerTokens {
var address = Self.inputAvailabilityAddress
- _ = AudioObjectRemovePropertyListenerBlock(deviceID, &address, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .audioHardwareObserver, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener, generation: self.inputAvailabilityRefreshGeneration)
+ #endif
+ let status = AudioObjectRemovePropertyListenerBlock(deviceID, &address, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .audioHardwareObserver, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener, status: status, generation: self.inputAvailabilityRefreshGeneration)
+ #endif
}
self.inputAvailabilityListenerTokens.removeAll()
}
diff --git a/Sources/Fluid/Services/AudioTopologyDiagnostics.swift b/Sources/Fluid/Services/AudioTopologyDiagnostics.swift
new file mode 100644
index 00000000..8cbb9666
--- /dev/null
+++ b/Sources/Fluid/Services/AudioTopologyDiagnostics.swift
@@ -0,0 +1,610 @@
+#if DEBUG
+import CoreAudio
+#if SWIFT_PACKAGE
+import CoreAudioCaptureSupport
+#endif
+import CoreFoundation
+import Darwin
+import Foundation
+
+nonisolated enum AudioTopologyTraceEvent: UInt32, CaseIterable, Sendable {
+ case callback = 1
+ case enumerationBegin
+ case enumerationEnd
+ case replaceBegin
+ case replaceEnd
+ case listenerAddBegin
+ case listenerAddEnd
+ case listenerRemoveBegin
+ case listenerRemoveEnd
+ case halQueryBegin
+ case halQueryEnd
+ case vpioEnableBegin
+ case vpioEnableEnd
+ case audioUnitBindBegin
+ case audioUnitBindEnd
+ case enginePrepareBegin
+ case enginePrepareEnd
+ case engineStartBegin
+ case engineStartEnd
+ case engineStopBegin
+ case engineStopEnd
+ case avfDiscoveryBegin
+ case avfDiscoveryEnd
+ case avfDefaultBegin
+ case avfDefaultEnd
+ case avfAuthorizationBegin
+ case avfAuthorizationEnd
+ case recoveryScheduled
+ case recoveryBegin
+ case recoveryEnd
+ case recoveryCancel
+ case topologySnapshot
+ case topologyGeneration
+ case phaseBegin
+ case phaseEnd
+ case probeCycleBegin
+ case probeCycleEnd
+ case readiness
+ case isolationActive
+ case policyExcluded
+
+ var label: String {
+ String(describing: self)
+ }
+}
+
+nonisolated enum AudioTopologyTraceOwner: UInt32, CaseIterable, Sendable {
+ case unknown = 0
+ case diagnostics
+ case audioHardwareObserver
+ case asrDefaultInput
+ case asrDefaultOutput
+ case asrDeviceList
+ case asrMonitoredInput
+ case directCoreAudio
+ case meetingDetector
+ case meetingMicrophone
+ case meetingOutputRoute
+ case meetingCatalog
+ case meetingCoordinator
+ case phaseZeroProbe
+
+ var label: String {
+ String(describing: self)
+ }
+}
+
+nonisolated enum AudioTopologyTraceQueueRole: UInt32, CaseIterable, Sendable {
+ case unknown = 0
+ case mainDelivery
+ case dedicatedDelivery
+ case mainControl
+ case dedicatedControl
+ case actorControl
+ case callbackCurrent
+
+ var label: String {
+ String(describing: self)
+ }
+}
+
+nonisolated enum AudioTopologyTracePhase: UInt32, CaseIterable, Sendable {
+ case none = 0
+ case catalog
+ case vpio
+ case engine
+ case listener
+ case recovery
+ case handoff
+ case quiescing
+
+ var label: String {
+ String(describing: self)
+ }
+}
+
+nonisolated enum AudioTopologyTraceTransport: UInt32, CaseIterable, Sendable {
+ case unknown = 0
+ case builtIn
+ case bluetooth
+ case usb
+ case aggregate
+ case virtual
+ case other
+
+ var label: String {
+ String(describing: self)
+ }
+}
+
+nonisolated struct AudioTopologyDiagnosticsConfiguration: Equatable, Sendable {
+ static let enabledKey = "FLUIDVOICE_AUDIO_TOPOLOGY_DIAGNOSTICS"
+ static let outputDirectoryKey = "FLUIDVOICE_AUDIO_TOPOLOGY_TRACE_DIRECTORY"
+ static let stallThresholdKey = "FLUIDVOICE_AUDIO_TOPOLOGY_STALL_SECONDS"
+
+ var enabled: Bool
+ var outputDirectory: URL
+ var stallThresholdSeconds: Double
+
+ static func resolve(
+ environment: [String: String],
+ temporaryDirectory: URL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
+ ) -> Self {
+ let enabled = environment[Self.enabledKey] == "1"
+ let outputDirectory = environment[Self.outputDirectoryKey]
+ .flatMap { $0.isEmpty ? nil : URL(fileURLWithPath: $0, isDirectory: true) }
+ ?? temporaryDirectory
+ let requestedThreshold = environment[Self.stallThresholdKey].flatMap(Double.init)
+ return Self(
+ enabled: enabled,
+ outputDirectory: outputDirectory,
+ stallThresholdSeconds: min(max(requestedThreshold ?? 2.0, 0.5), 30.0)
+ )
+ }
+}
+
+nonisolated enum AudioTopologyStallClassification: String, Sendable {
+ case heartbeatHealthy
+ case heartbeatMissing
+ case heartbeatStalledPhaseOpen
+ case heartbeatStalledPhaseClosed
+
+ static func classify(
+ heartbeatAgeSeconds: Double?,
+ thresholdSeconds: Double,
+ topologyPhaseOpen: Bool
+ ) -> Self {
+ guard let heartbeatAgeSeconds else { return .heartbeatMissing }
+ guard heartbeatAgeSeconds >= thresholdSeconds else { return .heartbeatHealthy }
+ return topologyPhaseOpen ? .heartbeatStalledPhaseOpen : .heartbeatStalledPhaseClosed
+ }
+}
+
+/// DEBUG-only, opt-in diagnostics for the meeting-start Core Audio freeze.
+///
+/// The event capture path is implemented in C and remains numeric, preallocated,
+/// non-blocking, and HAL-free. This Swift owner only drains or persists snapshots
+/// away from Core Audio callbacks.
+final nonisolated class AudioTopologyDiagnostics: @unchecked Sendable {
+ static let shared = AudioTopologyDiagnostics()
+ static let noStatus = Int32.min
+ static let schemaKeys: Set<String> = [
+ "kind", "sequence", "continuous_time", "wall_unix_ns", "event", "owner",
+ "object_id", "selector", "scope", "element", "queue_role", "phase",
+ "transport", "status", "generation", "pid", "heartbeat_age_ms",
+ "stall_classification", "trace_path", "stall_path",
+ ]
+
+ private let drainQueue = DispatchQueue(
+ label: "com.fluidvoice.audio-topology-diagnostics.drain",
+ qos: .utility
+ )
+ private let watchdogQueue = DispatchQueue(
+ label: "com.fluidvoice.audio-topology-diagnostics.watchdog",
+ qos: .userInitiated
+ )
+ private let lifecycleLock = NSLock()
+ private var started = false
+ private var configuration: AudioTopologyDiagnosticsConfiguration?
+ private var traceFileDescriptor: Int32 = -1
+ private var traceURL: URL?
+ private var lastDrainedSequence: UInt64 = 0
+ private var drainTimer: DispatchSourceTimer?
+ private var watchdogTimer: DispatchSourceTimer?
+ private var runLoopObserver: CFRunLoopObserver?
+ private var lastPersistedStallHeartbeat: UInt64 = 0
+
+ private init() {}
+
+ static var isEnabled: Bool {
+ fv_audio_topology_trace_is_enabled()
+ }
+
+ /// Call once during launch, before installing any instrumented listener.
+ func startIfRequested(environment: [String: String] = ProcessInfo.processInfo.environment) {
+ let resolved = AudioTopologyDiagnosticsConfiguration.resolve(environment: environment)
+ guard resolved.enabled else { return }
+
+ self.lifecycleLock.lock()
+ guard self.started == false else {
+ self.lifecycleLock.unlock()
+ return
+ }
+ self.started = true
+ self.configuration = resolved
+ self.lifecycleLock.unlock()
+
+ do {
+ try FileManager.default.createDirectory(
+ at: resolved.outputDirectory,
+ withIntermediateDirectories: true
+ )
+ } catch {
+ self.markStartFailed()
+ return
+ }
+ let pid = ProcessInfo.processInfo.processIdentifier
+ let traceURL = resolved.outputDirectory
+ .appendingPathComponent("fluidvoice-audio-topology-\(pid).jsonl")
+ let descriptor = Darwin.open(
+ traceURL.path,
+ O_WRONLY | O_CREAT | O_APPEND,
+ S_IRUSR | S_IWUSR
+ )
+ guard descriptor >= 0 else {
+ self.markStartFailed()
+ return
+ }
+ self.traceFileDescriptor = descriptor
+ self.traceURL = traceURL
+
+ fv_audio_topology_trace_set_enabled(true)
+ fv_audio_topology_trace_main_heartbeat()
+ self.installRunLoopHeartbeat()
+ self.writeClockAnchor(sync: false)
+ self.startDrainTimer()
+ self.startWatchdog(thresholdSeconds: resolved.stallThresholdSeconds)
+ }
+
+ func stop() {
+ self.lifecycleLock.lock()
+ guard self.started else {
+ self.lifecycleLock.unlock()
+ return
+ }
+ self.started = false
+ self.lifecycleLock.unlock()
+
+ fv_audio_topology_trace_set_enabled(false)
+ self.drainTimer?.cancel()
+ self.watchdogTimer?.cancel()
+ self.drainTimer = nil
+ self.watchdogTimer = nil
+ if let observer = self.runLoopObserver {
+ CFRunLoopRemoveObserver(CFRunLoopGetMain(), observer, .commonModes)
+ self.runLoopObserver = nil
+ }
+ self.drainQueue.sync {
+ self.drainAvailableEvents(sync: true)
+ if self.traceFileDescriptor >= 0 {
+ _ = Darwin.close(self.traceFileDescriptor)
+ self.traceFileDescriptor = -1
+ }
+ }
+ }
+
+ @inline(__always)
+ static func record(
+ _ event: AudioTopologyTraceEvent,
+ owner: AudioTopologyTraceOwner,
+ objectID: AudioObjectID = kAudioObjectUnknown,
+ selector: AudioObjectPropertySelector = 0,
+ scope: AudioObjectPropertyScope = 0,
+ element: AudioObjectPropertyElement = 0,
+ queueRole: AudioTopologyTraceQueueRole = .unknown,
+ phase: AudioTopologyTracePhase = .none,
+ transport: AudioTopologyTraceTransport = .unknown,
+ status: Int32 = AudioTopologyDiagnostics.noStatus,
+ generation: UInt64 = 0
+ ) {
+ _ = fv_audio_topology_trace_record(
+ event.rawValue,
+ owner.rawValue,
+ objectID,
+ selector,
+ scope,
+ element,
+ queueRole.rawValue,
+ phase.rawValue,
+ transport.rawValue,
+ status,
+ generation
+ )
+ }
+
+ static func transportClassification(_ transportType: UInt32) -> AudioTopologyTraceTransport {
+ switch transportType {
+ case kAudioDeviceTransportTypeBuiltIn:
+ return .builtIn
+ case kAudioDeviceTransportTypeBluetooth, kAudioDeviceTransportTypeBluetoothLE:
+ return .bluetooth
+ case kAudioDeviceTransportTypeUSB:
+ return .usb
+ case kAudioDeviceTransportTypeAggregate:
+ return .aggregate
+ case kAudioDeviceTransportTypeVirtual:
+ return .virtual
+ default:
+ return .other
+ }
+ }
+
+ static func snapshot(after sequence: UInt64 = 0) -> ([FVAudioTopologyTraceEvent], UInt64) {
+ let capacity = Int(fv_audio_topology_trace_capacity())
+ var events = [FVAudioTopologyTraceEvent](
+ repeating: FVAudioTopologyTraceEvent(),
+ count: capacity
+ )
+ var latest: UInt64 = 0
+ let count = events.withUnsafeMutableBufferPointer { buffer in
+ fv_audio_topology_trace_snapshot(
+ sequence,
+ buffer.baseAddress,
+ UInt32(buffer.count),
+ &latest
+ )
+ }
+ return (Array(events.prefix(Int(count))), latest)
+ }
+
+ static func heartbeatAgeSeconds(now: UInt64 = mach_continuous_time()) -> Double? {
+ let heartbeat = fv_audio_topology_trace_last_main_heartbeat()
+ guard heartbeat > 0, now >= heartbeat else { return nil }
+ return Self.seconds(fromContinuousTicks: now - heartbeat)
+ }
+
+ private func installRunLoopHeartbeat() {
+ let observer = CFRunLoopObserverCreateWithHandler(
+ kCFAllocatorDefault,
+ CFRunLoopActivity.beforeWaiting.rawValue,
+ true,
+ 0
+ ) { _, _ in
+ fv_audio_topology_trace_main_heartbeat()
+ }
+ guard let observer else { return }
+ self.runLoopObserver = observer
+ CFRunLoopAddObserver(CFRunLoopGetMain(), observer, .commonModes)
+ }
+
+ private func startDrainTimer() {
+ let timer = DispatchSource.makeTimerSource(queue: self.drainQueue)
+ timer.schedule(deadline: .now() + 0.25, repeating: 0.25, leeway: .milliseconds(100))
+ timer.setEventHandler { [weak self] in
+ self?.drainAvailableEvents(sync: false)
+ }
+ self.drainTimer = timer
+ timer.resume()
+ }
+
+ private func startWatchdog(thresholdSeconds: Double) {
+ let timer = DispatchSource.makeTimerSource(queue: self.watchdogQueue)
+ timer.schedule(deadline: .now() + 0.5, repeating: 0.5, leeway: .milliseconds(50))
+ timer.setEventHandler { [weak self] in
+ self?.checkHeartbeat(thresholdSeconds: thresholdSeconds)
+ }
+ self.watchdogTimer = timer
+ timer.resume()
+ }
+
+ private func checkHeartbeat(thresholdSeconds: Double) {
+ let heartbeat = fv_audio_topology_trace_last_main_heartbeat()
+ guard heartbeat > 0,
+ let age = Self.heartbeatAgeSeconds(),
+ age >= thresholdSeconds,
+ heartbeat != self.lastPersistedStallHeartbeat
+ else { return }
+ let snapshot = Self.snapshot()
+ let topologyPhaseOpen = Self.hasOpenTopologyPhase(snapshot.0)
+ let classification = AudioTopologyStallClassification.classify(
+ heartbeatAgeSeconds: age,
+ thresholdSeconds: thresholdSeconds,
+ topologyPhaseOpen: topologyPhaseOpen
+ )
+ let persisted = self.persistStallSnapshot(
+ events: snapshot.0,
+ latestSequence: snapshot.1,
+ heartbeatAgeSeconds: age,
+ classification: classification
+ )
+ if persisted {
+ self.lastPersistedStallHeartbeat = heartbeat
+ }
+ }
+
+ private func drainAvailableEvents(sync: Bool) {
+ guard self.traceFileDescriptor >= 0 else { return }
+ let snapshot = Self.snapshot(after: self.lastDrainedSequence)
+ guard snapshot.1 > self.lastDrainedSequence else { return }
+ self.writeClockAnchor(sync: false)
+ for event in snapshot.0 {
+ Self.writeAll(
+ descriptor: self.traceFileDescriptor,
+ bytes: Self.jsonLine(for: event)
+ )
+ }
+ self.lastDrainedSequence = snapshot.1
+ if sync {
+ _ = Darwin.fsync(self.traceFileDescriptor)
+ }
+ }
+
+ private func writeClockAnchor(sync: Bool) {
+ guard self.traceFileDescriptor >= 0 else { return }
+ let line = Self.clockAnchorLine(
+ continuousTime: mach_continuous_time(),
+ wallNanoseconds: UInt64((Date().timeIntervalSince1970 * 1_000_000_000).rounded()),
+ pid: ProcessInfo.processInfo.processIdentifier
+ )
+ Self.writeAll(descriptor: self.traceFileDescriptor, bytes: Array(line.utf8))
+ if sync {
+ _ = Darwin.fsync(self.traceFileDescriptor)
+ }
+ }
+
+ @discardableResult
+ private func persistStallSnapshot(
+ events: [FVAudioTopologyTraceEvent],
+ latestSequence: UInt64,
+ heartbeatAgeSeconds: Double,
+ classification: AudioTopologyStallClassification
+ ) -> Bool {
+ guard let configuration else { return false }
+ let pid = ProcessInfo.processInfo.processIdentifier
+ let stallURL = configuration.outputDirectory.appendingPathComponent(
+ "fluidvoice-audio-topology-stall-\(pid)-\(latestSequence).jsonl"
+ )
+ let descriptor = Darwin.open(
+ stallURL.path,
+ O_WRONLY | O_CREAT | O_TRUNC,
+ S_IRUSR | S_IWUSR
+ )
+ guard descriptor >= 0 else { return false }
+ let anchor = Self.clockAnchorLine(
+ continuousTime: mach_continuous_time(),
+ wallNanoseconds: UInt64((Date().timeIntervalSince1970 * 1_000_000_000).rounded()),
+ pid: pid
+ )
+ let header = "{\"kind\":\"stall\",\"pid\":\(pid),\"sequence\":\(latestSequence)," +
+ "\"heartbeat_age_ms\":\(Int((heartbeatAgeSeconds * 1000).rounded()))," +
+ "\"stall_classification\":\"\(classification.rawValue)\"}\n"
+ guard Self.writeAll(descriptor: descriptor, bytes: Array(anchor.utf8)),
+ Self.writeAll(descriptor: descriptor, bytes: Array(header.utf8))
+ else {
+ _ = Darwin.close(descriptor)
+ return false
+ }
+ for event in events {
+ guard Self.writeAll(descriptor: descriptor, bytes: Self.jsonLine(for: event)) else {
+ _ = Darwin.close(descriptor)
+ return false
+ }
+ }
+ guard Darwin.fsync(descriptor) == 0 else {
+ _ = Darwin.close(descriptor)
+ return false
+ }
+ _ = Darwin.close(descriptor)
+
+ let markerURL = configuration.outputDirectory.appendingPathComponent(
+ "fluidvoice-audio-topology-\(pid).stall"
+ )
+ let markerDescriptor = Darwin.open(
+ markerURL.path,
+ O_WRONLY | O_CREAT | O_TRUNC,
+ S_IRUSR | S_IWUSR
+ )
+ guard markerDescriptor >= 0 else { return false }
+ let marker = "{\"kind\":\"stall_marker\",\"pid\":\(pid)," +
+ "\"sequence\":\(latestSequence),\"stall_path\":\"\(stallURL.path)\"," +
+ "\"trace_path\":\"\(self.traceURL?.path ?? "")\"}\n"
+ let markerWritten = Self.writeAll(descriptor: markerDescriptor, bytes: Array(marker.utf8))
+ let markerSynced = markerWritten && Darwin.fsync(markerDescriptor) == 0
+ _ = Darwin.close(markerDescriptor)
+ return markerSynced
+ }
+
+ static func hasOpenTopologyPhase(_ events: [FVAudioTopologyTraceEvent]) -> Bool {
+ struct Key: Hashable {
+ var category: UInt8
+ var owner: UInt32
+ var objectID: UInt32
+ var generation: UInt64
+ }
+ var openCounts: [Key: Int] = [:]
+ for event in events {
+ guard let kind = AudioTopologyTraceEvent(rawValue: event.event) else { continue }
+ guard let pair = Self.phasePair(for: kind) else { continue }
+ let key = Key(category: pair.category, owner: event.owner, objectID: event.objectID, generation: event.generation)
+ if pair.isBegin {
+ openCounts[key, default: 0] += 1
+ } else if let count = openCounts[key], count > 0 {
+ openCounts[key] = count - 1
+ }
+ }
+ return openCounts.values.contains { $0 > 0 }
+ }
+
+ private static func phasePair(for event: AudioTopologyTraceEvent) -> (category: UInt8, isBegin: Bool)? {
+ switch event {
+ case .enumerationBegin: (1, true)
+ case .enumerationEnd: (1, false)
+ case .replaceBegin: (2, true)
+ case .replaceEnd: (2, false)
+ case .listenerAddBegin: (3, true)
+ case .listenerAddEnd: (3, false)
+ case .listenerRemoveBegin: (4, true)
+ case .listenerRemoveEnd: (4, false)
+ case .halQueryBegin: (5, true)
+ case .halQueryEnd: (5, false)
+ case .vpioEnableBegin: (6, true)
+ case .vpioEnableEnd: (6, false)
+ case .audioUnitBindBegin: (7, true)
+ case .audioUnitBindEnd: (7, false)
+ case .enginePrepareBegin: (8, true)
+ case .enginePrepareEnd: (8, false)
+ case .engineStartBegin: (9, true)
+ case .engineStartEnd: (9, false)
+ case .engineStopBegin: (10, true)
+ case .engineStopEnd: (10, false)
+ case .avfDiscoveryBegin: (11, true)
+ case .avfDiscoveryEnd: (11, false)
+ case .avfDefaultBegin: (12, true)
+ case .avfDefaultEnd: (12, false)
+ case .avfAuthorizationBegin: (13, true)
+ case .avfAuthorizationEnd: (13, false)
+ case .recoveryBegin: (14, true)
+ case .recoveryEnd: (14, false)
+ case .phaseBegin: (15, true)
+ case .phaseEnd: (15, false)
+ case .probeCycleBegin: (16, true)
+ case .probeCycleEnd: (16, false)
+ default: nil
+ }
+ }
+
+ static func jsonLine(for event: FVAudioTopologyTraceEvent) -> [UInt8] {
+ let eventLabel = AudioTopologyTraceEvent(rawValue: event.event)?.label ?? "unknown"
+ let ownerLabel = AudioTopologyTraceOwner(rawValue: event.owner)?.label ?? "unknown"
+ let queueLabel = AudioTopologyTraceQueueRole(rawValue: event.queueRole)?.label ?? "unknown"
+ let phaseLabel = AudioTopologyTracePhase(rawValue: event.phase)?.label ?? "none"
+ let transportLabel = AudioTopologyTraceTransport(rawValue: event.transport)?.label ?? "unknown"
+ let line = "{\"kind\":\"event\",\"sequence\":\(event.sequence)," +
+ "\"continuous_time\":\(event.continuousTime),\"event\":\"\(eventLabel)\"," +
+ "\"owner\":\"\(ownerLabel)\",\"object_id\":\(event.objectID)," +
+ "\"selector\":\(event.selector),\"scope\":\(event.scope)," +
+ "\"element\":\(event.element),\"queue_role\":\"\(queueLabel)\"," +
+ "\"phase\":\"\(phaseLabel)\",\"transport\":\"\(transportLabel)\"," +
+ "\"status\":\(event.status),\"generation\":\(event.generation)}\n"
+ return Array(line.utf8)
+ }
+
+ static func clockAnchorLine(
+ continuousTime: UInt64,
+ wallNanoseconds: UInt64,
+ pid: Int32
+ ) -> String {
+ "{\"kind\":\"clock_anchor\",\"continuous_time\":\(continuousTime)," +
+ "\"wall_unix_ns\":\(wallNanoseconds),\"pid\":\(pid)}\n"
+ }
+
+ private func markStartFailed() {
+ self.lifecycleLock.lock()
+ self.started = false
+ self.configuration = nil
+ self.lifecycleLock.unlock()
+ }
+
+ @discardableResult
+ private static func writeAll(descriptor: Int32, bytes: [UInt8]) -> Bool {
+ bytes.withUnsafeBytes { buffer -> Bool in
+ guard var pointer = buffer.baseAddress else { return true }
+ var remaining = buffer.count
+ while remaining > 0 {
+ let written = Darwin.write(descriptor, pointer, remaining)
+ guard written > 0 else { return false }
+ remaining -= written
+ pointer = pointer.advanced(by: written)
+ }
+ return true
+ }
+ }
+
+ private static func seconds(fromContinuousTicks ticks: UInt64) -> Double {
+ var info = mach_timebase_info_data_t()
+ mach_timebase_info(&info)
+ return Double(ticks) * Double(info.numer) / Double(info.denom) / 1_000_000_000
+ }
+}
+#endif
diff --git a/Sources/Fluid/Services/DirectCoreAudioInput.swift b/Sources/Fluid/Services/DirectCoreAudioInput.swift
index afecc745..291fc4bb 100644
--- a/Sources/Fluid/Services/DirectCoreAudioInput.swift
+++ b/Sources/Fluid/Services/DirectCoreAudioInput.swift
@@ -1489,6 +1489,18 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
}
let block = Self.makeDevicePropertyListener(objectID: objectID) { [weak self, weak input] objectID in
+ #if DEBUG
+ AudioTopologyDiagnostics.record(
+ .callback,
+ owner: .directCoreAudio,
+ objectID: objectID,
+ selector: selector,
+ scope: scope,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .dedicatedDelivery,
+ generation: generation
+ )
+ #endif
let deviceIsAlive =
name == "device_is_alive"
? Self.readDeviceLiveness(objectID: objectID)
@@ -1512,12 +1524,18 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
hardwareIsKnownStopped: hardwareIsKnownStopped
)
}
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .directCoreAudio, objectID: objectID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, generation: generation)
+ #endif
let status = AudioObjectAddPropertyListenerBlock(
objectID,
&address,
self.listenerQueue,
block
)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .directCoreAudio, objectID: objectID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, status: status, generation: generation)
+ #endif
guard status == noErr else {
if policy != .optional {
throw Self.error(
@@ -1657,6 +1675,9 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
)
var isAlive: UInt32 = 0
var size = UInt32(MemoryLayout<UInt32>.size)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.halQueryBegin, owner: .directCoreAudio, objectID: objectID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedDelivery, phase: .listener)
+ #endif
let status = AudioObjectGetPropertyData(
objectID,
&address,
@@ -1665,6 +1686,9 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
&size,
&isAlive
)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.halQueryEnd, owner: .directCoreAudio, objectID: objectID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedDelivery, phase: .listener, status: status)
+ #endif
// An object removed from HAL is gone; other unreadable results are
// unknown and must not authorize replacement after failed teardown.
if status == kAudioHardwareBadDeviceError || status == kAudioHardwareBadObjectError { return false }
@@ -1728,12 +1752,18 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
) {
for registration in registrations {
var address = registration.address
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .directCoreAudio, objectID: registration.objectID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener)
+ #endif
let status = AudioObjectRemovePropertyListenerBlock(
registration.objectID,
&address,
queue,
registration.block
)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .directCoreAudio, objectID: registration.objectID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, status: status)
+ #endif
if status != noErr, status != kAudioHardwareBadObjectError {
Self.log(
"Direct capture listener removal failed object=\(registration.objectID) " +
diff --git a/Sources/Fluid/Services/Meeting/MeetingAppRegistry.swift b/Sources/Fluid/Services/Meeting/MeetingAppRegistry.swift
new file mode 100644
index 00000000..34dc858f
--- /dev/null
+++ b/Sources/Fluid/Services/Meeting/MeetingAppRegistry.swift
@@ -0,0 +1,154 @@
+import Foundation
+
+/// Detection tier for a registry app. Tier 1 (native) is default-on; Tier 2 (browser) is an
+/// opt-in sub-toggle because it reads the frontmost tab's URL.
+nonisolated enum MeetingDetectionTier: Sendable, Equatable {
+ case nativeTier1
+ case browserTier2
+}
+
+/// Static, data-driven table of the apps the auto-detector watches. Every ambiguity resolves to
+/// "not in the registry" — Slack, Discord, FaceTime and generic browsers-without-a-known-meeting-URL
+/// are deliberately absent (see Phase A plan: dropped from v1).
+nonisolated enum MeetingAppRegistry {
+ /// Bundle identifiers for native meeting apps (Tier 1). Includes legacy Teams alongside the
+ /// current "new Teams" bundle since both ship in the wild.
+ static let nativeBundleIdentifiers: Set<String> = [
+ "us.zoom.xos",
+ "com.microsoft.teams2",
+ "com.microsoft.teams",
+ "com.cisco.webexmeetingsapp",
+ "Cisco-Systems.Spark",
+ ]
+
+ /// Bundle identifiers for browsers eligible for Tier 2 URL reading. Google Meet's "app" is a
+ /// Chrome/Edge PWA, not a separate bundle — it is matched via `pwaBundlePrefixes` instead.
+ static let browserBundleIdentifiers: Set<String> = [
+ "com.google.Chrome",
+ "com.apple.Safari",
+ "company.thebrowser.Browser",
+ "com.microsoft.edgemac",
+ "com.brave.Browser",
+ ]
+
+ /// PWA windows report a per-app bundle ID with one of these prefixes. Firefox has no PWA
+ /// mechanism comparable to this and is excluded from the registry entirely (its AX tree must
+ /// be force-enabled by the user, so it fails closed anyway).
+ static let pwaBundlePrefixes: [String] = [
+ "com.google.Chrome.app.",
+ "com.microsoft.edgemac.app.",
+ ]
+
+ static func tier(forBundleIdentifier bundleIdentifier: String) -> MeetingDetectionTier? {
+ if self.nativeBundleIdentifiers.contains(bundleIdentifier) {
+ return .nativeTier1
+ }
+ if self.browserBundleIdentifiers.contains(bundleIdentifier) {
+ return .browserTier2
+ }
+ if self.pwaBundlePrefixes.contains(where: { bundleIdentifier.hasPrefix($0) }) {
+ return .browserTier2
+ }
+ return nil
+ }
+
+ static func isNativeMeetingApp(bundleIdentifier: String) -> Bool {
+ self.tier(forBundleIdentifier: bundleIdentifier) == .nativeTier1
+ }
+
+ static func isBrowserApp(bundleIdentifier: String) -> Bool {
+ self.tier(forBundleIdentifier: bundleIdentifier) == .browserTier2
+ }
+
+ static func audioProcessBundleIdentifiers(for bundleIdentifier: String) -> Set<String> {
+ self.audioProcessBundleIdentifiersByPrimaryBundleIdentifier[bundleIdentifier] ?? [bundleIdentifier]
+ }
+
+ private static let audioProcessBundleIdentifiersByPrimaryBundleIdentifier: [String: Set<String>] = [
+ "us.zoom.xos": ["us.zoom.xos", "us.zoom.caphost"],
+ "com.microsoft.teams2": ["com.microsoft.teams2"],
+ "com.microsoft.teams": ["com.microsoft.teams"],
+ "com.cisco.webexmeetingsapp": ["com.cisco.webexmeetingsapp"],
+ "Cisco-Systems.Spark": ["Cisco-Systems.Spark"],
+ ]
+
+ private static let zoomMeetingTitles: Set<String> = [
+ // en
+ "Zoom", "Zoom Meeting", "Zoom Webinar",
+ // es
+ "Reunión de Zoom", "Seminario web de Zoom",
+ // fr
+ "Réunion Zoom", "Webinaire Zoom",
+ // de
+ "Zoom-Meeting", "Zoom-Webinar",
+ // pt
+ "Reunião do Zoom", "Webinar do Zoom",
+ // ja
+ "Zoom ミーティング", "Zoom ウェビナー",
+ ]
+
+ private static let zoomNonMeetingWindowTitles: Set<String> = [
+ "", "Zoom Workplace", "Zoom Client Healthcheck",
+ ]
+
+ static func isZoomMeetingWindowTitle(_ title: String) -> Bool {
+ guard !self.zoomNonMeetingWindowTitles.contains(title) else { return false }
+ return self.zoomMeetingTitles.contains(title)
+ }
+}
+
+/// Pure hostname+path matching for Tier 2 in-call URLs. Homepage/landing/post-call URLs never
+/// match — a parked meeting tab must not, by itself, ever produce a prompt.
+nonisolated enum MeetingInCallURLMatcher {
+ static func isInCallURL(host: String, path: String) -> Bool {
+ let host = host.lowercased()
+ switch true {
+ case host == "meet.google.com":
+ return self.matchesGoogleMeetPath(path)
+ case host.hasSuffix(".zoom.us") || host == "zoom.us":
+ return self.matchesZoomPath(path)
+ case host == "teams.microsoft.com" || host == "teams.live.com":
+ return self.matchesTeamsPath(path)
+ case host == "whereby.com" || host == "www.whereby.com":
+ return self.matchesRoomPath(path, excluding: Self.wherebyReservedPaths)
+ case host == "meet.jit.si":
+ return self.matchesRoomPath(path, excluding: Self.jitsiReservedPaths)
+ default:
+ return false
+ }
+ }
+
+ /// `/xxx-yyyy-zzz` — a lowercase-letter room code, three groups separated by hyphens.
+ private static func matchesGoogleMeetPath(_ path: String) -> Bool {
+ let segment = path.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
+ let parts = segment.split(separator: "-")
+ guard parts.count == 3 else { return false }
+ let lengths = parts.map(\.count)
+ guard lengths == [3, 4, 3] else { return false }
+ return parts.allSatisfy { $0.allSatisfy(\.isLowercaseASCIILetter) }
+ }
+
+ private static func matchesZoomPath(_ path: String) -> Bool {
+ path.hasPrefix("/j/") || path.hasPrefix("/wc/")
+ }
+
+ private static func matchesTeamsPath(_ path: String) -> Bool {
+ let lowered = path.lowercased()
+ return lowered.contains("meetup-join") || lowered.contains("prejoin") || lowered.contains("pre-join")
+ }
+
+ private static let wherebyReservedPaths: Set<String> = ["", "login", "signup", "pricing", "help", "download", "about"]
+ private static let jitsiReservedPaths: Set<String> = ["", "login", "signup", "pricing", "help", "static"]
+
+ private static func matchesRoomPath(_ path: String, excluding reserved: Set<String>) -> Bool {
+ let segment = path.trimmingCharacters(in: CharacterSet(charactersIn: "/")).lowercased()
+ guard !segment.isEmpty, !segment.contains("/") else { return false }
+ return !reserved.contains(segment)
+ }
+}
+
+private extension Character {
+ var isLowercaseASCIILetter: Bool {
+ ("a"..."z").contains(self)
+ }
+}
diff --git a/Sources/Fluid/Services/Meeting/MeetingAutoDetectSignals.swift b/Sources/Fluid/Services/Meeting/MeetingAutoDetectSignals.swift
new file mode 100644
index 00000000..5c31b879
--- /dev/null
+++ b/Sources/Fluid/Services/Meeting/MeetingAutoDetectSignals.swift
@@ -0,0 +1,580 @@
+import AppKit
+import ApplicationServices
+import AVFoundation
+import CoreAudio
+import Foundation
+
+// MARK: - Protocols (unit-testable via fakes; no CoreAudio/AX/NSWorkspace in tests)
+
+@MainActor
+protocol MeetingClockProviding: AnyObject {
+ func now() -> Date
+}
+
+@MainActor
+final class SystemClock: MeetingClockProviding {
+ func now() -> Date { Date() }
+}
+
+nonisolated enum WorkspaceEventKind: Sendable, Equatable {
+ case launched
+ case terminated
+ case activated
+}
+
+nonisolated struct WorkspaceEvent: Sendable, Equatable {
+ var kind: WorkspaceEventKind
+ var bundleIdentifier: String
+ var processID: Int32
+}
+
+@MainActor
+protocol WorkspaceEventsProviding: AnyObject {
+ var onEvent: ((WorkspaceEvent) -> Void)? { get set }
+ /// `isRegistryApp` selects which already-running apps get backfilled as armed (never prompted)
+ /// candidates at startup.
+ func start(isRegistryApp: @escaping (String) -> Bool, onBackfill: @escaping ([WorkspaceEvent]) -> Void)
+ func stop()
+}
+
+nonisolated struct MicActivityEdge: Sendable, Equatable {
+ /// true = device went from silent to in-use (0→1); false = the reverse.
+ var isActive: Bool
+}
+
+@MainActor
+protocol MicActivitySignalProviding: AnyObject {
+ var onEdge: ((MicActivityEdge) -> Void)? { get set }
+ func start()
+ func stop()
+}
+
+@MainActor
+protocol AudioProcessActivityProviding: AnyObject {
+ func isAudioActive(forBundleIdentifiers bundleIdentifiers: Set<String>) -> Bool
+}
+
+nonisolated struct WindowSnapshot: Sendable, Equatable {
+ var processID: Int32
+ var windowID: UInt32
+ /// Never logged — window titles are PII (repo invariant).
+ var title: String?
+ var layer: Int
+}
+
+/// Readiness is deliberately separate from meeting identity. A busy recorder is not a setup
+/// problem and must remain silent; an idle, confirmed meeting may still safely offer setup.
+nonisolated enum DetectionPreflightState: Sendable, Equatable {
+ case ready
+ case busy
+ case needsSetup(DetectionSetupReason)
+}
+
+nonisolated enum DetectionSetupReason: String, Sendable, Equatable {
+ case screenRecording
+ case microphone
+ case noInputDevice
+ case storage
+}
+
+@MainActor
+protocol WindowSnapshotProviding: AnyObject {
+ /// `.optionAll` + `excludeDesktopElements`, NOT `.optionOnScreenOnly` — a minimized meeting
+ /// window must not fail confirmation. Only windows owned by `interestPIDs` are returned.
+ func snapshot(interestPIDs: Set<Int32>) -> [WindowSnapshot]
+ /// Optional AX enrichment for redacted CG titles. Implementations must bound the AX call.
+ func titles(processID: Int32) async -> [String]
+}
+
+nonisolated struct BrowserTabURL: Sendable, Equatable {
+ var host: String
+ var path: String
+}
+
+@MainActor
+protocol BrowserTabReading: AnyObject {
+ /// nil = unreadable or the circuit breaker tripped — callers must fail closed (no prompt).
+ func frontmostTabURL(bundleIdentifier: String, processID: Int32) async -> BrowserTabURL?
+}
+
+/// Our own recording/dictation/preview state, read without materializing the meeting coordinator.
+@MainActor
+protocol DetectionActivityGate: AnyObject {
+ var isIdle: Bool { get }
+ /// Re-checked immediately before showing the prompt and atomically before Start.
+ func preflightPasses() -> Bool
+ func preflightState() -> DetectionPreflightState
+}
+
+extension WindowSnapshotProviding {
+ func titles(processID: Int32) async -> [String] { [] }
+}
+
+extension DetectionActivityGate {
+ func preflightState() -> DetectionPreflightState {
+ guard self.isIdle else { return .busy }
+ return self.preflightPasses() ? .ready : .needsSetup(.screenRecording)
+ }
+}
+
+// MARK: - Live implementations
+
+@MainActor
+final class WorkspaceEventsMonitor: WorkspaceEventsProviding {
+ var onEvent: ((WorkspaceEvent) -> Void)?
+
+ private var observers: [NSObjectProtocol] = []
+
+ func start(isRegistryApp: @escaping (String) -> Bool, onBackfill: @escaping ([WorkspaceEvent]) -> Void) {
+ self.stop()
+ let center = NSWorkspace.shared.notificationCenter
+ let workspace = NSWorkspace.shared
+
+ self.observers = [
+ center.addObserver(forName: NSWorkspace.didLaunchApplicationNotification, object: nil, queue: .main) { [weak self] note in
+ self?.forward(.launched, note: note)
+ },
+ center.addObserver(forName: NSWorkspace.didTerminateApplicationNotification, object: nil, queue: .main) { [weak self] note in
+ self?.forward(.terminated, note: note)
+ },
+ center.addObserver(forName: NSWorkspace.didActivateApplicationNotification, object: nil, queue: .main) { [weak self] note in
+ self?.forward(.activated, note: note)
+ },
+ ]
+
+ let backfill: [WorkspaceEvent] = workspace.runningApplications.compactMap { app in
+ guard let bundleIdentifier = app.bundleIdentifier, isRegistryApp(bundleIdentifier) else { return nil }
+ return WorkspaceEvent(kind: .launched, bundleIdentifier: bundleIdentifier, processID: app.processIdentifier)
+ }
+ if !backfill.isEmpty { onBackfill(backfill) }
+ }
+
+ func stop() {
+ let center = NSWorkspace.shared.notificationCenter
+ for observer in self.observers { center.removeObserver(observer) }
+ self.observers = []
+ }
+
+ private func forward(_ kind: WorkspaceEventKind, note: Notification) {
+ guard let app = note.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication,
+ let bundleIdentifier = app.bundleIdentifier
+ else { return }
+ self.onEvent?(WorkspaceEvent(kind: kind, bundleIdentifier: bundleIdentifier, processID: app.processIdentifier))
+ }
+}
+
+/// Listens for `kAudioDevicePropertyDeviceIsRunningSomewhere` on every input device, re-enumerating
+/// on `kAudioHardwarePropertyDevices` changes. HAL delivers listener callbacks off-main; the
+/// `DispatchQueue.main.async` wrapper mirrors ASRService's device-listener trampoline
+/// (deadlock-avoidance precedent) rather than acting synchronously inside the HAL callback.
+@MainActor
+final class CoreAudioMicActivitySignal: MicActivitySignalProviding {
+ var onEdge: ((MicActivityEdge) -> Void)?
+
+ private var deviceListToken: AudioObjectPropertyListenerBlock?
+ private var perDeviceTokens: [AudioObjectID: AudioObjectPropertyListenerBlock] = [:]
+ private var lastKnownRunning: [AudioObjectID: Bool] = [:]
+ private var started = false
+
+ func start() {
+ guard !self.started else { return }
+ self.started = true
+ self.registerDeviceListListener()
+ self.resyncMonitoredDevices()
+ }
+
+ func stop() {
+ guard self.started else { return }
+ self.started = false
+ var devicesAddress = Self.devicesAddress
+ if let token = self.deviceListToken {
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .meetingDetector, objectID: AudioObjectID(kAudioObjectSystemObject), selector: devicesAddress.mSelector, scope: devicesAddress.mScope, element: devicesAddress.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
+ let status = AudioObjectRemovePropertyListenerBlock(AudioObjectID(kAudioObjectSystemObject), &devicesAddress, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .meetingDetector, objectID: AudioObjectID(kAudioObjectSystemObject), selector: devicesAddress.mSelector, scope: devicesAddress.mScope, element: devicesAddress.mElement, queueRole: .mainControl, phase: .listener, status: status)
+ #endif
+ }
+ self.deviceListToken = nil
+ for (deviceID, token) in self.perDeviceTokens {
+ var address = Self.runningSomewhereAddress
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .meetingDetector, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
+ let status = AudioObjectRemovePropertyListenerBlock(deviceID, &address, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .meetingDetector, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener, status: status)
+ #endif
+ }
+ self.perDeviceTokens = [:]
+ self.lastKnownRunning = [:]
+ }
+
+ private static var devicesAddress: AudioObjectPropertyAddress {
+ AudioObjectPropertyAddress(
+ mSelector: kAudioHardwarePropertyDevices,
+ mScope: kAudioObjectPropertyScopeGlobal,
+ mElement: kAudioObjectPropertyElementMain
+ )
+ }
+
+ private static var runningSomewhereAddress: AudioObjectPropertyAddress {
+ AudioObjectPropertyAddress(
+ mSelector: kAudioDevicePropertyDeviceIsRunningSomewhere,
+ mScope: kAudioObjectPropertyScopeGlobal,
+ mElement: kAudioObjectPropertyElementMain
+ )
+ }
+
+ private func registerDeviceListListener() {
+ var address = Self.devicesAddress
+ let token: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.callback, owner: .meetingDetector, objectID: AudioObjectID(kAudioObjectSystemObject), selector: kAudioHardwarePropertyDevices, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainDelivery)
+ #endif
+ DispatchQueue.main.async { self?.resyncMonitoredDevices() }
+ }
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .meetingDetector, objectID: AudioObjectID(kAudioObjectSystemObject), selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
+ let status = AudioObjectAddPropertyListenerBlock(AudioObjectID(kAudioObjectSystemObject), &address, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .meetingDetector, objectID: AudioObjectID(kAudioObjectSystemObject), selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener, status: status)
+ #endif
+ if status == noErr {
+ self.deviceListToken = token
+ }
+ }
+
+ private func resyncMonitoredDevices() {
+ let currentIDs = Set(AudioDevice.listInputDevices().map(\.id))
+ let previousIDs = Set(self.perDeviceTokens.keys)
+
+ for removedID in previousIDs.subtracting(currentIDs) {
+ var address = Self.runningSomewhereAddress
+ if let token = self.perDeviceTokens[removedID] {
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .meetingDetector, objectID: removedID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
+ let status = AudioObjectRemovePropertyListenerBlock(removedID, &address, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .meetingDetector, objectID: removedID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener, status: status)
+ #endif
+ }
+ self.perDeviceTokens[removedID] = nil
+ self.lastKnownRunning[removedID] = nil
+ }
+
+ for addedID in currentIDs.subtracting(previousIDs) {
+ self.lastKnownRunning[addedID] = self.queryIsRunningSomewhere(addedID)
+ var address = Self.runningSomewhereAddress
+ let token: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.callback, owner: .meetingDetector, objectID: addedID, selector: kAudioDevicePropertyDeviceIsRunningSomewhere, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainDelivery)
+ #endif
+ DispatchQueue.main.async { self?.handleRunningSomewhereChanged(deviceID: addedID) }
+ }
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .meetingDetector, objectID: addedID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
+ let status = AudioObjectAddPropertyListenerBlock(addedID, &address, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .meetingDetector, objectID: addedID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener, status: status)
+ #endif
+ if status == noErr {
+ self.perDeviceTokens[addedID] = token
+ }
+ }
+ }
+
+ private func handleRunningSomewhereChanged(deviceID: AudioObjectID) {
+ let isRunning = self.queryIsRunningSomewhere(deviceID)
+ let wasRunning = self.lastKnownRunning[deviceID] ?? false
+ self.lastKnownRunning[deviceID] = isRunning
+ guard isRunning != wasRunning else { return }
+ self.onEdge?(MicActivityEdge(isActive: isRunning))
+ }
+
+ private func queryIsRunningSomewhere(_ deviceID: AudioObjectID) -> Bool {
+ var address = Self.runningSomewhereAddress
+ var value: UInt32 = 0
+ var size = UInt32(MemoryLayout<UInt32>.size)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.halQueryBegin, owner: .meetingDetector, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
+ let status = AudioObjectGetPropertyData(deviceID, &address, 0, nil, &size, &value)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.halQueryEnd, owner: .meetingDetector, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener, status: status)
+ #endif
+ return status == noErr && value != 0
+ }
+}
+
+@MainActor
+final class CoreAudioProcessActivityProvider: AudioProcessActivityProviding {
+ func isAudioActive(forBundleIdentifiers bundleIdentifiers: Set<String>) -> Bool {
+ guard #available(macOS 14.4, *) else { return false }
+ return Self.processObjectIDs().contains { processID in
+ guard let bundleIdentifier = Self.bundleIdentifier(for: processID), bundleIdentifiers.contains(bundleIdentifier) else { return false }
+ return Self.isRunning(processID, selector: kAudioProcessPropertyIsRunningInput)
+ || Self.isRunning(processID, selector: kAudioProcessPropertyIsRunningOutput)
+ }
+ }
+
+ private static func processObjectIDs() -> [AudioObjectID] {
+ var address = AudioObjectPropertyAddress(
+ mSelector: kAudioHardwarePropertyProcessObjectList,
+ mScope: kAudioObjectPropertyScopeGlobal,
+ mElement: kAudioObjectPropertyElementMain
+ )
+ var size: UInt32 = 0
+ let systemObject = AudioObjectID(kAudioObjectSystemObject)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.halQueryBegin, owner: .meetingDetector, objectID: systemObject, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
+ let sizeStatus = AudioObjectGetPropertyDataSize(systemObject, &address, 0, nil, &size)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.halQueryEnd, owner: .meetingDetector, objectID: systemObject, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener, status: sizeStatus)
+ #endif
+ guard sizeStatus == noErr else { return [] }
+ var processIDs = Array(repeating: AudioObjectID(), count: Int(size) / MemoryLayout<AudioObjectID>.size)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.halQueryBegin, owner: .meetingDetector, objectID: systemObject, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
+ let dataStatus = AudioObjectGetPropertyData(systemObject, &address, 0, nil, &size, &processIDs)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.halQueryEnd, owner: .meetingDetector, objectID: systemObject, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener, status: dataStatus)
+ #endif
+ guard dataStatus == noErr else { return [] }
+ return processIDs
+ }
+
+ private static func bundleIdentifier(for processID: AudioObjectID) -> String? {
+ var address = AudioObjectPropertyAddress(
+ mSelector: kAudioProcessPropertyBundleID,
+ mScope: kAudioObjectPropertyScopeGlobal,
+ mElement: kAudioObjectPropertyElementMain
+ )
+ var value: CFString = "" as CFString
+ var size = UInt32(MemoryLayout<CFString>.size)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.halQueryBegin, owner: .meetingDetector, objectID: processID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
+ let status = AudioObjectGetPropertyData(processID, &address, 0, nil, &size, &value)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.halQueryEnd, owner: .meetingDetector, objectID: processID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener, status: status)
+ #endif
+ guard status == noErr else { return nil }
+ return value as String
+ }
+
+ private static func isRunning(_ processID: AudioObjectID, selector: AudioObjectPropertySelector) -> Bool {
+ var address = AudioObjectPropertyAddress(
+ mSelector: selector,
+ mScope: kAudioObjectPropertyScopeGlobal,
+ mElement: kAudioObjectPropertyElementMain
+ )
+ var value: UInt32 = 0
+ var size = UInt32(MemoryLayout<UInt32>.size)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.halQueryBegin, owner: .meetingDetector, objectID: processID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener)
+ #endif
+ let status = AudioObjectGetPropertyData(processID, &address, 0, nil, &size, &value)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.halQueryEnd, owner: .meetingDetector, objectID: processID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener, status: status)
+ #endif
+ return status == noErr && value != 0
+ }
+}
+
+@MainActor
+final class CGWindowSnapshotProvider: WindowSnapshotProviding {
+ nonisolated private static let axTimeout: Float = 0.25
+ nonisolated private static let maxAXWindows = 8
+ private let axQueue = DispatchQueue(label: "com.fluidvoice.meeting.autodetect.ax-title", qos: .utility)
+
+ func snapshot(interestPIDs: Set<Int32>) -> [WindowSnapshot] {
+ let options: CGWindowListOption = [.optionAll, .excludeDesktopElements]
+ guard let list = CGWindowListCopyWindowInfo(options, kCGNullWindowID) as? [[String: Any]] else { return [] }
+ return list.compactMap { info in
+ guard let ownerPID = info[kCGWindowOwnerPID as String] as? Int32,
+ interestPIDs.contains(ownerPID),
+ let windowNumber = info[kCGWindowNumber as String] as? UInt32,
+ let layer = info[kCGWindowLayer as String] as? Int
+ else { return nil }
+ let title = info[kCGWindowName as String] as? String
+ return WindowSnapshot(processID: ownerPID, windowID: windowNumber, title: title, layer: layer)
+ }
+ }
+
+ func titles(processID: Int32) async -> [String] {
+ await withCheckedContinuation { continuation in
+ self.axQueue.async {
+ let app = AXUIElementCreateApplication(processID)
+ _ = AXUIElementSetMessagingTimeout(app, Self.axTimeout)
+ var value: CFTypeRef?
+ guard AXUIElementCopyAttributeValue(app, kAXWindowsAttribute as CFString, &value) == .success,
+ let windows = value as? [AXUIElement]
+ else { continuation.resume(returning: []); return }
+ var titles: [String] = []
+ for window in windows.prefix(Self.maxAXWindows) {
+ var titleValue: CFTypeRef?
+ if AXUIElementCopyAttributeValue(window, kAXTitleAttribute as CFString, &titleValue) == .success,
+ let title = titleValue as? String {
+ titles.append(title)
+ }
+ }
+ continuation.resume(returning: titles)
+ }
+ }
+ }
+}
+
+/// Reads the frontmost tab/window URL via Accessibility. All AX calls run on a dedicated serial
+/// queue with a short messaging timeout so a frozen browser cannot stall detection; a 2-timeout
+/// circuit breaker disables further scanning of that bundle for the session.
+@MainActor
+final class AXBrowserTabReader: BrowserTabReading {
+ private static let messagingTimeoutSeconds: Float = 0.3
+ private static let maxDepth = 4
+ private static let maxChildrenPerLevel = 24
+ private static let circuitBreakerThreshold = 2
+
+ private let queue = DispatchQueue(label: "com.fluidvoice.meeting.autodetect.ax", qos: .utility)
+ private var timeoutCounts: [String: Int] = [:]
+ private var trippedBundleIdentifiers: Set<String> = []
+
+ func frontmostTabURL(bundleIdentifier: String, processID: Int32) async -> BrowserTabURL? {
+ guard !self.trippedBundleIdentifiers.contains(bundleIdentifier) else { return nil }
+
+ let outcome = await withCheckedContinuation { (continuation: CheckedContinuation<ReadOutcome, Never>) in
+ self.queue.async {
+ continuation.resume(returning: Self.readFrontmostTabURL(processID: processID))
+ }
+ }
+
+ switch outcome {
+ case let .found(url):
+ self.timeoutCounts[bundleIdentifier] = 0
+ return url
+ case .notFound:
+ return nil
+ case .timedOut:
+ let count = (self.timeoutCounts[bundleIdentifier] ?? 0) + 1
+ self.timeoutCounts[bundleIdentifier] = count
+ if count >= Self.circuitBreakerThreshold {
+ self.trippedBundleIdentifiers.insert(bundleIdentifier)
+ }
+ return nil
+ }
+ }
+
+ private enum ReadOutcome {
+ case found(BrowserTabURL)
+ case notFound
+ case timedOut
+ }
+
+ /// Off-main: all work here is plain AX API calls bounded by the messaging timeout below.
+ nonisolated private static func readFrontmostTabURL(processID: Int32) -> ReadOutcome {
+ let appElement = AXUIElementCreateApplication(processID)
+ _ = AXUIElementSetMessagingTimeout(appElement, Self.messagingTimeoutSeconds)
+
+ var windowValue: CFTypeRef?
+ let windowStatus = AXUIElementCopyAttributeValue(appElement, kAXFocusedWindowAttribute as CFString, &windowValue)
+ guard windowStatus != .cannotComplete else { return .timedOut }
+ guard windowStatus == .success, let window = windowValue else { return .notFound }
+ // swiftlint:disable:next force_cast
+ let windowElement = window as! AXUIElement
+
+ if let urlString = self.stringAttribute(windowElement, attribute: "AXDocument"), let url = self.parse(urlString) {
+ return .found(url)
+ }
+
+ var timedOut = false
+ if let found = self.breadthFirstFindWebAreaURL(root: windowElement, depth: 0, timedOut: &timedOut) {
+ return .found(found)
+ }
+ return timedOut ? .timedOut : .notFound
+ }
+
+ nonisolated private static func breadthFirstFindWebAreaURL(root: AXUIElement, depth: Int, timedOut: inout Bool) -> BrowserTabURL? {
+ guard depth < Self.maxDepth else { return nil }
+ var childrenValue: CFTypeRef?
+ let status = AXUIElementCopyAttributeValue(root, kAXChildrenAttribute as CFString, &childrenValue)
+ if status == .cannotComplete { timedOut = true; return nil }
+ guard status == .success, let children = childrenValue as? [AXUIElement] else { return nil }
+
+ for child in children.prefix(Self.maxChildrenPerLevel) {
+ if let role = self.stringAttribute(child, attribute: kAXRoleAttribute as String), role == "AXWebArea",
+ let urlString = self.stringAttribute(child, attribute: "AXURL"),
+ let url = self.parse(urlString)
+ {
+ return url
+ }
+ }
+ for child in children.prefix(Self.maxChildrenPerLevel) {
+ if let found = self.breadthFirstFindWebAreaURL(root: child, depth: depth + 1, timedOut: &timedOut) {
+ return found
+ }
+ }
+ return nil
+ }
+
+ nonisolated private static func stringAttribute(_ element: AXUIElement, attribute: String) -> String? {
+ var value: CFTypeRef?
+ let status = AXUIElementCopyAttributeValue(element, attribute as CFString, &value)
+ guard status == .success else { return nil }
+ if let string = value as? String { return string }
+ if let url = value as? URL { return url.absoluteString }
+ return nil
+ }
+
+ nonisolated private static func parse(_ urlString: String) -> BrowserTabURL? {
+ guard let components = URLComponents(string: urlString), let host = components.host else { return nil }
+ return BrowserTabURL(host: host, path: components.path)
+ }
+}
+
+/// Reads recording/dictation/preview state without materializing the meeting coordinator (which
+/// is a lazy getter — forcing it here would defeat the point of a standalone detector).
+@MainActor
+final class LiveDetectionActivityGate: DetectionActivityGate {
+ var isIdle: Bool {
+ if AppServices.shared.isMeetingSessionCoordinatorMaterialized {
+ guard !AppServices.shared.hasActiveMeetingSessionActivity else { return false }
+ }
+ return AppServices.shared.activeExclusiveActivityIfASRMaterialized == nil
+ }
+
+ func preflightPasses() -> Bool {
+ if case .ready = self.preflightState() { return true }
+ return false
+ }
+
+ func preflightState() -> DetectionPreflightState {
+ guard self.isIdle else { return .busy }
+ guard CGPreflightScreenCaptureAccess() else { return .needsSetup(.screenRecording) }
+ guard AVCaptureDeviceAuthorization.isMicrophoneAuthorized() else { return .needsSetup(.microphone) }
+ guard !AudioDevice.listInputDevices().isEmpty else { return .needsSetup(.noInputDevice) }
+ guard MeetingStorageReadiness.hasSufficientFreeSpace() else { return .needsSetup(.storage) }
+ return .ready
+ }
+}
+
+nonisolated enum AVCaptureDeviceAuthorization {
+ static func isMicrophoneAuthorized() -> Bool {
+ AVCaptureDevice.authorizationStatus(for: .audio) == .authorized
+ }
+}
+
+nonisolated enum MeetingStorageReadiness {
+ static func hasSufficientFreeSpace() -> Bool {
+ guard let applicationSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first,
+ let capacity = try? applicationSupport.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])
+ .volumeAvailableCapacityForImportantUsage
+ else { return false }
+ return capacity >= 512 * 1024 * 1024
+ }
+}
diff --git a/Sources/Fluid/Services/Meeting/MeetingAutoDetector.swift b/Sources/Fluid/Services/Meeting/MeetingAutoDetector.swift
new file mode 100644
index 00000000..d8c12a2c
--- /dev/null
+++ b/Sources/Fluid/Services/Meeting/MeetingAutoDetector.swift
@@ -0,0 +1,647 @@
+import AppKit
+import Foundation
+
+/// Standalone meeting-detection state machine. Zero dependency on `MeetingSessionCoordinator` —
+/// it reads activity state through `DetectionActivityGate` and never materializes the lazy
+/// coordinator. Prompt-only: it never starts or stops a recording itself.
+///
+/// Every ambiguity resolves to no prompt: a false negative here is free, a false positive is not.
+@MainActor
+final class MeetingAutoDetector {
+ // MARK: Tunables (Phase A plan v2)
+
+ static let coincidenceWindowSeconds: TimeInterval = 30
+ static let confirmDeadlineSeconds: TimeInterval = 30
+ static let frontmostLeadSeconds: TimeInterval = 15
+ static let windowLossGraceSeconds: TimeInterval = 5
+ static let micReleaseEpisodeEndSeconds: TimeInterval = 60
+ static let dismissalSuppressionSeconds: TimeInterval = 30 * 60
+ static let rollingDismissalWindowSeconds: TimeInterval = 14 * 24 * 3600
+ static let dismissalCountThreshold = 3
+
+ struct PromptRequest: Equatable {
+ var episodeID: UUID
+ var bundleIdentifier: String
+ var pid: Int32
+ var tier: MeetingDetectionTier
+ var cta: PromptCTA = .record
+ }
+
+ enum PromptCTA: String, Equatable, Sendable { case record, setup }
+
+ enum Health: String, Equatable, Sendable {
+ case ready
+ case zoomWindowTitleUnreadable
+ }
+
+ struct ResolvedTarget: Equatable {
+ var bundleIdentifier: String
+ var pid: Int32
+ /// Set only for Tier 1 native evidence — the window auto-detection actually found.
+ var windowID: UInt32?
+ }
+
+ var onPromptRequested: ((PromptRequest) -> Void)?
+ var onStillRecordingNudge: (() -> Void)?
+ var onSuggestDisablingAutoDetect: (() -> Void)?
+ var onEpisodeInvalidated: ((UUID) -> Void)?
+ var onHealthChanged: ((Health) -> Void)?
+
+ private struct CandidateRecord {
+ var pid: Int32
+ var bundleIdentifier: String
+ var tier: MeetingDetectionTier
+ var lastFrontmostAt: Date?
+ var audioEvidenceAt: Date?
+ var audioEvidenceSource: AudioEvidenceSource?
+ var processAudioWasActive = false
+ var processAudioInactiveAt: Date?
+ var windowEvidenceAt: Date?
+ var windowEvidenceKey: String?
+ var windowEvidenceWindowID: UInt32?
+ var hasLiveWindow = false
+ var windowLostAt: Date?
+ }
+
+ private enum AudioEvidenceSource: Equatable {
+ case device
+ case process
+ }
+
+ private struct Episode {
+ var id: UUID
+ var pid: Int32
+ var bundleIdentifier: String
+ var tier: MeetingDetectionTier
+ var key: String
+ var windowID: UInt32?
+ var confirmedAt: Date
+ var consumed = false
+ var stillRecordingNudgeShown = false
+ var duplicateEpisodeRejectionLogged = false
+ }
+
+ private let workspaceEvents: any WorkspaceEventsProviding
+ private let micActivity: any MicActivitySignalProviding
+ private let audioProcessActivity: any AudioProcessActivityProviding
+ private let windowSnapshotProvider: any WindowSnapshotProviding
+ private let browserTabReader: any BrowserTabReading
+ private let activityGate: any DetectionActivityGate
+ private let clock: any MeetingClockProviding
+ private let isNativeDetectionEnabled: () -> Bool
+ private let isBrowserDetectionEnabled: () -> Bool
+
+ private var records: [Int32: CandidateRecord] = [:]
+ private var lastMicReleaseAt: Date?
+ private var episodesByKey: [String: Episode] = [:]
+ private var activeConsumedEpisodeKey: String?
+ private var dismissedBundleUntil: [String: Date] = [:]
+ private var dismissalTimestamps: [Date] = []
+ private var pollTask: Task<Void, Never>?
+ private var lastBrowserPollAt: [Int32: Date] = [:]
+ private var titleEnrichmentGeneration: [Int32: UInt64] = [:]
+ private var titleEnrichmentInFlight: Set<Int32> = []
+ private var lastHealth: Health?
+
+ init(
+ workspaceEvents: any WorkspaceEventsProviding,
+ micActivity: any MicActivitySignalProviding,
+ audioProcessActivity: any AudioProcessActivityProviding,
+ windowSnapshotProvider: any WindowSnapshotProviding,
+ browserTabReader: any BrowserTabReading,
+ activityGate: any DetectionActivityGate,
+ clock: any MeetingClockProviding,
+ isNativeDetectionEnabled: @escaping () -> Bool,
+ isBrowserDetectionEnabled: @escaping () -> Bool
+ ) {
+ self.workspaceEvents = workspaceEvents
+ self.micActivity = micActivity
+ self.audioProcessActivity = audioProcessActivity
+ self.windowSnapshotProvider = windowSnapshotProvider
+ self.browserTabReader = browserTabReader
+ self.activityGate = activityGate
+ self.clock = clock
+ self.isNativeDetectionEnabled = isNativeDetectionEnabled
+ self.isBrowserDetectionEnabled = isBrowserDetectionEnabled
+ }
+
+ // MARK: Lifecycle
+
+ func start() {
+ guard self.pollTask == nil else { return }
+ self.workspaceEvents.onEvent = { [weak self] event in self?.handleWorkspaceEvent(event, at: self?.clock.now() ?? Date()) }
+ self.workspaceEvents.start(isRegistryApp: { MeetingAppRegistry.tier(forBundleIdentifier: $0) != nil }) { [weak self] backfill in
+ self?.handleBackfill(backfill)
+ }
+ self.micActivity.onEdge = { [weak self] edge in self?.handleMicEdge(edge, at: self?.clock.now() ?? Date()) }
+ self.micActivity.start()
+ self.installTransientDisarmObservers()
+
+ self.pollTask = Task { [weak self] in
+ while !Task.isCancelled {
+ try? await Task.sleep(nanoseconds: 2_000_000_000)
+ guard let self else { return }
+ await self.pollTick()
+ }
+ }
+ }
+
+ func stop() {
+ self.pollTask?.cancel()
+ self.pollTask = nil
+ self.workspaceEvents.stop()
+ self.micActivity.stop()
+ self.titleEnrichmentInFlight.removeAll()
+ self.titleEnrichmentGeneration.removeAll()
+ self.removeTransientDisarmObservers()
+ }
+
+ private func pollTick() async {
+ let now = self.clock.now()
+ if self.isNativeDetectionEnabled() {
+ self.pollAudioProcessActivity(at: now)
+ }
+ if self.shouldCollectEvidence(at: now) {
+ if self.isNativeDetectionEnabled() {
+ let nativePIDs = Set(self.records.filter { $0.value.tier == .nativeTier1 }.keys)
+ if !nativePIDs.isEmpty {
+ self.handleWindowSnapshot(self.windowSnapshotProvider.snapshot(interestPIDs: nativePIDs), at: now)
+ }
+ }
+ if self.isBrowserDetectionEnabled() {
+ await self.pollBrowserTabsIfDue(at: now)
+ }
+ }
+ self.tick(at: self.clock.now())
+ }
+
+ private func shouldCollectEvidence(at now: Date) -> Bool {
+ if !self.episodesByKey.isEmpty { return true }
+ return self.records.values.contains { record in
+ record.hasLiveWindow || record.windowLostAt != nil
+ || record.audioEvidenceAt.map { now.timeIntervalSince($0) <= Self.confirmDeadlineSeconds } == true
+ }
+ }
+
+ private func pollBrowserTabsIfDue(at now: Date) async {
+ for (pid, record) in self.records where record.tier == .browserTier2 {
+ let lastPoll = self.lastBrowserPollAt[pid]
+ guard lastPoll == nil || now.timeIntervalSince(lastPoll!) >= 2 else { continue }
+ self.lastBrowserPollAt[pid] = now
+ let url = await self.browserTabReader.frontmostTabURL(bundleIdentifier: record.bundleIdentifier, processID: pid)
+ self.handleBrowserTabURL(url, pid: pid, bundleIdentifier: record.bundleIdentifier, at: self.clock.now())
+ }
+ }
+
+ // MARK: Workspace events
+
+ func handleWorkspaceEvent(_ event: WorkspaceEvent, at now: Date) {
+ guard let tier = MeetingAppRegistry.tier(forBundleIdentifier: event.bundleIdentifier) else { return }
+ guard tier == .nativeTier1 ? self.isNativeDetectionEnabled() : self.isBrowserDetectionEnabled() else { return }
+
+ switch event.kind {
+ case .launched:
+ self.armIfNeeded(pid: event.processID, bundleIdentifier: event.bundleIdentifier, tier: tier)
+ case .activated:
+ self.armIfNeeded(pid: event.processID, bundleIdentifier: event.bundleIdentifier, tier: tier)
+ self.records[event.processID]?.lastFrontmostAt = now
+ DebugLogger.shared.log("app-activated bundle=\(event.bundleIdentifier)", source: "MeetingAutoDetector")
+ case .terminated:
+ self.records[event.processID] = nil
+ self.lastBrowserPollAt[event.processID] = nil
+ self.titleEnrichmentInFlight.remove(event.processID)
+ self.titleEnrichmentGeneration[event.processID] = nil
+ }
+ }
+
+ /// Backfill only arms known-running apps; it never seeds mic/frontmost timestamps, so an
+ /// already-in-progress meeting can never be retroactively confirmed from this alone.
+ func handleBackfill(_ events: [WorkspaceEvent]) {
+ for event in events {
+ guard let tier = MeetingAppRegistry.tier(forBundleIdentifier: event.bundleIdentifier) else { continue }
+ self.armIfNeeded(pid: event.processID, bundleIdentifier: event.bundleIdentifier, tier: tier)
+ }
+ }
+
+ private func armIfNeeded(pid: Int32, bundleIdentifier: String, tier: MeetingDetectionTier) {
+ guard self.records[pid] == nil else { return }
+ self.records[pid] = CandidateRecord(pid: pid, bundleIdentifier: bundleIdentifier, tier: tier)
+ DebugLogger.shared.log("record-armed bundle=\(bundleIdentifier)", source: "MeetingAutoDetector")
+ }
+
+ // MARK: Mic activity
+
+ func handleMicEdge(_ edge: MicActivityEdge, at now: Date) {
+ guard edge.isActive else {
+ self.lastMicReleaseAt = now
+ for pid in self.records.keys {
+ if self.records[pid]?.audioEvidenceSource == .device {
+ self.records[pid]?.audioEvidenceAt = nil
+ self.records[pid]?.audioEvidenceSource = nil
+ if let bundleIdentifier = self.records[pid]?.bundleIdentifier {
+ DebugLogger.shared.log("audio-evidence-end path=device bundle=\(bundleIdentifier)", source: "MeetingAutoDetector")
+ }
+ }
+ }
+ return
+ }
+ self.lastMicReleaseAt = nil
+ for pid in self.records.keys {
+ guard let record = self.records[pid], self.isFrontmostNearEdge(record, edge: now) else { continue }
+ self.records[pid]?.audioEvidenceAt = now
+ self.records[pid]?.audioEvidenceSource = .device
+ DebugLogger.shared.log("audio-evidence-begin path=device bundle=\(record.bundleIdentifier)", source: "MeetingAutoDetector")
+ self.attemptConfirm(pid: pid, at: now)
+ }
+ }
+
+ func pollAudioProcessActivity(at now: Date) {
+ for (pid, record) in self.records where record.tier == .nativeTier1 {
+ let isActive = self.audioProcessActivity.isAudioActive(forBundleIdentifiers: MeetingAppRegistry.audioProcessBundleIdentifiers(for: record.bundleIdentifier))
+ self.handleAudioProcessActivity(isActive, pid: pid, at: now)
+ }
+ }
+
+ func handleAudioProcessActivity(_ isActive: Bool, pid: Int32, at now: Date) {
+ guard var record = self.records[pid], record.tier == .nativeTier1 else { return }
+ guard isActive != record.processAudioWasActive else { return }
+ record.processAudioWasActive = isActive
+ if isActive {
+ record.processAudioInactiveAt = nil
+ record.audioEvidenceAt = now
+ record.audioEvidenceSource = .process
+ self.records[pid] = record
+ DebugLogger.shared.log("audio-evidence-begin path=process bundle=\(record.bundleIdentifier)", source: "MeetingAutoDetector")
+ self.attemptConfirm(pid: pid, at: now)
+ } else {
+ record.processAudioInactiveAt = now
+ if record.audioEvidenceSource == .process {
+ record.audioEvidenceAt = nil
+ record.audioEvidenceSource = nil
+ }
+ self.records[pid] = record
+ DebugLogger.shared.log("audio-evidence-end path=process bundle=\(record.bundleIdentifier)", source: "MeetingAutoDetector")
+ }
+ }
+
+ private func isFrontmostNearEdge(_ record: CandidateRecord, edge: Date) -> Bool {
+ guard let frontmostAt = record.lastFrontmostAt else { return false }
+ let delta = edge.timeIntervalSince(frontmostAt)
+ return delta >= -5 && delta <= Self.frontmostLeadSeconds
+ }
+
+ // MARK: Window evidence (Tier 1)
+
+ func handleWindowSnapshot(_ snapshots: [WindowSnapshot], at now: Date) {
+ for pid in self.records.keys where self.records[pid]?.tier == .nativeTier1 {
+ guard let bundleIdentifier = self.records[pid]?.bundleIdentifier else { continue }
+ let ownedWindows = snapshots.filter { $0.processID == pid && $0.layer == 0 }
+ let matched = self.matchingNativeWindow(ownedWindows, bundleIdentifier: bundleIdentifier)
+
+ if matched == nil, bundleIdentifier == "us.zoom.xos",
+ let unreadableWindow = ownedWindows.first(where: { $0.title == nil }) {
+ guard !self.titleEnrichmentInFlight.contains(pid) else { continue }
+ self.titleEnrichmentInFlight.insert(pid)
+ let generation = (self.titleEnrichmentGeneration[pid] ?? 0) &+ 1
+ self.titleEnrichmentGeneration[pid] = generation
+ let provider = self.windowSnapshotProvider
+ Task { [weak self] in
+ let titles = await provider.titles(processID: pid)
+ guard let self else { return }
+ guard self.titleEnrichmentGeneration[pid] == generation else {
+ self.titleEnrichmentInFlight.remove(pid)
+ return
+ }
+ self.titleEnrichmentInFlight.remove(pid)
+ guard self.titleEnrichmentGeneration[pid] == generation,
+ let current = self.records[pid], current.bundleIdentifier == bundleIdentifier
+ else { return }
+ guard let title = titles.first(where: MeetingAppRegistry.isZoomMeetingWindowTitle) else {
+ self.publishHealth(titles.isEmpty ? .zoomWindowTitleUnreadable : .ready)
+ return
+ }
+ self.publishHealth(.ready)
+ self.handleWindowSnapshot(
+ ownedWindows.map { snapshot in
+ snapshot.windowID == unreadableWindow.windowID
+ ? WindowSnapshot(processID: snapshot.processID, windowID: snapshot.windowID, title: title, layer: snapshot.layer)
+ : snapshot
+ }, at: self.clock.now()
+ )
+ }
+ }
+
+ if let matched {
+ if bundleIdentifier == "us.zoom.xos" { self.publishHealth(.ready) }
+ let wasLiveWindow = self.records[pid]?.hasLiveWindow == true
+ self.records[pid]?.hasLiveWindow = true
+ self.records[pid]?.windowLostAt = nil
+ self.records[pid]?.windowEvidenceAt = now
+ self.records[pid]?.windowEvidenceKey = "win:\(matched.windowID)"
+ self.records[pid]?.windowEvidenceWindowID = matched.windowID
+ if !wasLiveWindow {
+ DebugLogger.shared.log("window-evidence-found bundle=\(bundleIdentifier)", source: "MeetingAutoDetector")
+ }
+ self.attemptConfirm(pid: pid, at: now)
+ } else if self.records[pid]?.hasLiveWindow == true {
+ self.records[pid]?.hasLiveWindow = false
+ if self.records[pid]?.windowLostAt == nil {
+ self.records[pid]?.windowLostAt = now
+ DebugLogger.shared.log("window-evidence-lost bundle=\(bundleIdentifier)", source: "MeetingAutoDetector")
+ }
+ }
+ }
+ }
+
+ /// Zoom requires a meeting/webinar-titled window (the home window never qualifies); Teams and
+ /// Webex have no generically nameable meeting window, so presence + frontmost-at-edge is the
+ /// whole attribution for them.
+ private func matchingNativeWindow(_ windows: [WindowSnapshot], bundleIdentifier: String) -> WindowSnapshot? {
+ if bundleIdentifier == "us.zoom.xos" {
+ return windows.first { MeetingAppRegistry.isZoomMeetingWindowTitle($0.title ?? "") }
+ }
+ return windows.first
+ }
+
+ private func publishHealth(_ health: Health) {
+ guard self.lastHealth != health else { return }
+ self.lastHealth = health
+ DebugLogger.shared.log("detector-health=\(health.rawValue)", source: "MeetingAutoDetector")
+ self.onHealthChanged?(health)
+ }
+
+ // MARK: Browser evidence (Tier 2)
+
+ func handleBrowserTabURL(_ url: BrowserTabURL?, pid: Int32, bundleIdentifier: String, at now: Date) {
+ guard let url, MeetingInCallURLMatcher.isInCallURL(host: url.host, path: url.path) else {
+ // Unreadable AXURL (nil) or the tab navigated off an in-call URL: fail closed and,
+ // if this record had live evidence, start the loss clock so the episode can end.
+ if self.records[pid]?.hasLiveWindow == true {
+ self.records[pid]?.hasLiveWindow = false
+ if self.records[pid]?.windowLostAt == nil {
+ self.records[pid]?.windowLostAt = now
+ DebugLogger.shared.log("window-evidence-lost bundle=\(bundleIdentifier)", source: "MeetingAutoDetector")
+ }
+ }
+ return
+ }
+ let wasLiveWindow = self.records[pid]?.hasLiveWindow == true
+ self.records[pid]?.windowEvidenceAt = now
+ self.records[pid]?.windowEvidenceKey = "url:\(url.host)\(url.path)"
+ self.records[pid]?.hasLiveWindow = true
+ self.records[pid]?.windowLostAt = nil
+ if !wasLiveWindow {
+ DebugLogger.shared.log("window-evidence-found bundle=\(bundleIdentifier)", source: "MeetingAutoDetector")
+ }
+ self.attemptConfirm(pid: pid, at: now)
+ }
+
+ // MARK: Confirm + episode lifecycle
+
+ private func attemptConfirm(pid: Int32, at now: Date) {
+ guard let record = self.records[pid],
+ let audioEvidenceAt = record.audioEvidenceAt,
+ let audioEvidenceSource = record.audioEvidenceSource,
+ let windowEvidenceAt = record.windowEvidenceAt,
+ let evidenceKey = record.windowEvidenceKey
+ else { return }
+ guard now.timeIntervalSince(audioEvidenceAt) <= Self.confirmDeadlineSeconds else {
+ self.logConfirmRejected("deadline", bundleIdentifier: record.bundleIdentifier)
+ return
+ }
+ guard abs(windowEvidenceAt.timeIntervalSince(audioEvidenceAt)) <= Self.coincidenceWindowSeconds else {
+ self.logConfirmRejected("coincidence", bundleIdentifier: record.bundleIdentifier)
+ return
+ }
+ let frontmostPasses = audioEvidenceSource == .process ? record.lastFrontmostAt != nil : self.isFrontmostNearEdge(record, edge: audioEvidenceAt)
+ guard frontmostPasses else {
+ self.logConfirmRejected("frontmost", bundleIdentifier: record.bundleIdentifier)
+ return
+ }
+
+ let readiness = self.activityGate.preflightState()
+ guard readiness != .busy else {
+ self.logConfirmRejected("busy", bundleIdentifier: record.bundleIdentifier)
+ return
+ }
+
+ let episodeKey = "pid:\(pid)|\(evidenceKey)"
+ if var existingEpisode = self.episodesByKey[episodeKey] {
+ if !existingEpisode.duplicateEpisodeRejectionLogged {
+ self.logConfirmRejected("duplicate-episode", bundleIdentifier: record.bundleIdentifier)
+ existingEpisode.duplicateEpisodeRejectionLogged = true
+ self.episodesByKey[episodeKey] = existingEpisode
+ }
+ return
+ }
+ guard (self.dismissedBundleUntil[record.bundleIdentifier].map { $0 > now }) != true else {
+ self.logConfirmRejected("bundle-suppressed", bundleIdentifier: record.bundleIdentifier)
+ return
+ }
+
+ let episode = Episode(
+ id: UUID(),
+ pid: pid,
+ bundleIdentifier: record.bundleIdentifier,
+ tier: record.tier,
+ key: episodeKey,
+ windowID: record.tier == .nativeTier1 ? record.windowEvidenceWindowID : nil,
+ confirmedAt: now
+ )
+ self.episodesByKey[episodeKey] = episode
+
+ DebugLogger.shared.log("preflight-state=\(Self.readinessToken(readiness)) bundle=\(record.bundleIdentifier)", source: "MeetingAutoDetector")
+ guard readiness != .busy else {
+ return
+ }
+ DebugLogger.shared.log("confirm-accepted bundle=\(record.bundleIdentifier)", source: "MeetingAutoDetector")
+ DebugLogger.shared.log("prompt-requested bundle=\(record.bundleIdentifier)", source: "MeetingAutoDetector")
+ let cta: PromptCTA = readiness == .ready ? .record : .setup
+ self.onPromptRequested?(PromptRequest(episodeID: episode.id, bundleIdentifier: episode.bundleIdentifier, pid: pid, tier: episode.tier, cta: cta))
+ }
+
+ private func logConfirmRejected(_ reason: String, bundleIdentifier: String) {
+ DebugLogger.shared.log("confirm-rejected reason=\(reason) bundle=\(bundleIdentifier)", source: "MeetingAutoDetector")
+ }
+
+ private static func readinessToken(_ state: DetectionPreflightState) -> String {
+ switch state {
+ case .ready: return "ready"
+ case .busy: return "busy"
+ case let .needsSetup(reason): return "setup-\(reason.rawValue)"
+ }
+ }
+
+ // MARK: Prompt outcomes
+
+ enum StartError: LocalizedError, Equatable {
+ case cannotStart
+
+ var errorDescription: String? {
+ "Can't start recording right now."
+ }
+ }
+
+ func canStart(episodeID: UUID) -> Bool {
+ guard let episode = self.episodesByKey.values.first(where: { $0.id == episodeID }),
+ !episode.consumed
+ else { return false }
+ return self.activityGate.preflightState() == .ready
+ }
+
+ /// Adopt after recording has actually started. Skips preflight because the live
+ /// recording itself would fail the idle gate. Re-adopts timeout-consumed episodes so
+ /// the live session still owns the key and clears the dismissal counter.
+ func adoptStartedEpisode(episodeID: UUID) {
+ guard let key = self.episodesByKey.first(where: { $0.value.id == episodeID })?.key,
+ var episode = self.episodesByKey[key]
+ else { return }
+ episode.consumed = true
+ self.episodesByKey[key] = episode
+ self.activeConsumedEpisodeKey = key
+ self.dismissalTimestamps.removeAll()
+ }
+
+ /// Atomic gate re-check + single-shot consume. Returns false if the episode is unknown,
+ /// already consumed, or the gate no longer passes — callers must not proceed with Start.
+ @discardableResult
+ func startTapped(episodeID: UUID) -> Bool {
+ guard self.canStart(episodeID: episodeID) else { return false }
+ self.adoptStartedEpisode(episodeID: episodeID)
+ return true
+ }
+
+ func resolvedTarget(for episodeID: UUID) -> ResolvedTarget? {
+ guard let episode = self.episodesByKey.values.first(where: { $0.id == episodeID }) else { return nil }
+ return ResolvedTarget(bundleIdentifier: episode.bundleIdentifier, pid: episode.pid, windowID: episode.windowID)
+ }
+
+ /// Explicit "X" dismiss: suppresses the bundle for 30 minutes and counts toward the rolling
+ /// 14-day counter. A 20s auto-dismiss timeout must call `timeoutDismissed` instead.
+ func dismissTapped(episodeID: UUID, at now: Date) {
+ guard let key = self.episodesByKey.first(where: { $0.value.id == episodeID })?.key,
+ var episode = self.episodesByKey[key], !episode.consumed
+ else { return }
+ episode.consumed = true
+ self.episodesByKey[key] = episode
+
+ self.dismissedBundleUntil[episode.bundleIdentifier] = now.addingTimeInterval(Self.dismissalSuppressionSeconds)
+ self.dismissalTimestamps.append(now)
+ self.dismissalTimestamps.removeAll { now.timeIntervalSince($0) > Self.rollingDismissalWindowSeconds }
+ if self.dismissalTimestamps.count >= Self.dismissalCountThreshold {
+ self.onSuggestDisablingAutoDetect?()
+ }
+ }
+
+ /// 20s auto-dismiss: consumes the episode (no re-prompt into the same meeting) but does NOT
+ /// suppress the bundle and does NOT count toward the dismissal counter.
+ func timeoutDismissed(episodeID: UUID) {
+ guard let key = self.episodesByKey.first(where: { $0.value.id == episodeID })?.key,
+ var episode = self.episodesByKey[key], !episode.consumed
+ else { return }
+ episode.consumed = true
+ self.episodesByKey[key] = episode
+ }
+
+ // MARK: Tick — grace, release, episode teardown, still-recording nudge
+
+ func tick(at now: Date) {
+ for pid in self.records.keys {
+ guard var record = self.records[pid] else { continue }
+ if let windowLostAt = record.windowLostAt, now.timeIntervalSince(windowLostAt) > Self.windowLossGraceSeconds {
+ record.windowEvidenceAt = nil
+ record.windowEvidenceKey = nil
+ record.windowEvidenceWindowID = nil
+ }
+ self.records[pid] = record
+ }
+
+ // Evaluated before eviction below: the active episode must still be present to nudge on
+ // the same tick its window-gone-60s threshold is crossed.
+ if let activeKey = self.activeConsumedEpisodeKey, let activeEpisode = self.episodesByKey[activeKey] {
+ self.evaluateStillRecordingNudge(key: activeKey, episode: activeEpisode, at: now)
+ }
+
+ // Uniform episode-end eviction (window/URL evidence gone ≥60s, or the app quit) applies
+ // even to a consumed episode still backing our own live recording — that IS episode end,
+ // e.g. the "stop mid-call, keep talking" rule: the episode stays consumed for as long as
+ // the meeting's own evidence persists, never merely because our recording stopped.
+ // Mic release ≥60s ends episodes too — Teams/Webex main windows persist after a call, so
+ // window loss alone would keep their episodes alive (and back-to-back meetings silent) forever.
+ let micReleasedLongEnough = self.lastMicReleaseAt.map { now.timeIntervalSince($0) >= Self.micReleaseEpisodeEndSeconds } == true
+ for (key, episode) in self.episodesByKey {
+ let ended: Bool
+ if let record = self.records[episode.pid] {
+ let windowGone = record.windowLostAt.map { now.timeIntervalSince($0) >= Self.micReleaseEpisodeEndSeconds } == true
+ let processAudioInactiveLongEnough = record.processAudioInactiveAt.map { now.timeIntervalSince($0) >= Self.micReleaseEpisodeEndSeconds } == true
+ ended = windowGone || micReleasedLongEnough || processAudioInactiveLongEnough
+ } else {
+ ended = true // the app quit
+ }
+ guard ended else { continue }
+ self.episodesByKey[key] = nil
+ if key == self.activeConsumedEpisodeKey { self.activeConsumedEpisodeKey = nil }
+ if !episode.consumed {
+ self.onEpisodeInvalidated?(episode.id)
+ }
+ DebugLogger.shared.log("episode-ended bundle=\(episode.bundleIdentifier)", source: "MeetingAutoDetector")
+ }
+ }
+
+ private func evaluateStillRecordingNudge(key: String, episode: Episode, at now: Date) {
+ guard !episode.stillRecordingNudgeShown else { return }
+ guard let record = self.records[episode.pid] else { return }
+ guard record.windowEvidenceAt == nil, let windowLostAt = record.windowLostAt else { return }
+ guard now.timeIntervalSince(windowLostAt) >= Self.micReleaseEpisodeEndSeconds else { return }
+ var updated = episode
+ updated.stillRecordingNudgeShown = true
+ self.episodesByKey[key] = updated
+ self.onStillRecordingNudge?()
+ }
+
+ // MARK: Disarm on lock / sleep / fast-user-switch — mic bits are unreliable across these.
+
+ func disarmAndClearTransientState() {
+ let unconsumedIDs = self.episodesByKey.values.compactMap { episode in
+ episode.consumed ? nil : episode.id
+ }
+ self.records = [:]
+ self.titleEnrichmentInFlight.removeAll()
+ self.titleEnrichmentGeneration.removeAll()
+ self.lastMicReleaseAt = nil
+ self.episodesByKey = [:]
+ self.activeConsumedEpisodeKey = nil
+ self.lastBrowserPollAt = [:]
+ for episodeID in unconsumedIDs {
+ self.onEpisodeInvalidated?(episodeID)
+ }
+ }
+
+ private var transientDisarmObservers: [NSObjectProtocol] = []
+
+ private func installTransientDisarmObservers() {
+ let center = NSWorkspace.shared.notificationCenter
+ self.transientDisarmObservers = [
+ center.addObserver(forName: NSWorkspace.screensDidSleepNotification, object: nil, queue: .main) { [weak self] _ in
+ self?.disarmAndClearTransientState()
+ },
+ center.addObserver(forName: NSWorkspace.sessionDidResignActiveNotification, object: nil, queue: .main) { [weak self] _ in
+ self?.disarmAndClearTransientState()
+ },
+ ]
+ self.transientDisarmObservers.append(
+ DistributedNotificationCenter.default().addObserver(
+ forName: Notification.Name("com.apple.screenIsLocked"), object: nil, queue: .main
+ ) { [weak self] _ in self?.disarmAndClearTransientState() }
+ )
+ }
+
+ private func removeTransientDisarmObservers() {
+ let center = NSWorkspace.shared.notificationCenter
+ for observer in self.transientDisarmObservers {
+ center.removeObserver(observer)
+ DistributedNotificationCenter.default().removeObserver(observer)
+ }
+ self.transientDisarmObservers = []
+ }
+}
diff --git a/Sources/Fluid/Services/Meeting/MeetingCaptureEngine.swift b/Sources/Fluid/Services/Meeting/MeetingCaptureEngine.swift
index af6faa7c..65de887c 100644
--- a/Sources/Fluid/Services/Meeting/MeetingCaptureEngine.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingCaptureEngine.swift
@@ -321,11 +321,15 @@ nonisolated enum MeetingWindowSelector {
static let minimumWidth: CGFloat = 200
static let minimumHeight: CGFloat = 100
- static func selectWindow(from candidates: [MeetingWindowCandidate]) -> MeetingWindowCandidate? {
- candidates
+ /// `preferredWindowID` — typically the window auto-detection found evidence in — wins outright
+ /// when it is still among the eligible candidates; otherwise falls back to ranked selection.
+ static func selectWindow(from candidates: [MeetingWindowCandidate], preferredWindowID: UInt32? = nil) -> MeetingWindowCandidate? {
+ let eligible = candidates
.filter { $0.layer == 0 && $0.frame.width >= self.minimumWidth && $0.frame.height >= self.minimumHeight }
- .sorted(by: self.isRanked)
- .first
+ if let preferredWindowID, let preferred = eligible.first(where: { $0.windowID == preferredWindowID }) {
+ return preferred
+ }
+ return eligible.sorted(by: self.isRanked).first
}
/// True when `lhs` should be preferred over `rhs`: non-empty title, then frontmost
@@ -450,7 +454,7 @@ private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCa
let filter: SCContentFilter
let scope: MeetingCaptureScope
- if let window = Self.selectWindow(for: runningApplication, in: content) {
+ if let window = Self.selectWindow(for: runningApplication, in: content, preferredWindowID: application.windowID) {
filter = SCContentFilter(desktopIndependentWindow: window)
scope = .window
} else {
@@ -480,7 +484,8 @@ private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCa
/// Window titles are PII and must never be logged or persisted.
private static func selectWindow(
for runningApplication: SCRunningApplication,
- in content: SCShareableContent
+ in content: SCShareableContent,
+ preferredWindowID: UInt32? = nil
) -> SCWindow? {
let ownedWindows = content.windows.enumerated().filter { _, window in
window.owningApplication?.processID == runningApplication.processID
@@ -494,7 +499,7 @@ private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCa
zOrderIndex: index
)
}
- guard let winner = MeetingWindowSelector.selectWindow(from: candidates) else { return nil }
+ guard let winner = MeetingWindowSelector.selectWindow(from: candidates, preferredWindowID: preferredWindowID) else { return nil }
return ownedWindows.first(where: { _, window in window.windowID == winner.windowID })?.element
}
@@ -1190,6 +1195,39 @@ nonisolated enum MeetingCaptureError: LocalizedError {
}
enum MeetingCaptureSourceCatalog {
+ static let preferredFallbackBundleIdentifiers = [
+ "us.zoom.xos",
+ "com.google.Chrome",
+ "com.microsoft.teams2",
+ ]
+
+ /// Manual setup keeps Zoom/Chrome/Teams fallback. Auto-detect must capture the
+ /// detected app or fail — never a different meeting.
+ static func resolveApplication(
+ from applications: [MeetingApplicationIdentity],
+ preferredBundleIdentifier: String?,
+ requirePreferredApplication: Bool
+ ) throws -> MeetingApplicationIdentity {
+ if requirePreferredApplication {
+ guard let preferredBundleIdentifier else {
+ throw MeetingCaptureError.applicationNotSelected
+ }
+ guard let match = applications.first(where: { $0.bundleIdentifier == preferredBundleIdentifier }) else {
+ throw MeetingCaptureError.applicationUnavailable(preferredBundleIdentifier)
+ }
+ return match
+ }
+
+ let preferredBundleIdentifiers = [preferredBundleIdentifier].compactMap { $0 }
+ + Self.preferredFallbackBundleIdentifiers
+ if let application = preferredBundleIdentifiers.lazy.compactMap({ bundleIdentifier in
+ applications.first(where: { $0.bundleIdentifier == bundleIdentifier })
+ }).first ?? applications.first {
+ return application
+ }
+ throw MeetingCaptureError.applicationNotSelected
+ }
+
static func availableApplications() async throws -> [MeetingApplicationIdentity] {
let content = try await SCShareableContent.current
let ownBundleIdentifier = Bundle.main.bundleIdentifier
@@ -1218,11 +1256,30 @@ enum MeetingCaptureSourceCatalog {
static func availableMicrophones() -> [MeetingMicrophoneIdentity] {
let coreAudioDevices = AudioDevice.listInputDevices()
- return AVCaptureDevice.DiscoverySession(
+ #if DEBUG
+ if Self.usesCoreAudioOnlyIsolationCatalog {
+ return coreAudioDevices.compactMap { device in
+ guard device.uid.isEmpty == false else { return nil }
+ return MeetingMicrophoneIdentity(
+ captureDeviceID: device.uid,
+ coreAudioUID: device.uid,
+ displayName: device.name
+ )
+ }
+ }
+ #endif
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.avfDiscoveryBegin, owner: .meetingCatalog, queueRole: .actorControl, phase: .catalog)
+ #endif
+ let devices = AVCaptureDevice.DiscoverySession(
deviceTypes: [.microphone, .external],
mediaType: .audio,
position: .unspecified
- ).devices.map { device in
+ ).devices
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.avfDiscoveryEnd, owner: .meetingCatalog, queueRole: .actorControl, phase: .catalog, status: Int32(clamping: devices.count))
+ #endif
+ return devices.map { device in
let sameName = coreAudioDevices.filter { $0.name == device.localizedName }
return MeetingMicrophoneIdentity(
captureDeviceID: device.uniqueID,
@@ -1239,11 +1296,35 @@ enum MeetingCaptureSourceCatalog {
{
return preferred
}
- guard let defaultDevice = AVCaptureDevice.default(for: .audio),
+ #if DEBUG
+ if Self.usesCoreAudioOnlyIsolationCatalog {
+ guard let defaultUID = AudioDevice.getDefaultInputDevice()?.uid,
+ let microphone = microphones.first(where: { $0.coreAudioUID == defaultUID })
+ else { throw MeetingCaptureError.microphoneUnavailable }
+ return microphone
+ }
+ #endif
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.avfDefaultBegin, owner: .meetingCatalog, queueRole: .actorControl, phase: .catalog)
+ #endif
+ let defaultDevice = AVCaptureDevice.default(for: .audio)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.avfDefaultEnd, owner: .meetingCatalog, queueRole: .actorControl, phase: .catalog, status: defaultDevice == nil ? -1 : noErr)
+ #endif
+ guard let defaultDevice,
let microphone = microphones.first(where: { $0.captureDeviceID == defaultDevice.uniqueID })
else { throw MeetingCaptureError.microphoneUnavailable }
return microphone
}
+
+ #if DEBUG
+ /// Phase-0 isolation only. This is intentionally meeting-catalog scoped and inert unless
+ /// the signed Debug app is launched with the exact opt-in value. It does not alter the
+ /// dictation catalog, preferred microphone, or Core Audio listener ownership.
+ private static var usesCoreAudioOnlyIsolationCatalog: Bool {
+ ProcessInfo.processInfo.environment["FLUIDVOICE_MEETING_COREAUDIO_CATALOG_ISOLATION"] == "1"
+ }
+ #endif
}
private extension CGRect {
@@ -1458,17 +1539,43 @@ private final nonisolated class MeetingOutputRouteListener: @unchecked Sendable
mElement: kAudioObjectPropertyElementMain
)
let defaultOutToken: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.callback, owner: .meetingOutputRoute, objectID: sys, selector: kAudioHardwarePropertyDefaultOutputDevice, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainDelivery)
+ #endif
self?.reattachDataSourceListener()
self?.reevaluate()
}
let restartedToken: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.callback, owner: .meetingOutputRoute, objectID: sys, selector: kAudioHardwarePropertyServiceRestarted, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainDelivery)
+ #endif
self?.reregisterAfterServiceRestart()
}
- guard AudioObjectAddPropertyListenerBlock(sys, &defaultOutAddr, DispatchQueue.main, defaultOutToken) == noErr else {
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .meetingOutputRoute, objectID: sys, selector: defaultOutAddr.mSelector, scope: defaultOutAddr.mScope, element: defaultOutAddr.mElement, queueRole: .dedicatedControl, phase: .listener)
+ #endif
+ let defaultStatus = AudioObjectAddPropertyListenerBlock(sys, &defaultOutAddr, DispatchQueue.main, defaultOutToken)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .meetingOutputRoute, objectID: sys, selector: defaultOutAddr.mSelector, scope: defaultOutAddr.mScope, element: defaultOutAddr.mElement, queueRole: .dedicatedControl, phase: .listener, status: defaultStatus)
+ #endif
+ guard defaultStatus == noErr else {
return false
}
- guard AudioObjectAddPropertyListenerBlock(sys, &restartedAddr, DispatchQueue.main, restartedToken) == noErr else {
- _ = AudioObjectRemovePropertyListenerBlock(sys, &defaultOutAddr, DispatchQueue.main, defaultOutToken)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .meetingOutputRoute, objectID: sys, selector: restartedAddr.mSelector, scope: restartedAddr.mScope, element: restartedAddr.mElement, queueRole: .dedicatedControl, phase: .listener)
+ #endif
+ let restartedStatus = AudioObjectAddPropertyListenerBlock(sys, &restartedAddr, DispatchQueue.main, restartedToken)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .meetingOutputRoute, objectID: sys, selector: restartedAddr.mSelector, scope: restartedAddr.mScope, element: restartedAddr.mElement, queueRole: .dedicatedControl, phase: .listener, status: restartedStatus)
+ #endif
+ guard restartedStatus == noErr else {
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .meetingOutputRoute, objectID: sys, selector: defaultOutAddr.mSelector, scope: defaultOutAddr.mScope, element: defaultOutAddr.mElement, queueRole: .dedicatedControl, phase: .listener)
+ #endif
+ let cleanupStatus = AudioObjectRemovePropertyListenerBlock(sys, &defaultOutAddr, DispatchQueue.main, defaultOutToken)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .meetingOutputRoute, objectID: sys, selector: defaultOutAddr.mSelector, scope: defaultOutAddr.mScope, element: defaultOutAddr.mElement, queueRole: .dedicatedControl, phase: .listener, status: cleanupStatus)
+ #endif
return false
}
self.defaultOutputToken = defaultOutToken
@@ -1487,8 +1594,20 @@ private final nonisolated class MeetingOutputRouteListener: @unchecked Sendable
mScope: kAudioObjectPropertyScopeOutput,
mElement: kAudioObjectPropertyElementMain
)
- let token: AudioObjectPropertyListenerBlock = { [weak self] _, _ in self?.reevaluate() }
- guard AudioObjectAddPropertyListenerBlock(device.id, &address, DispatchQueue.main, token) == noErr else { return false }
+ let token: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.callback, owner: .meetingOutputRoute, objectID: device.id, selector: kAudioDevicePropertyDataSource, scope: kAudioObjectPropertyScopeOutput, element: kAudioObjectPropertyElementMain, queueRole: .mainDelivery)
+ #endif
+ self?.reevaluate()
+ }
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .meetingOutputRoute, objectID: device.id, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener)
+ #endif
+ let status = AudioObjectAddPropertyListenerBlock(device.id, &address, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .meetingOutputRoute, objectID: device.id, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, status: status)
+ #endif
+ guard status == noErr else { return false }
self.dataSourceToken = token
self.dataSourceDeviceID = device.id
return true
@@ -1501,7 +1620,13 @@ private final nonisolated class MeetingOutputRouteListener: @unchecked Sendable
mScope: kAudioObjectPropertyScopeOutput,
mElement: kAudioObjectPropertyElementMain
)
- _ = AudioObjectRemovePropertyListenerBlock(deviceID, &address, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .meetingOutputRoute, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener)
+ #endif
+ let status = AudioObjectRemovePropertyListenerBlock(deviceID, &address, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .meetingOutputRoute, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, status: status)
+ #endif
self.dataSourceToken = nil
self.dataSourceDeviceID = nil
}
@@ -1533,10 +1658,22 @@ private final nonisolated class MeetingOutputRouteListener: @unchecked Sendable
mElement: kAudioObjectPropertyElementMain
)
if let token = self.defaultOutputToken {
- _ = AudioObjectRemovePropertyListenerBlock(sys, &defaultOutAddr, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .meetingOutputRoute, objectID: sys, selector: defaultOutAddr.mSelector, scope: defaultOutAddr.mScope, element: defaultOutAddr.mElement, queueRole: .dedicatedControl, phase: .listener)
+ #endif
+ let status = AudioObjectRemovePropertyListenerBlock(sys, &defaultOutAddr, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .meetingOutputRoute, objectID: sys, selector: defaultOutAddr.mSelector, scope: defaultOutAddr.mScope, element: defaultOutAddr.mElement, queueRole: .dedicatedControl, phase: .listener, status: status)
+ #endif
}
if let token = self.serviceRestartedToken {
- _ = AudioObjectRemovePropertyListenerBlock(sys, &restartedAddr, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .meetingOutputRoute, objectID: sys, selector: restartedAddr.mSelector, scope: restartedAddr.mScope, element: restartedAddr.mElement, queueRole: .dedicatedControl, phase: .listener)
+ #endif
+ let status = AudioObjectRemovePropertyListenerBlock(sys, &restartedAddr, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .meetingOutputRoute, objectID: sys, selector: restartedAddr.mSelector, scope: restartedAddr.mScope, element: restartedAddr.mElement, queueRole: .dedicatedControl, phase: .listener, status: status)
+ #endif
}
self.defaultOutputToken = nil
self.serviceRestartedToken = nil
diff --git a/Sources/Fluid/Services/Meeting/MeetingDetectorFeasibilityProbe.swift b/Sources/Fluid/Services/Meeting/MeetingDetectorFeasibilityProbe.swift
new file mode 100644
index 00000000..852ee033
--- /dev/null
+++ b/Sources/Fluid/Services/Meeting/MeetingDetectorFeasibilityProbe.swift
@@ -0,0 +1,672 @@
+#if DEBUG
+
+ import CoreAudio
+ import CoreGraphics
+ import CryptoKit
+ import Foundation
+
+ /// Ephemeral DEBUG-only feasibility probe for CoreAudio process-tap meeting detection.
+ /// Runs at most once per process when FLUIDVOICE_MEETING_PROBE_DURATION_SECONDS is 5...300.
+ /// Writes a closed-schema JSONL file to the temp dir; emits no raw IDs, names, paths, or errors.
+ nonisolated enum MeetingDetectorFeasibilityProbe {
+ private static let gate = ProbeOnceGate()
+
+ static func startIfRequested() {
+ guard let raw = ProcessInfo.processInfo.environment["FLUIDVOICE_MEETING_PROBE_DURATION_SECONDS"],
+ let duration = Int(raw),
+ ProbeLimits.validDurations.contains(duration)
+ else { return }
+ guard gate.checkAndSet() else { return }
+ ProbeSession(durationSeconds: duration).start()
+ }
+ }
+
+ private nonisolated enum ProbeLimits {
+ static let validDurations = 5 ... 300
+ static let maxObjectCount = 4096
+ static let maxBufferCount = 4096
+ static let maxStreamConfigBytes = 65_536
+ static let tokenDigestBytes = 16
+ static let saltBytes = 16
+ }
+
+ private nonisolated enum ProbeEvent: String, Codable, Sendable {
+ case start
+ case sample
+ case terminal
+ }
+
+ private nonisolated enum TerminalReason: String, Codable, Sendable {
+ case completed
+ case deadlineExceeded
+ case cancelled
+ case encodingFailure
+ case writeFailure
+ case validationFailure
+ case setupFailure
+ }
+
+ private nonisolated enum ProbeNote: String, Codable, Sendable {
+ case tempMayBePurged
+ }
+
+ private nonisolated enum ProbeReadStatus: String, Codable, Sendable {
+ case ok
+ case readError
+ case unsupported
+ case invalidLayout
+ }
+
+ private nonisolated enum ProbeStreamState: String, Codable, Sendable {
+ case active
+ case inactive
+ case readError
+ case unsupported
+ }
+
+ private nonisolated enum ProbeRunningState: String, Codable, Sendable {
+ case running
+ case notRunning
+ case readError
+ case unsupported
+ }
+
+ private nonisolated enum ProbeFamily: String, Codable, Sendable {
+ case zoom
+ case teams
+ case webex
+ case selfProcess
+ case other
+ }
+
+ private nonisolated enum ProbeTransport: String, Codable, Sendable {
+ case builtIn
+ case bluetooth
+ case usb
+ case virtual
+ case aggregate
+ case other
+ case unknown
+ }
+
+ private nonisolated struct ProbeStartLine: Codable, Sendable {
+ var schemaVersion: Int
+ var event: ProbeEvent
+ var durationSeconds: Int
+ var note: ProbeNote
+ }
+
+ private nonisolated struct ProbeTerminalLine: Codable, Sendable {
+ var schemaVersion: Int
+ var event: ProbeEvent
+ var monotonicOffsetMs: Int
+ var reason: TerminalReason
+ var recordCount: Int
+ }
+
+ private nonisolated struct ProbeSampleLine: Codable, Sendable {
+ var schemaVersion: Int
+ var event: ProbeEvent
+ var monotonicOffsetMs: Int
+ var processListStatus: ProbeReadStatus
+ var processCount: Int
+ var deviceListStatus: ProbeReadStatus
+ var deviceCount: Int
+ var hardwareDeviceCount: Int
+ var classificationFailureCount: Int
+ var windowListSuccess: Bool
+ var windowListCount: Int
+ var windowListLatencyMs: Int
+ var processes: [ProcessEntry]
+ var devices: [DeviceEntry]
+ }
+
+ private nonisolated struct ProcessEntry: Codable, Sendable {
+ var family: ProbeFamily
+ var input: ProbeStreamState
+ var output: ProbeStreamState
+ }
+
+ private nonisolated struct DeviceEntry: Codable, Sendable {
+ var token: String?
+ var inputChannels: Int
+ var streamStatus: ProbeReadStatus
+ var transport: ProbeTransport
+ var running: ProbeRunningState
+ }
+
+ /// NSLock-guarded one-run check-and-set; the only Swift 6 Sendable escape hatch this file needs.
+ private final nonisolated class ProbeOnceGate: @unchecked Sendable {
+ private let lock = NSLock()
+ private var hasRun = false
+
+ func checkAndSet() -> Bool {
+ lock.lock()
+ defer { lock.unlock() }
+ if hasRun { return false }
+ hasRun = true
+ return true
+ }
+ }
+
+ private nonisolated enum AudioListReadResult {
+ case ok([AudioObjectID])
+ case readError
+ case unsupported
+ case invalidLayout
+ }
+
+ private final nonisolated class ProbeSession: @unchecked Sendable {
+ private let durationSeconds: Int
+ private let baseInstant = ContinuousClock.now
+ private let salt: [UInt8]
+ private let samplingQueue = DispatchQueue(label: "com.fluidvoice.meetingprobe.sampling", qos: .utility)
+ // Sole owner of encoder, fileHandle, deadlineTimer, terminalReason, recordCount, outputPath, sampleInFlight.
+ private let controlQueue = DispatchQueue(label: "com.fluidvoice.meetingprobe.control")
+
+ private let encoder = JSONEncoder()
+ private var fileHandle: FileHandle?
+ private var deadlineTimer: DispatchSourceTimer?
+ private var terminalReason: TerminalReason?
+ private var recordCount = 0
+ private var outputPath = ""
+ private var sampleInFlight = false
+
+ private var deadlineMs: Int { durationSeconds * 1000 }
+
+ init(durationSeconds: Int) {
+ self.durationSeconds = durationSeconds
+ var generator = SystemRandomNumberGenerator()
+ self.salt = (0 ..< ProbeLimits.saltBytes).map { _ in UInt8.random(in: .min ... .max, using: &generator) }
+ }
+
+ func start() {
+ controlQueue.async { self.setup() }
+ }
+
+ func cancel() {
+ controlQueue.async { self.finalize(.cancelled) }
+ }
+
+ // MARK: - Control queue
+
+ private func setup() {
+ guard terminalReason == nil else { return }
+ guard Self.validateSchema() else {
+ finalize(.validationFailure)
+ return
+ }
+
+ let tempDir = FileManager.default.temporaryDirectory.standardizedFileURL
+ let candidate = tempDir.appendingPathComponent("fluidvoice-meeting-probe-\(UUID().uuidString).jsonl").standardizedFileURL
+ guard candidate.path.hasPrefix(tempDir.path + "/") else {
+ finalize(.setupFailure)
+ return
+ }
+ guard FileManager.default.createFile(
+ atPath: candidate.path,
+ contents: nil,
+ attributes: [.posixPermissions: 0o600]
+ ) else {
+ finalize(.setupFailure)
+ return
+ }
+ outputPath = candidate.path
+ do {
+ fileHandle = try FileHandle(forWritingTo: candidate)
+ } catch {
+ try? FileManager.default.removeItem(at: candidate)
+ outputPath = ""
+ finalize(.setupFailure)
+ return
+ }
+
+ let startLine = ProbeStartLine(
+ schemaVersion: 1,
+ event: .start,
+ durationSeconds: durationSeconds,
+ note: .tempMayBePurged
+ )
+ guard writeLine(startLine) else { return }
+
+ let timer = DispatchSource.makeTimerSource(queue: controlQueue)
+ timer.schedule(deadline: .now() + .seconds(durationSeconds))
+ timer.setEventHandler { [self] in
+ finalize(sampleInFlight ? .deadlineExceeded : .completed)
+ }
+ deadlineTimer = timer
+ timer.resume()
+
+ scheduleTick(after: 0)
+ }
+
+ private func scheduleTick(after seconds: Int) {
+ sampleInFlight = true
+ samplingQueue.asyncAfter(deadline: .now() + .seconds(seconds)) { [self] in
+ let snapshot = captureSnapshot()
+ controlQueue.async { [self] in
+ sampleInFlight = false
+ guard terminalReason == nil else { return }
+ guard Self.milliseconds(from: baseInstant) < deadlineMs else {
+ finalize(.deadlineExceeded)
+ return
+ }
+ guard writeLine(snapshot) else { return }
+ if Self.milliseconds(from: baseInstant) + 1000 < deadlineMs {
+ scheduleTick(after: 1)
+ }
+ }
+ }
+ }
+
+ private func writeLine(_ line: some Codable) -> Bool {
+ guard let handle = fileHandle else {
+ finalize(.setupFailure)
+ return false
+ }
+ let payload: Data
+ do {
+ payload = try encoder.encode(line)
+ } catch {
+ finalize(.encodingFailure)
+ return false
+ }
+ var framed = payload
+ framed.append(0x0A)
+ do {
+ try handle.write(contentsOf: framed)
+ } catch {
+ finalize(.writeFailure)
+ return false
+ }
+ recordCount += 1
+ return true
+ }
+
+ private func finalize(_ reason: TerminalReason) {
+ guard terminalReason == nil else { return }
+ terminalReason = reason
+ deadlineTimer?.cancel()
+ deadlineTimer = nil
+ var outcome = reason
+ if let handle = fileHandle {
+ let terminal = ProbeTerminalLine(
+ schemaVersion: 1,
+ event: .terminal,
+ monotonicOffsetMs: Self.milliseconds(from: baseInstant),
+ reason: reason,
+ recordCount: recordCount
+ )
+ do {
+ var framed = try encoder.encode(terminal)
+ framed.append(0x0A)
+ try handle.write(contentsOf: framed)
+ } catch is EncodingError {
+ outcome = .encodingFailure
+ } catch {
+ outcome = .writeFailure
+ }
+ try? handle.close()
+ fileHandle = nil
+ }
+ terminalReason = outcome
+ let message = "terminal=\(outcome.rawValue) records=\(recordCount) output=\(outputPath)"
+ DispatchQueue.main.async {
+ DebugLogger.shared.info(message, source: "MeetingProbe")
+ }
+ }
+
+ // MARK: - Sampling queue
+
+ private func captureSnapshot() -> ProbeSampleLine {
+ var processes: [ProcessEntry] = []
+ let processListStatus: ProbeReadStatus
+ var processCount = 0
+ switch readAudioObjectIDList(kAudioHardwarePropertyProcessObjectList) {
+ case let .ok(ids):
+ processListStatus = .ok
+ processCount = ids.count
+ for id in ids {
+ let family = Self.meetingFamily(for: readProcessBundleID(id))
+ guard family != .other else { continue }
+ processes.append(ProcessEntry(
+ family: family,
+ input: readProcessRunning(id, selector: kAudioProcessPropertyIsRunningInput),
+ output: readProcessRunning(id, selector: kAudioProcessPropertyIsRunningOutput)
+ ))
+ }
+ case .readError: processListStatus = .readError
+ case .unsupported: processListStatus = .unsupported
+ case .invalidLayout: processListStatus = .invalidLayout
+ }
+
+ var devices: [DeviceEntry] = []
+ let deviceListStatus: ProbeReadStatus
+ var hardwareDeviceCount = 0
+ var classificationFailureCount = 0
+ switch readAudioObjectIDList(kAudioHardwarePropertyDevices) {
+ case let .ok(ids):
+ deviceListStatus = .ok
+ hardwareDeviceCount = ids.count
+ for id in ids {
+ let stream = readInputChannels(id)
+ guard stream.status == .ok else {
+ classificationFailureCount += 1
+ continue
+ }
+ guard stream.channels > 0 else { continue }
+ devices.append(DeviceEntry(
+ token: readDeviceUID(id).map(saltedToken(for:)),
+ inputChannels: stream.channels,
+ streamStatus: stream.status,
+ transport: readTransport(id),
+ running: readRunningSomewhere(id)
+ ))
+ }
+ case .readError: deviceListStatus = .readError
+ case .unsupported: deviceListStatus = .unsupported
+ case .invalidLayout: deviceListStatus = .invalidLayout
+ }
+
+ let window = captureWindowList()
+ return ProbeSampleLine(
+ schemaVersion: 1,
+ event: .sample,
+ monotonicOffsetMs: Self.milliseconds(from: baseInstant),
+ processListStatus: processListStatus,
+ processCount: processCount,
+ deviceListStatus: deviceListStatus,
+ deviceCount: devices.count,
+ hardwareDeviceCount: hardwareDeviceCount,
+ classificationFailureCount: classificationFailureCount,
+ windowListSuccess: window.success,
+ windowListCount: window.count,
+ windowListLatencyMs: window.latencyMs,
+ processes: processes,
+ devices: devices
+ )
+ }
+
+ private static let selfBundleID: String? = Bundle.main.bundleIdentifier
+
+ private static func meetingFamily(for bundleID: String?) -> ProbeFamily {
+ if let selfBundleID, bundleID == selfBundleID { return .selfProcess }
+ switch bundleID {
+ case "us.zoom.xos", "us.zoom.caphost": return .zoom
+ case "com.microsoft.teams2", "com.microsoft.teams": return .teams
+ case "com.cisco.webexmeetingsapp", "Cisco-Systems.Spark": return .webex
+ default: return .other
+ }
+ }
+
+ private func saltedToken(for uid: String) -> String {
+ var hasher = SHA256()
+ hasher.update(data: Data(salt))
+ hasher.update(data: Data(uid.utf8))
+ return hasher.finalize().prefix(ProbeLimits.tokenDigestBytes).map { String(format: "%02x", $0) }.joined()
+ }
+
+ private static func milliseconds(from instant: ContinuousClock.Instant) -> Int {
+ Int((ContinuousClock.now - instant) / .milliseconds(1))
+ }
+
+ // MARK: - CoreAudio reads
+
+ private func readAudioObjectIDList(_ selector: AudioObjectPropertySelector) -> AudioListReadResult {
+ var address = AudioObjectPropertyAddress(
+ mSelector: selector,
+ mScope: kAudioObjectPropertyScopeGlobal,
+ mElement: kAudioObjectPropertyElementMain
+ )
+ let systemObject = AudioObjectID(kAudioObjectSystemObject)
+ guard AudioObjectHasProperty(systemObject, &address) else { return .unsupported }
+ let stride = MemoryLayout<AudioObjectID>.stride
+
+ var lastWasChurn = false
+ for _ in 0 ..< 2 {
+ var size: UInt32 = 0
+ guard AudioObjectGetPropertyDataSize(systemObject, &address, 0, nil, &size) == noErr else {
+ lastWasChurn = false
+ continue
+ }
+ if size == 0 { return .ok([]) }
+ guard size % UInt32(stride) == 0,
+ Int(size) / stride <= ProbeLimits.maxObjectCount
+ else { return .invalidLayout }
+
+ var dataSize = size
+ var buffer = [UInt8](repeating: 0, count: Int(size))
+ let status = buffer.withUnsafeMutableBytes { raw -> OSStatus in
+ guard let base = raw.baseAddress else { return -1 }
+ return AudioObjectGetPropertyData(systemObject, &address, 0, nil, &dataSize, base)
+ }
+ guard status == noErr else {
+ lastWasChurn = false
+ continue
+ }
+ guard dataSize <= size,
+ dataSize % UInt32(stride) == 0,
+ Int(dataSize) / stride <= ProbeLimits.maxObjectCount
+ else {
+ lastWasChurn = true
+ continue
+ }
+
+ let count = Int(dataSize) / stride
+ var result = [AudioObjectID](repeating: 0, count: count)
+ buffer.withUnsafeBytes { raw in
+ result.withUnsafeMutableBytes { destination in
+ destination.copyBytes(from: raw.prefix(count * stride))
+ }
+ }
+ return .ok(result)
+ }
+ return lastWasChurn ? .invalidLayout : .readError
+ }
+
+ private func readProcessBundleID(_ objectID: AudioObjectID) -> String? {
+ readStringProperty(objectID, selector: kAudioProcessPropertyBundleID)
+ }
+
+ private func readProcessRunning(_ objectID: AudioObjectID, selector: AudioObjectPropertySelector) -> ProbeStreamState {
+ var address = AudioObjectPropertyAddress(
+ mSelector: selector,
+ mScope: kAudioObjectPropertyScopeGlobal,
+ mElement: kAudioObjectPropertyElementMain
+ )
+ guard AudioObjectHasProperty(objectID, &address) else { return .unsupported }
+ var value: UInt32 = 0
+ var size = UInt32(MemoryLayout<UInt32>.stride)
+ guard AudioObjectGetPropertyData(objectID, &address, 0, nil, &size, &value) == noErr else {
+ return .readError
+ }
+ return value != 0 ? .active : .inactive
+ }
+
+ private func readDeviceUID(_ objectID: AudioObjectID) -> String? {
+ readStringProperty(objectID, selector: kAudioDevicePropertyDeviceUID)
+ }
+
+ private func readStringProperty(_ objectID: AudioObjectID, selector: AudioObjectPropertySelector) -> String? {
+ var address = AudioObjectPropertyAddress(
+ mSelector: selector,
+ mScope: kAudioObjectPropertyScopeGlobal,
+ mElement: kAudioObjectPropertyElementMain
+ )
+ guard AudioObjectHasProperty(objectID, &address) else { return nil }
+ // CoreAudio returns a +1 retained CFString; takeRetainedValue() transfers ownership.
+ var value: Unmanaged<CFString>?
+ var size = UInt32(MemoryLayout<Unmanaged<CFString>?>.size)
+ guard AudioObjectGetPropertyData(objectID, &address, 0, nil, &size, &value) == noErr else { return nil }
+ return value?.takeRetainedValue() as String?
+ }
+
+ private func readInputChannels(_ objectID: AudioObjectID) -> (channels: Int, status: ProbeReadStatus) {
+ var address = AudioObjectPropertyAddress(
+ mSelector: kAudioDevicePropertyStreamConfiguration,
+ mScope: kAudioDevicePropertyScopeInput,
+ mElement: kAudioObjectPropertyElementMain
+ )
+ guard AudioObjectHasProperty(objectID, &address) else { return (0, .unsupported) }
+ let headerOffset = MemoryLayout<AudioBufferList>.stride - MemoryLayout<AudioBuffer>.stride
+ let bufferStride = MemoryLayout<AudioBuffer>.stride
+
+ for _ in 0 ..< 2 {
+ var size: UInt32 = 0
+ guard AudioObjectGetPropertyDataSize(objectID, &address, 0, nil, &size) == noErr else { continue }
+ guard size > 0, size <= ProbeLimits.maxStreamConfigBytes else { return (0, .invalidLayout) }
+
+ var dataSize = size
+ var buffer = [UInt8](repeating: 0, count: Int(size))
+ let status = buffer.withUnsafeMutableBytes { raw -> OSStatus in
+ guard let base = raw.baseAddress else { return -1 }
+ return AudioObjectGetPropertyData(objectID, &address, 0, nil, &dataSize, base)
+ }
+ guard status == noErr else { continue }
+ guard dataSize <= size else { continue }
+ guard Int(dataSize) >= headerOffset else { return (0, .invalidLayout) }
+
+ var parsed: Int?
+ buffer.withUnsafeBytes { raw in
+ let byteCount = Int(dataSize)
+ let declared = Int(raw.loadUnaligned(fromByteOffset: 0, as: UInt32.self))
+ guard declared <= ProbeLimits.maxBufferCount,
+ headerOffset + declared * bufferStride <= byteCount
+ else { return }
+ var channels = 0
+ for index in 0 ..< declared {
+ let audioBuffer = raw.loadUnaligned(
+ fromByteOffset: headerOffset + index * bufferStride,
+ as: AudioBuffer.self
+ )
+ let (sum, overflow) = channels.addingReportingOverflow(Int(audioBuffer.mNumberChannels))
+ guard !overflow else { return }
+ channels = sum
+ }
+ parsed = channels
+ }
+ guard let channels = parsed else { return (0, .invalidLayout) }
+ return (channels, .ok)
+ }
+ return (0, .readError)
+ }
+
+ private func readTransport(_ objectID: AudioObjectID) -> ProbeTransport {
+ var address = AudioObjectPropertyAddress(
+ mSelector: kAudioDevicePropertyTransportType,
+ mScope: kAudioObjectPropertyScopeGlobal,
+ mElement: kAudioObjectPropertyElementMain
+ )
+ guard AudioObjectHasProperty(objectID, &address) else { return .unknown }
+ var value: UInt32 = 0
+ var size = UInt32(MemoryLayout<UInt32>.stride)
+ guard AudioObjectGetPropertyData(objectID, &address, 0, nil, &size, &value) == noErr else {
+ return .unknown
+ }
+ switch value {
+ case UInt32(kAudioDeviceTransportTypeBuiltIn): return .builtIn
+ case UInt32(kAudioDeviceTransportTypeBluetooth), UInt32(kAudioDeviceTransportTypeBluetoothLE): return .bluetooth
+ case UInt32(kAudioDeviceTransportTypeUSB): return .usb
+ case UInt32(kAudioDeviceTransportTypeVirtual): return .virtual
+ case UInt32(kAudioDeviceTransportTypeAggregate): return .aggregate
+ case UInt32(kAudioDeviceTransportTypeUnknown): return .unknown
+ default: return .other
+ }
+ }
+
+ private func readRunningSomewhere(_ objectID: AudioObjectID) -> ProbeRunningState {
+ var address = AudioObjectPropertyAddress(
+ mSelector: kAudioDevicePropertyDeviceIsRunningSomewhere,
+ mScope: kAudioObjectPropertyScopeGlobal,
+ mElement: kAudioObjectPropertyElementMain
+ )
+ guard AudioObjectHasProperty(objectID, &address) else { return .unsupported }
+ var value: UInt32 = 0
+ var size = UInt32(MemoryLayout<UInt32>.stride)
+ guard AudioObjectGetPropertyData(objectID, &address, 0, nil, &size, &value) == noErr else {
+ return .readError
+ }
+ return value != 0 ? .running : .notRunning
+ }
+
+ // MARK: - Window list
+
+ private func captureWindowList() -> (success: Bool, count: Int, latencyMs: Int) {
+ autoreleasepool {
+ let started = ContinuousClock.now
+ let list = CGWindowListCopyWindowInfo([.optionAll, .excludeDesktopElements], kCGNullWindowID)
+ let latencyMs = Int((ContinuousClock.now - started) / .milliseconds(1))
+ guard let list else { return (false, 0, latencyMs) }
+ return (true, CFArrayGetCount(list), latencyMs)
+ }
+ }
+
+ // MARK: - Schema validation
+
+ private static let allowedStartKeys: Set<String> = ["schemaVersion", "event", "durationSeconds", "note"]
+ private static let allowedSampleKeys: Set<String> = [
+ "schemaVersion", "event", "monotonicOffsetMs",
+ "processListStatus", "processCount", "deviceListStatus", "deviceCount",
+ "hardwareDeviceCount", "classificationFailureCount",
+ "windowListSuccess", "windowListCount", "windowListLatencyMs",
+ "processes", "devices",
+ ]
+ private static let allowedTerminalKeys: Set<String> = ["schemaVersion", "event", "monotonicOffsetMs", "reason", "recordCount"]
+ private static let allowedProcessKeys: Set<String> = ["family", "input", "output"]
+ private static let allowedDeviceKeys: Set<String> = ["token", "inputChannels", "streamStatus", "transport", "running"]
+
+ private static func encodedDictionary(_ record: some Codable) -> [String: Any]? {
+ guard let data = try? JSONEncoder().encode(record),
+ let dict = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
+ else { return nil }
+ return dict
+ }
+
+ private static func validateSchema() -> Bool {
+ let start = ProbeStartLine(schemaVersion: 1, event: .start, durationSeconds: 5, note: .tempMayBePurged)
+ guard let startDict = encodedDictionary(start),
+ Set(startDict.keys) == allowedStartKeys
+ else { return false }
+
+ let process = ProcessEntry(family: .zoom, input: .active, output: .inactive)
+ let device = DeviceEntry(token: "00", inputChannels: 2, streamStatus: .ok, transport: .builtIn, running: .running)
+ let sample = ProbeSampleLine(
+ schemaVersion: 1,
+ event: .sample,
+ monotonicOffsetMs: 0,
+ processListStatus: .ok,
+ processCount: 1,
+ deviceListStatus: .ok,
+ deviceCount: 1,
+ hardwareDeviceCount: 1,
+ classificationFailureCount: 0,
+ windowListSuccess: true,
+ windowListCount: 1,
+ windowListLatencyMs: 0,
+ processes: [process],
+ devices: [device]
+ )
+ guard let sampleDict = encodedDictionary(sample),
+ Set(sampleDict.keys) == allowedSampleKeys,
+ let processes = sampleDict["processes"] as? [[String: Any]],
+ processes.count == 1,
+ Set(processes[0].keys) == allowedProcessKeys,
+ let devices = sampleDict["devices"] as? [[String: Any]],
+ devices.count == 1,
+ Set(devices[0].keys) == allowedDeviceKeys
+ else { return false }
+
+ let tokenAbsent = DeviceEntry(token: nil, inputChannels: 1, streamStatus: .ok, transport: .usb, running: .notRunning)
+ guard let tokenAbsentDict = encodedDictionary(tokenAbsent),
+ Set(tokenAbsentDict.keys) == allowedDeviceKeys.subtracting(["token"])
+ else { return false }
+
+ let terminal = ProbeTerminalLine(schemaVersion: 1, event: .terminal, monotonicOffsetMs: 0, reason: .completed, recordCount: 0)
+ guard let terminalDict = encodedDictionary(terminal),
+ Set(terminalDict.keys) == allowedTerminalKeys
+ else { return false }
+ return true
+ }
+ }
+
+#endif
diff --git a/Sources/Fluid/Services/Meeting/MeetingMicrophoneCapture.swift b/Sources/Fluid/Services/Meeting/MeetingMicrophoneCapture.swift
index 5a3c77a9..bdcd97bf 100644
--- a/Sources/Fluid/Services/Meeting/MeetingMicrophoneCapture.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingMicrophoneCapture.swift
@@ -637,7 +637,21 @@ actor MeetingMicrophoneCapture {
guard !self.isRunning else { throw MeetingMicrophoneCaptureError.alreadyStarted }
let currentGeneration = self.generationBox.advance()
- guard AVCaptureDevice.authorizationStatus(for: .audio) == .authorized else {
+ #if DEBUG
+ var diagnosticsPhaseEnded = false
+ AudioTopologyDiagnostics.record(.phaseBegin, owner: .meetingMicrophone, queueRole: .actorControl, phase: .handoff, generation: currentGeneration)
+ AudioTopologyDiagnostics.record(.avfAuthorizationBegin, owner: .meetingMicrophone, queueRole: .actorControl, phase: .catalog, generation: currentGeneration)
+ defer {
+ if diagnosticsPhaseEnded == false {
+ AudioTopologyDiagnostics.record(.phaseEnd, owner: .meetingMicrophone, queueRole: .actorControl, phase: .handoff, status: -1, generation: currentGeneration)
+ }
+ }
+ #endif
+ let authorizationStatus = AVCaptureDevice.authorizationStatus(for: .audio)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.avfAuthorizationEnd, owner: .meetingMicrophone, queueRole: .actorControl, phase: .catalog, status: Int32(authorizationStatus.rawValue), generation: currentGeneration)
+ #endif
+ guard authorizationStatus == .authorized else {
return self.fail(microphone: microphone, reason: "Microphone permission is not granted.")
}
@@ -652,9 +666,18 @@ actor MeetingMicrophoneCapture {
let input = engine.inputNode
// VPIO replaces the I/O unit: enable before any format read or device bind.
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.vpioEnableBegin, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .vpio, generation: currentGeneration)
+ #endif
do {
try input.setVoiceProcessingEnabled(true)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.vpioEnableEnd, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .vpio, status: noErr, generation: currentGeneration)
+ #endif
} catch {
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.vpioEnableEnd, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .vpio, status: -1, generation: currentGeneration)
+ #endif
return self.fail(microphone: microphone, reason: "Voice processing could not be enabled: \(error.localizedDescription)")
}
var ducking = AVAudioVoiceProcessingOtherAudioDuckingConfiguration()
@@ -667,7 +690,13 @@ actor MeetingMicrophoneCapture {
}
// TODO(probe): bind order is a Phase-1 measurement; this hard-codes one attempt.
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.audioUnitBindBegin, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .vpio, generation: currentGeneration)
+ #endif
let bindStatus = Self.bindInputDevice(audioUnit, to: requestedDeviceID)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.audioUnitBindEnd, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .vpio, status: bindStatus, generation: currentGeneration)
+ #endif
// Tap before start(): added afterwards it sits on an inactive node — measured as
// 10 minutes of zero callbacks with healthy telemetry.
@@ -683,10 +712,25 @@ actor MeetingMicrophoneCapture {
tapState.handle(buffer: buffer, time: time)
}
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.enginePrepareBegin, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .engine, generation: currentGeneration)
+ #endif
engine.prepare()
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.enginePrepareEnd, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .engine, status: noErr, generation: currentGeneration)
+ #endif
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.engineStartBegin, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .engine, generation: currentGeneration)
+ #endif
do {
try engine.start()
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.engineStartEnd, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .engine, status: noErr, generation: currentGeneration)
+ #endif
} catch {
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.engineStartEnd, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .engine, status: -1, generation: currentGeneration)
+ #endif
input.removeTap(onBus: 0)
return self.fail(microphone: microphone, reason: "AVAudioEngine failed to start: \(error.localizedDescription)")
}
@@ -732,6 +776,11 @@ actor MeetingMicrophoneCapture {
outputChannelDecision: "mono (explicit downmix); observed ch=1 on today's SCStream mic, not derived from SCStream's stereo capture config"
)
self.registerEventObservers(engine: engine, outcome: outcome, requestedDeviceID: requestedDeviceID, onEvent: onEvent)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.readiness, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .engine, status: noErr, generation: currentGeneration)
+ AudioTopologyDiagnostics.record(.phaseEnd, owner: .meetingMicrophone, queueRole: .actorControl, phase: .handoff, status: noErr, generation: currentGeneration)
+ diagnosticsPhaseEnded = true
+ #endif
return outcome
}
@@ -739,11 +788,17 @@ actor MeetingMicrophoneCapture {
guard self.isRunning else { return }
self.isRunning = false
self.tearDownEventObservers() // first: stop-time churn must not poison a stats snapshot
- self.generationBox.advance()
+ let stopGeneration = self.generationBox.advance()
if let engine = self.engine {
engine.inputNode.removeTap(onBus: 0)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.engineStopBegin, owner: .meetingMicrophone, queueRole: .actorControl, phase: .engine, generation: stopGeneration)
+ #endif
engine.stop()
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.engineStopEnd, owner: .meetingMicrophone, queueRole: .actorControl, phase: .engine, status: noErr, generation: stopGeneration)
+ #endif
}
self.engine = nil
self.tapState = nil
@@ -821,10 +876,20 @@ actor MeetingMicrophoneCapture {
mElement: kAudioObjectPropertyElementMain
)
let token: AudioObjectPropertyListenerBlock = { _, _ in
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.callback, owner: .meetingMicrophone, objectID: AudioObjectID(kAudioObjectSystemObject), selector: kAudioHardwarePropertyDefaultInputDevice, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainDelivery)
+ #endif
statsBox.mutate { $0.defaultInputChangeEvents += 1 }
onEvent(.defaultInputChanged)
}
- if AudioObjectAddPropertyListenerBlock(AudioObjectID(kAudioObjectSystemObject), &address, DispatchQueue.main, token) == noErr {
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .meetingMicrophone, objectID: AudioObjectID(kAudioObjectSystemObject), selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .actorControl, phase: .listener)
+ #endif
+ let status = AudioObjectAddPropertyListenerBlock(AudioObjectID(kAudioObjectSystemObject), &address, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .meetingMicrophone, objectID: AudioObjectID(kAudioObjectSystemObject), selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .actorControl, phase: .listener, status: status)
+ #endif
+ if status == noErr {
self.defaultInputListenerToken = token
}
}
@@ -836,10 +901,20 @@ actor MeetingMicrophoneCapture {
mElement: kAudioObjectPropertyElementMain
)
let token: AudioObjectPropertyListenerBlock = { _, _ in
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.callback, owner: .meetingMicrophone, objectID: requestedDeviceID, selector: kAudioDeviceProcessorOverload, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainDelivery)
+ #endif
statsBox.mutate { $0.overloadCount += 1 }
onEvent(.overload)
}
- if AudioObjectAddPropertyListenerBlock(requestedDeviceID, &address, DispatchQueue.main, token) == noErr {
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .meetingMicrophone, objectID: requestedDeviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .actorControl, phase: .listener)
+ #endif
+ let status = AudioObjectAddPropertyListenerBlock(requestedDeviceID, &address, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .meetingMicrophone, objectID: requestedDeviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .actorControl, phase: .listener, status: status)
+ #endif
+ if status == noErr {
self.overloadListenerToken = token
self.overloadListenerDeviceID = requestedDeviceID
}
@@ -857,7 +932,13 @@ actor MeetingMicrophoneCapture {
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
- _ = AudioObjectRemovePropertyListenerBlock(AudioObjectID(kAudioObjectSystemObject), &address, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .meetingMicrophone, objectID: AudioObjectID(kAudioObjectSystemObject), selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .actorControl, phase: .listener)
+ #endif
+ let status = AudioObjectRemovePropertyListenerBlock(AudioObjectID(kAudioObjectSystemObject), &address, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .meetingMicrophone, objectID: AudioObjectID(kAudioObjectSystemObject), selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .actorControl, phase: .listener, status: status)
+ #endif
self.defaultInputListenerToken = nil
}
if let token = self.overloadListenerToken, let deviceID = self.overloadListenerDeviceID {
@@ -866,7 +947,13 @@ actor MeetingMicrophoneCapture {
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
- _ = AudioObjectRemovePropertyListenerBlock(deviceID, &address, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .meetingMicrophone, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .actorControl, phase: .listener)
+ #endif
+ let status = AudioObjectRemovePropertyListenerBlock(deviceID, &address, DispatchQueue.main, token)
+ #if DEBUG
+ AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .meetingMicrophone, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .actorControl, phase: .listener, status: status)
+ #endif
self.overloadListenerToken = nil
self.overloadListenerDeviceID = nil
}
diff --git a/Sources/Fluid/Services/Meeting/MeetingModels.swift b/Sources/Fluid/Services/Meeting/MeetingModels.swift
index da3aabf9..cc8b1fa8 100644
--- a/Sources/Fluid/Services/Meeting/MeetingModels.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingModels.swift
@@ -133,17 +133,24 @@ nonisolated struct MeetingApplicationIdentity: Codable, Equatable, Sendable {
var processID: Int32?
var displayName: String
var displayID: UInt32?
+ /// The specific window auto-detection found evidence in. Additive/optional so pre-existing
+ /// manifests still decode (synthesized Codable uses decodeIfPresent/encodeIfPresent for
+ /// Optional properties). `MeetingWindowSelector` prefers it when set and it still exists —
+ /// prevents recording a different foreground window than the one that was actually detected.
+ var windowID: UInt32?
init(
bundleIdentifier: String,
processID: Int32? = nil,
displayName: String,
- displayID: UInt32? = nil
+ displayID: UInt32? = nil,
+ windowID: UInt32? = nil
) {
self.bundleIdentifier = bundleIdentifier
self.processID = processID
self.displayName = displayName
self.displayID = displayID
+ self.windowID = windowID
}
}
diff --git a/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift b/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift
index e16bbe0b..f24a28f2 100644
--- a/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift
@@ -194,22 +194,36 @@ final class MeetingSessionCoordinator: ObservableObject {
func defaultConfiguration(
mode: MeetingCaptureMode,
title: String
+ ) async throws -> MeetingCaptureConfiguration {
+ try await self.defaultConfiguration(mode: mode, title: title, preferredBundleIdentifier: nil, preferredWindowID: nil)
+ }
+
+ /// Used by the auto-detection Start path: `preferredBundleIdentifier` is the detected app.
+ /// When `requirePreferredApplication` is true, that app must be available — no Zoom/Chrome/Teams
+ /// fallback. `preferredWindowID` is threaded onto the resulting identity when it still matches.
+ /// SCK content and microphone identities are refreshed here rather than reused.
+ func defaultConfiguration(
+ mode: MeetingCaptureMode,
+ title: String,
+ preferredBundleIdentifier: String?,
+ preferredWindowID: UInt32?,
+ requirePreferredApplication: Bool = false
) async throws -> MeetingCaptureConfiguration {
let microphone = try MeetingCaptureSourceCatalog.defaultMicrophone(
preferredCoreAudioUID: self.preferredMicrophoneUID()
)
- let application: MeetingApplicationIdentity?
+ var application: MeetingApplicationIdentity?
if mode == .onlineCall {
let applications = try await MeetingCaptureSourceCatalog.availableApplications()
- let preferredBundleIdentifiers = [
- "us.zoom.xos",
- "com.google.Chrome",
- "com.microsoft.teams2",
- ]
- application = preferredBundleIdentifiers.lazy.compactMap { bundleIdentifier in
- applications.first(where: { $0.bundleIdentifier == bundleIdentifier })
- }.first ?? applications.first
- guard application != nil else { throw MeetingCaptureError.applicationNotSelected }
+ var resolved = try MeetingCaptureSourceCatalog.resolveApplication(
+ from: applications,
+ preferredBundleIdentifier: preferredBundleIdentifier,
+ requirePreferredApplication: requirePreferredApplication
+ )
+ if let preferredWindowID, resolved.bundleIdentifier == preferredBundleIdentifier {
+ resolved.windowID = preferredWindowID
+ }
+ application = resolved
} else {
application = nil
}
diff --git a/Sources/Fluid/UI/FluidOverlayPrimitives.swift b/Sources/Fluid/UI/FluidOverlayPrimitives.swift
new file mode 100644
index 00000000..d24b57b4
--- /dev/null
+++ b/Sources/Fluid/UI/FluidOverlayPrimitives.swift
@@ -0,0 +1,108 @@
+import SwiftUI
+
+enum FluidOverlayAngularBorderStops {
+ static let dictationPill: [Gradient.Stop] = [
+ .init(color: .white.opacity(0.06), location: 0),
+ .init(color: .white.opacity(0.55), location: 0.13),
+ .init(color: .white.opacity(0.10), location: 0.30),
+ .init(color: .white.opacity(0.03), location: 0.55),
+ .init(color: .white.opacity(0.22), location: 0.80),
+ .init(color: .white.opacity(0.06), location: 1),
+ ]
+}
+
+struct FluidOverlaySurfaceBase: View {
+ struct Shadow {
+ var opacity: Double
+ var radius: CGFloat
+ var y: CGFloat
+ }
+
+ var cornerRadius: CGFloat
+ var shadow: Shadow?
+
+ var body: some View {
+ RoundedRectangle(cornerRadius: self.cornerRadius)
+ .fill(Color.black)
+ .shadow(
+ color: Color.black.opacity(self.shadow?.opacity ?? 0),
+ radius: self.shadow?.radius ?? 0,
+ x: 0,
+ y: self.shadow?.y ?? 0
+ )
+ }
+}
+
+struct FluidOverlayBorder: View {
+ enum Style {
+ case staticAngular(angle: Angle, lineWidth: CGFloat)
+ case linear(topOpacity: Double, bottomOpacity: Double, lineWidth: CGFloat)
+ }
+
+ var cornerRadius: CGFloat
+ var style: Style
+
+ var body: some View {
+ let shape = RoundedRectangle(cornerRadius: self.cornerRadius)
+ switch self.style {
+ case .staticAngular(let angle, let lineWidth):
+ shape.strokeBorder(
+ AngularGradient(
+ stops: FluidOverlayAngularBorderStops.dictationPill,
+ center: .center,
+ angle: angle
+ ),
+ lineWidth: lineWidth
+ )
+ case .linear(let topOpacity, let bottomOpacity, let lineWidth):
+ shape.strokeBorder(
+ LinearGradient(
+ colors: [
+ Color.white.opacity(topOpacity),
+ Color.white.opacity(bottomOpacity),
+ ],
+ startPoint: .top,
+ endPoint: .bottom
+ ),
+ lineWidth: lineWidth
+ )
+ }
+ }
+}
+
+struct FluidOverlaySurface: View {
+ typealias Border = FluidOverlayBorder.Style
+ typealias Shadow = FluidOverlaySurfaceBase.Shadow
+
+ var cornerRadius: CGFloat
+ var border: Border
+ var shadow: Shadow?
+
+ var body: some View {
+ ZStack {
+ FluidOverlaySurfaceBase(cornerRadius: self.cornerRadius, shadow: self.shadow)
+ FluidOverlayBorder(cornerRadius: self.cornerRadius, style: self.border)
+ }
+ }
+}
+
+struct FluidOverlayLevelBars: View {
+ var heights: [CGFloat]
+ var width: CGFloat
+ var spacing: CGFloat
+ var cornerRadius: CGFloat
+ var color: Color
+ var glowColor: Color
+ var glowRadius: CGFloat
+
+ var body: some View {
+ HStack(alignment: .center, spacing: self.spacing) {
+ ForEach(Array(self.heights.enumerated()), id: \.offset) { _, height in
+ RoundedRectangle(cornerRadius: self.cornerRadius)
+ .fill(self.color)
+ .frame(width: self.width, height: height)
+ .shadow(color: self.glowColor, radius: self.glowRadius)
+ }
+ }
+ }
+}
diff --git a/Sources/Fluid/UI/MeetingDetectionPrompt.swift b/Sources/Fluid/UI/MeetingDetectionPrompt.swift
new file mode 100644
index 00000000..6d402ffc
--- /dev/null
+++ b/Sources/Fluid/UI/MeetingDetectionPrompt.swift
@@ -0,0 +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))
+ .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 --git a/Sources/Fluid/UI/MeetingFloatingCaptionsPanel.swift b/Sources/Fluid/UI/MeetingFloatingCaptionsPanel.swift
index 68899eb8..b8f5662b 100644
--- a/Sources/Fluid/UI/MeetingFloatingCaptionsPanel.swift
+++ b/Sources/Fluid/UI/MeetingFloatingCaptionsPanel.swift
@@ -13,12 +13,32 @@ final class MeetingFloatingCaptionsPanel: NSPanel {
/// 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) -> MeetingFloatingCaptionsPanel {
+ 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(
@@ -42,6 +62,7 @@ enum MeetingFloatingPanelFactory {
panel.sharingType = .none
let hostingView = MeetingFloatingHostingView(rootView: content)
+ hostingView.overlayHitPadding = overlayHitPadding
hostingView.wantsLayer = true
hostingView.layer?.backgroundColor = .clear
panel.contentView = hostingView
@@ -78,7 +99,7 @@ final class MeetingFloatingCaptionsController: ObservableObject {
let panel = self.panelOrCreate(coordinator: coordinator)
self.subscribeIfNeeded(coordinator: coordinator)
- let sourceFrame = MeetingRecordingPillController.shared.expandedPanelFrame
+ let sourceFrame = MeetingRecordingPillController.shared.resolveCaptionsSourceFrame()
let reduceMotion = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion
if let sourceFrame, !panel.isVisible, !reduceMotion {
let targetFrame = panel.frame
diff --git a/Sources/Fluid/UI/MeetingOverlayModels.swift b/Sources/Fluid/UI/MeetingOverlayModels.swift
new file mode 100644
index 00000000..589771af
--- /dev/null
+++ b/Sources/Fluid/UI/MeetingOverlayModels.swift
@@ -0,0 +1,186 @@
+import CoreGraphics
+import Foundation
+
+enum MeetingOverlayPreference: String, Codable, CaseIterable, Equatable, Sendable {
+ case pill
+ case captions
+}
+
+enum MeetingOverlayPresentation: Equatable, Sendable {
+ case pill
+ case captions
+
+ init(_ preference: MeetingOverlayPreference) {
+ switch preference {
+ case .pill:
+ self = .pill
+ case .captions:
+ self = .captions
+ }
+ }
+
+ var toggled: MeetingOverlayPresentation {
+ switch self {
+ case .pill:
+ return .captions
+ case .captions:
+ return .pill
+ }
+ }
+
+ /// Visible surface size for this presentation. Panel geometry and SwiftUI
+ /// surface frames must both use this value; it is not the NSPanel frame.
+ var visibleSize: CGSize {
+ switch self {
+ case .pill:
+ return CGSize(width: 84, height: 32)
+ case .captions:
+ return CGSize(width: 340, height: 156)
+ }
+ }
+
+ /// Canonical bottom footer height within the captions surface. Fixed so the footer never
+ /// moves as caption content grows or shrinks.
+ static let captionsFooterHeight: CGFloat = 35
+
+ /// Canonical caption text viewport height: the remainder of the captions canvas above the
+ /// footer. viewport + footer must equal `captions.visibleSize.height`.
+ static let captionsViewportHeight: CGFloat = MeetingOverlayPresentation.captions.visibleSize.height
+ - MeetingOverlayPresentation.captionsFooterHeight
+
+ /// Canonical horizontal inset on both sides of the caption text content, inside the 340pt canvas.
+ static let captionsHorizontalInset: CGFloat = 16
+
+ /// Canonical inset above the caption text content, inside the caption viewport.
+ static let captionsTopInset: CGFloat = 12
+
+ /// Canonical inset below the caption text content, inside the caption viewport.
+ static let captionsBottomInset: CGFloat = 7
+
+ /// Caption text content width: the captions canvas width minus both horizontal insets.
+ static let captionsContentWidth: CGFloat = MeetingOverlayPresentation.captions.visibleSize.width
+ - (2 * MeetingOverlayPresentation.captionsHorizontalInset)
+
+ /// Caption text content height: the viewport height minus the top and bottom insets. The live
+ /// text and empty state are clipped to exactly this rectangle so an overflowing fixedSize Text
+ /// can never consume the top or bottom inset.
+ static let captionsContentHeight: CGFloat = MeetingOverlayPresentation.captionsViewportHeight
+ - MeetingOverlayPresentation.captionsTopInset
+ - MeetingOverlayPresentation.captionsBottomInset
+}
+
+struct MeetingOverlayVisibleAnchor: Equatable, Sendable {
+ var centerX: CGFloat
+ var bottomY: CGFloat
+}
+
+struct MeetingOverlayPadding: Equatable, Sendable {
+ var top: CGFloat
+ var left: CGFloat
+ var bottom: CGFloat
+ var right: CGFloat
+
+ static func uniform(_ value: CGFloat) -> MeetingOverlayPadding {
+ MeetingOverlayPadding(top: value, left: value, bottom: value, right: value)
+ }
+}
+
+struct MeetingOverlayLayout: Equatable, Sendable {
+ var panelFrame: CGRect
+ var visibleSurfaceFrame: CGRect
+}
+
+enum MeetingOverlayGeometry {
+ static func layout(
+ anchor: MeetingOverlayVisibleAnchor,
+ visibleSize: CGSize,
+ padding: CGFloat,
+ screenVisible: CGRect
+ ) -> MeetingOverlayLayout {
+ self.layout(
+ anchor: anchor,
+ visibleSize: visibleSize,
+ padding: .uniform(padding),
+ screenVisible: screenVisible
+ )
+ }
+
+ static func layout(
+ anchor: MeetingOverlayVisibleAnchor,
+ visibleSize: CGSize,
+ padding: MeetingOverlayPadding,
+ screenVisible: CGRect
+ ) -> MeetingOverlayLayout {
+ let visible = self.clampedVisibleSurface(
+ proposedOrigin: CGPoint(
+ x: anchor.centerX - visibleSize.width / 2,
+ y: anchor.bottomY
+ ),
+ proposedSize: visibleSize,
+ screenVisible: screenVisible
+ )
+ let panel = CGRect(
+ x: visible.minX - padding.left,
+ y: visible.minY - padding.bottom,
+ width: visible.width + padding.left + padding.right,
+ height: visible.height + padding.top + padding.bottom
+ )
+ return MeetingOverlayLayout(panelFrame: panel, visibleSurfaceFrame: visible)
+ }
+
+ private static func clampedVisibleSurface(
+ proposedOrigin: CGPoint,
+ proposedSize: CGSize,
+ screenVisible: CGRect
+ ) -> CGRect {
+ let width = min(max(proposedSize.width, 0), max(screenVisible.width, 0))
+ let height = min(max(proposedSize.height, 0), max(screenVisible.height, 0))
+ let minX = screenVisible.minX
+ let maxX = screenVisible.maxX - width
+ let minY = screenVisible.minY
+ let maxY = screenVisible.maxY - height
+ let x = min(max(proposedOrigin.x, minX), max(minX, maxX))
+ let y = min(max(proposedOrigin.y, minY), max(minY, maxY))
+ return CGRect(x: x, y: y, width: width, height: height)
+ }
+}
+
+enum MeetingOverlayPresentationEvent: Equatable, Sendable {
+ case recordingStarted(sessionID: UUID)
+ case recordingStateChanged
+ case recordingDegraded
+ case recordingStopped
+ case preferenceChanged(MeetingOverlayPreference)
+ case toggleRequested
+}
+
+struct MeetingOverlayPresentationReducer: Equatable, Sendable {
+ private(set) var preference: MeetingOverlayPreference
+ private(set) var presentation: MeetingOverlayPresentation?
+ private(set) var sessionID: UUID?
+
+ init(preference: MeetingOverlayPreference = .pill) {
+ self.preference = preference
+ self.presentation = nil
+ self.sessionID = nil
+ }
+
+ mutating func apply(_ event: MeetingOverlayPresentationEvent) {
+ switch event {
+ case .recordingStarted(let sessionID):
+ guard self.sessionID != sessionID else { return }
+ self.sessionID = sessionID
+ self.presentation = MeetingOverlayPresentation(self.preference)
+ case .recordingStateChanged, .recordingDegraded:
+ break
+ case .recordingStopped:
+ self.sessionID = nil
+ self.presentation = nil
+ case .preferenceChanged(let preference):
+ self.preference = preference
+ case .toggleRequested:
+ guard self.sessionID != nil, let presentation else { return }
+ self.presentation = presentation.toggled
+ }
+ }
+}
diff --git a/Sources/Fluid/UI/MeetingRecordingPill.swift b/Sources/Fluid/UI/MeetingRecordingPill.swift
index b11ae82d..7e69e5c0 100644
--- a/Sources/Fluid/UI/MeetingRecordingPill.swift
+++ b/Sources/Fluid/UI/MeetingRecordingPill.swift
@@ -2,22 +2,30 @@ import AppKit
import Combine
import SwiftUI
-/// Small always-on-top pill shown automatically while a meeting is recording: live mic level and a
+/// 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 isExpanded = false
+ @Published private(set) var presentation: MeetingOverlayPresentation = .pill
- private static let pillSize = NSSize(width: 84, height: 32)
- private static let subtitleSize = NSSize(width: 480, height: 132)
- private static let autosaveName = "MeetingRecordingPill"
+ 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() {}
@@ -27,109 +35,258 @@ final class MeetingRecordingPillController: ObservableObject {
.receive(on: DispatchQueue.main)
.sink { [weak self, weak coordinator] state in
guard let self, let coordinator else { return }
- if MeetingFloatingCaptionsController.isVisible(for: state) {
- self.show(coordinator: coordinator)
- } else {
- self.setExpanded(false)
- self.panel?.orderOut(nil)
- }
+ self.handleCoordinatorState(state, coordinator: coordinator)
}
}
- private func show(coordinator: MeetingSessionCoordinator) {
- let panel = self.panelOrCreate(coordinator: coordinator)
- panel.orderFrontRegardless()
- }
-
func toggleExpanded() {
- self.setExpanded(!self.isExpanded)
+ 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() {
- self.setExpanded(false)
+ 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()
}
- /// Where the subtitle strip currently sits, if expanded — the captions window slides out from here.
- var expandedPanelFrame: NSRect? {
- guard self.isExpanded, let panel, panel.isVisible else { return nil }
- return panel.frame
+ private func hideOverlay() {
+ self.invalidateTransition()
+ self.reducer.apply(.recordingStopped)
+ self.presentation = .pill
+ self.panel?.orderOut(nil)
}
- private func setExpanded(_ expanded: Bool) {
- guard self.isExpanded != expanded, let panel else {
- self.isExpanded = expanded
+ private func setPresentation(_ presentation: MeetingOverlayPresentation) {
+ guard self.presentation != presentation, self.panel != nil else {
+ self.presentation = presentation
return
}
- self.isExpanded = expanded
- let size = expanded ? Self.subtitleSize : Self.pillSize
- var frame = panel.frame
- let centerX = frame.midX
- frame.origin.x = centerX - size.width / 2
- frame.size = size
+ 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
- guard panel.isVisible, !reduceMotion else {
- panel.setFrame(frame, display: true)
- self.clampIntoVisibleFrame(panel)
+ 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 = 0.55
+ context.duration = Self.morphDuration
context.timingFunction = CAMediaTimingFunction(controlPoints: 0.22, 1.0, 0.36, 1.0)
- panel.animator().setFrame(frame, display: true)
+ panel.animator().setFrame(layout.panelFrame, display: true)
} completionHandler: { [weak self] in
Task { @MainActor [weak self] in
- guard let self, let panel = self.panel else { return }
- self.clampIntoVisibleFrame(panel)
+ 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: Self.pillSize, resizable: false, content: content)
+ let panel = MeetingFloatingPanelFactory.make(
+ size: layout.panelFrame.size,
+ resizable: false,
+ content: content,
+ overlayHitPadding: Self.overlayPadding
+ )
- panel.setFrameAutosaveName(Self.autosaveName)
- if panel.setFrameUsingName(Self.autosaveName) {
- // Only the position is user-controlled; the size must track the current design.
- var frame = panel.frame
- frame.size = Self.pillSize
- panel.setFrame(frame, display: false)
- } else {
- self.placeAtDefaultPosition(panel)
+ if self.loadPersistedAnchor() == nil, panel.setFrameUsingName(Self.legacyAutosaveName) {
+ let restored = panel.frame
+ self.visibleAnchor = MeetingOverlayVisibleAnchor(centerX: restored.midX, bottomY: restored.minY)
+ self.persistAnchor()
}
- self.clampIntoVisibleFrame(panel)
self.panel = panel
+ self.applyFrame(for: presentation, animated: false)
+ self.installWindowMoveObserverIfNeeded(for: panel)
self.installScreenParametersObserverIfNeeded()
return panel
}
- private func placeAtDefaultPosition(_ panel: NSPanel) {
+ private func defaultAnchor() -> MeetingOverlayVisibleAnchor {
let screen = OverlayScreenResolver.screenForCurrentPointer() ?? NSScreen.main
- guard let screen else { return }
- let visible = screen.visibleFrame
- let origin = NSPoint(
- x: visible.midX - Self.pillSize.width / 2,
- y: visible.minY + Self.defaultBottomInset
+ 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))
)
- panel.setFrame(NSRect(origin: origin, size: Self.pillSize), 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 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() {
@@ -140,17 +297,14 @@ final class MeetingRecordingPillController: ObservableObject {
queue: .main
) { [weak self] _ in
Task { @MainActor [weak self] in
- self?.repositionIfOffscreen()
+ self?.repositionForDisplayChange()
}
}
}
- 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)
+ private func repositionForDisplayChange() {
+ guard let panel, panel.isVisible else { return }
+ self.applyFrame(for: self.presentation, animated: false)
}
}
@@ -160,6 +314,7 @@ struct MeetingRecordingPillContent: View {
@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
@@ -170,17 +325,13 @@ struct MeetingRecordingPillContent: View {
}
@ObservedObject private var pill = MeetingRecordingPillController.shared
- @Namespace private var morph
-
- private var morphAnimation: Animation? {
- self.reduceMotion ? nil : .spring(response: 0.55, dampingFraction: 0.88)
- }
var body: some View {
Group {
- if self.pill.isExpanded {
+ switch self.pill.presentation {
+ case .captions:
self.subtitleStrip
- } else {
+ case .pill:
self.compactPill
}
}
@@ -188,68 +339,129 @@ struct MeetingRecordingPillContent: View {
.onChange(of: self.isRecordingActive) { _, active in
if active { self.isStopping = false }
}
- .animation(self.morphAnimation, value: self.pill.isExpanded)
+ .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 morphSurface: some View {
- RoundedRectangle(cornerRadius: 16, style: .continuous)
- .fill(self.theme.palette.contentBackground.opacity(0.96))
- .overlay(
- RoundedRectangle(cornerRadius: 16, style: .continuous)
- .stroke(self.theme.palette.accent.opacity(0.7), lineWidth: 1.2)
- )
- .shadow(color: .black.opacity(0.3), radius: 11, x: 0, y: 4)
- .matchedGeometryEffect(id: "surface", in: self.morph)
+ 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)
- .matchedGeometryEffect(id: "wave", in: self.morph)
self.stopButton
- .matchedGeometryEffect(id: "stop", in: self.morph)
}
.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.morphSurface)
+ .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 Group {
- if rows.isEmpty {
- Text("Listening…")
- .font(.system(size: 13, design: .monospaced))
- .foregroundStyle(self.theme.palette.secondaryText)
- .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
- } else {
- Text(self.rollingSubtitle(rows: rows))
- .font(.system(size: 14, design: .monospaced))
- .lineSpacing(4)
- .foregroundStyle(self.theme.palette.primaryText)
- // fixedSize is load-bearing — a height-constrained Text truncates its END,
- // freezing the display on the oldest words instead of clipping the top.
- .fixedSize(horizontal: false, vertical: true)
- .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading)
- .clipped()
+ return VStack(spacing: 0) {
+ VStack(spacing: 0) {
+ Color.clear
+ .frame(height: MeetingOverlayPresentation.captionsTopInset)
+
+ Group {
+ if rows.isEmpty {
+ Text(self.emptyCaptionStatusText)
+ .font(.system(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 {
+ Text(self.rollingSubtitle(rows: rows))
+ .font(.system(size: 14, design: .monospaced))
+ .lineSpacing(4)
+ .foregroundStyle(Color.white.opacity(0.94))
+ // fixedSize is load-bearing — a height-constrained Text truncates its END,
+ // freezing the display on the oldest words instead of clipping the top.
+ .fixedSize(horizontal: false, vertical: true)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading)
+ .accessibilityHidden(true)
+ }
+ }
+ .frame(
+ width: MeetingOverlayPresentation.captionsContentWidth,
+ height: MeetingOverlayPresentation.captionsContentHeight
+ )
+ // Clip strictly to the content rectangle so an overflowing fixedSize Text can never
+ // consume the top or bottom inset — clipping only at the outer viewport let overflow
+ // eat into the top inset before reaching that boundary.
+ .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
+ )
}
- .transition(.opacity)
- .padding(.horizontal, 16)
- .padding(.vertical, 12)
- .background(self.morphSurface)
+ .frame(
+ width: MeetingOverlayPresentation.captions.visibleSize.width,
+ height: MeetingOverlayPresentation.captions.visibleSize.height
+ )
+ .background(self.captionsSurface)
// Pure text island; controls surface only on hover so it reads as subtitles, not a widget.
.overlay(alignment: .topTrailing) {
if self.isHoveringStrip {
@@ -261,7 +473,7 @@ struct MeetingRecordingPillContent: View {
} label: {
Image(systemName: "rectangle.portrait.and.arrow.right")
.font(.system(size: 10, weight: .semibold))
- .foregroundStyle(self.theme.palette.secondaryText)
+ .foregroundStyle(Color.white.opacity(0.68))
}
.buttonStyle(.plain)
.accessibilityLabel("Open captions window")
@@ -270,7 +482,7 @@ struct MeetingRecordingPillContent: View {
} label: {
Image(systemName: "chevron.down")
.font(.system(size: 10, weight: .semibold))
- .foregroundStyle(self.theme.palette.secondaryText)
+ .foregroundStyle(Color.white.opacity(0.68))
}
.buttonStyle(.plain)
.accessibilityLabel("Collapse captions")
@@ -278,7 +490,7 @@ struct MeetingRecordingPillContent: View {
}
.padding(.horizontal, 8)
.padding(.vertical, 4)
- .background(Capsule().fill(self.theme.palette.contentBackground.opacity(0.92)))
+ .background(Capsule().fill(Color.black.opacity(0.82)))
.padding(6)
.transition(.opacity)
}
@@ -286,6 +498,73 @@ struct MeetingRecordingPillContent: View {
.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))
+ .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 word stream across all turns — no bubbles, no speaker structure, just the last
@@ -303,21 +582,25 @@ struct MeetingRecordingPillContent: View {
return words.suffix(maxWords).joined(separator: " ")
}
+ 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 {
- guard !self.isStopping else { return }
- self.isStopping = true
- let coordinator = self.coordinator
- Task {
- _ = try? await coordinator.stopAndTranscribe()
- }
+ self.stopRecording()
} label: {
Image(systemName: "stop.fill")
.font(.system(size: 8, weight: .bold))
- .foregroundStyle(self.theme.palette.primaryText)
+ .foregroundStyle(Color.white.opacity(0.92))
.frame(width: 18, height: 18)
- .background(self.theme.palette.contentBackground, in: Circle())
- .overlay(Circle().stroke(self.theme.palette.separator.opacity(0.5), lineWidth: 1))
+ .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)
@@ -335,13 +618,41 @@ private struct MeetingRecordingLevelBars: View {
private static let weights: [CGFloat] = [0.45, 0.75, 1.0, 0.75, 0.45]
var body: some View {
- HStack(alignment: .center, spacing: 2.5) {
- ForEach(Array(Self.weights.enumerated()), id: \.offset) { _, weight in
- Capsule()
- .fill(self.theme.palette.accent)
- .frame(width: 2, height: max(2.5, CGFloat(self.level) * 11 * weight))
- }
- }
+ 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 --git a/Sources/Fluid/UI/MeetingTranscriptionView.swift b/Sources/Fluid/UI/MeetingTranscriptionView.swift
index ba3b78ed..d26f661b 100644
--- a/Sources/Fluid/UI/MeetingTranscriptionView.swift
+++ b/Sources/Fluid/UI/MeetingTranscriptionView.swift
@@ -1714,6 +1714,9 @@ private struct MeetingHistoryRow: View {
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]
@@ -1828,6 +1831,18 @@ private struct MeetingRecordingSettingsSheet: View {
}
}
+ 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",
@@ -1890,6 +1905,52 @@ private struct MeetingRecordingSettingsSheet: View {
.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)
+ }
}
}
diff --git a/Sources/Fluid/UI/SettingsView.swift b/Sources/Fluid/UI/SettingsView.swift
index 49ccd857..ecb4a16e 100644
--- a/Sources/Fluid/UI/SettingsView.swift
+++ b/Sources/Fluid/UI/SettingsView.swift
@@ -1368,7 +1368,7 @@ struct SettingsView: View {
HStack {
VStack(alignment: .leading, spacing: 2) {
- Text(self.settings.overlayPosition == .bottom ? "Overlay Size" : "Notch Style")
+ Text(self.settings.overlayPosition == .bottom ? "Dictation Overlay Size" : "Notch Style")
.font(self.theme.typography.bodyStrong)
.foregroundStyle(self.settingsTitleText)
Text(
@@ -1402,6 +1402,29 @@ struct SettingsView: View {
}
.settingsSearchTarget(.overlayStyle)
+ Divider().padding(.vertical, 4)
+
+ HStack {
+ VStack(alignment: .leading, spacing: 2) {
+ Text("Meeting Overlay")
+ .font(self.theme.typography.bodyStrong)
+ .foregroundStyle(self.settingsTitleText)
+ Text("Choose the display used when your next meeting starts")
+ .font(self.theme.typography.bodySmall)
+ .foregroundStyle(self.settingsSecondaryText)
+ }
+
+ Spacer()
+
+ Picker("", selection: self.$settings.meetingOverlayPreference) {
+ ForEach(MeetingOverlayPreference.allCases, id: \.self) { preference in
+ Text(preference == .pill ? "Pill" : "Captions").tag(preference)
+ }
+ }
+ .pickerStyle(.menu)
+ .frame(width: 170, alignment: .trailing)
+ }
+
HStack {
VStack(alignment: .leading, spacing: 2) {
Text("Live Preview")
diff --git a/Sources/Fluid/Views/BottomOverlayView.swift b/Sources/Fluid/Views/BottomOverlayView.swift
index f7463aa4..10d5b85f 100644
--- a/Sources/Fluid/Views/BottomOverlayView.swift
+++ b/Sources/Fluid/Views/BottomOverlayView.swift
@@ -3354,35 +3354,23 @@ struct BottomOverlayView: View {
ZStack {
// Solid pitch black background, with a soft drop shadow so the pill lifts
// off whatever is behind it (pill size only; outer padding reserves room).
- RoundedRectangle(cornerRadius: self.layout.cornerRadius)
- .fill(Color.black)
- .shadow(
- color: Color.black.opacity(self.isPillSize ? 0.32 : 0),
+ FluidOverlaySurfaceBase(
+ cornerRadius: self.layout.cornerRadius,
+ shadow: .init(
+ opacity: self.isPillSize ? 0.32 : 0,
radius: self.isPillSize ? PillShadowMetrics.radius : 0,
- x: 0,
y: self.isPillSize ? PillShadowMetrics.yOffset : 0
)
+ )
if self.isPillSize {
// Glossy border: a bright highlight that slowly rotates around the edge.
// Paused under reduce-motion to avoid continuous redraws on low-resource Macs.
if self.reduceMotion || !self.contentState.isBottomOverlayPresented {
- RoundedRectangle(cornerRadius: self.layout.cornerRadius)
- .strokeBorder(
- AngularGradient(
- gradient: Gradient(stops: [
- .init(color: .white.opacity(0.06), location: 0.00),
- .init(color: .white.opacity(0.55), location: 0.13),
- .init(color: .white.opacity(0.10), location: 0.30),
- .init(color: .white.opacity(0.03), location: 0.55),
- .init(color: .white.opacity(0.22), location: 0.80),
- .init(color: .white.opacity(0.06), location: 1.00),
- ]),
- center: .center,
- angle: .degrees(0)
- ),
- lineWidth: 1.2
- )
+ FluidOverlayBorder(
+ cornerRadius: self.layout.cornerRadius,
+ style: .staticAngular(angle: .degrees(0), lineWidth: 1.2)
+ )
} else {
TimelineView(.animation(minimumInterval: 1.0 / 30.0)) { timeline in
let seconds = max(
@@ -3390,38 +3378,22 @@ struct BottomOverlayView: View {
timeline.date.timeIntervalSince(self.borderAnimationStartedAt ?? timeline.date)
)
let angle = (seconds.truncatingRemainder(dividingBy: 6.0) / 6.0) * 360.0
- RoundedRectangle(cornerRadius: self.layout.cornerRadius)
- .strokeBorder(
- AngularGradient(
- gradient: Gradient(stops: [
- .init(color: .white.opacity(0.06), location: 0.00),
- .init(color: .white.opacity(0.55), location: 0.13),
- .init(color: .white.opacity(0.10), location: 0.30),
- .init(color: .white.opacity(0.03), location: 0.55),
- .init(color: .white.opacity(0.22), location: 0.80),
- .init(color: .white.opacity(0.06), location: 1.00),
- ]),
- center: .center,
- angle: .degrees(angle)
- ),
- lineWidth: 1.2
- )
+ FluidOverlayBorder(
+ cornerRadius: self.layout.cornerRadius,
+ style: .staticAngular(angle: .degrees(angle), lineWidth: 1.2)
+ )
}
}
} else {
// Inner border
- RoundedRectangle(cornerRadius: self.layout.cornerRadius)
- .strokeBorder(
- LinearGradient(
- colors: [
- Color.white.opacity(self.overlayBorderTopOpacity),
- Color.white.opacity(self.overlayBorderBottomOpacity),
- ],
- startPoint: .top,
- endPoint: .bottom
- ),
+ FluidOverlayBorder(
+ cornerRadius: self.layout.cornerRadius,
+ style: .linear(
+ topOpacity: self.overlayBorderTopOpacity,
+ bottomOpacity: self.overlayBorderBottomOpacity,
lineWidth: self.overlayBorderLineWidth
)
+ )
}
}
)
@@ -3626,13 +3598,21 @@ struct BottomWaveformView: View {
var body: some View {
ZStack {
- self.barsView
- .foregroundStyle(self.barFillColor)
+ self.barsView(
+ color: self.barFillColor,
+ glowColor: self.color.opacity(self.isReleaseAnimationActive ? 0 : self.currentGlowIntensity),
+ glowRadius: self.isReleaseAnimationActive ? 0 : self.currentGlowRadius
+ )
+ .foregroundStyle(self.barFillColor)
if self.isProcessingVisualActive {
CompositorShimmerSweep(duration: 1.05, peakOpacity: 0.9)
.mask {
- self.barsView
+ self.barsView(
+ color: .white,
+ glowColor: .clear,
+ glowRadius: 0
+ )
}
.shadow(color: .white.opacity(0.28), radius: 2.5, x: 0, y: 0)
}
@@ -3680,19 +3660,16 @@ struct BottomWaveformView: View {
}
}
- private var barsView: some View {
- HStack(spacing: self.barSpacing) {
- ForEach(0..<self.barCount, id: \.self) { index in
- RoundedRectangle(cornerRadius: self.barWidth / 2)
- .frame(width: self.barWidth, height: self.displayHeight(at: index))
- .shadow(
- color: self.color.opacity(self.isReleaseAnimationActive ? 0 : self.currentGlowIntensity),
- radius: self.isReleaseAnimationActive ? 0 : self.currentGlowRadius,
- x: 0,
- y: 0
- )
- }
- }
+ private func barsView(color: Color, glowColor: Color, glowRadius: CGFloat) -> some View {
+ FluidOverlayLevelBars(
+ heights: (0..<self.barCount).map { self.displayHeight(at: $0) },
+ width: self.barWidth,
+ spacing: self.barSpacing,
+ cornerRadius: self.barWidth / 2,
+ color: color,
+ glowColor: glowColor,
+ glowRadius: glowRadius
+ )
}
private func displayHeight(at index: Int) -> CGFloat {
diff --git a/Tests/FluidDictationIntegrationTests/AudioTopologyDiagnosticsTests.swift b/Tests/FluidDictationIntegrationTests/AudioTopologyDiagnosticsTests.swift
new file mode 100644
index 00000000..d3b6bad3
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/AudioTopologyDiagnosticsTests.swift
@@ -0,0 +1,288 @@
+@testable import FluidVoice_Debug
+import CoreAudio
+import XCTest
+
+final class AudioTopologyDiagnosticsTests: XCTestCase {
+ override func setUp() {
+ super.setUp()
+ fv_audio_topology_trace_reset()
+ fv_audio_topology_trace_set_enabled(true)
+ }
+
+ override func tearDown() {
+ fv_audio_topology_trace_reset()
+ super.tearDown()
+ }
+
+ func testDisabledRingDoesNotReserveSequence() {
+ fv_audio_topology_trace_set_enabled(false)
+ let sequence = Self.record(.callback, objectID: 41)
+ XCTAssertEqual(sequence, 0)
+ XCTAssertEqual(fv_audio_topology_trace_latest_sequence(), 0)
+ }
+
+ func testRingPublishesMonotonicEventsInOrder() {
+ let first = Self.record(.listenerRemoveBegin, objectID: 71)
+ let second = Self.record(.listenerRemoveEnd, objectID: 71, status: noErr)
+
+ let snapshot = Self.snapshot()
+ XCTAssertEqual(first, 1)
+ XCTAssertEqual(second, 2)
+ XCTAssertEqual(snapshot.latest, 2)
+ XCTAssertEqual(snapshot.events.map(\.sequence), [1, 2])
+ XCTAssertEqual(snapshot.events.map(\.objectID), [71, 71])
+ }
+
+ func testRingWrapRetainsNewestCapacityWithoutReordering() {
+ let capacity = Int(fv_audio_topology_trace_capacity())
+ for index in 0..<(capacity + 17) {
+ _ = Self.record(.callback, objectID: AudioObjectID(index + 1))
+ }
+
+ let snapshot = Self.snapshot()
+ XCTAssertEqual(snapshot.events.count, capacity)
+ XCTAssertEqual(snapshot.events.first?.sequence, 18)
+ XCTAssertEqual(snapshot.events.last?.sequence, UInt64(capacity + 17))
+ XCTAssertEqual(snapshot.events.map(\.sequence), snapshot.events.map(\.sequence).sorted())
+ }
+
+ func testUnmatchedBeginSurvivesSnapshotAndClassifiesPhaseOpen() throws {
+ _ = Self.record(.listenerRemoveBegin, objectID: 99)
+ let snapshot = Self.snapshot()
+
+ XCTAssertEqual(snapshot.events.count, 1)
+ XCTAssertTrue(AudioTopologyDiagnostics.hasOpenTopologyPhase(snapshot.events))
+ let line = AudioTopologyDiagnostics.jsonLine(for: try XCTUnwrap(snapshot.events.first))
+ let object = try XCTUnwrap(
+ JSONSerialization.jsonObject(with: Data(line)) as? [String: Any]
+ )
+ XCTAssertEqual(object["event"] as? String, "listenerRemoveBegin")
+ XCTAssertEqual((object["object_id"] as? NSNumber)?.uint32Value, 99)
+ XCTAssertNil(object["device_name"])
+ XCTAssertNil(object["device_uid"])
+ XCTAssertNil(object["meeting_title"])
+ }
+
+ func testEveryBlockingBoundaryClassifiesAsOpenUntilItsMatchingEnd() {
+ let pairs: [(AudioTopologyTraceEvent, AudioTopologyTraceEvent)] = [
+ (.enumerationBegin, .enumerationEnd),
+ (.replaceBegin, .replaceEnd),
+ (.listenerAddBegin, .listenerAddEnd),
+ (.listenerRemoveBegin, .listenerRemoveEnd),
+ (.halQueryBegin, .halQueryEnd),
+ (.vpioEnableBegin, .vpioEnableEnd),
+ (.audioUnitBindBegin, .audioUnitBindEnd),
+ (.enginePrepareBegin, .enginePrepareEnd),
+ (.engineStartBegin, .engineStartEnd),
+ (.engineStopBegin, .engineStopEnd),
+ (.avfDiscoveryBegin, .avfDiscoveryEnd),
+ (.avfDefaultBegin, .avfDefaultEnd),
+ (.avfAuthorizationBegin, .avfAuthorizationEnd),
+ (.recoveryBegin, .recoveryEnd),
+ (.phaseBegin, .phaseEnd),
+ (.probeCycleBegin, .probeCycleEnd),
+ ]
+
+ for (begin, end) in pairs {
+ fv_audio_topology_trace_reset()
+ fv_audio_topology_trace_set_enabled(true)
+ _ = Self.record(begin, objectID: 17)
+ XCTAssertTrue(AudioTopologyDiagnostics.hasOpenTopologyPhase(Self.snapshot().events), "\(begin)")
+ _ = Self.record(end, objectID: 17)
+ XCTAssertFalse(AudioTopologyDiagnostics.hasOpenTopologyPhase(Self.snapshot().events), "\(end)")
+ }
+ }
+
+ func testRecoveryCancelCannotCloseAnUnrelatedPhase() {
+ _ = Self.record(.phaseBegin, objectID: 17)
+ _ = Self.record(.recoveryCancel, objectID: 17)
+ XCTAssertTrue(AudioTopologyDiagnostics.hasOpenTopologyPhase(Self.snapshot().events))
+ }
+
+ func testClockAnchorContainsBothTimeDomains() throws {
+ let line = AudioTopologyDiagnostics.clockAnchorLine(
+ continuousTime: 123,
+ wallNanoseconds: 456,
+ pid: 789
+ )
+ let object = try XCTUnwrap(
+ JSONSerialization.jsonObject(with: Data(line.utf8)) as? [String: Any]
+ )
+ XCTAssertEqual((object["continuous_time"] as? NSNumber)?.uint64Value, 123)
+ XCTAssertEqual((object["wall_unix_ns"] as? NSNumber)?.uint64Value, 456)
+ XCTAssertEqual((object["pid"] as? NSNumber)?.int32Value, 789)
+ }
+
+ func testConcurrentProducersAndSnapshotsRemainOrdered() {
+ DispatchQueue.concurrentPerform(iterations: 1_000) { index in
+ _ = Self.record(.callback, objectID: AudioObjectID(index + 1))
+ if index.isMultiple(of: 17) { _ = Self.snapshot() }
+ }
+ let snapshot = Self.snapshot()
+ XCTAssertEqual(snapshot.latest, 1_000)
+ XCTAssertEqual(snapshot.events.map(\.sequence), snapshot.events.map(\.sequence).sorted())
+ XCTAssertEqual(Set(snapshot.events.map(\.sequence)).count, snapshot.events.count)
+ }
+
+ func testJSONSchemaContainsOnlyPrivacyAllowlistedKeys() throws {
+ _ = Self.record(.topologySnapshot, objectID: 123)
+ let event = try XCTUnwrap(Self.snapshot().events.first)
+ let object = try XCTUnwrap(
+ JSONSerialization.jsonObject(
+ with: Data(AudioTopologyDiagnostics.jsonLine(for: event))
+ ) as? [String: Any]
+ )
+ XCTAssertTrue(Set(object.keys).isSubset(of: AudioTopologyDiagnostics.schemaKeys))
+ }
+
+ func testStallClassificationAlwaysRecordsDeadHeartbeat() {
+ XCTAssertEqual(
+ AudioTopologyStallClassification.classify(
+ heartbeatAgeSeconds: nil,
+ thresholdSeconds: 2,
+ topologyPhaseOpen: false
+ ),
+ .heartbeatMissing
+ )
+ XCTAssertEqual(
+ AudioTopologyStallClassification.classify(
+ heartbeatAgeSeconds: 1.9,
+ thresholdSeconds: 2,
+ topologyPhaseOpen: true
+ ),
+ .heartbeatHealthy
+ )
+ XCTAssertEqual(
+ AudioTopologyStallClassification.classify(
+ heartbeatAgeSeconds: 2,
+ thresholdSeconds: 2,
+ topologyPhaseOpen: true
+ ),
+ .heartbeatStalledPhaseOpen
+ )
+ XCTAssertEqual(
+ AudioTopologyStallClassification.classify(
+ heartbeatAgeSeconds: 2,
+ thresholdSeconds: 2,
+ topologyPhaseOpen: false
+ ),
+ .heartbeatStalledPhaseClosed
+ )
+ }
+
+ func testConfigurationParsingIsBoundedAndOptIn() {
+ let temporary = URL(fileURLWithPath: "/tmp/fv-audio-topology-tests", isDirectory: true)
+ XCTAssertEqual(
+ AudioTopologyDiagnosticsConfiguration.resolve(
+ environment: [:],
+ temporaryDirectory: temporary
+ ),
+ .init(enabled: false, outputDirectory: temporary, stallThresholdSeconds: 2)
+ )
+ XCTAssertEqual(
+ AudioTopologyDiagnosticsConfiguration.resolve(
+ environment: [
+ AudioTopologyDiagnosticsConfiguration.enabledKey: "1",
+ AudioTopologyDiagnosticsConfiguration.outputDirectoryKey: "/tmp/custom-trace",
+ AudioTopologyDiagnosticsConfiguration.stallThresholdKey: "0.1",
+ ],
+ temporaryDirectory: temporary
+ ),
+ .init(
+ enabled: true,
+ outputDirectory: URL(fileURLWithPath: "/tmp/custom-trace", isDirectory: true),
+ stallThresholdSeconds: 0.5
+ )
+ )
+ }
+
+ func testTransientInputIsolationExcludesOnlyAggregateVirtualAndUnknownTransports() {
+ XCTAssertFalse(
+ InputLivenessLedgerIsolationPolicy.permitsListenerForTransientIsolation(
+ transportType: kAudioDeviceTransportTypeAggregate
+ )
+ )
+ XCTAssertFalse(
+ InputLivenessLedgerIsolationPolicy.permitsListenerForTransientIsolation(
+ transportType: kAudioDeviceTransportTypeVirtual
+ )
+ )
+ XCTAssertFalse(
+ InputLivenessLedgerIsolationPolicy.permitsListenerForTransientIsolation(
+ transportType: kAudioDeviceTransportTypeUnknown
+ )
+ )
+
+ for persistentTransport in [
+ kAudioDeviceTransportTypeBuiltIn,
+ kAudioDeviceTransportTypeUSB,
+ kAudioDeviceTransportTypeBluetooth,
+ kAudioDeviceTransportTypeBluetoothLE,
+ kAudioDeviceTransportTypePCI,
+ kAudioDeviceTransportTypeDisplayPort,
+ kAudioDeviceTransportTypeHDMI,
+ ] {
+ XCTAssertTrue(
+ InputLivenessLedgerIsolationPolicy.permitsListenerForTransientIsolation(
+ transportType: persistentTransport
+ ),
+ "Expected persistent transport \(persistentTransport) to retain liveness monitoring"
+ )
+ }
+ }
+
+ func testAggregateInputLivenessLedgerPolicyExcludesOnlyAggregateTransport() {
+ XCTAssertFalse(
+ AggregateInputLivenessLedgerPolicy.permitsBroadLedgerMembership(
+ transportType: kAudioDeviceTransportTypeAggregate
+ )
+ )
+
+ for retainedTransport in [
+ kAudioDeviceTransportTypeVirtual,
+ kAudioDeviceTransportTypeUnknown,
+ kAudioDeviceTransportTypeBuiltIn,
+ kAudioDeviceTransportTypeUSB,
+ kAudioDeviceTransportTypeBluetooth,
+ kAudioDeviceTransportTypeBluetoothLE,
+ kAudioDeviceTransportTypePCI,
+ kAudioDeviceTransportTypeDisplayPort,
+ kAudioDeviceTransportTypeHDMI,
+ ] {
+ XCTAssertTrue(
+ AggregateInputLivenessLedgerPolicy.permitsBroadLedgerMembership(
+ transportType: retainedTransport
+ ),
+ "Expected non-aggregate transport \(retainedTransport) to retain liveness monitoring"
+ )
+ }
+ }
+
+ @discardableResult
+ private static func record(
+ _ event: AudioTopologyTraceEvent,
+ objectID: AudioObjectID,
+ status: OSStatus = AudioTopologyDiagnostics.noStatus
+ ) -> UInt64 {
+ fv_audio_topology_trace_record(
+ event.rawValue,
+ AudioTopologyTraceOwner.audioHardwareObserver.rawValue,
+ objectID,
+ kAudioDevicePropertyDeviceIsAlive,
+ kAudioObjectPropertyScopeGlobal,
+ kAudioObjectPropertyElementMain,
+ AudioTopologyTraceQueueRole.mainControl.rawValue,
+ AudioTopologyTracePhase.listener.rawValue,
+ AudioTopologyTraceTransport.unknown.rawValue,
+ status,
+ 7
+ )
+ }
+
+ private static func snapshot(after sequence: UInt64 = 0) -> (
+ events: [FVAudioTopologyTraceEvent],
+ latest: UInt64
+ ) {
+ AudioTopologyDiagnostics.snapshot(after: sequence)
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/MeetingAutoDetectorTests.swift b/Tests/FluidDictationIntegrationTests/MeetingAutoDetectorTests.swift
new file mode 100644
index 00000000..2653dd7d
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/MeetingAutoDetectorTests.swift
@@ -0,0 +1,855 @@
+@testable import FluidVoice_Debug
+import Foundation
+import XCTest
+
+// MARK: - Fakes (protocols only — no CoreAudio/AX/NSWorkspace)
+
+@MainActor
+private final class FakeClock: MeetingClockProviding {
+ var current: Date
+ init(_ date: Date = Date(timeIntervalSince1970: 1_700_000_000)) { self.current = date }
+ func now() -> Date { self.current }
+}
+
+@MainActor
+private final class FakeWorkspaceEvents: WorkspaceEventsProviding {
+ var onEvent: ((WorkspaceEvent) -> Void)?
+ func start(isRegistryApp: @escaping (String) -> Bool, onBackfill: @escaping ([WorkspaceEvent]) -> Void) {}
+ func stop() {}
+}
+
+@MainActor
+private final class FakeMicActivity: MicActivitySignalProviding {
+ var onEdge: ((MicActivityEdge) -> Void)?
+ func start() {}
+ func stop() {}
+}
+
+@MainActor
+private final class FakeAudioProcessActivity: AudioProcessActivityProviding {
+ var activeBundleIdentifiers: Set<String> = []
+
+ func isAudioActive(forBundleIdentifiers bundleIdentifiers: Set<String>) -> Bool {
+ !self.activeBundleIdentifiers.isDisjoint(with: bundleIdentifiers)
+ }
+}
+
+@MainActor
+private final class FakeWindowSnapshotProvider: WindowSnapshotProviding {
+ var axTitles: [String] = []
+ func snapshot(interestPIDs: Set<Int32>) -> [WindowSnapshot] { [] }
+ func titles(processID: Int32) async -> [String] { self.axTitles }
+}
+
+@MainActor
+private final class FakeBrowserTabReader: BrowserTabReading {
+ func frontmostTabURL(bundleIdentifier: String, processID: Int32) async -> BrowserTabURL? { nil }
+}
+
+@MainActor
+private final class FakeActivityGate: DetectionActivityGate {
+ var isIdle = true
+ var preflightResult = true
+ func preflightPasses() -> Bool { self.preflightResult }
+}
+
+/// Plain reference box so the detector's enablement closures don't need to capture `self` while
+/// `DetectorHarness` is still mid-initialization.
+@MainActor
+private final class ToggleFlags {
+ var nativeEnabled = true
+ var browserEnabled = true
+}
+
+@MainActor
+private final class DetectorHarness {
+ let clock = FakeClock()
+ let gate = FakeActivityGate()
+ let flags = ToggleFlags()
+ let audioProcessActivity = FakeAudioProcessActivity()
+ let windowProvider = FakeWindowSnapshotProvider()
+ var prompts: [MeetingAutoDetector.PromptRequest] = []
+ var nudges = 0
+ var invalidated: [UUID] = []
+ let detector: MeetingAutoDetector
+
+ var nativeEnabled: Bool {
+ get { self.flags.nativeEnabled }
+ set { self.flags.nativeEnabled = newValue }
+ }
+
+ var browserEnabled: Bool {
+ get { self.flags.browserEnabled }
+ set { self.flags.browserEnabled = newValue }
+ }
+
+ init() {
+ let flags = self.flags
+ self.detector = MeetingAutoDetector(
+ workspaceEvents: FakeWorkspaceEvents(),
+ micActivity: FakeMicActivity(),
+ audioProcessActivity: self.audioProcessActivity,
+ windowSnapshotProvider: self.windowProvider,
+ browserTabReader: FakeBrowserTabReader(),
+ activityGate: self.gate,
+ clock: self.clock,
+ isNativeDetectionEnabled: { flags.nativeEnabled },
+ isBrowserDetectionEnabled: { flags.browserEnabled }
+ )
+ self.detector.onPromptRequested = { [weak self] request in self?.prompts.append(request) }
+ self.detector.onStillRecordingNudge = { [weak self] in self?.nudges += 1 }
+ self.detector.onEpisodeInvalidated = { [weak self] episodeID in self?.invalidated.append(episodeID) }
+ }
+
+ func advance(_ seconds: TimeInterval) {
+ self.clock.current.addTimeInterval(seconds)
+ }
+
+ /// Arms + fronts a native app, then confirms it with a matching window and a coincident mic edge.
+ @discardableResult
+ func confirmZoom(pid: Int32 = 100) -> UUID? {
+ self.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "us.zoom.xos", processID: pid), at: self.clock.now())
+ self.detector.handleWindowSnapshot(
+ [.init(processID: pid, windowID: 900, title: "Zoom Meeting", layer: 0)],
+ at: self.clock.now()
+ )
+ self.detector.handleMicEdge(.init(isActive: true), at: self.clock.now())
+ return self.prompts.last?.episodeID
+ }
+}
+
+@MainActor
+final class MeetingAutoDetectorTests: XCTestCase {
+ // MARK: Prompt suppression
+
+ func testPromptSuppressionAllowsDetectedMeetingAppFullScreen() {
+ let reason = MeetingDetectionPromptController.suppressionReason(
+ frontmostBundleIdentifier: "us.zoom.xos",
+ isFrontmostFullScreen: true,
+ isDictationOverlayPresented: false,
+ requestBundleIdentifier: "us.zoom.xos"
+ )
+ XCTAssertNil(reason)
+ }
+
+ func testPromptSuppressionBlocksDifferentFullScreenAppAndDictationOverlay() {
+ let fullScreenReason = MeetingDetectionPromptController.suppressionReason(
+ frontmostBundleIdentifier: "com.apple.iWork.Keynote",
+ isFrontmostFullScreen: true,
+ isDictationOverlayPresented: false,
+ requestBundleIdentifier: "us.zoom.xos"
+ )
+ XCTAssertEqual(fullScreenReason, .fullscreenOtherApp)
+
+ let overlayReason = MeetingDetectionPromptController.suppressionReason(
+ frontmostBundleIdentifier: "us.zoom.xos",
+ isFrontmostFullScreen: true,
+ isDictationOverlayPresented: true,
+ requestBundleIdentifier: "us.zoom.xos"
+ )
+ XCTAssertEqual(overlayReason, .dictationOverlay)
+ }
+
+ func testPromptAutoDismissRemainingTimeClampsElapsedTime() {
+ XCTAssertEqual(MeetingDetectionPromptController.remainingAutoDismissSeconds(20, after: 7.5), 12.5)
+ XCTAssertEqual(MeetingDetectionPromptController.remainingAutoDismissSeconds(2, after: 4), 0)
+ XCTAssertEqual(MeetingDetectionPromptController.remainingAutoDismissSeconds(2, after: -1), 2)
+ }
+
+ func testPromptDefaultsToTopCenterOfVisibleFrame() {
+ let visibleFrame = NSRect(x: 100, y: 50, width: 1_200, height: 800)
+ let frame = MeetingDetectionPromptController.defaultFrame(
+ panelSize: MeetingDetectionPromptController.panelSize,
+ visibleFrame: visibleFrame
+ )
+
+ XCTAssertEqual(frame.midX, visibleFrame.midX)
+ XCTAssertEqual(frame.maxY, visibleFrame.maxY - 12)
+ XCTAssertEqual(frame.size, MeetingDetectionPromptController.panelSize)
+ }
+
+ func testSuppressedReminderRetriesThenTimesOutWithinBudget() {
+ XCTAssertEqual(
+ MeetingDetectionPromptController.reminderPresentationDecision(remainingBudget: 20, isSuppressed: false),
+ .present
+ )
+ XCTAssertEqual(
+ MeetingDetectionPromptController.reminderPresentationDecision(remainingBudget: 20, isSuppressed: true),
+ .retryAfter(MeetingDetectionPromptController.suppressionRetryInterval)
+ )
+ XCTAssertEqual(
+ MeetingDetectionPromptController.reminderPresentationDecision(remainingBudget: 0.2, isSuppressed: true),
+ .retryAfter(0.2)
+ )
+ XCTAssertEqual(
+ MeetingDetectionPromptController.reminderPresentationDecision(remainingBudget: 0, isSuppressed: true),
+ .timeout
+ )
+ XCTAssertEqual(
+ MeetingDetectionPromptController.reminderPresentationDecision(remainingBudget: 0, isSuppressed: false),
+ .timeout
+ )
+ }
+
+ func testReplacingPromptTimesOutThePreviousEpisodeOnly() {
+ let first = UUID()
+ let second = UUID()
+ XCTAssertEqual(
+ MeetingDetectionPromptController.episodeToTimeoutOnReplacement(existing: first, incoming: second),
+ first
+ )
+ XCTAssertNil(MeetingDetectionPromptController.episodeToTimeoutOnReplacement(existing: first, incoming: first))
+ XCTAssertNil(MeetingDetectionPromptController.episodeToTimeoutOnReplacement(existing: nil, incoming: second))
+ }
+
+ func testCheapSuppressionDecisionShortCircuitsAX() {
+ XCTAssertEqual(
+ MeetingDetectionPromptController.cheapSuppressionDecision(
+ frontmostBundleIdentifier: "us.zoom.xos",
+ frontmostProcessIdentifier: 100,
+ isDictationOverlayPresented: true,
+ requestBundleIdentifier: "us.zoom.xos"
+ ),
+ .suppressed(.dictationOverlay)
+ )
+ XCTAssertEqual(
+ MeetingDetectionPromptController.cheapSuppressionDecision(
+ frontmostBundleIdentifier: "us.zoom.xos",
+ frontmostProcessIdentifier: 100,
+ isDictationOverlayPresented: false,
+ requestBundleIdentifier: "us.zoom.xos"
+ ),
+ .presentNow
+ )
+ XCTAssertEqual(
+ MeetingDetectionPromptController.cheapSuppressionDecision(
+ frontmostBundleIdentifier: "com.apple.iWork.Keynote",
+ frontmostProcessIdentifier: 200,
+ isDictationOverlayPresented: false,
+ requestBundleIdentifier: "us.zoom.xos"
+ ),
+ .queryFullscreen(200)
+ )
+ XCTAssertEqual(
+ MeetingDetectionPromptController.cheapSuppressionDecision(
+ frontmostBundleIdentifier: nil,
+ frontmostProcessIdentifier: nil,
+ isDictationOverlayPresented: false,
+ requestBundleIdentifier: "us.zoom.xos"
+ ),
+ .presentNow
+ )
+ }
+
+ func testSilentInvalidationOnlyMatchesVisibleOrPendingPrompt() {
+ let visible = UUID()
+ let pending = UUID()
+ let other = UUID()
+ XCTAssertTrue(
+ MeetingDetectionPromptController.shouldSilentlyInvalidatePrompt(
+ episodeID: visible,
+ visibleEpisodeID: visible,
+ pendingEpisodeID: pending
+ )
+ )
+ XCTAssertTrue(
+ MeetingDetectionPromptController.shouldSilentlyInvalidatePrompt(
+ episodeID: pending,
+ visibleEpisodeID: visible,
+ pendingEpisodeID: pending
+ )
+ )
+ XCTAssertFalse(
+ MeetingDetectionPromptController.shouldSilentlyInvalidatePrompt(
+ episodeID: other,
+ visibleEpisodeID: visible,
+ pendingEpisodeID: pending
+ )
+ )
+ }
+
+ func testStartErrorMessageSurfacesCaptureAndPreflightFailures() {
+ XCTAssertEqual(
+ MeetingDetectionPromptController.startErrorMessage(
+ from: MeetingCaptureError.applicationUnavailable("us.zoom.xos"),
+ appDisplayName: "Zoom"
+ ),
+ "Zoom is no longer available to record."
+ )
+ XCTAssertEqual(
+ MeetingDetectionPromptController.startErrorMessage(
+ from: MeetingAutoDetector.StartError.cannotStart,
+ appDisplayName: "Zoom"
+ ),
+ "Can't start recording right now."
+ )
+ XCTAssertEqual(
+ MeetingDetectionPromptController.startErrorMessage(
+ from: MeetingCaptureError.microphonePermissionDenied,
+ appDisplayName: "Zoom"
+ ),
+ "Microphone permission is required to record this meeting."
+ )
+ }
+
+ func testCaptureTargetFailsClosedWhenPreferredAppIsRequiredAndMissing() {
+ let chrome = MeetingApplicationIdentity(bundleIdentifier: "com.google.Chrome", displayName: "Chrome")
+ let zoom = MeetingApplicationIdentity(bundleIdentifier: "us.zoom.xos", displayName: "Zoom")
+
+ XCTAssertEqual(
+ try MeetingCaptureSourceCatalog.resolveApplication(
+ from: [chrome, zoom],
+ preferredBundleIdentifier: "us.zoom.xos",
+ requirePreferredApplication: true
+ ).bundleIdentifier,
+ "us.zoom.xos"
+ )
+
+ XCTAssertThrowsError(
+ try MeetingCaptureSourceCatalog.resolveApplication(
+ from: [chrome],
+ preferredBundleIdentifier: "us.zoom.xos",
+ requirePreferredApplication: true
+ )
+ ) { error in
+ guard let captureError = error as? MeetingCaptureError,
+ case .applicationUnavailable("us.zoom.xos") = captureError
+ else {
+ return XCTFail("expected applicationUnavailable, got \(error)")
+ }
+ }
+
+ XCTAssertEqual(
+ try MeetingCaptureSourceCatalog.resolveApplication(
+ from: [chrome],
+ preferredBundleIdentifier: "us.zoom.xos",
+ requirePreferredApplication: false
+ ).bundleIdentifier,
+ "com.google.Chrome",
+ "manual/default setup may still fall back when the preferred app is absent"
+ )
+
+ XCTAssertEqual(
+ try MeetingCaptureSourceCatalog.resolveApplication(
+ from: [chrome],
+ preferredBundleIdentifier: nil,
+ requirePreferredApplication: false
+ ).bundleIdentifier,
+ "com.google.Chrome"
+ )
+ }
+
+ // MARK: Coincidence window
+
+ func testParkedTabWithLateMicNeverPrompts() {
+ let h = DetectorHarness()
+ h.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "com.google.Chrome", processID: 1), at: h.clock.now())
+ h.detector.handleBrowserTabURL(.init(host: "meet.google.com", path: "/abc-defg-hij"), pid: 1, bundleIdentifier: "com.google.Chrome", at: h.clock.now())
+
+ h.advance(40) // evidence is now stale relative to the coincidence window
+ h.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "com.google.Chrome", processID: 1), at: h.clock.now())
+ h.detector.handleMicEdge(.init(isActive: true), at: h.clock.now())
+
+ XCTAssertTrue(h.prompts.isEmpty, "evidence older than the 30s coincidence window must not confirm")
+ }
+
+ // MARK: Fail-closed on unreadable AXURL
+
+ func testUnreadableAXURLNeverPrompts() {
+ let h = DetectorHarness()
+ h.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "com.google.Chrome", processID: 1), at: h.clock.now())
+ h.detector.handleBrowserTabURL(nil, pid: 1, bundleIdentifier: "com.google.Chrome", at: h.clock.now())
+ h.detector.handleMicEdge(.init(isActive: true), at: h.clock.now())
+ XCTAssertTrue(h.prompts.isEmpty)
+ }
+
+ // MARK: YouTube-hostname never matches
+
+ func testYouTubeNeverMatchesInCallURL() {
+ XCTAssertFalse(MeetingInCallURLMatcher.isInCallURL(host: "www.youtube.com", path: "/watch"))
+ XCTAssertFalse(MeetingInCallURLMatcher.isInCallURL(host: "youtube.com", path: "/live/abc-defg-hij"))
+ }
+
+ // MARK: Tier-1 frontmost-at-edge gate
+
+ func testZoomConfirmsOnlyWhenFrontmostNearTheMicEdge() {
+ let h = DetectorHarness()
+ h.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "us.zoom.xos", processID: 5), at: h.clock.now())
+ h.detector.handleWindowSnapshot(
+ [.init(processID: 5, windowID: 42, title: "Zoom Meeting", layer: 0)],
+ at: h.clock.now()
+ )
+ h.advance(20) // beyond the 15s frontmost lead
+ h.detector.handleMicEdge(.init(isActive: true), at: h.clock.now())
+ XCTAssertTrue(h.prompts.isEmpty, "stale frontmost must not confirm")
+
+ let h2 = DetectorHarness()
+ XCTAssertNotNil(h2.confirmZoom(), "frontmost within the lead window must confirm")
+ }
+
+ func testZoomNonMeetingWindowTitlesNeverConfirm() {
+ for title in ["Zoom Workplace", "Zoom Client Healthcheck", ""] {
+ let h = DetectorHarness()
+ h.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "us.zoom.xos", processID: 5), at: h.clock.now())
+ h.detector.handleWindowSnapshot(
+ [.init(processID: 5, windowID: 42, title: title, layer: 0)],
+ at: h.clock.now()
+ )
+ h.detector.handleMicEdge(.init(isActive: true), at: h.clock.now())
+ XCTAssertTrue(h.prompts.isEmpty, "\(title) must not count as meeting evidence")
+ }
+ }
+
+ func testZoomTitleConfirmsWithAudioAndWindowEvidence() {
+ let h = DetectorHarness()
+ h.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "us.zoom.xos", processID: 5), at: h.clock.now())
+ h.detector.handleWindowSnapshot(
+ [.init(processID: 5, windowID: 42, title: "Zoom", layer: 0)],
+ at: h.clock.now()
+ )
+ h.detector.handleMicEdge(.init(isActive: true), at: h.clock.now())
+ XCTAssertEqual(h.prompts.count, 1)
+ }
+
+ func testProcessAudioConfirmsMutedZoomJoinWithoutDeviceMicEdge() {
+ let h = DetectorHarness()
+ h.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "us.zoom.xos", processID: 5), at: h.clock.now())
+ h.detector.handleWindowSnapshot(
+ [.init(processID: 5, windowID: 42, title: "Zoom", layer: 0)],
+ at: h.clock.now()
+ )
+ h.audioProcessActivity.activeBundleIdentifiers = ["us.zoom.caphost"]
+ h.detector.pollAudioProcessActivity(at: h.clock.now())
+ XCTAssertEqual(h.prompts.count, 1)
+ }
+
+ func testAudioEvidenceAloneNeverPromptsAndWindowEvidenceAloneNeverPrompts() {
+ let audioOnly = DetectorHarness()
+ audioOnly.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "us.zoom.xos", processID: 5), at: audioOnly.clock.now())
+ audioOnly.detector.handleAudioProcessActivity(true, pid: 5, at: audioOnly.clock.now())
+ XCTAssertTrue(audioOnly.prompts.isEmpty)
+
+ let windowOnly = DetectorHarness()
+ windowOnly.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "us.zoom.xos", processID: 5), at: windowOnly.clock.now())
+ windowOnly.detector.handleWindowSnapshot(
+ [.init(processID: 5, windowID: 42, title: "Zoom", layer: 0)],
+ at: windowOnly.clock.now()
+ )
+ XCTAssertTrue(windowOnly.prompts.isEmpty)
+ }
+
+ // MARK: Backfill arms only
+
+ func testBackfillAlonesNeverConfirms() {
+ let h = DetectorHarness()
+ h.detector.handleBackfill([.init(kind: .launched, bundleIdentifier: "us.zoom.xos", processID: 7)])
+ h.detector.handleWindowSnapshot(
+ [.init(processID: 7, windowID: 1, title: "Zoom Meeting", layer: 0)],
+ at: h.clock.now()
+ )
+ h.detector.handleMicEdge(.init(isActive: true), at: h.clock.now())
+ XCTAssertTrue(h.prompts.isEmpty, "backfill seeds no frontmost timestamp, so it can never confirm by itself")
+ }
+
+ // MARK: Episode dedup + back-to-back re-arm
+
+ func testDuplicateConfirmDoesNotReprompt() {
+ let h = DetectorHarness()
+ h.confirmZoom()
+ XCTAssertEqual(h.prompts.count, 1)
+ h.detector.handleMicEdge(.init(isActive: true), at: h.clock.now())
+ XCTAssertEqual(h.prompts.count, 1, "the same window key must not re-arm while still live")
+ }
+
+ func testBackToBackMeetingAfterReleaseRearmsTheSameWindow() {
+ let h = DetectorHarness()
+ let firstEpisode = h.confirmZoom()
+ XCTAssertNotNil(firstEpisode)
+ h.detector.timeoutDismissed(episodeID: firstEpisode!)
+
+ // Window disappears; after grace + the 60s release window the episode is evicted.
+ h.detector.handleWindowSnapshot([], at: h.clock.now())
+ h.advance(70)
+ h.detector.tick(at: h.clock.now())
+
+ // A fresh meeting on the same window number re-arms.
+ h.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "us.zoom.xos", processID: 100), at: h.clock.now())
+ h.detector.handleWindowSnapshot(
+ [.init(processID: 100, windowID: 900, title: "Zoom Meeting", layer: 0)],
+ at: h.clock.now()
+ )
+ h.detector.handleMicEdge(.init(isActive: true), at: h.clock.now())
+ XCTAssertEqual(h.prompts.count, 2, "a genuinely new meeting must re-arm after the old episode ends")
+ }
+
+ func testTeamsBackToBackRearmsViaMicReleaseDespitePersistentWindow() {
+ // Teams' main window never closes, so window loss can't end the episode — mic release must.
+ let h = DetectorHarness()
+ h.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "com.microsoft.teams2", processID: 300), at: h.clock.now())
+ h.detector.handleWindowSnapshot([.init(processID: 300, windowID: 950, title: nil, layer: 0)], at: h.clock.now())
+ h.detector.handleMicEdge(.init(isActive: true), at: h.clock.now())
+ XCTAssertEqual(h.prompts.count, 1)
+ h.detector.timeoutDismissed(episodeID: h.prompts[0].episodeID)
+
+ h.detector.handleMicEdge(.init(isActive: false), at: h.clock.now())
+ h.advance(70)
+ h.detector.tick(at: h.clock.now())
+
+ h.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "com.microsoft.teams2", processID: 300), at: h.clock.now())
+ h.detector.handleWindowSnapshot([.init(processID: 300, windowID: 950, title: nil, layer: 0)], at: h.clock.now())
+ h.detector.handleMicEdge(.init(isActive: true), at: h.clock.now())
+ XCTAssertEqual(h.prompts.count, 2, "a second Teams meeting after mic release must re-prompt even though the main window persisted")
+ }
+
+ func testProcessAudioInactiveForSixtySecondsEndsEpisodeAndReprompts() {
+ let h = DetectorHarness()
+ h.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "us.zoom.xos", processID: 100), at: h.clock.now())
+ h.detector.handleWindowSnapshot(
+ [.init(processID: 100, windowID: 900, title: "Zoom", layer: 0)],
+ at: h.clock.now()
+ )
+ h.detector.handleAudioProcessActivity(true, pid: 100, at: h.clock.now())
+ XCTAssertEqual(h.prompts.count, 1)
+ h.detector.timeoutDismissed(episodeID: h.prompts[0].episodeID)
+
+ h.detector.handleAudioProcessActivity(false, pid: 100, at: h.clock.now())
+ h.advance(70)
+ h.detector.tick(at: h.clock.now())
+
+ h.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "us.zoom.xos", processID: 100), at: h.clock.now())
+ h.detector.handleWindowSnapshot(
+ [.init(processID: 100, windowID: 900, title: "Zoom", layer: 0)],
+ at: h.clock.now()
+ )
+ h.detector.handleAudioProcessActivity(true, pid: 100, at: h.clock.now())
+ XCTAssertEqual(h.prompts.count, 2)
+ }
+
+ // MARK: Stop mid-call, no re-prompt
+
+ func testStoppingOurRecordingMidCallDoesNotReprompt() {
+ let h = DetectorHarness()
+ let episodeID = h.confirmZoom()!
+ XCTAssertTrue(h.detector.startTapped(episodeID: episodeID))
+
+ // The window is still there (the user is still in the call) — no eviction, no re-prompt.
+ h.detector.handleWindowSnapshot(
+ [.init(processID: 100, windowID: 900, title: "Zoom Meeting", layer: 0)],
+ at: h.clock.now()
+ )
+ h.advance(70)
+ h.detector.tick(at: h.clock.now())
+ h.detector.handleMicEdge(.init(isActive: true), at: h.clock.now())
+ XCTAssertEqual(h.prompts.count, 1, "stopping our own recording must not retire a still-live episode")
+ }
+
+ // MARK: Manual start consumes the episode
+
+ func testStartTappedIsSingleShot() {
+ let h = DetectorHarness()
+ let episodeID = h.confirmZoom()!
+ XCTAssertTrue(h.detector.startTapped(episodeID: episodeID))
+ XCTAssertFalse(h.detector.startTapped(episodeID: episodeID), "a second Start on the same episode must be a no-op")
+ }
+
+ func testStartTappedFailsWhenPreflightNoLongerPasses() {
+ let h = DetectorHarness()
+ let episodeID = h.confirmZoom()!
+ h.gate.preflightResult = false
+ XCTAssertFalse(h.detector.startTapped(episodeID: episodeID))
+ }
+
+ func testCanStartDoesNotConsumeEpisode() {
+ let h = DetectorHarness()
+ let episodeID = h.confirmZoom()!
+ XCTAssertTrue(h.detector.canStart(episodeID: episodeID))
+ XCTAssertTrue(h.detector.canStart(episodeID: episodeID), "canStart must not consume")
+ XCTAssertTrue(h.detector.startTapped(episodeID: episodeID))
+ XCTAssertFalse(h.detector.canStart(episodeID: episodeID))
+ }
+
+ func testAdoptStartedEpisodeSkipsPreflightAndStartTappedStaysSingleShot() {
+ let h = DetectorHarness()
+ let episodeID = h.confirmZoom()!
+ h.gate.preflightResult = false
+ XCTAssertFalse(h.detector.startTapped(episodeID: episodeID))
+ h.detector.adoptStartedEpisode(episodeID: episodeID)
+ XCTAssertFalse(h.detector.canStart(episodeID: episodeID))
+ XCTAssertFalse(h.detector.startTapped(episodeID: episodeID))
+ h.detector.adoptStartedEpisode(episodeID: episodeID)
+ }
+
+ func testAdoptStartedEpisodeAfterTimeoutOwnsTheEpisodeAndResetsDismissals() {
+ let h = DetectorHarness()
+ var suggested = false
+ h.detector.onSuggestDisablingAutoDetect = { suggested = true }
+
+ for pid: Int32 in [1, 2] {
+ let episodeID = h.confirmZoom(pid: pid)!
+ h.detector.dismissTapped(episodeID: episodeID, at: h.clock.now())
+ h.advance(3600)
+ }
+
+ let timedOut = h.confirmZoom(pid: 3)!
+ h.detector.timeoutDismissed(episodeID: timedOut)
+ XCTAssertFalse(h.detector.startTapped(episodeID: timedOut))
+ XCTAssertFalse(h.detector.canStart(episodeID: timedOut))
+ h.detector.adoptStartedEpisode(episodeID: timedOut)
+
+ h.detector.handleWindowSnapshot([], at: h.clock.now())
+ h.advance(65)
+ h.detector.tick(at: h.clock.now())
+ XCTAssertEqual(h.nudges, 1, "adopting after timeout must still arm the still-recording nudge")
+
+ let dismissedEpisode = h.confirmZoom(pid: 4)!
+ h.detector.dismissTapped(episodeID: dismissedEpisode, at: h.clock.now())
+ XCTAssertFalse(suggested, "adopting after timeout must still reset the rolling counter")
+ }
+
+ // MARK: Preflight gate silence
+
+ func testMissingScreenRecordingAtConfirmRequestsSetup() {
+ let h = DetectorHarness()
+ h.gate.preflightResult = false
+ h.confirmZoom()
+ XCTAssertEqual(h.prompts.count, 1)
+ XCTAssertEqual(h.prompts.first?.cta, .setup)
+ }
+
+ func testBusyEvidenceStaysSilentThenPromptsWhenIdle() {
+ let h = DetectorHarness()
+ h.gate.isIdle = false
+ h.confirmZoom()
+ XCTAssertTrue(h.prompts.isEmpty)
+ h.gate.isIdle = true
+ h.detector.handleWindowSnapshot(
+ [.init(processID: 100, windowID: 900, title: "Zoom Meeting", layer: 0)],
+ at: h.clock.now()
+ )
+ XCTAssertEqual(h.prompts.count, 1)
+ XCTAssertEqual(h.prompts.first?.cta, .record)
+ }
+
+ func testRedactedZoomUsesAXMeetingTitleEvenWhenWorkplaceComesFirst() async {
+ let h = DetectorHarness()
+ h.windowProvider.axTitles = ["Zoom Workplace", "Zoom Meeting"]
+ h.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "us.zoom.xos", processID: 100), at: h.clock.now())
+ h.detector.handleWindowSnapshot([.init(processID: 100, windowID: 900, title: nil, layer: 0)], at: h.clock.now())
+ h.detector.handleMicEdge(.init(isActive: true), at: h.clock.now())
+ await Task.yield()
+ XCTAssertEqual(h.prompts.count, 1)
+ XCTAssertEqual(h.prompts.first?.cta, .record)
+ }
+
+ func testRedactedZoomWithoutAXTitlesDedupesUnreadableHealth() async {
+ let h = DetectorHarness()
+ var health: [MeetingAutoDetector.Health] = []
+ h.detector.onHealthChanged = { health.append($0) }
+ h.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "us.zoom.xos", processID: 100), at: h.clock.now())
+ let redacted: [WindowSnapshot] = [.init(processID: 100, windowID: 900, title: nil, layer: 0)]
+ h.detector.handleWindowSnapshot(redacted, at: h.clock.now())
+ h.detector.handleWindowSnapshot(redacted, at: h.clock.now())
+ await Task.yield()
+ XCTAssertEqual(health, [.zoomWindowTitleUnreadable])
+ XCTAssertTrue(h.prompts.isEmpty)
+ }
+
+ func testRedactedZoomWithOnlyWorkplaceIsReadableButDoesNotPrompt() async {
+ let h = DetectorHarness()
+ h.windowProvider.axTitles = ["Zoom Workplace"]
+ var health: [MeetingAutoDetector.Health] = []
+ h.detector.onHealthChanged = { health.append($0) }
+ h.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "us.zoom.xos", processID: 100), at: h.clock.now())
+ h.detector.handleWindowSnapshot([.init(processID: 100, windowID: 900, title: nil, layer: 0)], at: h.clock.now())
+ await Task.yield()
+ XCTAssertEqual(health, [.ready])
+ XCTAssertTrue(h.prompts.isEmpty)
+ }
+
+ func testPrimaryActionSetupNeverRoutesToRecording() {
+ XCTAssertEqual(
+ MeetingDetectionPromptController.primaryAction(for: .setup),
+ .openSetup
+ )
+ XCTAssertEqual(
+ MeetingDetectionPromptController.primaryAction(for: .record),
+ .startRecording
+ )
+ }
+
+ func testTeamsNilWindowTitleStillPrompts() {
+ let h = DetectorHarness()
+ h.detector.handleWorkspaceEvent(
+ .init(kind: .activated, bundleIdentifier: "com.microsoft.teams2", processID: 100),
+ at: h.clock.now()
+ )
+ h.detector.handleWindowSnapshot(
+ [.init(processID: 100, windowID: 901, title: nil, layer: 0)],
+ at: h.clock.now()
+ )
+ h.detector.handleMicEdge(.init(isActive: true), at: h.clock.now())
+ XCTAssertEqual(h.prompts.count, 1)
+ XCTAssertEqual(h.prompts.first?.cta, .record)
+ }
+
+ // MARK: Dismissal suppression + rolling counter
+
+ func testExplicitDismissSuppressesTheBundleForThirtyMinutes() {
+ let h = DetectorHarness()
+ let firstEpisode = h.confirmZoom(pid: 1)!
+ h.detector.dismissTapped(episodeID: firstEpisode, at: h.clock.now())
+
+ h.detector.handleWindowSnapshot([], at: h.clock.now()) // window loss + eviction so the same window can re-arm
+ h.advance(70)
+ h.detector.tick(at: h.clock.now())
+
+ h.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "us.zoom.xos", processID: 1), at: h.clock.now())
+ h.detector.handleWindowSnapshot(
+ [.init(processID: 1, windowID: 900, title: "Zoom Meeting", layer: 0)],
+ at: h.clock.now()
+ )
+ h.detector.handleMicEdge(.init(isActive: true), at: h.clock.now())
+ XCTAssertEqual(h.prompts.count, 1, "the bundle stays suppressed for 30 minutes after an explicit dismiss")
+ }
+
+ func testTimeoutDismissDoesNotSuppressOrCount() {
+ let h = DetectorHarness()
+ let episodeID = h.confirmZoom()!
+ h.detector.timeoutDismissed(episodeID: episodeID)
+
+ h.detector.handleWindowSnapshot([], at: h.clock.now())
+ h.advance(70)
+ h.detector.tick(at: h.clock.now())
+
+ h.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "us.zoom.xos", processID: 100), at: h.clock.now())
+ h.detector.handleWindowSnapshot(
+ [.init(processID: 100, windowID: 900, title: "Zoom Meeting", layer: 0)],
+ at: h.clock.now()
+ )
+ h.detector.handleMicEdge(.init(isActive: true), at: h.clock.now())
+ XCTAssertEqual(h.prompts.count, 2, "a 20s auto-dismiss must not suppress the bundle")
+ }
+
+ func testThreeDismissalsWithinFourteenDaysSuggestsDisabling() {
+ let h = DetectorHarness()
+ var suggested = false
+ h.detector.onSuggestDisablingAutoDetect = { suggested = true }
+
+ for pid: Int32 in [1, 2, 3] {
+ let episodeID = h.confirmZoom(pid: pid)!
+ h.detector.dismissTapped(episodeID: episodeID, at: h.clock.now())
+ h.advance(3600)
+ }
+ XCTAssertTrue(suggested)
+ }
+
+ func testAcceptedStartResetsTheDismissalCounter() {
+ let h = DetectorHarness()
+ var suggested = false
+ h.detector.onSuggestDisablingAutoDetect = { suggested = true }
+
+ for pid: Int32 in [1, 2] {
+ let episodeID = h.confirmZoom(pid: pid)!
+ h.detector.dismissTapped(episodeID: episodeID, at: h.clock.now())
+ h.advance(3600)
+ }
+ let acceptedEpisode = h.confirmZoom(pid: 3)!
+ XCTAssertTrue(h.detector.startTapped(episodeID: acceptedEpisode))
+
+ let dismissedEpisode = h.confirmZoom(pid: 4)!
+ h.detector.dismissTapped(episodeID: dismissedEpisode, at: h.clock.now())
+ XCTAssertFalse(suggested, "an accepted Start must reset the rolling counter")
+ }
+
+ // MARK: Lock / sleep disarm
+
+ func testDisarmClearsAllTransientState() {
+ let h = DetectorHarness()
+ h.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "us.zoom.xos", processID: 9), at: h.clock.now())
+ h.detector.handleWindowSnapshot(
+ [.init(processID: 9, windowID: 1, title: "Zoom Meeting", layer: 0)],
+ at: h.clock.now()
+ )
+ h.detector.disarmAndClearTransientState()
+ h.detector.handleMicEdge(.init(isActive: true), at: h.clock.now())
+ XCTAssertTrue(h.prompts.isEmpty, "disarm must drop frontmost/window evidence so a later edge cannot confirm")
+ }
+
+ func testEvictingUnconsumedEpisodeInvalidatesAndConsumedDoesNot() {
+ let h = DetectorHarness()
+ let unconsumed = h.confirmZoom(pid: 1)!
+ let consumed = h.confirmZoom(pid: 2)!
+ XCTAssertTrue(h.detector.startTapped(episodeID: consumed))
+
+ h.detector.handleWindowSnapshot([], at: h.clock.now())
+ h.advance(70)
+ h.detector.tick(at: h.clock.now())
+ XCTAssertEqual(h.invalidated, [unconsumed])
+ }
+
+ func testDisarmInvalidatesUnconsumedEpisodesOnly() {
+ let h = DetectorHarness()
+ let unconsumed = h.confirmZoom(pid: 1)!
+ let consumed = h.confirmZoom(pid: 2)!
+ XCTAssertTrue(h.detector.startTapped(episodeID: consumed))
+
+ h.detector.disarmAndClearTransientState()
+ XCTAssertEqual(h.invalidated, [unconsumed])
+ }
+
+ // MARK: Still-recording nudge
+
+ func testStillRecordingNudgeFiresOnceAfterWindowGoneSixtySeconds() {
+ let h = DetectorHarness()
+ let episodeID = h.confirmZoom()!
+ XCTAssertTrue(h.detector.startTapped(episodeID: episodeID))
+
+ h.detector.handleWindowSnapshot([], at: h.clock.now())
+ h.advance(65)
+ h.detector.tick(at: h.clock.now())
+ XCTAssertEqual(h.nudges, 1)
+
+ h.detector.tick(at: h.clock.now())
+ XCTAssertEqual(h.nudges, 1, "the nudge fires once per session")
+ }
+
+ // MARK: Registry / URL matcher sanity
+
+ func testRegistryTierLookup() {
+ XCTAssertEqual(MeetingAppRegistry.tier(forBundleIdentifier: "us.zoom.xos"), .nativeTier1)
+ XCTAssertEqual(MeetingAppRegistry.tier(forBundleIdentifier: "com.google.Chrome"), .browserTier2)
+ XCTAssertEqual(MeetingAppRegistry.tier(forBundleIdentifier: "com.google.Chrome.app.abcdef"), .browserTier2)
+ XCTAssertNil(MeetingAppRegistry.tier(forBundleIdentifier: "com.tinyspeck.slackmacgap"))
+ XCTAssertNil(MeetingAppRegistry.tier(forBundleIdentifier: "com.apple.FaceTime"))
+ }
+
+ func testInCallURLMatcherAcceptsRoomsAndRejectsLandingPages() {
+ XCTAssertTrue(MeetingInCallURLMatcher.isInCallURL(host: "meet.google.com", path: "/abc-defg-hij"))
+ XCTAssertFalse(MeetingInCallURLMatcher.isInCallURL(host: "meet.google.com", path: "/"))
+ XCTAssertTrue(MeetingInCallURLMatcher.isInCallURL(host: "us04web.zoom.us", path: "/j/123456789"))
+ XCTAssertFalse(MeetingInCallURLMatcher.isInCallURL(host: "zoom.us", path: "/pricing"))
+ XCTAssertTrue(MeetingInCallURLMatcher.isInCallURL(host: "teams.microsoft.com", path: "/l/meetup-join/abc"))
+ XCTAssertTrue(MeetingInCallURLMatcher.isInCallURL(host: "whereby.com", path: "/my-room"))
+ XCTAssertFalse(MeetingInCallURLMatcher.isInCallURL(host: "whereby.com", path: "/pricing"))
+ XCTAssertTrue(MeetingInCallURLMatcher.isInCallURL(host: "meet.jit.si", path: "/SomeRoomName"))
+ }
+
+ // MARK: windowID preference in MeetingWindowSelector
+
+ func testWindowSelectorPrefersPreferredWindowIDWhenEligible() {
+ let candidates = [
+ MeetingWindowCandidate(windowID: 1, title: "Untitled", frame: CGRect(x: 0, y: 0, width: 400, height: 400), layer: 0, zOrderIndex: 0),
+ MeetingWindowCandidate(windowID: 2, title: "Small", frame: CGRect(x: 0, y: 0, width: 210, height: 110), layer: 0, zOrderIndex: 1),
+ ]
+ let selected = MeetingWindowSelector.selectWindow(from: candidates, preferredWindowID: 2)
+ XCTAssertEqual(selected?.windowID, 2, "the preferred window must win even though it ranks lower")
+ }
+
+ func testWindowSelectorFallsBackWhenPreferredWindowIsGone() {
+ let candidates = [
+ MeetingWindowCandidate(windowID: 1, title: "Untitled", frame: CGRect(x: 0, y: 0, width: 400, height: 400), layer: 0, zOrderIndex: 0),
+ ]
+ let selected = MeetingWindowSelector.selectWindow(from: candidates, preferredWindowID: 999)
+ XCTAssertEqual(selected?.windowID, 1)
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/MeetingOverlayModelsTests.swift b/Tests/FluidDictationIntegrationTests/MeetingOverlayModelsTests.swift
new file mode 100644
index 00000000..8fbf2323
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/MeetingOverlayModelsTests.swift
@@ -0,0 +1,258 @@
+@testable import FluidVoice_Debug
+import CoreGraphics
+import Foundation
+import XCTest
+
+final class MeetingOverlayGeometryTests: XCTestCase {
+ private let pill = MeetingOverlayPresentation.pill.visibleSize
+ private let captions = MeetingOverlayPresentation.captions.visibleSize
+ private let screen = CGRect(x: 100, y: 50, width: 1440, height: 900)
+
+ func testCanonicalPresentationVisibleSizes() {
+ XCTAssertEqual(MeetingOverlayPresentation.pill.visibleSize, CGSize(width: 84, height: 32))
+ XCTAssertEqual(MeetingOverlayPresentation.captions.visibleSize, CGSize(width: 340, height: 156))
+ XCTAssertEqual(MeetingOverlayPresentation.pill.toggled.visibleSize, CGSize(width: 340, height: 156))
+ XCTAssertEqual(MeetingOverlayPresentation.captions.toggled.visibleSize, CGSize(width: 84, height: 32))
+ }
+
+ func testCaptionsViewportAndFooterHeightsSumToCanvasHeight() {
+ XCTAssertEqual(
+ MeetingOverlayPresentation.captionsViewportHeight + MeetingOverlayPresentation.captionsFooterHeight,
+ MeetingOverlayPresentation.captions.visibleSize.height
+ )
+ XCTAssertEqual(MeetingOverlayPresentation.captionsViewportHeight, 121)
+ XCTAssertEqual(MeetingOverlayPresentation.captionsFooterHeight, 35)
+ }
+
+ func testCaptionsContentInsetsSumToViewportAndCanvasWidth() {
+ XCTAssertEqual(MeetingOverlayPresentation.captionsHorizontalInset, 16)
+ XCTAssertEqual(MeetingOverlayPresentation.captionsTopInset, 12)
+ XCTAssertEqual(MeetingOverlayPresentation.captionsBottomInset, 7)
+ XCTAssertEqual(
+ MeetingOverlayPresentation.captionsTopInset
+ + MeetingOverlayPresentation.captionsContentHeight
+ + MeetingOverlayPresentation.captionsBottomInset,
+ MeetingOverlayPresentation.captionsViewportHeight
+ )
+ XCTAssertEqual(
+ MeetingOverlayPresentation.captionsContentWidth
+ + (2 * MeetingOverlayPresentation.captionsHorizontalInset),
+ MeetingOverlayPresentation.captions.visibleSize.width
+ )
+ XCTAssertEqual(MeetingOverlayPresentation.captionsContentWidth, 308)
+ XCTAssertEqual(MeetingOverlayPresentation.captionsContentHeight, 102)
+ }
+
+ func testUnclampedLayoutVisibleSurfaceMatchesCanonicalPresentationSize() {
+ let padding = MeetingOverlayPadding.uniform(24)
+ for presentation in [MeetingOverlayPresentation.pill, .captions] {
+ let size = presentation.visibleSize
+ let layout = MeetingOverlayGeometry.layout(
+ anchor: MeetingOverlayVisibleAnchor(centerX: 820, bottomY: 114),
+ visibleSize: size,
+ padding: padding,
+ screenVisible: self.screen
+ )
+ XCTAssertEqual(layout.visibleSurfaceFrame.size, size)
+ XCTAssertEqual(
+ layout.panelFrame.size,
+ CGSize(
+ width: size.width + padding.left + padding.right,
+ height: size.height + padding.top + padding.bottom
+ )
+ )
+ }
+ }
+
+ func testPillSizeAtUnclampedAnchorUsesUniformPadding() {
+ let layout = MeetingOverlayGeometry.layout(
+ anchor: MeetingOverlayVisibleAnchor(centerX: 820, bottomY: 114),
+ visibleSize: self.pill,
+ padding: 16,
+ screenVisible: self.screen
+ )
+ XCTAssertEqual(layout.visibleSurfaceFrame, CGRect(x: 778, y: 114, width: 84, height: 32))
+ XCTAssertEqual(layout.panelFrame, CGRect(x: 762, y: 98, width: 116, height: 64))
+ XCTAssertTrue(self.screen.contains(layout.visibleSurfaceFrame))
+ }
+
+ func testCaptionsSizeUsesEdgeInsetsLikePadding() {
+ let padding = MeetingOverlayPadding(top: 4, left: 8, bottom: 12, right: 16)
+ let layout = MeetingOverlayGeometry.layout(
+ anchor: MeetingOverlayVisibleAnchor(centerX: 820, bottomY: 114),
+ visibleSize: self.captions,
+ padding: padding,
+ screenVisible: self.screen
+ )
+ XCTAssertEqual(layout.visibleSurfaceFrame, CGRect(x: 650, y: 114, width: 340, height: 156))
+ XCTAssertEqual(layout.panelFrame, CGRect(x: 642, y: 102, width: 364, height: 172))
+ XCTAssertTrue(self.screen.contains(layout.visibleSurfaceFrame))
+ }
+
+ func testVisibleSurfaceIsClampedOnEveryScreenEdgeBeforePadding() {
+ let padding = MeetingOverlayPadding(top: 10, left: 12, bottom: 14, right: 16)
+ let cases: [(MeetingOverlayVisibleAnchor, CGSize, CGRect)] = [
+ (MeetingOverlayVisibleAnchor(centerX: self.screen.minX, bottomY: 200), self.pill, CGRect(x: 100, y: 200, width: 84, height: 32)),
+ (MeetingOverlayVisibleAnchor(centerX: self.screen.maxX, bottomY: 200), self.pill, CGRect(x: 1456, y: 200, width: 84, height: 32)),
+ (MeetingOverlayVisibleAnchor(centerX: 820, bottomY: self.screen.minY - 40), self.pill, CGRect(x: 778, y: 50, width: 84, height: 32)),
+ (MeetingOverlayVisibleAnchor(centerX: 820, bottomY: self.screen.maxY), self.pill, CGRect(x: 778, y: 918, width: 84, height: 32)),
+ (MeetingOverlayVisibleAnchor(centerX: self.screen.minX, bottomY: self.screen.minY - 8), self.captions, CGRect(x: 100, y: 50, width: 340, height: 156)),
+ (MeetingOverlayVisibleAnchor(centerX: self.screen.maxX, bottomY: self.screen.maxY), self.captions, CGRect(x: 1200, y: 794, width: 340, height: 156)),
+ ]
+
+ for (anchor, size, expectedVisible) in cases {
+ let layout = MeetingOverlayGeometry.layout(
+ anchor: anchor,
+ visibleSize: size,
+ padding: padding,
+ screenVisible: self.screen
+ )
+ XCTAssertEqual(layout.visibleSurfaceFrame, expectedVisible)
+ XCTAssertTrue(self.screen.contains(layout.visibleSurfaceFrame))
+ XCTAssertEqual(
+ layout.panelFrame,
+ CGRect(
+ x: expectedVisible.minX - padding.left,
+ y: expectedVisible.minY - padding.bottom,
+ width: expectedVisible.width + padding.left + padding.right,
+ height: expectedVisible.height + padding.top + padding.bottom
+ )
+ )
+ }
+ }
+
+ func testUndersizedScreenShrinksVisibleSurfaceThenAddsPadding() {
+ let tiny = CGRect(x: 40, y: 20, width: 100, height: 50)
+ let padding: CGFloat = 18
+ let layout = MeetingOverlayGeometry.layout(
+ anchor: MeetingOverlayVisibleAnchor(centerX: 90, bottomY: 10),
+ visibleSize: self.captions,
+ padding: padding,
+ screenVisible: tiny
+ )
+ XCTAssertEqual(layout.visibleSurfaceFrame, tiny)
+ XCTAssertEqual(layout.panelFrame, CGRect(x: 22, y: 2, width: 136, height: 86))
+ XCTAssertTrue(tiny.contains(layout.visibleSurfaceFrame))
+ XCTAssertFalse(tiny.contains(layout.panelFrame))
+ }
+
+ func testTargetWiderAndTallerThanScreenPinsToOriginDeterministically() {
+ let screen = CGRect(x: 12, y: 8, width: 200, height: 80)
+ let layout = MeetingOverlayGeometry.layout(
+ anchor: MeetingOverlayVisibleAnchor(centerX: 10_000, bottomY: 10_000),
+ visibleSize: CGSize(width: 480, height: 132),
+ padding: MeetingOverlayPadding(top: 1, left: 2, bottom: 3, right: 4),
+ screenVisible: screen
+ )
+ XCTAssertEqual(layout.visibleSurfaceFrame, screen)
+ XCTAssertEqual(layout.panelFrame, CGRect(x: 10, y: 5, width: 206, height: 84))
+ }
+}
+
+final class MeetingOverlayPresentationReducerTests: XCTestCase {
+ func testNewSessionInitializesFromPreferenceAndDuplicateStartPreservesTemporaryState() {
+ var reducer = MeetingOverlayPresentationReducer(preference: .pill)
+ let session = UUID()
+ reducer.apply(.recordingStarted(sessionID: session))
+ XCTAssertEqual(reducer.presentation, .pill)
+ XCTAssertEqual(reducer.sessionID, session)
+
+ reducer.apply(.toggleRequested)
+ XCTAssertEqual(reducer.presentation, .captions)
+
+ reducer.apply(.recordingStarted(sessionID: session))
+ XCTAssertEqual(reducer.presentation, .captions)
+ XCTAssertEqual(reducer.preference, .pill)
+
+ let next = UUID()
+ reducer.apply(.recordingStarted(sessionID: next))
+ XCTAssertEqual(reducer.sessionID, next)
+ XCTAssertEqual(reducer.presentation, .pill)
+ }
+
+ func testDegradeAndRecoverPreservePresentation() {
+ var reducer = MeetingOverlayPresentationReducer(preference: .pill)
+ let session = UUID()
+ reducer.apply(.recordingStarted(sessionID: session))
+ reducer.apply(.toggleRequested)
+ XCTAssertEqual(reducer.presentation, .captions)
+
+ reducer.apply(.recordingDegraded)
+ reducer.apply(.recordingStateChanged)
+ reducer.apply(.recordingStarted(sessionID: session))
+ XCTAssertEqual(reducer.presentation, .captions)
+ XCTAssertEqual(reducer.sessionID, session)
+ XCTAssertEqual(reducer.preference, .pill)
+ }
+
+ func testMidMeetingPreferenceChangeAppliesToNextMeetingOnly() {
+ var reducer = MeetingOverlayPresentationReducer(preference: .pill)
+ let first = UUID()
+ reducer.apply(.recordingStarted(sessionID: first))
+ reducer.apply(.toggleRequested)
+ reducer.apply(.preferenceChanged(.captions))
+ XCTAssertEqual(reducer.preference, .captions)
+ XCTAssertEqual(reducer.presentation, .captions)
+
+ reducer.apply(.recordingStopped)
+ XCTAssertNil(reducer.presentation)
+ XCTAssertNil(reducer.sessionID)
+ XCTAssertEqual(reducer.preference, .captions)
+
+ let second = UUID()
+ reducer.apply(.recordingStarted(sessionID: second))
+ XCTAssertEqual(reducer.presentation, .captions)
+
+ reducer.apply(.preferenceChanged(.pill))
+ XCTAssertEqual(reducer.preference, .pill)
+ XCTAssertEqual(reducer.presentation, .captions)
+
+ reducer.apply(.recordingStopped)
+ reducer.apply(.recordingStarted(sessionID: UUID()))
+ XCTAssertEqual(reducer.presentation, .pill)
+ }
+
+ func testStopClearsSessionAndIgnoresToggleUntilNextStart() {
+ var reducer = MeetingOverlayPresentationReducer(preference: .captions)
+ reducer.apply(.toggleRequested)
+ XCTAssertNil(reducer.presentation)
+
+ let session = UUID()
+ reducer.apply(.recordingStarted(sessionID: session))
+ XCTAssertEqual(reducer.presentation, .captions)
+
+ reducer.apply(.recordingStopped)
+ reducer.apply(.recordingStopped)
+ reducer.apply(.toggleRequested)
+ reducer.apply(.recordingDegraded)
+ reducer.apply(.recordingStateChanged)
+ XCTAssertNil(reducer.presentation)
+ XCTAssertNil(reducer.sessionID)
+
+ reducer.apply(.recordingStarted(sessionID: session))
+ XCTAssertEqual(reducer.presentation, .captions)
+ }
+
+ func testRapidTogglesAreDeterministic() {
+ var reducer = MeetingOverlayPresentationReducer(preference: .pill)
+ reducer.apply(.recordingStarted(sessionID: UUID()))
+ reducer.apply(.toggleRequested)
+ reducer.apply(.toggleRequested)
+ reducer.apply(.toggleRequested)
+ reducer.apply(.toggleRequested)
+ XCTAssertEqual(reducer.presentation, .pill)
+ reducer.apply(.toggleRequested)
+ XCTAssertEqual(reducer.presentation, .captions)
+ reducer.apply(.toggleRequested)
+ XCTAssertEqual(reducer.presentation, .pill)
+ }
+
+ func testPreferenceRoundTripAndCaseIterable() {
+ XCTAssertEqual(MeetingOverlayPreference.allCases, [.pill, .captions])
+ for preference in MeetingOverlayPreference.allCases {
+ let data = try! JSONEncoder().encode(preference)
+ let decoded = try! JSONDecoder().decode(MeetingOverlayPreference.self, from: data)
+ XCTAssertEqual(decoded, preference)
+ }
+ }
+}
diff --git a/build.sh b/build.sh
index 01fe4d83..5e8edbf2 100755
--- a/build.sh
+++ b/build.sh
@@ -33,9 +33,42 @@ resolve_development_team() {
| sed -n 's/.*OU=\([^,]*\).*/\1/p'
}
+resolve_development_identity_hash() {
+ security find-identity -v -p codesigning 2>/dev/null \
+ | sed -n 's/.* \([[:xdigit:]]\{40\}\) "Apple Development:[^"]*".*/\1/p' \
+ | awk 'NR == 1 { print; exit }'
+}
+
+replace_with_symlink() {
+ local path="$1"
+ local target="$2"
+
+ if [ -L "${path}" ] || [ -f "${path}" ]; then
+ rm -f "${path}"
+ elif [ -d "${path}" ]; then
+ rm -R "${path}"
+ elif [ -e "${path}" ]; then
+ echo "Unexpected file type at ${path}" >&2
+ return 1
+ fi
+
+ ln -s "${target}" "${path}"
+}
+
run_public_build() {
local signing_mode="$1"
local development_team
+ local signing_identity_hash
+ local app_path
+ local ctranscribe_framework
+ local ctranscribe_versions
+ local ctranscribe_version_a
+ local ctranscribe_version_a_binary
+ local ctranscribe_version_a_resources
+ local ctranscribe_current
+ local ctranscribe_root_binary
+ local ctranscribe_root_resources
+ local entitlements_file
local -a build_args=(
-project Fluid.xcodeproj
-scheme Fluid
@@ -49,10 +82,11 @@ run_public_build() {
if [ "${signing_mode}" = "unsigned" ]; then
echo "Running unsigned public FluidVoice build..."
- echo "Accessibility permission may need to be granted again after rebuilding."
+ echo "Accessibility, Screen Recording, and microphone permissions may need to be granted again after rebuilding."
exec xcodebuild "${build_args[@]}" CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO
fi
+ signing_identity_hash="$(resolve_development_identity_hash)"
development_team="$(resolve_development_team)"
if [ -z "${development_team}" ]; then
if [ -n "${FLUIDVOICE_DEVELOPMENT_TEAM:-}" ]; then
@@ -76,14 +110,95 @@ teams, set FLUIDVOICE_DEVELOPMENT_TEAM to the desired 10-character Team ID.
To build without signing instead, run:
./build.sh unsigned
-Unsigned builds may require Accessibility permission again after rebuilding.
+Unsigned builds may require Accessibility, Screen Recording, and microphone permissions again after rebuilding.
EOF
exit 1
fi
+ if [ -z "${signing_identity_hash}" ]; then
+ echo "Unable to resolve the Apple Development signing identity hash." >&2
+ exit 1
+ fi
+
echo "Running signed public FluidVoice build..."
echo "Build product: ${DERIVED_DATA_PATH}/Build/Products/Debug/FluidVoice Debug.app"
- exec xcodebuild "${build_args[@]}" DEVELOPMENT_TEAM="${development_team}"
+ xcodebuild "${build_args[@]}" DEVELOPMENT_TEAM="${development_team}"
+
+ app_path="${DERIVED_DATA_PATH}/Build/Products/Debug/FluidVoice Debug.app"
+ ctranscribe_framework="${app_path}/Contents/Frameworks/CTranscribe.framework"
+ if [ ! -d "${app_path}" ]; then
+ echo "Signed build product is missing: ${app_path}" >&2
+ exit 1
+ fi
+ if [ ! -d "${ctranscribe_framework}" ]; then
+ echo "Signed CTranscribe framework is missing: ${ctranscribe_framework}" >&2
+ exit 1
+ fi
+
+ ctranscribe_versions="${ctranscribe_framework}/Versions"
+ ctranscribe_version_a="${ctranscribe_versions}/A"
+ ctranscribe_version_a_binary="${ctranscribe_version_a}/CTranscribe"
+ ctranscribe_version_a_resources="${ctranscribe_version_a}/Resources"
+ ctranscribe_current="${ctranscribe_versions}/Current"
+ ctranscribe_root_binary="${ctranscribe_framework}/CTranscribe"
+ ctranscribe_root_resources="${ctranscribe_framework}/Resources"
+ if [ ! -d "${ctranscribe_versions}" ] || [ -L "${ctranscribe_versions}" ]; then
+ echo "CTranscribe.framework has no regular Versions directory: ${ctranscribe_versions}" >&2
+ exit 1
+ fi
+ if [ ! -d "${ctranscribe_version_a}" ] || [ -L "${ctranscribe_version_a}" ]; then
+ echo "CTranscribe.framework has no regular Versions/A directory: ${ctranscribe_version_a}" >&2
+ exit 1
+ fi
+ if [ ! -f "${ctranscribe_version_a_binary}" ] || [ -L "${ctranscribe_version_a_binary}" ]; then
+ echo "CTranscribe.framework Versions/A/CTranscribe is not a regular file: ${ctranscribe_version_a_binary}" >&2
+ exit 1
+ fi
+ if [ ! -d "${ctranscribe_version_a_resources}" ] || [ -L "${ctranscribe_version_a_resources}" ]; then
+ echo "CTranscribe.framework Versions/A/Resources is not a regular directory: ${ctranscribe_version_a_resources}" >&2
+ exit 1
+ fi
+
+ echo "Normalizing CTranscribe.framework layout..."
+ replace_with_symlink "${ctranscribe_current}" "A"
+ replace_with_symlink "${ctranscribe_root_binary}" "Versions/Current/CTranscribe"
+ replace_with_symlink "${ctranscribe_root_resources}" "Versions/Current/Resources"
+
+ echo "Re-sealing CTranscribe.framework with the resolved Apple Development identity..."
+ codesign --force --sign "${signing_identity_hash}" \
+ --options runtime --timestamp=none \
+ --preserve-metadata=identifier,requirements,flags "${ctranscribe_framework}"
+
+ entitlements_file="$(mktemp -t fluidvoice-entitlements)"
+ if ! codesign --display --entitlements :- "${app_path}" > "${entitlements_file}" 2>/dev/null; then
+ rm -f "${entitlements_file}"
+ echo "Unable to read existing app entitlements: ${app_path}" >&2
+ exit 1
+ fi
+
+ echo "Re-signing the app while preserving its existing entitlements..."
+ if [ -s "${entitlements_file}" ]; then
+ if ! codesign --force --sign "${signing_identity_hash}" \
+ --options runtime --timestamp=none \
+ --preserve-metadata=identifier,requirements,flags \
+ --entitlements "${entitlements_file}" "${app_path}"; then
+ rm -f "${entitlements_file}"
+ echo "Unable to re-sign the app: ${app_path}" >&2
+ exit 1
+ fi
+ else
+ if ! codesign --force --sign "${signing_identity_hash}" \
+ --options runtime --timestamp=none \
+ --preserve-metadata=identifier,requirements,flags "${app_path}"; then
+ rm -f "${entitlements_file}"
+ echo "Unable to re-sign the app: ${app_path}" >&2
+ exit 1
+ fi
+ fi
+ rm -f "${entitlements_file}"
+
+ echo "Verifying the signed app..."
+ codesign --verify --deep --strict "${app_path}"
}
case "${PROFILE}" in
diff --git a/tools/capture_audio_topology_stall.sh b/tools/capture_audio_topology_stall.sh
new file mode 100755
index 00000000..c27cd2e2
--- /dev/null
+++ b/tools/capture_audio_topology_stall.sh
@@ -0,0 +1,30 @@
+#!/bin/zsh
+
+set -eu
+
+trace_directory="${1:-/tmp/fluidvoice-audio-evidence}"
+
+if [[ ! -d "$trace_directory" ]]; then
+ print -u2 "Trace directory does not exist: $trace_directory"
+ exit 2
+fi
+
+marker="$(find "$trace_directory" -maxdepth 1 -type f -name 'fluidvoice-audio-topology-*.stall' -print | sort | tail -n 1)"
+if [[ -z "$marker" ]]; then
+ print -u2 "No stall marker found in: $trace_directory"
+ exit 3
+fi
+
+pid="$(sed -n 's/.*"pid":\([0-9][0-9]*\).*/\1/p' "$marker" | head -n 1)"
+if [[ -z "$pid" ]] || ! kill -0 "$pid" 2>/dev/null; then
+ print -u2 "Marker does not reference a live process: $marker"
+ exit 4
+fi
+
+timestamp="$(date -u +%Y%m%dT%H%M%SZ)"
+sample_path="$trace_directory/fluidvoice-audio-sample-$pid-$timestamp.txt"
+
+print "Capturing live process $pid to $sample_path"
+/usr/bin/sample "$pid" 10 1 -file "$sample_path"
+print "Captured: $sample_path"
+print "If the stack is inconclusive, capture sysdiagnose now and record its timestamp outside the repository."