Skip to content

feat(desktop): microphone picker with Ray-Ban Meta glasses support (port of #9181) - #10917

Merged
eulicesl merged 12 commits into
mainfrom
claude/meta-rayban-ios-pr-j34v0q
Jul 31, 2026
Merged

eulicesl merged 12 commits into
mainfrom
claude/meta-rayban-ios-pr-j34v0q

Conversation

@eulicesl

@eulicesl eulicesl commented Jul 31, 2026 •

Copy link
Copy Markdown
Collaborator

What changed and why

Port of #9181 (desktop microphone picker with Ray-Ban Meta glasses support) onto current main. The original branch predates the repository history rewrite, so it can no longer be merged — this PR re-lands the same feature set as a fresh branch, re-integrated with everything that landed on main since July 7. Supersedes and closes #9181.

  • Microphone card in Settings → Transcription: System Default or any CoreAudio input device, persisted by device UID (device IDs are not stable across reconnects), applied through the existing AudioCaptureService(overrideDeviceID:) path and honored when transcription starts. The list refreshes from a kAudioHardwarePropertyDevices listener, not polling. Meta glasses get an explanatory subtitle and badge; the HFP voice-quality tradeoff is stated in plain language.
  • Listening button shows the live capture source — an explicitly selected device's real name, or "Ray-Ban Meta" when the name matches a Meta product (including the EssilorLuxottica codename, e.g. "EL AI 000F"). Landed in CaptureListeningLogic (main's shared status derivation), so the persistent status bar and the Home header both surface it.
  • PTT mic-contention fix: AudioCaptureService gains a process-wide active-capture registry; PTT input routing yields to the built-in mic when the would-be input is held by another capture (e.g. transcription capturing from the glasses) or is Bluetooth while any capture runs — extending the existing isDefaultOutputBluetooth() guard's philosophy, with recordFallback telemetry on every contention degradation.
  • PTT warm mic keep-alive: a finished turn parks its capture for 120 s and the next turn with the same routing adopts it through a lock-guarded lease, instead of tearing down and rebuilding the CoreAudio IOProc. Terminal cleanup is generation-watermarked so a cancelled turn can never leave the mic open; ambient transcription releases and awaits the parked capture's HAL teardown before opening its own.

Adaptations forced by current main (vs. the original branch): Swift 6 strict concurrency (@unchecked Sendable lease, lock-justified nonisolated(unsafe) statics per repo precedent); the capture-source label integrates into CaptureListeningLogic; the contention policy reads default-input/built-in/transport facts from PTTInputDeviceRouting's off-main-actor probe snapshot — extra HAL reads gated on live-capture state so the idle probe pattern is unchanged, with a stale_contention_snapshot fallback recorded when a pre-capture snapshot is consumed while a capture is live; the preferred-mic UID is resolved off the main actor at the device-open boundary (covers initial start, the meetings-only gate, and recovery rebuilds); MicrophonePickerCard uses main's availableInputDevices()/isBluetoothTransport enumeration; the hub seed-stale reconnect deferral already exists on main, so only its guard test ships here.

Deferred with tracking issue #10921 (need macOS hardware to verify): preferred-mic reapply on reconnect, and awaiting waitForPhysicalStop() in the shared settings-restart path.

Product invariants affected

  • INV-CHAT-1
  • INV-DATA-1
  • INV-BETA-1
  • INV-VOICE-1

None of these invariants' behavior changes. INV-CHAT-1 / INV-VOICE-1 are path-triggered by PushToTalkManager.swift and hub guard-test changes: the PTT turn lifecycle keeps its single owner (the warm-parked capture is adopted only through the same startMicCapture entry point and generation counter), and no chat-transcript surface is added or forked. INV-DATA-1 / INV-BETA-1 are path-triggered by AppBuild.swift, where this PR only reformats one doc comment to the pinned swift-format style (drift inherited from main that was failing every PR's lint) — no build-identity or data-plane routing value changes.

How it was verified

  • python3 desktop/macos/scripts/check-e2e-flow-coverage.py --strict --base origin/main — passed, all changed desktop Swift files covered, 0 uncovered.
  • make preflight (Linux lane) — all 18 selected manifest checks pass, including diff-hygiene, changelog schema/entry, desktop-test-quality, swiftlint-baseline, product-file-line-count-ratchet (baselines raised with justifications), product-invariants against this body, and production-data-plane-routing.
  • All touched Swift files verified format-idempotent against swift-format 602 (Swift 6.2 toolchain, repo .swift-format config) — the exact signal desktop-swift-format-lint enforces; the macOS CI manifest-checks step confirmed this on the pinned toolchain.
  • Not verified here: compilation. This session runs on Linux with no Swift toolchain, so the Swift sources were not compiled — the macOS CI lanes are the compile/test authority for this PR. Reviewer should not merge before they are green.
  • Hardware validation happened on the original branch before the history rewrite (feat(desktop): microphone picker with Ray-Ban Meta glasses support #9181): Ray-Ban Meta glasses (Bluetooth codename "EL AI 000F") selected in the picker in a named bundle captured live speech → transcript end-to-end, and the PTT contention behavior was exercised with transcription holding the glasses while PTT fell back to the built-in mic. That evidence carries over; the port must still be re-exercised on hardware before stable release.

Tests

  • PTTWarmMicKeepAliveTests.swift (new): labeled source-inspection tripwires for warm parking/adoption, terminal-cleanup discard, contention routing excluding the manager's own parked capture, the picker's listener-not-polling contract, and the hub seed-stale deferral — asserting the strings as they exist on current main.
  • TranscriptionTransportTests.swift: registry release ordering — unregisterActiveCapture() after HAL teardown in stopCapture, and unconditionally in deinit (regression guard for the dealloc-race registry leak found in review).
  • PTTInputDeviceProbeTests: all injected probes now provide deterministic fakes for the two new explicit callbacks, keeping the wedged-driver tests hermetic; the existing zero-builtIn-walk expectation passes because contention probing is gated on live-capture state.

Failure class (fixes)

Failure-Class: none

New guards (only when adding a check or ratchet)

No new check or ratchet; the two raised line-count baselines carry one-line justifications in the baseline files per the ratchet's own protocol.

🤖 Generated with Claude Code

https://claude.ai/code/session_01TWim8oQvjk8ebdfuuBt5fd

Port of PR #9181 onto current main (the original branch predates the repo
history rewrite and cannot be merged). Same feature set, re-integrated with
the code that landed on main since July 7:

- Microphone card in Settings -> Transcription: System Default or any
  CoreAudio input, persisted by device UID (IDs are not stable across
  reconnects), applied through the existing AudioCaptureService
  overrideDeviceID path and honored when transcription starts
  (AppState+Transcription). Refreshes from a kAudioHardwarePropertyDevices
  listener, not polling.
- Listening button surfaces the live capture source; an explicitly selected
  Meta-glasses mic shows as "Ray-Ban Meta". Integrated into
  CaptureListeningLogic (main's shared status derivation) so the persistent
  status bar and Home header both get it.
- PTT mic contention: AudioCaptureService gains a process-wide
  active-capture registry; PTT routing yields to the built-in mic when the
  would-be input is held by another capture, or is Bluetooth while any
  capture runs. Integrated into PTTInputDeviceRouting's off-main-actor
  probe/snapshot seam (registry reads are lock-guarded process state, not
  HAL reads, so resolution stays main-actor safe).
- PTT warm mic keep-alive: a finished turn parks its capture for 120s and
  the next turn with the same routing adopts it via a lock-guarded lease,
  instead of tearing down and rebuilding the CoreAudio IOProc.

Adaptations vs the original branch, forced by current main:
- listeningModeTitle override moved into CaptureListeningLogic (new home of
  that logic).
- Contention policy reads default-input/built-in/transport info from the
  probe snapshot instead of calling the HAL on the main actor, honoring the
  PTT routing seam's no-main-actor-HAL invariant; explicit user mic choices
  are always respected.
- MicrophonePickerCard uses availableInputDevices()/isBluetoothTransport
  (main's enumeration) rather than the original listInputDevices().
- Source-inspection tripwires live in PTTWarmMicKeepAliveTests.swift and
  assert current main's publish()-based coordinator strings; the hub
  seed-stale reconnect deferral they guard already landed on main, so its
  changelog fragment is not re-shipped here.

Verification: python3 desktop/macos/scripts/check-e2e-flow-coverage.py
--strict --base origin/main passes (8/8 changed Swift files covered); flow
YAML parses; changelog fragments are valid JSON. No Swift toolchain exists
in this Linux environment, so the Swift sources are NOT compiled here — CI
must be the compile/test authority for this PR. Hardware validation of the
original branch (glasses as picker selection, end-to-end transcript) was
done on the fork before the rewrite; see PR #9181.
@eulicesl
eulicesl requested a review from Copilot July 31, 2026 01:26
@eulicesl
eulicesl marked this pull request as ready for review July 31, 2026 01:26

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Not ready to approve

The active-capture registry can leak entries when AudioCaptureService is deallocated after stopCapture(), and the listening-source UI logic can misrepresent whether the preferred mic is actually in use.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

This review doesn't count toward merge requirements. Sign up for the private preview to control whether Copilot approvals count.

Pull request overview

Ports the desktop macOS microphone picker + Ray-Ban Meta glasses capture-source surfacing onto current main, and extends push-to-talk (PTT) routing to avoid CoreAudio device contention while adding a warm mic keep-alive for faster consecutive turns.

Changes:

  • Add a Settings → Transcription “Microphone” picker persisted by CoreAudio device UID and refreshed via kAudioHardwarePropertyDevices listener.
  • Surface the active capture source in shared CaptureListeningLogic, and honor the preferred mic when starting transcription.
  • Add an AudioCaptureService active-capture registry + PTT contention policy, plus warm mic parking/adoption to avoid IOProc teardown between nearby turns.
File summaries
File Description
desktop/macos/e2e/flows/settings-basic.yaml Adds coverage for the new transcription microphone settings UI.
desktop/macos/e2e/flows/ptt-microphone-routing.yaml New manual E2E flow covering PTT routing, warm mic reuse, and contention behavior.
desktop/macos/e2e/flows/audio-recording.yaml Extends coverage list for transcription + audio capture changes.
desktop/macos/Desktop/Tests/VoiceTurnDomainTests/TranscriptionTransportTests.swift Adds source-inspection guard for registry unregister ordering in stopCapture/deinit.
desktop/macos/Desktop/Tests/PTTWarmMicKeepAliveTests.swift Adds source-inspection “tripwire” tests for warm mic keep-alive, contention routing, and device-list listener usage.
desktop/macos/Desktop/Sources/MainWindow/Pages/Settings/Sections/SettingsContentView+Transcription.swift Inserts the new microphone picker card into the transcription settings section.
desktop/macos/Desktop/Sources/MainWindow/Pages/Settings/Sections/MicrophonePickerCard.swift Implements the CoreAudio device list observer + UI to select and persist a preferred input UID.
desktop/macos/Desktop/Sources/MainWindow/CaptureListeningLogic.swift Updates listening title logic to surface capture source / Meta label.
desktop/macos/Desktop/Sources/FloatingControlBar/PushToTalkManager+InputDeviceRouting.swift Extends routing snapshot with default-input transport facts and applies mic-contention policy.
desktop/macos/Desktop/Sources/FloatingControlBar/PushToTalkManager.swift Adds warm mic lease/parking/adoption and integrates with stop paths and silent-mic recovery.
desktop/macos/Desktop/Sources/DefaultsKey.swift Adds the preferredMicrophoneDeviceUID defaults key for persistence.
desktop/macos/Desktop/Sources/AudioCaptureService.swift Adds the active-capture registry, exposes default input device ID helper, and Meta-name matching.
desktop/macos/Desktop/Sources/AppState/AppState+Transcription.swift Honors the preferred microphone UID when creating the transcription capture service.
desktop/macos/changelog/unreleased/20260707-ptt-warm-mic-keepalive.json Changelog entry for warm mic keep-alive behavior.
desktop/macos/changelog/unreleased/20260707-ptt-mic-contention.json Changelog entry for PTT contention fallback behavior.
desktop/macos/changelog/unreleased/20260706-rayban-meta-microphone-picker.json Changelog entry for microphone picker + listening source display.
.github/scripts/product_file_line_count_ratchet_baseline/desktop-swift-floatingcontrolbar.json Raises baseline for PushToTalkManager line count with justification.
.github/scripts/product_file_line_count_ratchet_baseline/desktop-swift-appstate.json Raises baseline for AppState+Transcription line count with justification.
Review details
  • Files reviewed: 18/18 changed files
  • Comments generated: 3
  • Review effort level: Lite

We're testing this review assessment. Please use 👍 or 👎 to tell us if it's correct.

Comment on lines +38 to +42
UserDefaults.standard.string(
forKey: AudioCaptureService.preferredInputUIDDefaultsKey) ?? ""
if !preferredUID.isEmpty {
return name
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this one — the premise doesn't quite hold. recordingInputDeviceName is written at capture start with the device actually in use: when the saved UID resolves, AppState+Transcription sets it to the override device's name; when the UID is stale and capture falls back, it keeps the system-default mic's name from getCurrentMicrophoneName(). So in the stale-UID case this label shows the real fallback device (e.g. "MacBook Pro Microphone"), not the unavailable selection — which is the honest surface we want. The !preferredUID.isEmpty guard only decides whether to show a device name instead of the capture-mode word; it never re-labels the fallback as the selected mic.


Generated by Claude Code

claude added 2 commits July 31, 2026 01:32
CI failed on the language mode the package now pins (swiftLanguageModes:
[.v6]) plus format drift:

- MicCaptureLease moved out of the @mainactor manager to a top-level
  @unchecked Sendable class: nesting inherited main-actor isolation, which
  both made the type non-Sendable for the @sendable audio closures and
  would forbid its lock calls off the main actor. Every stored property is
  read and written under its lock.
- AudioCaptureService.activeCaptures marked nonisolated(unsafe) with the
  lock-guard justification, matching ScreenCaptureService's existing
  pattern for lock-guarded statics.
- AudioInputDeviceListObserver.listenerBlock marked nonisolated(unsafe) so
  the nonisolated deinit can remove the CoreAudio listener; writes stay on
  the main actor.
- All touched Swift files reformatted with swift-format 602 (Swift 6.2
  toolchain, repo .swift-format config) and verified format-idempotent —
  the exact signal desktop-swift-format-lint enforces.

Verification: swift-format format is a no-op on every touched file;
make preflight passes all 17 selected checks (PushToTalkManager line-count
baseline updated to the exact new count); source-inspection tripwire
strings re-verified after formatting. Still not compiled locally (no
macOS); CI is the compile authority.

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TWim8oQvjk8ebdfuuBt5fd
…ename

Two findings from PR review:

- The active-capture registry could leak an entry forever: stopCapture()
  queues its unregister behind [weak self], and deinit only unregistered
  inside the isCapturing branch — which stopCapture() had already cleared.
  A service deallocated right after stopCapture() (the common caller
  pattern) left hasActiveCapture()/isDeviceActivelyCaptured() stuck true,
  permanently pinning PTT to the built-in mic. deinit now unregisters
  unconditionally; removing an absent key is a no-op, so the queued-block
  path stays correct.
- isMetaGlassesName() now also matches the EssilorLuxottica codename
  prefix ("el ai ") that real glasses present as their CoreAudio device
  name (observed "EL AI 000F" on hardware) — without it the picker badge
  and "Ray-Ban Meta" label never trigger on actual hardware. Prefix-
  anchored so it cannot swallow unrelated names.

Verification: swift-format idempotent on both touched files; make
preflight passes all 17 checks; the deinit registry tripwire window in
TranscriptionTransportTests widened to cover the moved (now
unconditional) unregister. Not compiled locally (no macOS toolchain).

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TWim8oQvjk8ebdfuuBt5fd

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 305004efda

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +16 to +19
let listener: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
Task { @MainActor in
self?.revision &+= 1
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reapply the preferred mic when it reconnects

When a selected device disconnects during transcription, AudioCaptureService falls back from its numeric override to the system default and begins observing only that default route. On reconnection this devices listener merely refreshes the picker list; it never restarts capture or resolves the persisted UID again, so the session continues recording from the fallback device while the preferred microphone appears selected in Settings. Trigger the existing restart path when the saved UID becomes available again, or make the capture service track the UID across reconnects.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real gap, deferred to #10921 rather than fixed here: re-resolving the persisted UID on reconnect means adding a device-list observer to the shared capture lifecycle and restarting live capture, which I can only verify with physical disconnect/reconnect cycles on macOS hardware — this PR's changes are all statically checkable, and I don't want to land an unverifiable behavior change in the same diff. The issue carries the fix direction (trigger restartTranscriptionIfNeeded() when the saved UID resolves again).


Generated by Claude Code

VStack(spacing: OmiSpacing.xl) {
// Microphone (input device — e.g. Ray-Ban Meta glasses)
settingsCard(settingId: "transcription.microphone") {
MicrophonePickerCard(onChanged: { restartTranscriptionIfNeeded() })

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Wait for the old mic before applying a picker change

Changing the microphone while transcription is live calls restartTranscriptionIfNeeded(), which stops the old AudioCaptureService asynchronously and starts the replacement after an arbitrary one-second delay. stopCapture() explicitly allows HAL teardown to block for multiple seconds, so the replacement can open while the old IOProc is still alive; on Bluetooth devices this recreates the same profile-flap and silent-capture contention the change is intended to prevent. Await the old service's waitForPhysicalStop() before starting with the new UID rather than relying on the timer.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed the window is real, but it predates this PR: restartTranscriptionIfNeeded()'s stop-then-delayed-start is the shared restart path every settings change already uses (language mode, VAD gate, etc.), so the fix belongs in that path, verified on hardware, not folded into this port. Tracked in #10921 with the waitForPhysicalStop() fix direction. Note the picker's primary Bluetooth case is also mitigated in this PR from another angle: the active-capture registry now makes PTT refuse to open a second IOProc against a held device, and ambient starts discard PTT's parked capture first.


Generated by Claude Code

Fixes from PR #10917 review (Codex):

- Probe seam stays hermetic: the two new PTTAudioDeviceProbe callbacks are
  now explicit (no real-HAL defaults inside injected fakes), and every test
  probe provides deterministic fakes.
- The built-in-mic device walk (the most expensive HAL enumeration) and the
  default-input read are gated on AudioCaptureService.hasActiveCapture() —
  contention data is only gathered when another capture is actually live,
  restoring the exact pre-existing probe pattern (and the guarding test's
  zero-calls expectation) when idle.
- Both contention fallbacks now call recordFallback (area
  ptt_input_routing, outcome degraded) per the shared fallback-telemetry
  contract, instead of only logging locally.
- A terminal stop (parkWarm: false) that raced an in-flight startCapture
  no longer leaks a live mic into the 120 s keep-alive: the late completion
  now stops the capture instead of parking it (discardLateCaptureStarts).
- Ambient transcription posts .ambientMicCaptureStarting before opening
  its mic; PTT discards its parked warm capture on that signal so the two
  paths cannot open a second IOProc against the same device.
- rebuildCoreAudioCaptureStack() now resolves the persisted microphone UID
  through the new makeMicrophoneCaptureService() helper (shared with
  initial construction), so a recovery rebuild no longer silently abandons
  the user's selection; the displayed name only falls back to the system
  default when no override resolved (AudioCaptureService.hasOverrideDevice).

Deferred with tracking issue #10921 (need macOS hardware to verify):
preferred-mic reapply on reconnect, and awaiting waitForPhysicalStop() in
the shared restart path when switching mics live.

Verification: swift-format idempotent on all touched files; make preflight
passes all 17 checks; warm-keep-alive tripwire strings re-verified. Not
compiled locally (no macOS toolchain) — CI is the compile authority.

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TWim8oQvjk8ebdfuuBt5fd

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a5825d5be8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

claude added 3 commits July 31, 2026 02:00
Six findings from Codex on the previous revision, all confirmed real:

- Terminal-cleanup decisions are now a generation watermark, not a global
  flag: cancelling a turn while its capture start is in flight and then
  starting a new turn no longer clears the older generation's terminal
  fate — the late completion of the cancelled start is stopped instead of
  parked alongside the new turn's capture.
- Audio/level/silent-mic/route closures snapshot the lease BEFORE
  scheduling their main-actor Task, so a frame emitted under the previous
  turn's authority can no longer be re-authorized by a warm adoption that
  renews the lease while the Task is queued.
- The ambient handoff is now synchronous and awaited: startMicCaptureIfNeeded
  calls PushToTalkManager.releaseParkedMicCapture() directly and awaits
  waitForPhysicalStop() before opening the device, replacing the
  fire-and-forget notification (removed). This also covers the
  meetings-only gate, where capture opens long after session arm.
- Preferred-microphone resolution moved off the main actor and to the
  device-open boundary (startMicCaptureIfNeeded): the full-device HAL
  enumeration now runs in a detached task, cannot freeze the UI behind a
  wedged driver, and applies to every open path — initial start, the
  meeting gate, and recovery rebuilds — through a shared watchdog-wiring
  helper. makeMicrophoneCaptureService() is gone.
- A routing snapshot probed before any capture was live is now marked
  contentionResolved=false; a PTT turn that consumes it while a capture
  has since started records a stale_contention_snapshot fallback instead
  of silently lacking the data (the same call already kicks the refresh
  that carries the facts for the next turn).
- The listening title keeps the 'Meetings only' mode word while the
  meeting gate is holding capture closed, instead of showing a device
  name that implies live capture.

Verification: swift-format idempotent on all touched files; make preflight
passes all 17 checks (line-count baselines synced); warm-keep-alive and
contention tripwire strings re-verified. Not compiled locally (no macOS
toolchain) — CI is the compile authority.

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TWim8oQvjk8ebdfuuBt5fd
Scoped cleanup: main's release-path advancement commit (637b539) shipped
a doc comment indented off the pinned swift-format style, which fails
desktop-swift-format-lint for every PR whose CI merge includes it — this
PR's macOS lane was red on it despite never touching the file. One-line
reformat, verified format-idempotent against swift-format 602 with the
repo config.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TWim8oQvjk8ebdfuuBt5fd

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 10a47d0b22

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +375 to +376
if let parked = PushToTalkManager.shared.releaseParkedMicCapture() {
await parked.waitForPhysicalStop()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Arbitrate active PTT capture before starting Listening

When Listening is enabled during an active PTT turn, especially a locked turn, this only releases parkedMicCapture; the manager's live audioCaptureService remains open. Ambient capture then proceeds to open the selected/default device, so if both owners resolve to the same microphone they still run overlapping IOProcs and can trigger the Bluetooth profile flap or silent capture this arbitration is meant to prevent. Defer the ambient open or coordinate teardown with the active PTT owner as well as the parked one.

AGENTS.md reference: AGENTS.md:L43-L43

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deferred to #10921 (item 3) rather than fixed here: an ambient start overlapping a live PTT turn predates this PR — before it, no capture arbitration existed at all, so this PR narrows the overlap (parked captures released + awaited; PTT routing yields to held devices on the next turn) without governing the live-turn case it never touched. Deciding which owner yields mid-turn (kill the user's in-flight locked dictation, or delay ambient?) is a product-behavior call, and the teardown handshake needs hardware verification — both out of place in this port.


Generated by Claude Code

parkedMicExpiryTask = nil
parkedMicCapture = nil
parked.lease.renew(generation: generation, batchMode: batchMode, turnID: turnID)
parked.service.resetSilentMicWatchdog()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Serialize watchdog reset with audio callbacks

When a parked capture is adopted, its IOProc is still actively executing handleAudioInput, which reads and mutates the watchdog counters and timestamps. This direct resetSilentMicWatchdog() call writes the same fields from the main actor without a lock or dispatching to audioQueue, creating a data race on every warm reuse that can cause missed or spurious silent-mic recovery. Perform the reset on the capture's serialized audio queue or otherwise synchronize the watchdog state.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Race is real but not introduced by this call: main's existing stopCapture() resets the same unguarded watchdog fields from the main actor while the HAL IO thread can still be inside handleAudioInput — the adoption-time reset shares that established shape. Dispatching to audioQueue wouldn't fix it either: the IOProc callback runs on the HAL's own IO thread, not audioQueue, so the correct fix is a lock-guarded watchdog state container on the hot audio path — a change I won't land unverified from a Linux box. Tracked as #10921 item 4 with that fix direction; blast radius meanwhile is one missed/spurious silent-mic recovery trigger that self-corrects on the next ~1 s window.


Generated by Claude Code

…tadata caching

Third review round (Codex on 10a47d0), three fixes:

- Registry release now happens strictly after physical teardown: the
  queued stopCapture block unregisters by captured owner identity (so it
  survives service deallocation), and deinit's unregister moved back
  inside the direct-teardown branch — the previous unconditional deinit
  unregister could mark a device free while its queued AudioDeviceStop
  had not run yet. Fixes both halves: no leaked key, no early release.
- Warm adoption no longer reads the HAL on the main actor: the route
  class noted at the original capture start is cached and reused (the
  parked IOProc pins the device, so the route cannot have changed),
  keeping the warm path instant even against a wedged driver.
- A preferred microphone that no longer resolves records a
  device_unavailable fallback (area transcription_input) instead of
  silently substituting the system default.

Deferred to #10921 (need hardware verification; see PR replies):
active-PTT-turn vs ambient arbitration (pre-existing overlap this PR
never governed) and lock-guarding the silent-mic watchdog state (the
adoption-time reset shares its race shape with main's existing
stopCapture-time reset).

Verification: swift-format idempotent on all touched files; make
preflight passes all 18 checks; tripwire literals updated for the
owner-identity rename and re-verified. Not compiled locally (no macOS
toolchain) — CI is the compile authority.

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TWim8oQvjk8ebdfuuBt5fd

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e6f68a3d88

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

}

self.deviceID = newDeviceID
registerActiveCapture(deviceID: newDeviceID)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reserve the new default device throughout reconfiguration

When an active default-input capture receives a system route change from device A to non-Bluetooth device B, handleConfigurationChange() stops A and waits 300 ms while the registry still identifies A; B is not registered until this delayed line executes. If PTT starts during that window, its contention policy sees B as free and opens it, after which the ambient reconfiguration opens a second IOProc on B. Represent the owner as reconfiguring or reserve B before exposing this gap so routing cannot admit another owner during the transition.

AGENTS.md reference: AGENTS.md:L43-L43

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deferred to #10921 (item 5): through the ~300 ms window the registry still carries this owner's entry for device A, so hasActiveCapture() stays true and the Bluetooth-contention branch still yields — the residual gap is only isDeviceActivelyCaptured(B) admitting B specifically, for one turn, during an active route flap. A reserving registry state ("reconfiguring" owner, or B reserved at route-change time) is the right shape, but it changes recovery-path ownership semantics and can only be validated against real route flaps on hardware, so it goes with the other capture-lifecycle items rather than into this port.


Generated by Claude Code

…handshake

Fourth review round (Codex on e6f68a3), three fixes:

- Registry entries are keyed by a per-instance UUID token instead of
  ObjectIdentifier: the queued HAL-teardown unregister can run after the
  service deallocates, and a replacement allocated at the same address
  would collide on an identity key — the stale removal would delete the
  replacement's live entry. A UUID can never be reused.
- A parked capture displaced by a different-route turn is now released
  and its waitForPhysicalStop() awaited inside the start Task before the
  replacement opens — the two routes can even resolve to the same
  physical device (nil-override on the built-in default vs. an explicit
  built-in override), so the enqueued stop alone left an overlap window.
- A stale late capture start is stopped, never parked, whenever a newer
  turn's capture is already live (audioCaptureService non-nil): parking
  beside a live capture would hold two open IOProcs, possibly on the
  same Bluetooth device. Parking remains only for the quiet gap between
  turns.

Deferred to #10921 item 5: reserving the post-route-change device during
an active capture's ~300 ms reconfiguration window (registry keeps the
old device's entry through the window, so hasActiveCapture stays true
and the Bluetooth-contention fallback still yields; the residual
same-device admit needs a reserving registry state, hardware-verified).

Verification: swift-format idempotent on all touched files; make
preflight passes all 18 checks; tripwire literals updated for the token
rename and re-verified. Not compiled locally (no macOS toolchain) — CI
is the compile authority.

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TWim8oQvjk8ebdfuuBt5fd

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 20494c18e1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +137 to +145
let latest = await Task.detached(priority: .utility) {
AudioCaptureService.availableInputDevices().map { device in
PickerInputDevice(
uid: device.uid,
name: device.name,
isBluetooth: AudioCaptureService.isBluetoothTransport(deviceID: device.id)
)
}
}.value

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Coalesce non-cancellable picker HAL refreshes

When CoreAudio emits multiple device-list notifications while a driver is slow or wedged, each revision cancels the SwiftUI .task, but the detached task created here is unstructured and continues blocking in availableInputDevices() because HAL property reads have no cancellation or deadline. Every notification therefore strands another worker and starts another full device/transport enumeration; even opening the card can race its initial task with the observer's first revision. Serialize or coalesce these reads behind a single in-flight probe rather than launching a detached task per revision.

Useful? React with 👍 / 👎.

…aced-route and refresh paths

Fifth review round (Codex on 20494c1), four fixes — the first one matters
most:

- The warm keep-alive was unreachable: every turn's .terminal effect
  (including reason=success) ran performTerminalCleanup with an
  unconditional parkWarm:false, discarding the capture the finalization
  path had just parked — so the advertised 120 s IOProc reuse never
  happened between turns. Terminal cleanup now keeps the park for benign
  endings (success, too-short, silent-rejected, barge-in — the cases
  where an immediate follow-up turn is likely) and still fully releases
  the mic on cancellation, owner change, and every failure reason.
- The displaced-route start revalidates generation and turn liveness
  after awaiting the displaced capture's HAL teardown, so a turn
  cancelled during that await can no longer open its stale device
  alongside a newer turn's capture.
- Conversation provenance records the microphone the session actually
  uses: the crash-safe session row now waits for the preferred-mic name
  resolution (off-main) instead of persisting the system-default name.
- Picker device-list refreshes are coalesced behind a single in-flight
  probe with one trailing rerun — a wedged HAL can strand at most one
  worker no matter how many kAudioHardwarePropertyDevices notifications
  arrive.

Verification: swift-format idempotent on all touched files; make
preflight passes all 18 checks; warm-keep-alive tripwire literals
re-verified (parkWarm: false remains on the silent-mic and CoreAudio
recovery paths). Not compiled locally (no macOS toolchain) — CI is the
compile authority.

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TWim8oQvjk8ebdfuuBt5fd

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3565885593

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

// running (or starting) service, parking this stale one would leave
// two open IOProcs — possibly on the same Bluetooth device. Parking
// is only for the quiet gap between turns.
if generation <= self.discardLateStartsThroughGeneration || self.audioCaptureService != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Stop a stale start when a newer capture is parked

When turn A's CoreAudio start remains in flight, turn B can start, finish, and park its service before A returns. At that point audioCaptureService is nil even though parkedMicCapture holds B, so this condition lets A take the parking branch; parkMicCapture then asynchronously stops B and replaces it with the revoked older capture, briefly overlapping IOProcs and warming the wrong route. Fresh evidence in this revision is that the new stale-start guard checks only the active service, not a newer parked service; reject A whenever parkedMicCapture already exists.

AGENTS.md reference: desktop/macos/AGENTS.md:L38-L40

Useful? React with 👍 / 👎.

Comment on lines +394 to +395
if let parked = PushToTalkManager.shared.releaseParkedMicCapture() {
await parked.waitForPhysicalStop()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Release captures parked during preferred-device resolution

When Listening starts with a saved microphone and the detached UID resolution is slow, a PTT turn can start and finish during that later await, leaving a newly parked capture after this one-time release has already completed. Ambient capture then proceeds directly to mic.startCapture() without rechecking PTT ownership, so it can open a second IOProc against the same default or selected Bluetooth device. Fresh evidence in this revision is that the teardown handshake now occurs before the independently suspending preferred-device lookup; repeat the ownership handoff after resolution or serialize the entire open boundary.

AGENTS.md reference: AGENTS.md:L43-L43

Useful? React with 👍 / 👎.

Comment on lines +210 to +212
if let preferredName = await Self.resolvePreferredMicrophoneName() {
recordingInputDeviceName = preferredName
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Skip preferred desktop mic resolution for BLE sessions

When the user has a preferred desktop microphone saved but starts transcription from a connected BLE device, the earlier source-selection branch correctly sets recordingInputDeviceName to the BLE device's display name, but this unconditional lookup overwrites it with the desktop microphone name before creating the session. The resulting BLE conversation is persisted—and the live capture-source label can be updated—with the wrong input-device provenance. Fresh evidence in this revision is that the metadata fix is not gated on effectiveSource == .microphone.

Useful? React with 👍 / 👎.

}
}.value
devices = latest
} while refreshQueued && !Task.isCancelled

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve queued refreshes after SwiftUI cancels the old task

When a device-list notification changes the .task(id:) value during a slow enumeration, SwiftUI cancels the old task and starts a new one; the new invocation sees refreshInFlight, sets refreshQueued, and returns. Once the detached enumeration finishes, the cancelled old task reaches this condition with Task.isCancelled == true, discards the requested trailing rerun, and clears refreshInFlight, so a device connected after the completed enumeration's snapshot can remain absent until another notification or the card is reopened. Fresh evidence in this revision is that the coalescer's cancellation check defeats the queued rerun it was added to preserve.

Useful? React with 👍 / 👎.

Comment on lines 2201 to 2202
let leased = lease.snapshot()
Task { @MainActor [weak self] in

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Revoke frame delivery while the capture is parked

After a normal or too-short turn parks the mic for up to 120 seconds, the live IOProc continues invoking this callback for every audio buffer, and each invocation unconditionally snapshots the old lease and allocates a @MainActor task before the generation guard rejects it; the level callback does the same. The supposedly idle keep-alive period therefore continuously converts audio and queues discarded main-executor work, causing avoidable CPU, battery, and UI scheduling load after every PTT turn. Revoke the lease in a form the callbacks can check synchronously, or suppress frame and level delivery while parked.

Useful? React with 👍 / 👎.

Comment on lines +1087 to +1088
isCapturing = false
unregisterActiveCapture()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Remove CoreAudio listeners when reconfiguration gives up

For a system-default capture whose route reconfiguration exhausts all retries, setting isCapturing to false here leaves the still-registered default-device listener installed. A later stopCapture() returns at its guard isCapturing, and deinit also skips removePropertyListeners() for the same reason, so CoreAudio retains the listener block indefinitely; repeated unrecoverable route changes can accumulate registrations and callbacks. Remove the listeners on this terminal failure path before clearing the capture state.

Useful? React with 👍 / 👎.

Comment on lines +406 to +409
let resolved = await Task.detached(priority: .userInitiated) {
AudioCaptureService.inputDeviceID(forUID: preferredUID)
.map { (id: $0, name: AudioCaptureService.deviceName(for: $0)) }
}.value

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Coalesce preferred-microphone HAL resolution

When CoreAudio is slow or wedged and a preferred microphone is saved, each transcription session launches this non-cancellable detached enumeration, while the session-metadata task independently launches another enumeration through resolvePreferredMicrophoneName(). Stopping and retrying transcription cannot cancel either blocked HAL read, so repeated retries accumulate detached workers and can exhaust executor capacity even though the picker and PTT probes are explicitly single-flight for the same reason. Resolve the UID and name through one shared in-flight probe rather than spawning a new detached task at each call site.

Useful? React with 👍 / 👎.

Comment on lines +419 to +421
log(
"Transcription: using preferred microphone \(recordingInputDeviceName ?? "?") (uid=\(preferredUID))"
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Remove the raw CoreAudio UID from logs

When an explicit USB or Bluetooth microphone is selected, this writes its raw CoreAudio UID into the production log. Device UIDs are stable hardware identifiers and can embed vendor, product, or device-serial information, so retaining the value exposes unnecessary identifying data in diagnostics; the numeric route class and bounded device description already provide enough troubleshooting context. Omit or irreversibly redact the UID before logging.

AGENTS.md reference: AGENTS.md:L92-L92

Useful? React with 👍 / 👎.

…provenance and cleanup fixes

Sixth review round (Codex on 3565885), eight fixes:

- Preferred-microphone resolution is now a shared single-flight
  AudioCaptureService.resolvePreferredMicrophone() serialized on one
  dedicated queue: session metadata, capture open, and retries share it,
  so a wedged HAL strands at most one worker instead of accumulating
  detached enumerations.
- The ambient parked-capture handshake moved to be the LAST await before
  the device opens — a PTT turn finishing during the preferred-mic
  resolution can park a fresh capture that the earlier handshake missed.
- Session provenance resolution is gated on effectiveSource == .microphone
  so a BLE session no longer records the desktop mic's name.
- MicCaptureLease gains a parked revocation the audio callbacks check
  synchronously (snapshotIfActive): a parked IOProc no longer allocates a
  main-actor task per audio buffer for up to the whole keep-alive window;
  adoption's renew() reactivates the lease.
- A stale late start is also stopped when a NEWER parked capture exists —
  parking the older capture would displace the newer one and warm the
  wrong route.
- reconfiguration give-up now removes the CoreAudio property listeners it
  would otherwise leak (isCapturing=false makes stopCapture and deinit
  skip cleanup).
- The picker coalescer's trailing rerun survives SwiftUI task
  cancellation — the cancelled owner still runs the rerun the newer
  invocation delegated to it.
- The raw CoreAudio device UID is no longer written to logs (stable
  hardware identifier); the device name suffices.

Verification: swift-format idempotent on all touched files; make
preflight passes all 18 checks; warm-keep-alive tripwires re-verified.
Not compiled locally (no macOS toolchain) — CI is the compile authority.

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TWim8oQvjk8ebdfuuBt5fd

Copy link
Copy Markdown
Collaborator Author

CI note: the red Listen Pusher Stack Gauntlet on 8c730c3f1 is a harness flake, not this PR. The job log shows the mock Parakeet server and the Pusher app racing for the same ephemeral port ([Errno 98] address already in use on 127.0.0.1:47963), so the Pusher server never bound and the listen session's trigger socket got 403s. This PR touches no backend files, and the same Backend Hermetic E2E suite passed on all four previous heads of this branch with byte-identical backend content. A re-run should go green — I don't have re-run permissions from this session, so if it's gating, a manual re-run of the failed job is all it needs. The port-allocation race in the gauntlet harness may deserve its own issue if it recurs.


Generated by Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8c730c3f13

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +211 to +214
if effectiveSource == .microphone,
let preferredName = await AudioCaptureService.resolvePreferredMicrophone()?.name
{
recordingInputDeviceName = preferredName

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reject session creation after the recording has stopped

When a preferred-microphone HAL lookup is slow and the user stops or restarts Listening before this await returns, stopTranscription() observes currentSessionId == nil and therefore has no session to finish. This task then resumes anyway, creates a session for the stopped recording, and assigns it to the shared currentSessionId; if another recording has started, the stale task can overwrite that recording's session pointer and send subsequent persistence/finalization to the wrong session. Capture recordingGeneration for this task and revalidate it after the lookup, closing any session that becomes stale after creation.

Useful? React with 👍 / 👎.

Comment on lines +394 to +398
let replacement = AudioCaptureService(overrideDeviceID: resolved.id)
configureSharedCaptureWatchdog(replacement)
audioCaptureService = replacement
mic = replacement
recordingInputDeviceName = resolved.name ?? recordingInputDeviceName

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Publish preferred microphone name changes

When Listening starts in Always or Mic-only mode with an explicit microphone, isTranscribing publishes while recordingInputDeviceName still contains the system-default name, and this later assignment emits no objectWillChange because that AppState property is not @Published. Consequently CaptureListeningLogic.listeningModeTitle can keep showing the default microphone even after capture has opened the selected device, until some unrelated published state changes. Make the capture-source property observable or explicitly publish when the resolved route is installed.

Useful? React with 👍 / 👎.

…source name

Seventh review round (Codex on 8c730c3), two fixes:

- The crash-safe session task now captures recordingGeneration and
  revalidates it after the preferred-mic HAL await, before creating the
  session, and before assigning currentSessionId (guarding the whole task,
  not just the assignment closure, so the backend binding below cannot run
  against a stale session either). A recording stopped — or stopped and
  restarted — during a slow HAL lookup can no longer have a session created
  for it posthumously or have a newer recording's session pointer
  overwritten; an orphaned created-but-unassigned row is left to the
  crash-safe reconciler by design.
- recordingInputDeviceName is now @published: the capture-source label
  reads it, and the preferred-mic resolution assigns it after
  isTranscribing has already published — as a plain var the UI kept
  showing the default device until unrelated state churned.

Verification: swift-format idempotent on both touched files; make
preflight passes all 18 checks. Not compiled locally (no macOS
toolchain) — CI is the compile authority. Committed behind the in-flight
Desktop Swift CI run on 8c730c3; pushed only after that verdict so the
first uncancelled compile+test result is not reset.

Failure-Class: none

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TWim8oQvjk8ebdfuuBt5fd
@eulicesl
eulicesl merged commit be04764 into main Jul 31, 2026
24 of 25 checks passed
@eulicesl
eulicesl deleted the claude/meta-rayban-ios-pr-j34v0q branch July 31, 2026 03:23

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d5c10e1e89

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +218 to +221
guard recordingGeneration == sessionGeneration else { return }
recordingInputDeviceName = preferredName
}
guard recordingGeneration == sessionGeneration else { return }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Revoke the session generation when Listening stops

If the user stops Listening while preferred-microphone resolution is in flight without immediately restarting, both generation guards still pass: recordingGeneration is incremented only by startTranscription() and is never changed by stopTranscription() or state clearing. The task can therefore create a session after the recording has stopped, install its ID into currentSessionId, and let a later recording persist against that stale session. Fresh evidence after the attempted generation guard is the absence of any terminal generation increment; revoke the generation on stop or also validate the active recording identity/state.

AGENTS.md reference: desktop/macos/AGENTS.md:L38-L40

Useful? React with 👍 / 👎.

VStack(spacing: OmiSpacing.xl) {
// Microphone (input device — e.g. Ray-Ban Meta glasses)
settingsCard(settingId: "transcription.microphone") {
MicrophonePickerCard(onChanged: { restartTranscriptionIfNeeded() })

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Await the local recording shutdown before restarting

When a microphone row is selected during the default Apple Silicon on-device STT path, this invokes the fixed-delay restart helper, but stopTranscription() returns before its task finishes awaiting mic.finish() and sys.finish(). If either tail drain exceeds one second, the new recording starts first; the old task then runs clearTranscriptionState(), clearing the new session ID, transcript, and Live Notes state, while late old segments can also enter the new recording. Chain the restart to completion of the old shutdown rather than using the timer.

AGENTS.md reference: desktop/macos/AGENTS.md:L38-L40

Useful? React with 👍 / 👎.

Comment on lines +405 to +410
if let resolved {
let replacement = AudioCaptureService(overrideDeviceID: resolved.id)
configureSharedCaptureWatchdog(replacement)
audioCaptureService = replacement
mic = replacement
recordingInputDeviceName = resolved.name ?? recordingInputDeviceName

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Confirm the preferred device used at capture start

If the selected microphone disconnects after this resolution but before startCapture() opens it—particularly while awaiting parked-PTT teardown—the override service's resolveInputDeviceID() silently falls back to the system default. This assignment and the session-creation task still retain the preferred device's name, while the resolved == nil fallback telemetry branch is skipped, so the UI and persisted provenance claim the wrong microphone and the mode switch is invisible in diagnostics. Propagate the device actually opened, or revalidate the override at the open boundary and record the fallback.

AGENTS.md reference: desktop/macos/AGENTS.md:L48-L49

Useful? React with 👍 / 👎.

} else {
audioCaptureService?.stopCapture()
if !parkWarm {
discardParkedMicCapture()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Await parked capture teardown at the owner fence

When an effective-owner transition occurs while the PTT microphone is parked, terminal cleanup reaches this branch and discards the parked service reference after merely enqueueing its HAL stop. quiesceForEffectiveOwnerTransition() only saves and awaits audioCaptureService, which is nil for a parked capture, so it returns to the account transition while the previous owner's IOProc may still be physically alive; a new owner can then start ambient or PTT capture during that teardown and recreate the cross-capture contention. Preserve the released parked service and await waitForPhysicalStop() as part of the owner fence.

AGENTS.md reference: desktop/macos/AGENTS.md:L38-L40

Useful? React with 👍 / 👎.

Comment on lines +15 to +18
XCTAssertTrue(source.contains("let generation = micCaptureGeneration"))
XCTAssertTrue(source.contains("self.parkMicCapture(capture, lease: lease, overrideID: overrideDeviceID)"))
XCTAssertTrue(source.contains("self.audioCaptureService === capture"))
XCTAssertTrue(source.contains("PushToTalkManager: mic capture start completed after turn ended — parked warm"))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add behavioral coverage for warm capture ownership

These assertions only verify that selected implementation strings remain in the source, so the suite still passes if parking, adoption, generation rejection, or contention ordering is behaviorally broken—as several race paths can retain every asserted string while doing the wrong thing. The component test rules explicitly state that source inspection cannot replace a production-API behavioral test; introduce a controllable capture seam and assert the park/adopt/terminal outcomes instead of treating these tripwires as the regression coverage.

AGENTS.md reference: desktop/macos/AGENTS.md:L178-L184

Useful? React with 👍 / 👎.

Comment on lines +38 to +39
if AudioCaptureService.isMetaGlassesName(name) {
return "Ray-Ban Meta"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the Oakley Meta product name

isMetaGlassesName() explicitly classifies names containing oakley meta as Meta glasses, but every matching device is relabeled here as “Ray-Ban Meta.” Consequently an Oakley Meta user sees the wrong product and brand in both Listening status surfaces even though CoreAudio supplied the correct name. Return the selected device's name for non-Ray-Ban matches, or distinguish the recognized product families.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants