forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDesktopDiagnosticsManager.swift
More file actions
1303 lines (1203 loc) · 45.3 KB
/
Copy pathDesktopDiagnosticsManager.swift
File metadata and controls
1303 lines (1203 loc) · 45.3 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
import Darwin
import Foundation
import Sentry
enum DesktopHealthEventName: String {
case authTokenStorageFallback = "auth_token_storage_fallback"
case authSessionCleared = "auth_session_cleared"
case transcriptionWsReconnectExhausted = "transcription_ws_reconnect_exhausted"
case pttStarted = "ptt_started"
case pttAudioCaptureSilentTurn = "ptt_audio_capture_silent_turn"
case pttAudioCaptureWatchdogTriggered = "ptt_audio_capture_watchdog_triggered"
case pttAudioCaptureDeviceRouteChanged = "ptt_audio_capture_device_route_changed"
case pttCommitted = "ptt_committed"
case pttAudioCaptureLifecycle = "ptt_audio_capture_lifecycle"
case voiceTurnStarted = "voice_turn_started"
case voiceTurnTerminal = "voice_turn_terminal"
case voiceToolLatency = "voice_tool_latency"
case realtimeTokenMintFailed = "realtime_token_mint_failed"
case realtimeProviderExpectedIdleTeardown = "realtime_provider_expected_idle_teardown"
case realtimeProviderExpectedSessionRotation = "realtime_provider_expected_session_rotation"
case realtimeProviderPolicyClose = "realtime_provider_policy_close"
case realtimeProviderSessionError = "realtime_provider_session_error"
case userVisibleIssue = "user_visible_issue"
case betaDiagnosticTrail = "beta_diagnostic_trail"
case fallbackTriggered = "fallback_triggered"
}
enum DesktopFallbackOutcome: String {
case recovered
case degraded
case exhausted
}
struct DesktopHealthSnapshot: @unchecked Sendable {
let timestamp: Date
let event: DesktopHealthEventName
let properties: [String: Any]
func dictionary() -> [String: Any] {
var dict = properties
dict["timestamp"] = ISO8601DateFormatter.desktopDiagnostics.string(from: timestamp)
dict["event"] = event.rawValue
return dict
}
}
extension ISO8601DateFormatter {
fileprivate nonisolated(unsafe) static let desktopDiagnostics: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
return formatter
}()
}
/// Desktop health telemetry matrix (RealtimeHub pattern — copy for new surfaces):
/// - **Local log** (`log`): always, with `failure_class` / `recovery_action` / `recovery_result`.
/// - **Ring buffer** (`record*` → `writeDiagnosticsAttachment`): always via this manager.
/// - **PostHog** (`desktopHealthEvent`): prod/beta when `trackRemotely` is true (default).
/// - **Sentry** (`logError` / `SentrySDK.capture`): only when a domain classifier marks the failure actionable.
/// Do not call `AnalyticsManager.desktopHealthEvent` directly — it bypasses the ring buffer.
final class DesktopDiagnosticsManager {
nonisolated(unsafe) static let shared = DesktopDiagnosticsManager()
private let lock = NSLock()
private var snapshots: [DesktopHealthSnapshot] = []
private var betaTrailSnapshots: [DesktopHealthSnapshot] = []
private let snapshotLimit = 150
/// Wall-clock start of each in-flight realtime voice tool call, keyed by the
/// hub's transport key. A start/stop timer for `voice_tool_latency`; cleared
/// on turn reset so it can't grow unbounded.
private var voiceToolStarts: [String: Date] = [:]
private let betaTrailSnapshotLimit = 50
private var consecutiveNearZeroPTTTurns = 0
private var lastPTTWatchdogIncidentAt: Date?
private var lastUserVisibleSentryIncidentAt: [String: Date] = [:]
private let pttWatchdogThreshold = 3
private let pttWatchdogDedupWindow: TimeInterval = 15 * 60
private let userVisibleSentryDedupWindow: TimeInterval = 60
private let pttWatchdogMinimumAudioSeconds: Double = 0.35
private init() {}
func recordAuthTokenStorageFallback(reason: String, updateChannel: String) {
record(
.authTokenStorageFallback,
properties: [
"storage": "user_defaults",
"reason": reason,
"update_channel": updateChannel,
])
}
func recordAuthSessionCleared(
reason: String,
httpStatusCode: Int?,
failureClass: String = "definitive_auth_failure"
) {
var properties: [String: Any] = [
"reason": reason,
"failure_class": failureClass,
"recovery_action": "clear_session",
"recovery_result": "cleared",
]
if let httpStatusCode {
properties["http_status_code"] = httpStatusCode
}
record(.authSessionCleared, properties: properties)
}
func recordTranscriptionWsReconnectExhausted(
reconnectAttempts: Int,
streamingMode: String
) {
record(
.transcriptionWsReconnectExhausted,
properties: [
"reconnect_attempts": reconnectAttempts,
"streaming_mode": streamingMode,
"failure_class": "ws_reconnect_exhausted",
"recovery_action": "surface_error",
"recovery_result": "exhausted",
])
}
func recordWalPersistenceDegraded(reason: String, recoveryAction: String, recoveryResult: String) {
recordFallback(
area: "wal_persistence",
from: "disk",
to: "memory",
reason: reason,
outcome: .degraded,
extra: [
"failure_class": "wal_persistence_degraded",
"recovery_action": recoveryAction,
"recovery_result": recoveryResult,
])
}
func recordWalWriteFailed(walId: String, reason: String) {
recordFallback(
area: "wal_persistence",
from: "disk",
to: "memory",
reason: "wal_write_failed",
outcome: .degraded,
extra: [
"wal_id": walId,
"detail_reason": reason,
"failure_class": "wal_write_failed",
"recovery_action": "retain_frames",
"recovery_result": "degraded",
])
}
func recordWalUploadFailed(walId: String, reason: String) {
recordFallback(
area: "wal_upload",
from: "disk",
to: "pending",
reason: "upload_failed",
outcome: .degraded,
extra: [
"wal_id": walId,
"detail_reason": reason,
"failure_class": "wal_upload_failed",
"recovery_action": "leave_pending",
"recovery_result": "degraded",
])
}
func recordAgentRuntimeStaleAliveCheck() {
recordFallback(
area: "agent_runtime",
from: "alive_latch",
to: "termination_cleanup",
reason: "stale_alive_latch",
outcome: .degraded,
extra: [
"failure_class": "stale_alive_latch",
"recovery_action": "route_to_termination",
"recovery_result": "degraded",
])
}
func recordAgentRuntimeUnexpectedExit(exitCode: Int32, oom: Bool) {
recordFallback(
area: "agent_runtime",
from: "running",
to: "stopped",
reason: oom ? "out_of_memory" : "process_exited",
outcome: .degraded,
extra: [
"exit_code": Int(exitCode),
"oom": oom,
"failure_class": oom ? "out_of_memory" : "process_exited",
"recovery_action": "restart_on_next_send",
"recovery_result": "degraded",
])
}
func recordApiAuthRetry(endpoint: String, outcome: String) {
let fallbackOutcome: DesktopFallbackOutcome =
outcome == "succeeded" ? .recovered : (outcome == "retrying" ? .degraded : .exhausted)
recordFallback(
area: "api_auth",
from: "expired_token",
to: outcome == "succeeded" ? "refreshed_token" : "reauth",
reason: "http_401",
outcome: fallbackOutcome,
extra: [
"endpoint": endpoint,
"retry_outcome": outcome,
"failure_class": "auth_retry",
"recovery_action": "refresh_token",
"recovery_result": fallbackOutcome.rawValue,
])
}
func recordDbLockContention(source: String) {
recordFallback(
area: "db_lock",
from: "query",
to: "backoff",
reason: "db_lock_contention",
outcome: .degraded,
extra: [
"source": source,
"failure_class": "db_lock_contention",
"recovery_action": "backoff",
"recovery_result": "degraded",
])
}
func recordChatBridgeModeSwitchTimeout(waitSeconds: Int) {
recordFallback(
area: "chat_bridge",
from: "mode_switch",
to: "continue_waiting",
reason: "mode_switch_timeout",
outcome: .degraded,
extra: [
"wait_seconds": waitSeconds,
"failure_class": "mode_switch_timeout",
"recovery_action": "clear_waiters",
"recovery_result": "degraded",
])
}
func recordBleDecodeDegraded(codec: String, failures: Int) {
recordFallback(
area: "ble_audio",
from: "decode",
to: "raw_capture",
reason: "ble_decode_failed",
outcome: .degraded,
extra: [
"codec": codec,
"consecutive_failures": failures,
"failure_class": "ble_decode_degraded",
"recovery_action": "continue_raw_capture",
"recovery_result": "degraded",
])
}
func recordAutomationBridgeBindFailed(port: Int, reason: String) {
recordFallback(
area: "automation_bridge",
from: "unbound",
to: "bind_failed",
reason: "bind_failed",
outcome: .exhausted,
extra: [
"port": port,
"detail_reason": reason,
"failure_class": "bind_failed",
"recovery_action": "retry_exhausted",
"recovery_result": "exhausted",
])
}
func recordPTTStarted(mode: String, hubActive: Bool, micPermissionGranted: Bool) {
record(
.pttStarted,
properties: [
"mode": mode,
"hub_active": hubActive,
"tcc_microphone_granted": micPermissionGranted,
],
trackRemotely: false)
}
/// Per-tool wall time on a realtime voice turn: from the provider's tool
/// request to the result being returned — i.e. the "dead air" the user hears
/// while a tool runs. Instruments where voice latency actually goes (fast
/// local reads vs. slow backend/RAG round-trips) so optimization targets the
/// real cost instead of a guess. Bounded dimensions only: `tool_name` and
/// `provider` are a fixed low-cardinality set; no arguments or output content.
func recordVoiceToolLatency(toolName: String, provider: String, durationMs: Double, resultBytes: Int) {
record(
.voiceToolLatency,
properties: [
"tool_name": toolName,
"provider": provider,
"duration_ms": rounded(durationMs),
"result_bytes": resultBytes,
])
}
/// Start a `voice_tool_latency` timer for a realtime tool call (the hub's
/// transport key). Kept here rather than on the hub so the 1500-line
/// RealtimeHubController does not grow.
func markVoiceToolStart(key: String) {
lock.lock()
voiceToolStarts[key] = Date()
lock.unlock()
}
/// Stop the timer for `key` and emit `voice_tool_latency`. No-op if no start
/// was recorded (stale/dropped result).
func finishVoiceToolLatency(key: String, toolName: String, provider: String, resultBytes: Int) {
lock.lock()
let start = voiceToolStarts.removeValue(forKey: key)
lock.unlock()
guard let start else { return }
recordVoiceToolLatency(
toolName: toolName,
provider: provider,
durationMs: Date().timeIntervalSince(start) * 1000,
resultBytes: resultBytes)
}
/// Drop any in-flight voice tool timers — called on realtime turn reset.
func clearVoiceToolStarts() {
lock.lock()
voiceToolStarts.removeAll()
lock.unlock()
}
func recordPTTSilentTurn(
source: String,
mode: String,
audioSeconds: Double,
voicedSeconds: Double?,
peak: Int,
rms: Int,
deviceDescription: String?,
micPermissionGranted: Bool,
hubActive: Bool,
recoveryAction: String = "none",
recoveryResult: String = "not_attempted"
) {
let nearZero = peak <= 5 && rms <= 5
let watchdogEligible = audioSeconds >= pttWatchdogMinimumAudioSeconds
if nearZero && micPermissionGranted && watchdogEligible {
consecutiveNearZeroPTTTurns += 1
} else if peak > 50 || rms > 20 {
consecutiveNearZeroPTTTurns = 0
}
var properties: [String: Any] = [
"source": source,
"mode": mode,
"hub_active": hubActive,
"turn_audio_seconds": rounded(audioSeconds),
"peak": peak,
"rms": rms,
"is_near_zero": nearZero,
"watchdog_eligible": watchdogEligible,
"consecutive_silent_turns": consecutiveNearZeroPTTTurns,
"tcc_microphone_granted": micPermissionGranted,
"input_device_class": classifyInputDevice(deviceDescription),
"recovery_action": recoveryAction,
"recovery_result": recoveryResult,
]
if let voicedSeconds {
properties["voiced_audio_seconds"] = rounded(voicedSeconds)
}
record(.pttAudioCaptureSilentTurn, properties: properties)
if nearZero && micPermissionGranted && watchdogEligible {
recordUserVisibleIssue(
area: "ptt",
failureClass: "silent_capture",
phase: "audio_capture",
extra: properties)
}
guard nearZero && micPermissionGranted && watchdogEligible && consecutiveNearZeroPTTTurns >= pttWatchdogThreshold
else { return }
recordPTTWatchdogTriggered(latestProperties: properties)
}
func recordPTTCommitted(mode: String, hubActive: Bool) {
consecutiveNearZeroPTTTurns = 0
record(
.pttCommitted,
properties: [
"mode": mode,
"hub_active": hubActive,
],
trackRemotely: false)
}
/// Record one bounded PTT attempt lifecycle snapshot (see
/// `PTTAttemptLifecycleRecorder`). Routes through the shared ring buffer + Sentry
/// attachment path; the event is remote (PostHog) only for non-committed
/// terminations so successful turns stay local-only (matching
/// `recordPTTStarted` / `recordPTTCommitted`). This is the causal-correlation
/// complement to the late `recordPTTSilentTurn` snapshot: same attempt context,
/// but with the capture-start / first-audio / first-usable-frame / recovery
/// boundaries that the silent-turn snapshot cannot see.
func recordPTTAttemptLifecycle(_ snapshot: PTTAttemptLifecycleRecorder.Snapshot) {
record(
.pttAudioCaptureLifecycle,
properties: snapshot.properties,
trackRemotely: snapshot.failureClass != .committed)
}
/// Records a typed chat failure as a fleet-health metric. The existing bounded
/// `logError` path owns the matching Sentry incident to avoid duplicate capture.
func recordChatFailure(errorClass: String) {
recordUserVisibleIssue(
area: "chat",
failureClass: errorClass,
phase: "query",
captureSentry: false)
}
/// Records a global-hotkey registration failure surfaced by Carbon
/// `RegisterEventHotKey`.
///
/// This is a hard-terminal failure — the shortcut will not fire on this machine
/// (typically another app, or a macOS System Settings > Keyboard > Shortcuts
/// entry — even a disabled one — already owns the combination). Because no
/// provider, mode, or correctness path switches and there is nothing to fail
/// open to, the telemetry contract routes this through the incident path, not
/// `recordFallback`. `isConflict` distinguishes `eventHotKeyExistsErr` (-9878),
/// which is a property of the user's machine, from other `OSStatus` values.
func recordHotkeyRegistrationFailed(osStatus: Int, keycode: Int, modifiers: Int, isConflict: Bool) {
recordUserVisibleIssue(
area: "startup",
failureClass: isConflict ? "hotkey_conflict" : "unknown",
phase: "startup",
extra: [
"osstatus": osStatus,
"keycode": keycode,
"modifiers": modifiers,
])
}
/// Records a beta-only typed error trail entry. The caller passes free-form local
/// log text only for local classification; no message or error description is
/// retained in the trail or cloud attachment.
func recordBetaLogError(
message: String,
error: Error?,
enabled: Bool = BetaEnhancedDiagnosticsConfiguration.isEnabled
) {
guard enabled else { return }
let nsError = error as NSError?
let snapshot = DesktopHealthSnapshot(
timestamp: Date(),
event: .betaDiagnosticTrail,
properties: commonProperties().merging(
sanitized([
"component": betaComponent(for: message),
"operation": "error",
"phase": "handling",
"outcome": "failed",
"failure_class": betaFailureClass(for: nsError),
"error_domain": betaErrorDomain(nsError?.domain),
"error_code": betaErrorCode(nsError?.code),
])
) { _, new in new })
lock.lock()
betaTrailSnapshots.append(snapshot)
if betaTrailSnapshots.count > betaTrailSnapshotLimit {
betaTrailSnapshots.removeFirst(betaTrailSnapshots.count - betaTrailSnapshotLimit)
}
lock.unlock()
}
func recordVoiceTurnStarted(turnID: String, intent: String) {
record(
.voiceTurnStarted,
properties: [
"attempt_id": turnID,
"intent": intent,
"telemetry_schema_version": 1,
])
}
func recordVoiceTurnTerminal(
turnID: String,
reason: String,
route: String,
intent: String,
durationMs: Int?,
answerDelivered: Bool,
staleEventCount: Int,
invalidTransitionCount: Int
) {
var properties: [String: Any] = [
"attempt_id": turnID,
"terminal_reason": reason,
"outcome": Self.voiceTurnOutcome(for: reason),
"response_outcome": Self.voiceResponseOutcome(for: reason, answerDelivered: answerDelivered),
"route": route,
"intent": intent,
"stale_event_count": staleEventCount,
"invalid_transition_count": invalidTransitionCount,
"telemetry_schema_version": 1,
]
if let durationMs {
properties["duration_ms"] = max(0, durationMs)
}
record(.voiceTurnTerminal, properties: properties)
let breadcrumb = Breadcrumb(level: .info, category: "voice.turn.terminal")
breadcrumb.message = "Voice turn reached terminal state"
breadcrumb.data = properties
SentrySDK.addBreadcrumb(breadcrumb)
}
static func voiceTurnOutcome(for reason: String) -> String {
switch reason {
case "success":
return "success"
case "too_short", "silent_rejected", "cancelled", "owner_changed",
"interrupted_by_barge_in", "explicit_interrupt", "cleanup":
return "excluded"
default:
return "failure"
}
}
static func voiceResponseOutcome(for reason: String, answerDelivered: Bool) -> String {
if answerDelivered || reason == "success" {
return "success"
}
return voiceTurnOutcome(for: reason)
}
func recordVoiceTurnAnomaly(kind: String, phase: String, route: String) {
let breadcrumb = Breadcrumb(level: .warning, category: "voice.turn.anomaly")
breadcrumb.message = "Voice turn rejected an anomalous event"
breadcrumb.data = [
"kind": kind,
"phase": phase,
"route": route,
]
SentrySDK.addBreadcrumb(breadcrumb)
}
func recordPTTDeviceRouteChanged(recoveryAction: String, recoveryResult: String) {
record(
.pttAudioCaptureDeviceRouteChanged,
properties: [
"recovery_action": recoveryAction,
"recovery_result": recoveryResult,
])
}
/// Shared fallback / resilience telemetry. Prefer this over inventing new
/// `DesktopHealthEventName` cases for provider/mode switches.
///
/// - Parameters match the backend `record_fallback` contract.
/// - `outcome`: recovered (full UX restored), degraded (continues with hit),
/// exhausted (no acceptable path left).
/// - Always tracks remotely on prod/beta so ops can see silent UX heals.
func recordFallback(
area: String,
from: String,
to: String,
reason: String,
outcome: DesktopFallbackOutcome,
extra: [String: Any] = [:]
) {
var properties: [String: Any] = [
"area": bucketFallbackArea(area),
"from": safeFallbackLabel(from, default: "none"),
"to": safeFallbackLabel(to, default: "none"),
"reason": bucketFallbackReason(reason),
"outcome": outcome.rawValue,
]
for (key, value) in sanitized(extra) {
if properties[key] == nil {
properties[key] = value
}
}
record(.fallbackTriggered, properties: properties, trackRemotely: true)
}
func recordRealtimeTokenMintFailed(
provider: String,
reason: String,
phase: String,
httpStatusCode: Int? = nil,
backendRoute: String? = nil,
upstreamStatusCode: Int? = nil,
providerCode: String? = nil,
retryable: Bool? = nil
) {
var properties: [String: Any] = [
"provider": safeProvider(provider),
"reason": reason,
"phase": phase,
]
if let httpStatusCode {
properties["http_status_code"] = httpStatusCode
}
if let backendRoute {
properties["backend_route"] = backendRoute
}
if let upstreamStatusCode {
properties["upstream_status_code"] = upstreamStatusCode
}
if let providerCode {
properties["provider_code"] = providerCode
}
if let retryable {
properties["retryable"] = retryable
}
record(
.realtimeTokenMintFailed,
properties: properties)
}
func recordRealtimeProviderClose(
provider: String,
category: String?,
aliveFor: TimeInterval,
activeTurn: Bool,
authMode: CredentialAuthMode?,
failureClass: CredentialFailureClass?
) {
let normalizedCategory = category ?? failureClass?.logValue ?? "unclassified"
let event: DesktopHealthEventName
switch normalizedCategory {
case RealtimeHubCloseCategory.expectedIdleTeardown.rawValue:
event = .realtimeProviderExpectedIdleTeardown
case RealtimeHubCloseCategory.expectedSessionRotation.rawValue:
event = .realtimeProviderExpectedSessionRotation
case RealtimeHubCloseCategory.providerPolicyCloseFast.rawValue,
CredentialFailureClass.providerPolicyClose(provider: .openai).logValue:
event = .realtimeProviderPolicyClose
default:
event = .realtimeProviderSessionError
}
var properties: [String: Any] = [
"provider": safeProvider(provider),
"category": normalizedCategory,
"alive_for_seconds": Int(aliveFor),
"active_turn": activeTurn,
]
if normalizedCategory == RealtimeHubCloseCategory.expectedSessionRotation.rawValue {
properties["recovery_action"] = "rotate_realtime_session"
properties["recovery_result"] = activeTurn ? "turn_terminated_and_rewarm_started" : "rewarm_started"
}
if let authMode {
properties["auth_mode"] = authMode.rawValue
}
if let failureClass {
properties["failure_class"] = failureClass.logValue
if let httpStatusCode = failureClass.httpStatusCode {
properties["http_status_code"] = httpStatusCode
}
}
record(
event,
properties: properties)
}
func currentSnapshotsForSentry() -> [[String: Any]] {
lock.lock()
let current = snapshots.map { $0.dictionary() }
lock.unlock()
return current
}
private func currentCloudSnapshotsForSentry(
includeBetaDiagnostics: Bool = BetaEnhancedDiagnosticsConfiguration.isEnabled
) -> [[String: Any]] {
lock.lock()
var current = snapshots.map { cloudSafeSnapshot($0, includeBetaDiagnostics: includeBetaDiagnostics) }
if includeBetaDiagnostics {
current.append(
contentsOf: betaTrailSnapshots.map {
cloudSafeSnapshot($0, includeBetaDiagnostics: true)
})
}
lock.unlock()
return current
}
private func currentSnapshotsForLocalExport() -> [[String: Any]] {
currentSnapshotsForSentry()
}
private func cloudSafeSnapshot(
_ snapshot: DesktopHealthSnapshot,
includeBetaDiagnostics: Bool
) -> [String: Any] {
var result: [String: Any] = [
"timestamp": ISO8601DateFormatter.desktopDiagnostics.string(from: snapshot.timestamp),
"event": snapshot.event.rawValue,
]
let includesTypedIncidentContext =
snapshot.event == .userVisibleIssue
|| snapshot.event == .pttAudioCaptureWatchdogTriggered
|| snapshot.event == .pttAudioCaptureLifecycle
|| (includeBetaDiagnostics && snapshot.event == .betaDiagnosticTrail)
guard includesTypedIncidentContext else {
return result
}
for key in DesktopDiagnosticsManager.cloudIncidentSnapshotKeys {
if let value = snapshot.properties[key] {
result[key] = value
}
}
return result
}
private static let cloudIncidentSnapshotKeys: Set<String> = [
"area", "failure_class", "phase", "build", "build_number", "os_version", "device_model",
"source", "mode", "hub_active", "turn_audio_seconds", "voiced_audio_seconds", "peak", "rms",
"is_near_zero", "watchdog_eligible", "consecutive_silent_turns", "tcc_microphone_granted",
"input_device_class", "recovery_action", "recovery_result", "threshold",
"component", "operation", "outcome", "error_domain", "error_code",
"osstatus", "keycode", "modifiers",
// PTT attempt lifecycle correlation (PTTAttemptLifecycleRecorder).
"attempt_id", "capture_start_outcome", "capture_start_status_class",
"ms_to_first_audio_bucket", "ms_to_first_usable_frame_bucket",
"first_chunks_energy_bucket", "turn_disposition",
"input_route_class", "input_route_source", "route_changed_during_attempt",
"recovery_triggered", "recovery_attempt_id", "recovery_outcome_of_next_turn",
"judgeable", "telemetry_schema_version",
]
func writeDiagnosticsAttachment() -> URL? {
let payload: [String: Any] = [
"generated_at": ISO8601DateFormatter.desktopDiagnostics.string(from: Date()),
"privacy": "safe_operational_fields_only",
"snapshots": currentSnapshotsForSentry(),
]
return writeDiagnosticsPayload(payload, prefix: "omi-desktop-diagnostics")
}
/// Creates a bounded, redacted local-context attachment for a cloud incident.
/// This intentionally replaces raw `omi.log` uploads: the attachment includes
/// safe health snapshots and a scrubbed tail only, never the entire log file.
func writeIncidentDiagnosticsAttachment(
incidentID: String = UUID().uuidString,
area: String,
failureClass: String,
phase: String,
logPath: String = omiLogFilePath(),
maxLogLines: Int = 200,
includeBetaDiagnostics: Bool = BetaEnhancedDiagnosticsConfiguration.isEnabled
) -> URL? {
let incident = incidentProperties(
id: incidentID,
area: area,
failureClass: failureClass,
phase: phase)
var payload: [String: Any] = [
"generated_at": ISO8601DateFormatter.desktopDiagnostics.string(from: Date()),
"privacy": "redacted_incident_context",
"incident": incident,
"snapshots": currentCloudSnapshotsForSentry(includeBetaDiagnostics: includeBetaDiagnostics),
]
// Beta uploads the independently assembled typed trail only. The free-form
// local-log tail remains available exclusively to the existing non-beta path.
if !includeBetaDiagnostics {
payload["redacted_log_tail"] = redactedLogTail(
logPath: logPath,
maxLines: maxLogLines,
strictCloudRedaction: true)
}
return writeDiagnosticsPayload(payload, prefix: "omi-desktop-incident")
}
// MARK: - Local (offline) diagnostics export
/// Build a redacted, offline diagnostics bundle and write it to `url`.
///
/// Unlike the Sentry path, this works with no network and without a crash
/// reporter — it backs the local "Save Diagnostics…" export so users can share
/// a report manually (BL-023 / SET-03). The bundle carries app/version/OS
/// metadata, the already-sanitized health snapshots, and a redacted tail of the
/// local log. Returns `true` on success.
@discardableResult
func writeLocalDiagnosticsBundle(
to url: URL,
logPath: String = omiLogFilePath(),
maxLogLines: Int = 500
) -> Bool {
let text = buildLocalDiagnosticsText(logPath: logPath, maxLogLines: maxLogLines)
guard let data = text.data(using: .utf8) else { return false }
do {
try data.write(to: url, options: .atomic)
return true
} catch {
log("DesktopDiagnostics: failed to write local diagnostics bundle")
return false
}
}
/// Render the redacted diagnostics bundle as plain text (metadata header,
/// sanitized health snapshots, redacted recent log tail). Exposed for testing
/// the redaction guarantee without disk I/O.
func buildLocalDiagnosticsText(logPath: String, maxLogLines: Int = 500) -> String {
var sections: [String] = []
let meta = commonProperties()
var header = ["# Omi Desktop Diagnostics"]
header.append("generated_at: \(ISO8601DateFormatter.desktopDiagnostics.string(from: Date()))")
header.append("privacy: redacted_local_export")
for key in ["build", "build_number", "os_version", "device_model", "system_audio_mode"] {
if let value = meta[key] {
header.append("\(key): \(value)")
}
}
sections.append(header.joined(separator: "\n"))
let snapshots = currentSnapshotsForLocalExport()
if JSONSerialization.isValidJSONObject(snapshots),
let data = try? JSONSerialization.data(withJSONObject: snapshots, options: [.prettyPrinted]),
let json = String(data: data, encoding: .utf8)
{
sections.append("## Health snapshots\n\(json)")
}
let tail = redactedLogTail(logPath: logPath, maxLines: maxLogLines)
sections.append("## Recent log (redacted, last \(maxLogLines) lines)\n\(tail)")
return sections.joined(separator: "\n\n") + "\n"
}
/// Read up to `maxLines` from the end of the log file, redacting anything that
/// looks like a secret (tokens, JWTs, credential kv pairs) line by line.
private func redactedLogTail(
logPath: String,
maxLines: Int,
strictCloudRedaction: Bool = false
) -> String {
guard let handle = FileHandle(forReadingAtPath: logPath) else {
return "(no readable log file at \(logPath))"
}
defer { handle.closeFile() }
// Read only a bounded tail from the end rather than loading the whole log
// into memory, so export latency and memory stay predictable on large logs.
// 512 KB comfortably covers maxLines (default 500) of log text.
let maxTailBytes: UInt64 = 512 * 1024
let fileSize = handle.seekToEndOfFile()
let start = fileSize > maxTailBytes ? fileSize - maxTailBytes : 0
handle.seek(toFileOffset: start)
let data = handle.readDataToEndOfFile()
// Lenient decode: a byte-offset seek can split a multibyte character, so
// substitute rather than fail; the possibly-partial first line is dropped.
var content = String(decoding: data, as: UTF8.self)
if start > 0, let newline = content.firstIndex(of: "\n") {
content = String(content[content.index(after: newline)...])
}
let lines = content.split(separator: "\n", omittingEmptySubsequences: false)
let tail = lines.suffix(max(0, maxLines))
return tail.map {
redactSensitive(String($0), strictCloudRedaction: strictCloudRedaction)
}.joined(separator: "\n")
}
/// Defensive best-effort redaction. The desktop log is not expected to contain
/// raw credentials, but a manually-shared export must never leak one, so we
/// mask common token shapes before including any log text.
private static let redactionPatterns: [(NSRegularExpression, String)] = {
let specs: [(String, String)] = [
// JWT: three base64url segments starting with a typical header.
("eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+", "[redacted-jwt]"),
// Authorization: Bearer <token>
("(?i)(bearer)\\s+[A-Za-z0-9._~+/=-]{8,}", "$1 [redacted]"),
// Authorization: Basic <base64 credentials>. Anchored to the header prefix
// so benign phrases like "basic settings" aren't over-redacted.
("(?i)(authorization:\\s*basic)\\s+[A-Za-z0-9+/=]{8,}", "$1 [redacted]"),
// Bare OpenAI-style API keys.
("sk-[A-Za-z0-9_-]{20,}", "sk-[redacted]"),
// Email addresses and absolute filesystem paths are operationally unnecessary
// in a cloud diagnostic attachment.
("(?i)[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}", "[redacted-email]"),
("/(?:Users|private|tmp|var|Applications)/[^\\s\\\"']+", "/[redacted-path]"),
// URLs can contain query parameters and opaque resource identifiers.
("https?://[^\\s\\\"']+", "https://[redacted-url]"),
// key=..., token: ..., password="..." in query strings, JSON, or kv logs.
(
"(?i)(api[_-]?key|access[_-]?token|refresh[_-]?token|id[_-]?token|token|password|passwd|secret|client[_-]?secret|authorization)([\"']?\\s*[=:]\\s*[\"']?)[A-Za-z0-9._~+/=-]{6,}",
"$1$2[redacted]"
),
]
return specs.compactMap { pattern, template in
(try? NSRegularExpression(pattern: pattern)).map { ($0, template) }
}
}()
private static let safeOperationalLogMarkers = [
"ptt", "audio_capture", "audiocapture", "silent capture", "voiceturn", "voice turn",
"realtime", "sentry", "desktopdiagnostics", "app crash", "crash recovery",
"chat telemetry event=",
]
private static let contentBearingLogMarkers = [
"conversation", "transcript", "prompt", "response", "message", "memory", "title",
"window", "screen", "ocr", "clipboard",
]
private func redactSensitive(_ line: String, strictCloudRedaction: Bool = false) -> String {
let normalized = line.lowercased()
if strictCloudRedaction, normalized.contains("device=[") {
return "[redacted-device-bearing-log-line]"
}
if strictCloudRedaction,
DesktopDiagnosticsManager.contentBearingLogMarkers.contains(where: normalized.contains)
{
return "[redacted-content-bearing-log-line]"
}
if strictCloudRedaction,
!DesktopDiagnosticsManager.safeOperationalLogMarkers.contains(where: normalized.contains)
{
return "[redacted-unclassified-log-line]"
}
var result = line
for (regex, template) in DesktopDiagnosticsManager.redactionPatterns {
let range = NSRange(result.startIndex..., in: result)
result = regex.stringByReplacingMatches(in: result, range: range, withTemplate: template)
}
return result
}
#if DEBUG
func resetForTests() {
lock.lock()
snapshots.removeAll()
betaTrailSnapshots.removeAll()
consecutiveNearZeroPTTTurns = 0
lastPTTWatchdogIncidentAt = nil
lastUserVisibleSentryIncidentAt.removeAll()
lock.unlock()
}
#endif
private func shouldCaptureIncident(area: String, failureClass: String) -> Bool {
let key = "\(area):\(failureClass)"
let now = Date()
lock.lock()
defer { lock.unlock() }
if let last = lastUserVisibleSentryIncidentAt[key],
now.timeIntervalSince(last) < userVisibleSentryDedupWindow
{
return false
}
lastUserVisibleSentryIncidentAt[key] = now
return true
}
private func recordUserVisibleIssue(
area: String,
failureClass: String,
phase: String,
extra: [String: Any] = [:],
captureSentry: Bool = true
) {
let incidentID = UUID().uuidString
var properties: [String: Any] = [
"area": safeIncidentArea(area),
"failure_class": safeIncidentLabel(failureClass),
"phase": safeIncidentPhase(phase),
]
let allowedExtras = sanitized(extra).filter {
DesktopDiagnosticsManager.allowedIncidentExtraKeys.contains($0.key)
}
for (key, value) in allowedExtras where properties[key] == nil {
properties[key] = value
}
record(.userVisibleIssue, properties: properties)
let sentryProperties = properties.merging(["incident_id": incidentID]) { _, new in new }
guard captureSentry,
!AppBuild.isNonProduction,
shouldCaptureIncident(
area: properties["area"] as? String ?? "other",
failureClass: properties["failure_class"] as? String ?? "other"),
let attachmentURL = writeIncidentDiagnosticsAttachment(
incidentID: incidentID,
area: area,
failureClass: failureClass,
phase: phase)
else { return }
defer { try? FileManager.default.removeItem(at: attachmentURL) }