forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPushToTalkManager.swift
More file actions
4193 lines (3939 loc) · 188 KB
/
Copy pathPushToTalkManager.swift
File metadata and controls
4193 lines (3939 loc) · 188 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
@preconcurrency import AVFoundation
import Cocoa
import Combine
@preconcurrency import CoreAudio
import OmiSupport
import VoiceTurnDomain
struct PTTSilentMicRecoveryPolicy {
enum RecoveryOutcome: String, Equatable {
case succeeded
case failed
}
struct DiscardedTurnDecision: Equatable {
let shouldRebuildCapture: Bool
let recoveryOutcome: RecoveryOutcome?
}
static let deadMicPeakThreshold = 5
static let minDeadTurnSeconds: TimeInterval = 0.25
static let consecutiveDeadTurnThreshold = 2
/// The first dead turn of a session rebuilds on its own. Waiting for a second
/// one assumes the user will press again, and on a fresh install they mostly
/// do not: the first press is the one that fails, it fails silently as
/// "Hold longer to record", and the recovery that exists for exactly this
/// never runs. Once a rebuild has been issued, the ordinary two-turn threshold
/// applies again so a genuinely broken mic cannot spin.
static let firstRecoveryDeadTurnThreshold = 1
private(set) var consecutiveDeadMicTurns = 0
private var awaitingRecoveryOutcome = false
/// Set once this policy has issued a capture rebuild. Gates the lower
/// first-of-session threshold above.
private(set) var hasRequestedRecovery = false
/// - Parameters:
/// - holdSec: wall time the user held the key. Judgeability is measured on
/// the press, not on delivered audio: a capture that never became
/// operational reports zero seconds, which read as "too short to judge"
/// and made the dead-mic evidence for the worst failure class invisible.
/// - totalSec: audio the capture actually delivered.
mutating func recordDiscardedTurn(
holdSec: TimeInterval,
totalSec: TimeInterval,
peak: Int
) -> DiscardedTurnDecision {
let recoveryOutcome: RecoveryOutcome?
let shouldRebuildCapture: Bool
let judgeableSeconds = Swift.max(holdSec, totalSec)
if peak > Self.deadMicPeakThreshold {
// Audible input proves the mic is alive, so a pending rebuild succeeded.
// It does not clear a dead-turn streak: a turn that was audible and still
// discarded is not evidence that capture is healthy for a whole turn, and
// clearing here is what let the observed fresh-install sequence (dead,
// audible, audible, dead) never reach the rebuild threshold. Only a turn
// that actually committed proves that, and that goes through
// `recordSuccessfulTurn`.
recoveryOutcome = resolveRecoveryOutcome(.succeeded)
shouldRebuildCapture = false
} else if judgeableSeconds >= Self.minDeadTurnSeconds {
recoveryOutcome = resolveRecoveryOutcome(.failed)
consecutiveDeadMicTurns += 1
let threshold =
hasRequestedRecovery ? Self.consecutiveDeadTurnThreshold : Self.firstRecoveryDeadTurnThreshold
shouldRebuildCapture = consecutiveDeadMicTurns >= threshold
if shouldRebuildCapture {
// Arm the outcome before issuing the side effect. This prevents a third
// consecutive turn from asking for a second rebuild while the first awaits
// its next judgeable turn.
consecutiveDeadMicTurns = 0
awaitingRecoveryOutcome = true
hasRequestedRecovery = true
}
} else {
// A press too short to judge carries no evidence either way — an accidental
// tap that released before CoreAudio could deliver a frame. It must not
// erase a dead-mic streak or resolve a pending rebuild.
recoveryOutcome = nil
shouldRebuildCapture = false
}
return DiscardedTurnDecision(
shouldRebuildCapture: shouldRebuildCapture,
recoveryOutcome: recoveryOutcome)
}
mutating func recordSuccessfulTurn() -> RecoveryOutcome? {
consecutiveDeadMicTurns = 0
return resolveRecoveryOutcome(.succeeded)
}
/// Bluetooth silent-mic fallback only needs the dead-mic streak cleared. It must
/// not arm `capture_rebuild` outcomes — that recovery uses `switch_to_built_in_mic`.
mutating func recordCaptureRebuild() {
consecutiveDeadMicTurns = 0
}
/// Arm truthful success/failure reporting for a CoreAudio capture rebuild. Used by
/// both the dead-mic threshold path and the mid-turn silent-mic watchdog rebuild.
mutating func armCaptureRebuildOutcome() {
consecutiveDeadMicTurns = 0
awaitingRecoveryOutcome = true
hasRequestedRecovery = true
}
private mutating func resolveRecoveryOutcome(_ outcome: RecoveryOutcome) -> RecoveryOutcome? {
guard awaitingRecoveryOutcome else { return nil }
awaitingRecoveryOutcome = false
return outcome
}
}
/// Routes a shortcut press through the reveal decision. Both PTT entry points call this,
/// so injecting `reveal`/`start` in a test exercises the shipping ordering rather than a
/// restatement of it.
///
/// The bar used to swallow the very press that revealed it, which cost the start sound,
/// the listening animation and — a double tap being two presses — locked mode. That bit
/// every press on a second display, where following the cursor re-places the window so it
/// is routinely not yet visible.
enum PushToTalkBarRevealPolicy {
/// Reveals the bar when it is hidden, then *always* starts the turn.
static func startPress(
barVisible: Bool,
reveal: () -> Void,
start: () -> Void
) {
if !barVisible { reveal() }
start()
}
}
/// Modifier-only shortcuts (Option, Fn, etc.) overlap with normal text editing:
/// Option-arrow navigation and dead-key entry first emit `flagsChanged`, then a
/// normal key-down. Do not let that first modifier event barge into an active
/// spoken reply before the accompanying editing key arrives.
///
/// The gate deliberately has no timing policy. `PushToTalkManager` supplies the
/// short hold delay, while this model makes the admission/cancellation contract
/// deterministic and independently testable.
struct ModifierOnlyPTTActivationGate {
enum Action: Equatable {
case scheduleStart
case cancelPendingStart
/// The modifier was released before the activation delay elapsed and no other
/// key was pressed with it: a deliberate quick tap. No turn was started (an
/// accidental brush of the modifier must stay inert), but the tap is real
/// input and is offered to the double-tap detector.
case cancelPendingStartAsQuickTap
case releaseStartedTurn
case none
}
private(set) var hasPendingStart = false
private(set) var hasStartedTurn = false
mutating func modifierStateChanged(isShortcutActive: Bool) -> Action {
if isShortcutActive {
guard !hasPendingStart, !hasStartedTurn else { return .none }
hasPendingStart = true
return .scheduleStart
}
if hasPendingStart {
hasPendingStart = false
return .cancelPendingStartAsQuickTap
}
guard hasStartedTurn else { return .none }
hasStartedTurn = false
return .releaseStartedTurn
}
mutating func nonModifierKeyPressed() -> Action {
guard hasPendingStart else { return .none }
hasPendingStart = false
return .cancelPendingStart
}
mutating func consumePendingStart() -> Bool {
guard hasPendingStart else { return false }
hasPendingStart = false
hasStartedTurn = true
return true
}
mutating func cancelPendingStart() {
hasPendingStart = false
}
mutating func reset() {
hasPendingStart = false
hasStartedTurn = false
}
}
extension Notification.Name {
static let coreAudioCaptureRecoveryRequested = Notification.Name("coreAudioCaptureRecoveryRequested")
}
#if DEBUG
struct PTTOwnerBoundarySnapshot: Equatable {
let activeTurnID: VoiceTurnID?
let hasCaptureDriver: Bool
let captureStartInFlight: Bool
let hasTranscriptionDriver: Bool
let hasOmniDriver: Bool
let captureGeneration: UInt64
}
#endif
/// One delegate instance belongs to one reducer-issued transcription effect.
/// Retiring the proxy when its physical service stops prevents a late callback
/// from service A from reading service B's current turn identity.
@MainActor
private final class VoiceTurnOmniDelegateProxy: RealtimeOmniServiceDelegate {
weak var owner: PushToTalkManager?
let identity: VoiceEffectIdentity
init(owner: PushToTalkManager, identity: VoiceEffectIdentity) {
self.owner = owner
self.identity = identity
}
func omniDidConnect() { owner?.omniDidConnect(identity: identity) }
func omniDidReceiveInputTranscript(_ text: String, isFinal: Bool, itemID: String?) {
owner?.omniDidReceiveInputTranscript(
text, isFinal: isFinal, itemID: itemID, identity: identity)
}
func omniDidReceiveAudio(_ pcm24k: Data) {
owner?.omniDidReceiveAudio(pcm24k, identity: identity)
}
func omniDidFinishTurn() { owner?.omniDidFinishTurn(identity: identity) }
func omniDidError(_ message: String) { owner?.omniDidError(message, identity: identity) }
}
/// Push-to-talk manager for voice input via the Option (⌥) key.
///
/// State machine:
/// idle → [Option down] → listening → [Option up] → finalizing → sends query → idle
/// idle → [Quick tap] → pendingLockDecision → [tap again within 400ms] → lockedListening
/// pendingLockDecision → [timeout] → finalizing → sends query → idle
@MainActor
class PushToTalkManager: ObservableObject {
static let shared = PushToTalkManager()
/// An automation turn drives provider/reducer boundaries itself;
/// it has no physical capture buffer for this manager to silence-gate. Let the
/// reducer reach `.finalizing`, then leave the exact commit to the harness.
nonisolated static func shouldFinalizeCapturedInputPhysically(
turnIntent: VoiceTurnIntent?
) -> Bool {
turnIntent != .automation
}
/// Whether a shortcut-down may begin a fresh capture generation. The reducer
/// owns supersession: response phases are deliberately admitted here so its
/// `.start` event can atomically interrupt the old turn before mic capture
/// for the new turn begins. Recording/finalizing phases remain exclusive to
/// their existing physical capture lifecycle.
nonisolated static func admitsListeningStart(
activeTurnID: VoiceTurnID?,
phase: VoiceTurnPhase?
) -> Bool {
guard activeTurnID != nil else { return true }
switch phase {
case .pendingLockDecision, .awaitingResponse, .awaitingTools, .awaitingJournal, .playing:
return true
case .idle, .recording, .lockedRecording, .finalizing, .terminal, .none:
return false
}
}
private let voiceTurnCoordinator = VoiceTurnCoordinator.shared
private var voiceTurnSnapshotObservation: VoiceTurnSnapshotObservation?
/// A projection of the authoritative reducer. This manager owns microphone and
/// provider I/O only; it never stores a second logical lifecycle state.
var phase: VoiceTurnPhase? { voiceTurnCoordinator.activeTurn?.phase }
private var currentVoiceTurnID: VoiceTurnID? { voiceTurnCoordinator.activeTurnID }
private var isIdle: Bool { currentVoiceTurnID == nil }
// MARK: - Private Properties
private var globalMonitor: Any?
private var localMonitor: Any?
private var modifierOnlyActivationGate = ModifierOnlyPTTActivationGate()
private var modifierOnlyShortcutStartWorkItem: DispatchWorkItem?
/// Give text-editing chords (Fn-arrow, Option-letter, etc.) enough time to
/// deliver their accompanying key-down before treating a modifier-only press
/// as an intentional PTT barge-in. This is below perceptual PTT latency.
private static let modifierOnlyShortcutActivationDelay: TimeInterval = 0.08
private var barState: FloatingControlBarState?
private var automationBarState: FloatingControlBarState?
private var automationCaptureBypass = false
/// The ordinary bridge start/stop probe intentionally avoids providers. This
/// opt-in lane exercises the same manager routing and controller admission as
/// a physical hold, while injecting PCM rather than opening CoreAudio.
private var automationExercisesRealtimePath = false
/// Capture-only `ptt_start` must not block on WindowServer. The realtime
/// automation path (`beginRealtimePushToTalkForAutomation`, `ptt_manager_turn`,
/// synthetic PCM) still needs the pre-overlay frame for the screen-evidence
/// protocol and native OCR, so it is excluded.
private var skipsCompositorCaptureForAutomation: Bool {
automationCaptureBypass && !automationExercisesRealtimePath
}
// Double-tap detection
private var lastOptionDownTime: TimeInterval = 0
private var lastOptionUpTime: TimeInterval = 0
/// Uptime of the last modifier-only quick tap that did not start a turn.
private var lastModifierQuickTapTime: TimeInterval = 0
private let doubleTapThreshold: TimeInterval = 0.4
/// Longest hold that still counts as a tap and opens the tap-to-lock window.
/// Read by the discard judgement's tests: a tap this short must always be a
/// short tap, never a late capture, and that only holds while the hold is
/// latched at key-up rather than at the lock deadline.
nonisolated static let tapToLockMaxHoldDuration: TimeInterval = 0.22
// Transcription
private var transcriptionService: TranscriptionService?
// Realtime omni STT (replaces Deepgram). Connects through the omi backend relay.
private var realtimeOmniService: RealtimeOmniService?
private var omniDelegateProxy: VoiceTurnOmniDelegateProxy?
// Realtime-as-hub (Phase 1): when active, the realtime model is THE hub — it does
// in-session STT + reasoning + routing (tool choice) + speaks the reply. Mic PCM is
// streamed to RealtimeHubController; there is no transcript→router→ChatProvider hop.
// Mic chunks captured before the relay finishes connecting (raw 16k PCM),
// flushed once the service exists so the user's first words aren't clipped.
private var omniPreconnectBuffer: [Data] = []
// True once the omni model returned any transcript this turn — gates the
// Batch-STT fallback so a benign trailing socket error doesn't trigger it.
private var audioCaptureService: AudioCaptureService?
private var micCaptureStartInFlight = false
private var silentMicRecoveryPolicy = PTTSilentMicRecoveryPolicy()
/// Privacy-bounded capture-lifecycle correlation for each PTT attempt and any
/// recovery it triggers. Fed from the same seams as the late silent-turn
/// snapshot; emits one classified `ptt_audio_capture_lifecycle` event.
private let pttLifecycle = PTTAttemptLifecycleRecorder()
private var micCaptureGeneration: UInt64 = 0
private var transcriptSegments: [String] = []
// Stable provider item ids of finals already appended this turn. Dedup relay
// re-deliveries by id, never by text (INV-6: never dedupe by user text), so a
// legitimately repeated phrase within a turn is not silently dropped. Reset
// wherever transcriptSegments is reset.
private var seenFinalSegmentIDs: Set<String> = []
private var lastInterimText: String = ""
/// Owns the "type <text>" branch of a turn: whether this utterance dictates
/// into the focused app instead of asking Omi, and the paste if it does.
private let voiceTypeSession = VoiceTypeSession()
/// 60s of 16 kHz mono s16le.
private var hasMicPermission: Bool = false
private var isCurrentSessionFollowUp = false
private var currentContextSnapshot: PTTContextSnapshot?
/// OCR text of this turn's pre-overlay frame, waiting briefly for the in-flight OCR when the
/// realtime model escalates before it finished. Nil when no turn is capturing.
func visibleScreenText(timeout: TimeInterval) async -> String? {
let deadline = Date().addingTimeInterval(timeout)
while currentVoiceTurnID != nil {
if let snapshot = currentContextSnapshot { return snapshot.visibleText }
if Date() >= deadline { return nil }
try? await Task.sleep(nanoseconds: 100_000_000)
}
return nil
}
private var contextCaptureTask: Task<Void, Never>?
// Batch mode: accumulate raw audio for post-recording transcription
private var batchAudioBuffer = Data()
private let batchAudioLock = NSLock()
/// Hard cap on a single turn's buffered PCM (16 kHz mono int16) so a runaway
/// (>~4.5 min) dictation can't grow RSS without bound. Kept just under the
/// backend's ~5-min limit (HTTP 413) so we surface a client-side warning before
/// buffering forever and failing at submit. 4.5 min × 16000 Hz × 2 bytes.
nonisolated static let maxBatchAudioBytes = Int(4.5 * 60) * 16_000 * 2
/// Set once per turn when the buffer hits the cap, so the warning fires once.
private var batchAudioOverflowSignaled = false
private static let hubWarmGraceSeconds: TimeInterval = 1.0
private var activeVoiceRoute: VoiceTurnRoute? {
voiceTurnCoordinator.activeTurn?.route
}
private var isOmniSTT: Bool {
activeVoiceRoute == .omniSTT
}
private var isWaitingForHub: Bool {
activeVoiceRoute == .hubWarmWait
}
private var isOnDeviceASR: Bool {
activeVoiceRoute == .onDeviceASR
}
private var isHubMode: Bool {
if case .hub = activeVoiceRoute { return true }
return false
}
private var voiceTypingObservation: AnyCancellable?
private init() {
voiceTypingObservation = voiceTypeSession.objectWillChange.sink { [weak self] in
self?.objectWillChange.send()
}
}
// MARK: - Setup / Teardown
func setup(barState: FloatingControlBarState) {
self.barState = barState
configureVoiceTurnCoordinator(barState: barState)
hasMicPermission = AudioCaptureService.checkPermission()
warmPTTInputRouting()
installEventMonitors()
// Realtime hub: wire it to the bar and warm the WS if it's enabled + BYOK-keyed,
// so the persistent socket is ready before the first PTT (and stays warm after).
RealtimeHubController.shared.setup()
// Hermetic local harness has no Firebase SDK and no live realtime providers.
if !DesktopLocalProfile.isEnabled {
RealtimeHubController.shared.ensureWarm(userInitiated: true)
}
log("PushToTalkManager: setup complete, micPermission=\(hasMicPermission)")
}
func configureVoiceTurnCoordinator(barState: FloatingControlBarState) {
voiceTurnCoordinator.configure(barState: barState)
voiceTurnCoordinator.setEffectHandler { [weak self] effect in
self?.handleVoiceTurnEffect(effect)
}
voiceTurnSnapshotObservation?.cancel()
voiceTurnSnapshotObservation = voiceTurnCoordinator.observeSnapshots { [weak self] _ in
self?.objectWillChange.send()
}
}
func cleanup() {
stopListening()
voiceTurnCoordinator.reset()
audioCaptureService = nil
resetModifierOnlyShortcutActivation()
removeEventMonitors()
log("PushToTalkManager: cleanup complete")
}
// MARK: - Event Monitors
private func installEventMonitors() {
// Remove any existing monitors to make setup() safely re-entrant
removeEventMonitors()
let monitorMask: NSEvent.EventTypeMask = [.flagsChanged, .keyDown, .keyUp]
// Global monitor — fires when OTHER apps are focused
globalMonitor = NSEvent.addGlobalMonitorForEvents(matching: monitorMask) {
[weak self] event in
Task { @MainActor in
self?.handleShortcutEvent(event)
}
}
// Local monitor — fires when THIS app is focused
localMonitor = NSEvent.addLocalMonitorForEvents(matching: monitorMask) { [weak self] event in
Task { @MainActor in
self?.handleShortcutEvent(event)
}
return event
}
log("PushToTalkManager: event monitors installed")
}
private func removeEventMonitors() {
resetModifierOnlyShortcutActivation()
if let monitor = globalMonitor {
NSEvent.removeMonitor(monitor)
globalMonitor = nil
}
if let monitor = localMonitor {
NSEvent.removeMonitor(monitor)
localMonitor = nil
}
}
private func handleVoiceTurnEffect(_ effect: VoiceTurnEffect) {
switch effect {
case .stopCapture(let turnID, let captureID):
_ = stopMicCapture(captureID: captureID)
_ = turnID
case .finalizeCapturedInput(let turnID):
guard voiceTurnCoordinator.activeTurnID == turnID else { return }
guard
Self.shouldFinalizeCapturedInputPhysically(
turnIntent: voiceTurnCoordinator.activeTurn?.intent)
else {
log("PushToTalkManager: local automation turn owns synthetic captured-input finalization")
return
}
continueFinalization()
case .commitClaimedHubInput(let turnID):
RealtimeHubController.shared.commitClaimedHubInput(turnID: turnID)
case .prepareHubInput(let turnID, _):
guard voiceTurnCoordinator.activeTurnID == turnID else { return }
resolveRealtimeHubWarmWait(ready: true)
case .transcriptionFinalizationTimedOut(let turnID, let mode):
guard voiceTurnCoordinator.activeTurnID == turnID,
voiceTurnCoordinator.activeTurn?.phase == .finalizing
else { return }
switch mode {
case .omni:
log("PushToTalkManager: omni finalization timeout — falling back to backend batch STT")
fallBackToBatchTranscription(reason: "timeout")
case .live:
log("PushToTalkManager: live finalization timeout — sending transcript")
sendTranscript(turnID: turnID)
}
case .screenEvidenceProtocolExpired(let turnID, let token):
RealtimeHubController.shared.expireScreenEvidenceProtocol(turnID: turnID, token: token)
case .finalizeJournal(let turnID, let identity):
guard voiceTurnCoordinator.activeTurnID == turnID else { return }
if Self.isHubRoute(voiceTurnCoordinator.activeTurn?.route ?? .undecided) {
RealtimeHubController.shared.finalizeJournal(turnID: turnID, identity: identity)
}
case .cancelHub(let turnID, let route):
if Self.isHubRoute(route) {
_ = RealtimeHubController.shared.cancelTurn(turnID: turnID)
}
case .fallbackToTranscription(let turnID, let reason):
guard voiceTurnCoordinator.activeTurnID == turnID else { return }
RealtimeHubController.shared.abandonInputPreparation(turnID: turnID)
// A dictation has already left the hub behind; the warm deadline firing
// under it must not start the omni cascade over a turn that types.
guard !voiceTypeSession.claimsTurn else {
log("PushToTalkManager: hub warm deadline ignored — turn is a dictation")
return
}
recordBackupTranscriptionFallback(reason: reason)
resolveRealtimeHubWarmWait(ready: false)
case .stopPlayback(let lease):
if lease.lane == .nativeRealtime {
_ = RealtimeHubController.shared.stopNativePlayback(lease: lease)
} else {
_ = FloatingBarVoicePlaybackService.shared.interruptCurrentResponse(leaseID: lease.id)
}
case .terminal(let record):
RealtimeHubController.shared.voiceTurnDidTerminate(turnID: record.turnID)
performTerminalCleanup(
discardBufferedAudio: record.reason == .ownerChanged,
parkWarm: Self.terminalReasonKeepsWarmCapture(record.reason))
case .scheduleDeadline, .cancelDeadline, .cancelAllDeadlines,
.staleEventDropped, .invalidTransition:
break
}
}
nonisolated static func isHubRoute(_ route: VoiceTurnRoute) -> Bool {
switch route {
case .hub, .hubWarmWait:
return true
case .undecided, .omniSTT, .deepgramBatch, .deepgramLive, .onDeviceASR:
return false
}
}
// MARK: - Shortcut Handling
private func handleShortcutEvent(_ event: NSEvent) {
guard ShortcutSettings.shared.pttEnabled else { return }
let shortcut = ShortcutSettings.shared.pttShortcut
switch event.type {
case .flagsChanged:
guard shortcut.modifierOnly else { return }
handleModifierOnlyShortcutStateChanged(
isShortcutActive: shortcut.matchesFlagsChanged(event))
return
case .keyDown:
if shortcut.modifierOnly {
if modifierOnlyActivationGate.nonModifierKeyPressed() == .cancelPendingStart {
cancelPendingModifierOnlyShortcutStart()
}
return
}
guard !event.isARepeat else { return }
handleKeyShortcutDown(isShortcutActive: shortcut.matchesKeyDown(event))
case .keyUp:
guard !shortcut.modifierOnly else { return }
if shortcut.matchesKeyUp(event) {
handleShortcutUp()
}
default:
return
}
}
private func handleModifierOnlyShortcutStateChanged(isShortcutActive: Bool) {
switch modifierOnlyActivationGate.modifierStateChanged(isShortcutActive: isShortcutActive) {
case .scheduleStart:
scheduleModifierOnlyShortcutStart()
case .cancelPendingStart:
cancelPendingModifierOnlyShortcutStart()
case .cancelPendingStartAsQuickTap:
cancelPendingModifierOnlyShortcutStart()
handleModifierOnlyQuickTap()
case .releaseStartedTurn:
handleShortcutUp()
case .none:
break
}
}
private func scheduleModifierOnlyShortcutStart() {
guard modifierOnlyShortcutStartWorkItem == nil else { return }
let workItem = DispatchWorkItem { [weak self] in
guard let self, self.modifierOnlyActivationGate.consumePendingStart() else { return }
self.modifierOnlyShortcutStartWorkItem = nil
self.handleKeyShortcutDown(isShortcutActive: true)
}
modifierOnlyShortcutStartWorkItem = workItem
DispatchQueue.main.asyncAfter(
deadline: .now() + Self.modifierOnlyShortcutActivationDelay,
execute: workItem)
}
/// A modifier-only shortcut released inside `modifierOnlyShortcutActivationDelay`
/// never starts a turn — that delay is what keeps an accidental brush of the
/// modifier (or the modifier held as part of another shortcut) from recording.
/// A *pair* of such taps is unambiguous intent, so it drives locked mode, and a
/// tap while already locked sends, matching "Tap again to send".
private func handleModifierOnlyQuickTap() {
guard ShortcutSettings.shared.doubleTapForLock else { return }
let now = ProcessInfo.processInfo.systemUptime
if phase == .lockedRecording {
lastModifierQuickTapTime = 0
finalize()
return
}
guard (now - lastModifierQuickTapTime) < doubleTapThreshold else {
// First tap: stay completely inert. Nothing records, nothing is shown.
lastModifierQuickTapTime = now
return
}
lastModifierQuickTapTime = 0
// Same reveal rule as a held press: the lock must happen even when the bar was not
// showing on this display yet, or the double tap is lost on a second monitor.
PushToTalkBarRevealPolicy.startPress(
barVisible: FloatingControlBarManager.shared.isVisible,
reveal: { FloatingControlBarManager.shared.show() },
start: {
log("PushToTalkManager: modifier-only double tap — entering locked listening")
self.enterLockedListening()
})
}
private func cancelPendingModifierOnlyShortcutStart() {
modifierOnlyShortcutStartWorkItem?.cancel()
modifierOnlyShortcutStartWorkItem = nil
modifierOnlyActivationGate.cancelPendingStart()
}
private func resetModifierOnlyShortcutActivation() {
modifierOnlyShortcutStartWorkItem?.cancel()
modifierOnlyShortcutStartWorkItem = nil
modifierOnlyActivationGate.reset()
}
private func handleKeyShortcutDown(isShortcutActive: Bool) {
guard isShortcutActive else { return }
// Let the first shortcut press reveal the compact bar instead of requiring it
// to already be visible. This keeps onboarding step 3 quiet on entry while
// still allowing the user to trigger the bar by pressing the key.
PushToTalkBarRevealPolicy.startPress(
barVisible: FloatingControlBarManager.shared.isVisible,
reveal: {
FloatingControlBarManager.shared.show()
log("PushToTalkManager: revealed the bar for this press — starting the turn")
},
start: { self.handleShortcutDown() })
}
private func handleShortcutDown() {
let now = ProcessInfo.processInfo.systemUptime
switch phase {
case .idle, .awaitingResponse, .awaitingTools, .awaitingJournal, .playing, .terminal, .none:
// Check for double-tap: if last Option-up was recent, enter locked mode
// A first tap can arrive either as a completed turn (`lastOptionUpTime`) or, on a
// modifier-only key, as a quick tap that never started one. Either counts, so a
// double tap locks even when the two taps differ in speed.
let recentFirstTap = max(lastOptionUpTime, lastModifierQuickTapTime)
if ShortcutSettings.shared.doubleTapForLock && (now - recentFirstTap) < doubleTapThreshold {
lastOptionUpTime = 0
lastModifierQuickTapTime = 0
enterLockedListening()
} else {
lastOptionDownTime = now
startListening()
}
case .recording:
// Already listening (hold mode), ignore repeated flagsChanged
break
case .pendingLockDecision:
stopListening(endInterjectHold: false)
enterLockedListening()
case .lockedRecording:
// Tap while locked → finalize
finalize()
case .finalizing:
break
}
}
private func handleShortcutUp() {
let now = ProcessInfo.processInfo.systemUptime
switch phase {
case .recording:
let holdDuration = now - lastOptionDownTime
// The key is up: latch the hold here, not at finalization. Finalization can
// be a whole `lockDecision` window (0.4 s) later on the tap-to-lock path —
// which is on by default — and a second or more later on a cold realtime
// hub. Either wait would otherwise be counted as part of the user's press,
// and every sub-220 ms tap would be reported as a capture failure.
//
// The modifier-only chord starts its attempt `modifierOnlyShortcutActivationDelay`
// after the physical key-down, so the hold under-reports by that much. That
// is the safe direction: it can only turn a capture failure into "hold
// longer", never the reverse, so it cannot contaminate the
// `capture_never_operational` measurement.
pttLifecycle.noteRelease()
if ShortcutSettings.shared.doubleTapForLock && holdDuration < Self.tapToLockMaxHoldDuration {
lastOptionUpTime = now
lastModifierQuickTapTime = 0
enterPendingLockDecision()
} else {
lastOptionUpTime = 0
// Long hold released — finalize immediately
finalize()
}
case .pendingLockDecision:
break
case .lockedRecording:
// In locked mode, Option-up is ignored (we finalize on next Option-down)
break
case .idle, .finalizing, .awaitingResponse, .awaitingTools, .awaitingJournal, .playing,
.terminal, .none:
break
}
}
// MARK: - Listening Lifecycle
/// True iff the user is on the Omi account (not BYOK) and has hit the monthly free-tier
/// chat-question limit. PTT turns count toward that limit (desktop_chat_realtime), so they
/// must be gated by it too — same as typed chat (ChatProvider / floating bar). Without this,
/// a free user over 30 questions could keep talking for free. Posts the same usage-limit
/// popup and returns true so the caller early-returns.
private func isBlockedByUsageLimit() -> Bool {
guard isPushToTalkUsageLimitBlocked else { return false }
log("PushToTalkManager: PTT blocked — monthly free-tier chat limit reached")
NotificationCenter.default.post(
name: .showUsageLimitPopup, object: nil, userInfo: ["reason": "ptt"])
return true
}
private func startListening() {
guard Self.admitsListeningStart(activeTurnID: currentVoiceTurnID, phase: phase) else {
log("PushToTalkManager: startListening ignored — phase=\(String(describing: phase))")
return
}
if isBlockedByUsageLimit() { return }
_ = voiceTurnCoordinator.begin(intent: .hold)
RealtimeHubController.shared.prefetchVoiceContextSnapshotIfNeeded()
warmPTTInputRouting()
// Reset the overflow flag under the buffer lock so it's atomic w.r.t. the
// audio thread's appendBatchAudioBounded (fresh turn → allow the warning again).
batchAudioLock.lock()
batchAudioOverflowSignaled = false
batchAudioLock.unlock()
FloatingBarVoicePlaybackService.shared.interruptCurrentResponse()
if ShortcutSettings.shared.pttMuteSystemAudio {
SystemAudioMuteController.shared.muteForListening()
}
startActiveTracer()
isCurrentSessionFollowUp = barState?.showingAIResponse == true
transcriptSegments = []
seenFinalSegmentIDs.removeAll()
lastInterimText = ""
voiceTypeSession.begin()
resetVoiceTypingSources()
voiceTypingLastOutcome = VoiceTypingOutcome()
currentContextSnapshot = nil
// Play start-of-PTT sound. Capture-only `ptt_start` skips CoreAudio init so a
// cold first press is not blocked on output-device bring-up. The realtime
// automation path keeps the sound, matching a physical hold.
if ShortcutSettings.shared.pttSoundsEnabled, !skipsCompositorCaptureForAutomation {
let sound = NSSound(named: "Funk")
sound?.volume = 0.3
sound?.play()
}
let mode = currentPTTMode()
AnalyticsManager.shared.floatingBarPTTStarted(mode: mode)
DesktopDiagnosticsManager.shared.recordPTTStarted(
mode: mode,
hubActive: RealtimeHubController.shared.isTransportReady,
micPermissionGranted: refreshedMicPermission())
pttLifecycle.beginAttempt(
mode: mode,
hubActive: RealtimeHubController.shared.isTransportReady,
micPermissionGranted: refreshedMicPermission())
let preOverlayImage = captureTurnScreenEvidence()
updateBarState()
FloatingControlBarManager.shared.interjectPushToTalkDidStart()
captureContextAndStartAudio(preOverlayImage: preOverlayImage)
log("PushToTalkManager: started listening (mode=\(mode))")
}
func enterLockedListening() {
if isBlockedByUsageLimit() { return }
RealtimeHubController.shared.prefetchVoiceContextSnapshotIfNeeded()
warmPTTInputRouting()
FloatingBarVoicePlaybackService.shared.interruptCurrentResponse()
if ShortcutSettings.shared.pttMuteSystemAudio {
SystemAudioMuteController.shared.muteForListening()
}
if let turnID = currentVoiceTurnID, Self.locksExistingTurn(phase: phase),
voiceTurnCoordinator.activeTurnID == turnID
{
voiceTurnCoordinator.publish(.lock(turnID: turnID))
} else {
_ = voiceTurnCoordinator.begin(intent: .locked)
}
isCurrentSessionFollowUp = barState?.showingAIResponse == true
// Play start-of-PTT sound for locked mode
if ShortcutSettings.shared.pttSoundsEnabled {
let sound = NSSound(named: "Funk")
sound?.volume = 0.3
sound?.play()
}
let mode = currentPTTMode()
AnalyticsManager.shared.floatingBarPTTStarted(mode: mode)
DesktopDiagnosticsManager.shared.recordPTTStarted(
mode: mode,
hubActive: RealtimeHubController.shared.isTransportReady,
micPermissionGranted: refreshedMicPermission())
pttLifecycle.beginAttempt(
mode: mode,
hubActive: RealtimeHubController.shared.isTransportReady,
micPermissionGranted: refreshedMicPermission())
// If we were already listening from the first tap, keep going.
// Otherwise start fresh.
if transcriptionService == nil {
if activeTracer == nil { startActiveTracer() }
transcriptSegments = []
seenFinalSegmentIDs.removeAll()
lastInterimText = ""
voiceTypeSession.begin()
resetVoiceTypingSources()
voiceTypingLastOutcome = VoiceTypingOutcome()
currentContextSnapshot = nil
let preOverlayImage = captureTurnScreenEvidence()
captureContextAndStartAudio(preOverlayImage: preOverlayImage)
}
updateBarState()
FloatingControlBarManager.shared.interjectPushToTalkDidStart()
log("PushToTalkManager: entered locked listening mode (mode=\(mode))")
}
private func enterPendingLockDecision() {
guard phase == .recording else { return }
guard let turnID = currentVoiceTurnID else { return }
voiceTurnCoordinator.publish(.openLockWindow(turnID: turnID))
stopMicCapture()
updateBarState()
}
private func stopListening(endInterjectHold: Bool = true) {
if endInterjectHold {
FloatingControlBarManager.shared.interjectPushToTalkDidCancel()
}
if let turnID = currentVoiceTurnID,
voiceTurnCoordinator.activeTurnID == turnID
{
voiceTurnCoordinator.publish(.cancel(turnID: turnID, reason: .cancelled))
return
}
performTerminalCleanup()
}
/// Benign turn endings keep the warm capture parked for the keep-alive reuse
/// window — success, too-short, silent-rejected, and barge-in all make an
/// immediate follow-up turn likely. Cancellations, owner changes, and every
/// failure fully release the microphone: an explicitly ended or unhealthy
/// session must never leave it open.
///
/// `captureNotReady` is in the keep list precisely because it is the retry:
/// the capture that missed the press is running by the time the turn ends, and
/// parking it is what makes the "hold again" the hint asks for actually work.
static func terminalReasonKeepsWarmCapture(_ reason: VoiceTurnTerminalReason) -> Bool {
switch reason {
case .success, .tooShort, .silentRejected, .interruptedByBargeIn, .captureNotReady:
return true
default:
return false
}
}
private func performTerminalCleanup(discardBufferedAudio: Bool = false, parkWarm: Bool = false) {
// Always restore audio on teardown (cancel, error, cleanup) so we never leave it muted.
SystemAudioMuteController.shared.restore()
// OCR is a turn-scoped evidence producer, not a prerequisite for ending
// audio. Leave the task alive after normal cleanup so a late result can
// finish the exact journal row through RealtimeTurnEvidenceLedger. Its
// owner/turn fence prevents it from touching a replacement turn.
contextCaptureTask = nil
micCaptureStartInFlight = false
stopAudioTranscription(discardBufferedAudio: discardBufferedAudio, parkWarm: parkWarm)
// A dictation is delivered before its turn terminates, so there is nothing
// in flight to protect here: a terminal that arrives mid-pipeline (owner
// change, explicit cancel) is exactly the case where nothing may be pasted.
voiceTypeSession.abandon()
resetVoiceTypingSources()
transcriptSegments = []
seenFinalSegmentIDs.removeAll()
lastInterimText = ""
currentContextSnapshot = nil
batchAudioLock.lock()
batchAudioBuffer = Data()
batchAudioLock.unlock()
isCurrentSessionFollowUp = false
// Abandoned session (cancel / silent turn) — drop its tracer unsent so it
// doesn't leak into the next PTT turn. No trace is written for these.
activeTracer = nil
automationCaptureBypass = false
automationExercisesRealtimePath = false
}
/// Drain every previous-owner voice authority before the defaults/auth owner
/// mutation becomes visible. Logical termination enters through the reducer;
/// the remaining calls close idle/warm physical resources that have no active
/// turn and therefore cannot be represented by a reducer effect.
func quiesceForEffectiveOwnerTransition(
previousOwnerID: String?,
cleanupCapability: RuntimeOwnerTransitionCleanupCapability
) async {
guard
RuntimeOwnerIdentity.authorizesTransitionCleanup(
cleanupCapability,
previousOwnerID: previousOwnerID)
else {
assertionFailure("Push-to-talk owner cleanup capability mismatched")
return
}
let captureBeingStopped = audioCaptureService
_ = voiceTurnCoordinator.terminateForEffectiveOwnerTransition(
previousOwnerID: previousOwnerID)
// Setup is intentionally lazy. If no effect handler was installed, there
// cannot be a legitimate active capture, but fail closed and clear every
// driver anyway.
performTerminalCleanup(discardBufferedAudio: true)
OfflinePTTQuestionRecovery.shared.clear()
voiceTypeSession.invalidateUndoLastDictation()
FloatingBarVoicePlaybackService.shared.stop()
await captureBeingStopped?.waitForPhysicalStop()
// A warm capture opened for the previous owner must not still be starting
// when the defaults/auth mutation becomes visible. A longer bound than the
// press path — this is fencing, not latency — but still bounded: see
// `drainInFlightWarmCapture`.
await drainInFlightWarmCapture(timeout: Self.ownerTransitionWarmCaptureWaitSeconds)
await RealtimeHubController.shared.quiesceForEffectiveOwnerTransition(
previousOwnerID: previousOwnerID,
cleanupCapability: cleanupCapability)
}
#if DEBUG
var ownerBoundarySnapshot: PTTOwnerBoundarySnapshot {
PTTOwnerBoundarySnapshot(
activeTurnID: currentVoiceTurnID,
hasCaptureDriver: audioCaptureService != nil,
captureStartInFlight: micCaptureStartInFlight,
hasTranscriptionDriver: transcriptionService != nil,
hasOmniDriver: realtimeOmniService != nil,