forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnalyticsManager.swift
More file actions
1749 lines (1513 loc) · 63.1 KB
/
Copy pathAnalyticsManager.swift
File metadata and controls
1749 lines (1513 loc) · 63.1 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 AppKit
import Foundation
import Sentry
/// Closed reason a presented notification left the screen. Auto-hide and explicit
/// close must not share a single "dismissed" bucket — that made engagement
/// unreadable (expiry counted as a user dismiss).
enum NotificationDismissalKind: String, CaseIterable, Sendable {
case user
case timeout
case replaced
}
/// Closed source for `floating_bar_query_sent`. Historical events omit this
/// property; dashboards that need continuity with that volume should filter
/// `source=typed`.
enum FloatingBarQuerySource: String, CaseIterable, Sendable {
case typed
case ptt
case pttVoiceOnly = "ptt_voice_only"
case pttRealtime = "ptt_realtime"
static func visibleQuery(fromVoice: Bool) -> Self {
fromVoice ? .ptt : .typed
}
}
/// Unified analytics manager that sends events to PostHog.
/// Use this instead of calling PostHogManager directly
@MainActor
class AnalyticsManager {
static let shared = AnalyticsManager()
/// Returns true for non-production Omi bundles so test apps don't pollute production analytics.
nonisolated static var isDevBuild: Bool {
AppBuild.isNonProduction
}
private var lastTranscriptionStartedAt: Date?
/// Main-actor-isolated test observation at the actual AnalyticsManager
/// boundary. It is nil in production and is deliberately not a mutable global
/// outside the actor, so tests can observe the real event/payload safely under
/// Swift concurrency.
private var memoryAssistantTelemetryCaptureForTests: (@MainActor (String, [String: Any]) -> Void)?
private var devicePairingTelemetryCaptureForTests: (@MainActor (String?, [String: Any], [String: Any]) -> Void)?
private init() {}
/// Install a scoped test observer for MemoryAssistant telemetry. Tests must
/// clear it in teardown; production behavior remains the PostHog call below.
func setMemoryAssistantTelemetryCaptureForTests(
_ capture: (@MainActor (String, [String: Any]) -> Void)?
) {
memoryAssistantTelemetryCaptureForTests = capture
}
private func captureMemoryAssistantTelemetryForTests(_ event: String, properties: [String: Any]) {
memoryAssistantTelemetryCaptureForTests?(event, properties)
}
/// Scoped observation of the privacy-safe live-suggestion funnel. This lives
/// at the same production boundary as PostHog so tests can assert the real
/// event payload without initializing analytics or exposing a mutable global.
private var suggestionAssistantTelemetryCaptureForTests: (@MainActor (String, [String: Any]) -> Void)?
private var insightAssistantTelemetryCaptureForTests: (@MainActor (String, [String: Any]) -> Void)?
/// Delivery callbacks can race (for example a floating-bar enqueue and a system-banner
/// completion). Keep one terminal outcome per opaque advice delivery ID at this boundary.
private var recordedInsightDeliveryIDSet: Set<UUID> = []
private var recordedInsightDeliveryIDOrder: [UUID] = []
private static let maxRecordedInsightDeliveryIDs = 512
func setSuggestionAssistantTelemetryCaptureForTests(
_ capture: (@MainActor (String, [String: Any]) -> Void)?
) {
suggestionAssistantTelemetryCaptureForTests = capture
}
private func captureSuggestionAssistantTelemetryForTests(_ event: String, properties: [String: Any]) {
suggestionAssistantTelemetryCaptureForTests?(event, properties)
}
/// Scoped observation of Advice delivery telemetry. Tests install a capture at the same
/// production boundary as PostHog; production leaves it nil.
func setInsightAssistantTelemetryCaptureForTests(
_ capture: (@MainActor (String, [String: Any]) -> Void)?
) {
if capture != nil {
recordedInsightDeliveryIDSet.removeAll()
recordedInsightDeliveryIDOrder.removeAll()
}
insightAssistantTelemetryCaptureForTests = capture
}
private func captureInsightAssistantTelemetryForTests(_ event: String, properties: [String: Any]) {
insightAssistantTelemetryCaptureForTests?(event, properties)
}
/// Test observer for integration-connect telemetry. Mirrors the
/// MemoryAssistant seam: nil in production; tests install a scoped capture
/// to observe the real event/payload without a mutable unsafe global.
private var integrationConnectTelemetryCaptureForTests: (@MainActor (String, [String: Any]) -> Void)?
/// Install a scoped test observer for integration-connect telemetry. Tests
/// must clear it in teardown; production behavior remains the PostHog call.
func setIntegrationConnectTelemetryCaptureForTests(
_ capture: (@MainActor (String, [String: Any]) -> Void)?
) {
integrationConnectTelemetryCaptureForTests = capture
}
private func captureIntegrationConnectTelemetryForTests(_ event: String, properties: [String: Any]) {
integrationConnectTelemetryCaptureForTests?(event, properties)
}
/// Integration-nudge seam: nil in production; tests install a scoped capture
/// to observe the real event names and payloads these methods emit.
private var integrationNudgeTelemetryCaptureForTests: (@MainActor (String, [String: Any]) -> Void)?
func setIntegrationNudgeTelemetryCaptureForTests(
_ capture: (@MainActor (String, [String: Any]) -> Void)?
) {
integrationNudgeTelemetryCaptureForTests = capture
}
private func trackIntegrationNudge(_ event: String, properties: [String: Any]) {
integrationNudgeTelemetryCaptureForTests?(event, properties)
PostHogManager.shared.track(event, properties: properties)
}
/// Notification-delivery-drop seam: nil in production; tests install a scoped
/// capture to observe the real event/payload `NotificationService` emits when
/// it drops a notification for lack of authorization.
private var notificationDeliveryTelemetryCaptureForTests: (@MainActor (String, [String: Any]) -> Void)?
func setNotificationDeliveryTelemetryCaptureForTests(
_ capture: (@MainActor (String, [String: Any]) -> Void)?
) {
notificationDeliveryTelemetryCaptureForTests = capture
}
/// Monitoring-duration seam: nil in production; tests install a scoped
/// capture to observe the real event names/payloads these methods emit.
private var monitoringTelemetryCaptureForTests: (@MainActor (String, [String: Any]) -> Void)?
func setMonitoringTelemetryCaptureForTests(
_ capture: (@MainActor (String, [String: Any]) -> Void)?
) {
monitoringTelemetryCaptureForTests = capture
}
private func trackMonitoring(_ event: String, properties: [String: Any]) {
monitoringTelemetryCaptureForTests?(event, properties)
PostHogManager.shared.track(event, properties: properties)
}
func setDevicePairingTelemetryCaptureForTests(
_ capture: (@MainActor (String?, [String: Any], [String: Any]) -> Void)?
) {
devicePairingTelemetryCaptureForTests = capture
}
/// Scoped observation of floating-bar query telemetry. Nil in production;
/// tests install a capture at the same boundary as PostHog.
private var floatingBarQueryTelemetryCaptureForTests: (@MainActor (String, [String: Any]) -> Void)?
/// Test seam for `question_asked` / `question_answered`; the emitters live in
/// `Analytics/AnalyticsManager+Questions.swift`, so this is internal, not private.
var questionTelemetryCaptureForTests: (@MainActor (String, [String: Any]) -> Void)?
/// Test seam for search events; emitters live in `Analytics/AnalyticsManager+Search.swift`.
var searchTelemetryCaptureForTests: (@MainActor (String, [String: Any]) -> Void)?
/// Scoped observation of floating-bar PTT terminal telemetry. Nil in
/// production; tests install a capture at the same boundary as PostHog.
private var floatingBarPTTTelemetryCaptureForTests: (@MainActor (String, [String: Any]) -> Void)?
func setFloatingBarQueryTelemetryCaptureForTests(
_ capture: (@MainActor (String, [String: Any]) -> Void)?
) {
floatingBarQueryTelemetryCaptureForTests = capture
}
func setSearchTelemetryCaptureForTests(
_ capture: (@MainActor (String, [String: Any]) -> Void)?
) {
searchTelemetryCaptureForTests = capture
}
func setFloatingBarPTTTelemetryCaptureForTests(
_ capture: (@MainActor (String, [String: Any]) -> Void)?
) {
floatingBarPTTTelemetryCaptureForTests = capture
}
// MARK: - Initialization
func initialize() {
// Skip analytics in development builds
guard !Self.isDevBuild else {
log("Analytics: Skipping initialization (development build)")
return
}
PostHogManager.shared.initialize()
}
// MARK: - User Identification
func identify() {
PostHogManager.shared.identify()
}
func reset() {
PostHogManager.shared.reset()
}
// MARK: - Opt In/Out
func optInTracking() {
PostHogManager.shared.optIn()
}
func optOutTracking() {
PostHogManager.shared.optOut()
}
// MARK: - Onboarding Events
func onboardingStepCompleted(step: Int, stepName: String) {
PostHogManager.shared.onboardingStepCompleted(step: step, stepName: stepName)
}
func onboardingHowDidYouHear(source: String) {
let props: [String: Any] = ["source": source, "is_referral": source == "Friend"]
PostHogManager.shared.track("Onboarding How Did You Hear", properties: props)
}
func onboardingCompleted() {
PostHogManager.shared.onboardingCompleted()
}
func onboardingChatToolUsed(tool: String, properties: [String: Any] = [:]) {
var props = properties
props["tool"] = ChatTelemetryDimension.toolName(tool)
PostHogManager.shared.track("Onboarding Chat Tool Used", properties: props)
}
func onboardingChatMessage(role: String, step: String) {
let props: [String: Any] = ["role": role, "step": step]
PostHogManager.shared.track("Onboarding Chat Message", properties: props)
}
/// Track onboarding chat shape without sending the user's message content.
func onboardingChatMessageDetailed(
role: String, text: String, step: String, toolCalls: [String]? = nil, model: String? = nil, error: String? = nil
) {
var props: [String: Any] = [
"role": role,
"step": step,
"text_length": text.count,
]
if let toolCalls = toolCalls, !toolCalls.isEmpty {
let boundedTools = Array(Set(toolCalls.map(ChatTelemetryDimension.toolName))).sorted().prefix(8)
props["tool_calls"] = boundedTools.joined(separator: ",")
props["tool_call_count"] = toolCalls.count
}
if let model = model { props["model"] = Self.boundedAnalyticsDimension(model) }
if let error = error {
let errorClass = PostHogManager.diagnosticErrorClass(error)
props["error"] = errorClass
props["error_class"] = errorClass
}
PostHogManager.shared.track("onboarding_chat_message_detailed", properties: props)
}
private static func boundedAnalyticsDimension(_ value: String) -> String {
let normalized = value.lowercased().map { character in
character.isLetter || character.isNumber || "._:-".contains(character) ? character : "_"
}
return String(normalized.prefix(80))
}
// MARK: - Authentication Events
func signInStarted(provider: String) {
PostHogManager.shared.signInStarted(provider: provider)
}
func signInCompleted(provider: String) {
PostHogManager.shared.signInCompleted(provider: provider)
}
func signInFailed(provider: String, error: String, errorClass: String? = nil) {
PostHogManager.shared.signInFailed(provider: provider, error: error, errorClass: errorClass)
}
func authFlowEvent(_ eventName: String, properties: [String: Any]) {
PostHogManager.shared.authFlowEvent(eventName, properties: properties)
}
func signedOut() {
PostHogManager.shared.signedOut()
}
// MARK: - Integration Connect Events
/// Privacy-safe macOS integration-connect funnel. Mirrors the Flutter
/// `Integration Connect Attempted/Succeeded/Failed` event names for
/// cross-platform PostHog aggregation; dimensions are bounded by
/// ``IntegrationConnectTelemetry``. See that type for the full contract.
func integrationConnectAttempted(
integrationName: String,
connectorID: String,
surface: IntegrationConnectTelemetry.Surface,
stage: String
) {
let payload = IntegrationConnectTelemetry.attemptedPayload(
integrationName: integrationName, connectorID: connectorID,
surface: surface, stage: stage)
captureIntegrationConnectTelemetryForTests(
IntegrationConnectTelemetry.attemptedEventName, properties: payload)
PostHogManager.shared.track(
IntegrationConnectTelemetry.attemptedEventName, properties: payload)
}
func integrationConnectSucceeded(
integrationName: String,
connectorID: String,
surface: IntegrationConnectTelemetry.Surface,
stage: String,
durationMs: Int? = nil,
sourceCount: Int? = nil,
memoryCount: Int? = nil,
wasFirstSync: Bool = false
) {
let payload = IntegrationConnectTelemetry.succeededPayload(
integrationName: integrationName, connectorID: connectorID,
surface: surface, stage: stage, durationMs: durationMs,
sourceCount: sourceCount, memoryCount: memoryCount, wasFirstSync: wasFirstSync)
captureIntegrationConnectTelemetryForTests(
IntegrationConnectTelemetry.succeededEventName, properties: payload)
PostHogManager.shared.track(
IntegrationConnectTelemetry.succeededEventName, properties: payload)
}
func integrationConnectFailed(
integrationName: String,
connectorID: String,
surface: IntegrationConnectTelemetry.Surface,
stage: String,
errorClass: IntegrationConnectTelemetry.ErrorClass,
durationMs: Int? = nil,
wasFirstSync: Bool = false
) {
let payload = IntegrationConnectTelemetry.failedPayload(
integrationName: integrationName, connectorID: connectorID,
surface: surface, stage: stage, errorClass: errorClass,
durationMs: durationMs, wasFirstSync: wasFirstSync)
captureIntegrationConnectTelemetryForTests(
IntegrationConnectTelemetry.failedEventName, properties: payload)
PostHogManager.shared.track(
IntegrationConnectTelemetry.failedEventName, properties: payload)
}
// MARK: - Integration Nudge Events
func integrationNudgeShown(
entry: IntegrationNudgeCatalogEntry,
trigger: IntegrationNudgeTrigger,
shownCount: Int
) {
trackIntegrationNudge(
IntegrationNudgeTelemetry.shownEventName,
properties: IntegrationNudgeTelemetry.shownPayload(
integrationName: entry.displayName,
route: entry.route,
triggerID: trigger.id,
triggerKind: trigger.kind,
shownCount: shownCount
)
)
}
func integrationNudgeActioned(
entry: IntegrationNudgeCatalogEntry,
action: IntegrationNudgeTelemetry.Action,
triggerID: String
) {
trackIntegrationNudge(
IntegrationNudgeTelemetry.actionedEventName,
properties: IntegrationNudgeTelemetry.actionedPayload(
integrationName: entry.displayName,
route: entry.route,
action: action,
triggerID: triggerID
)
)
}
// MARK: - Notification Delivery Events
/// A proactive notification was dropped because the app is not authorized to
/// show it. See `NotificationDeliveryTelemetry` for the full contract. Never
/// call this from a permission-request path — it only observes an existing
/// drop, it must never itself trigger the system prompt.
func notificationDeliverySkipped(
authStatus: NotificationDeliveryTelemetry.AuthStatus,
surface: ProactiveNotificationKind
) {
let payload = NotificationDeliveryTelemetry.skippedPayload(authStatus: authStatus, surface: surface)
notificationDeliveryTelemetryCaptureForTests?(NotificationDeliveryTelemetry.skippedEventName, payload)
PostHogManager.shared.track(NotificationDeliveryTelemetry.skippedEventName, properties: payload)
}
// MARK: - Monitoring Events
func monitoringStarted(sessionID: String) {
trackMonitoring(
MonitoringTelemetry.startedEventName,
properties: MonitoringTelemetry.startedPayload(sessionID: sessionID))
}
func monitoringStopped(summary: MonitoringSummary) {
trackMonitoring(
MonitoringTelemetry.stoppedEventName,
properties: MonitoringTelemetry.stoppedPayload(summary: summary))
}
/// Emits the missing `Monitoring Stopped` for a session recovered from disk
/// at launch (crash or quit — see `MonitoringSessionRecovery`). Shares the
/// `Monitoring Stopped` event name with a live stop; `duration_source`
/// (`recovered_clean` / `recovered_heartbeat`) is what distinguishes a
/// recovered row in analysis.
func monitoringSessionRecovered(_ outcome: MonitoringSessionRecovery.Outcome) {
trackMonitoring(
MonitoringTelemetry.stoppedEventName,
properties: MonitoringTelemetry.recoveredStoppedPayload(outcome))
}
/// Recovers a monitoring session that never got to emit its live
/// `Monitoring Stopped` — either the app quit (`applicationWillTerminate`
/// stamped `endedAt`/`endReason` synchronously; there is no synchronous
/// PostHog flush available at terminate time) or crashed outright (no
/// stamp at all; the last heartbeat is the only evidence). Call once at
/// launch, adjacent to `detectAndReportCrash()`.
///
/// Ownership is enforced in the store, not here: a rewind-only process reads
/// nil and writes nothing, so this is a no-op there without needing its own
/// launch-mode check. See `MonitoringSessionDefaultsStore.shared`.
func recoverMonitoringSessionIfNeeded() {
guard let record = MonitoringSessionDefaultsStore.shared.load() else { return }
let outcome = MonitoringSessionRecovery.recover(record, now: Date())
monitoringSessionRecovered(outcome)
MonitoringSessionDefaultsStore.shared.clear()
}
// MARK: - Recording Events
func transcriptionStarted() {
// Debounce: skip if called within 5 seconds (catches rapid wake/reconnect double-fires)
if let last = lastTranscriptionStartedAt, Date().timeIntervalSince(last) < 5 {
return
}
lastTranscriptionStartedAt = Date()
PostHogManager.shared.transcriptionStarted()
}
func transcriptionStopped(wordCount: Int) {
PostHogManager.shared.transcriptionStopped(wordCount: wordCount)
}
func recordingError(
error: String,
reason: String? = nil,
source: String? = nil,
stage: String? = nil,
retryCount: Int? = nil
) {
PostHogManager.shared.recordingError(
error: error,
reason: reason,
source: source,
stage: stage,
retryCount: retryCount
)
}
func conversationReconciliationFailed(
error: String,
reason: String,
source: String?,
stage: String?,
retryCount: Int,
hasBackendId: Bool,
hasClientConversationId: Bool,
segmentCount: Int?,
diagnostics: ReconciliationFailureDiagnostics? = nil
) {
PostHogManager.shared.conversationReconciliationFailed(
error: error,
reason: reason,
source: source,
stage: stage,
retryCount: retryCount,
hasBackendId: hasBackendId,
hasClientConversationId: hasClientConversationId,
segmentCount: segmentCount,
diagnostics: diagnostics
)
}
// MARK: - Permission Events
func permissionRequested(permission: String, extraProperties: [String: Any] = [:]) {
PostHogManager.shared.permissionRequested(
permission: permission, extraProperties: extraProperties)
}
func permissionGranted(permission: String, extraProperties: [String: Any] = [:]) {
PostHogManager.shared.permissionGranted(
permission: permission, extraProperties: extraProperties)
}
func permissionDenied(permission: String, extraProperties: [String: Any] = [:]) {
PostHogManager.shared.permissionDenied(permission: permission, extraProperties: extraProperties)
}
func permissionSkipped(permission: String, extraProperties: [String: Any] = [:]) {
PostHogManager.shared.permissionSkipped(
permission: permission, extraProperties: extraProperties)
}
/// Track Bluetooth state changes for debugging
func bluetoothStateChanged(
oldState: String, newState: String, oldStateRaw: Int, newStateRaw: Int, authorization: String,
authorizationRaw: Int
) {
let properties: [String: Any] = [
"old_state": oldState,
"new_state": newState,
"old_state_raw": oldStateRaw,
"new_state_raw": newStateRaw,
"authorization": authorization,
"authorization_raw": authorizationRaw,
]
PostHogManager.shared.track("Bluetooth State Changed", properties: properties)
}
func devicePairingReady(
device: BtDevice,
isNewPair: Bool,
isFirstPair: Bool,
firstPairedAt: Date?
) {
let vendor = device.type.analyticsVendorSlug
let eventProperties: [String: Any] = [
"device_vendor": vendor,
"device_type": device.type.rawValue,
"model": device.displayModelNumber,
"is_first_pair": isFirstPair,
]
var userProperties: [String: Any] = [
"has_paired_device": true,
"paired_device_type": device.type.rawValue,
"device_vendor": vendor,
]
if let firstPairedAt {
userProperties["first_paired_at"] = ISO8601DateFormatter().string(from: firstPairedAt)
}
devicePairingTelemetryCaptureForTests?(
isNewPair ? "Device Paired" : nil,
eventProperties,
userProperties
)
if isNewPair {
PostHogManager.shared.track("Device Paired", properties: eventProperties)
}
PostHogManager.shared.setUserProperties(userProperties)
}
private var deviceConnectionTelemetryCaptureForTests: (@MainActor (String) -> Void)?
func setDeviceConnectionTelemetryCaptureForTests(
_ capture: (@MainActor (String) -> Void)?
) {
deviceConnectionTelemetryCaptureForTests = capture
}
func deviceConnected(device: BtDevice) {
let vendor = device.type.analyticsVendorSlug
let eventProperties: [String: Any] = [
"device_vendor": vendor,
"device_type": device.type.rawValue,
]
deviceConnectionTelemetryCaptureForTests?("Device Connected")
PostHogManager.shared.track("Device Connected", properties: eventProperties)
PostHogManager.shared.setUserProperties(["device_vendor": vendor])
}
func deviceDisconnected() {
deviceConnectionTelemetryCaptureForTests?("Device Disconnected")
PostHogManager.shared.track("Device Disconnected")
}
/// Report when ScreenCaptureKit broken state is detected (TCC granted but capture failing).
func screenCaptureBrokenDetected() {
guard !Self.isDevBuild else { return }
let breadcrumb = Breadcrumb(level: .warning, category: "screen_capture")
breadcrumb.message = "Screen Capture Broken Detected"
SentrySDK.addBreadcrumb(breadcrumb)
SentrySDK.capture(message: "Screen Capture Broken Detected") { scope in
scope.setLevel(.warning)
scope.setTag(value: "screen_capture_broken", key: "diagnostic")
}
}
/// Track when user clicks reset button or notification to reset screen capture
func screenCaptureResetClicked(source: String) {
PostHogManager.shared.screenCaptureResetClicked(source: source)
}
/// Track when screen capture reset completes (success or failure)
func screenCaptureResetCompleted(success: Bool) {
PostHogManager.shared.screenCaptureResetCompleted(success: success)
}
/// Track when notification repair is triggered (auto-repair or error-triggered)
func notificationRepairTriggered(reason: String, previousStatus: String, currentStatus: String) {
PostHogManager.shared.notificationRepairTriggered(
reason: reason, previousStatus: previousStatus, currentStatus: currentStatus)
}
/// Track notification settings status (auth, alertStyle, sound, badge)
func notificationSettingsChecked(
authStatus: String,
alertStyle: String,
soundEnabled: Bool,
badgeEnabled: Bool,
bannersDisabled: Bool
) {
PostHogManager.shared.notificationSettingsChecked(
authStatus: authStatus,
alertStyle: alertStyle,
soundEnabled: soundEnabled,
badgeEnabled: badgeEnabled,
bannersDisabled: bannersDisabled
)
}
// MARK: - Crash Detection
/// Detect if the previous session crashed (no clean exit) and report to PostHog.
/// Must be called AFTER analytics initialization but BEFORE appLaunched().
func detectAndReportCrash() {
guard !Self.isDevBuild else { return }
let cleanExitKey = "lastSessionCleanExit"
let hasLaunchedBeforeKey = "crashDetection_hasLaunchedBefore"
let hadPreviousSession = UserDefaults.standard.bool(forKey: hasLaunchedBeforeKey)
let lastCleanExit = UserDefaults.standard.bool(forKey: cleanExitKey)
// Mark that we've launched at least once (skip crash report on very first launch)
UserDefaults.standard.set(true, forKey: hasLaunchedBeforeKey)
// Clear the flag — will be set back to true only on clean exit
UserDefaults.standard.set(false, forKey: cleanExitKey)
if hadPreviousSession && !lastCleanExit {
log("Analytics: Previous session did not exit cleanly — reporting crash")
let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "unknown"
let attachmentURL = DesktopDiagnosticsManager.shared.writeIncidentDiagnosticsAttachment(
area: "crash",
failureClass: "unknown",
phase: "startup")
defer {
if let attachmentURL {
try? FileManager.default.removeItem(at: attachmentURL)
}
}
SentrySDK.capture(message: "App Crash Detected") { scope in
scope.setLevel(.warning)
scope.setTag(value: "app_crash_detected", key: "diagnostic")
scope.setContext(
value: [
"app_version": version,
"os_version": ProcessInfo.processInfo.operatingSystemVersionString,
], key: "crash")
if let attachmentURL {
scope.addAttachment(
Attachment(
path: attachmentURL.path,
filename: "desktop-incident-diagnostics.json",
contentType: "application/json"))
}
}
}
}
// MARK: - App Lifecycle Events
func appLaunched() {
PostHogManager.shared.appLaunched()
}
/// A process reports startup once. `ViewModelContainer.loadAllData()` runs
/// again after an owner switch, and that second run is not a launch.
private var didReportStartupTiming = false
/// Report one launch's startup timing.
///
/// - `dataLoadMs` is the critical startup path inside `loadAllData()`. This is
/// what the old `time_to_interactive_ms` actually measured, which is why it
/// reported 11–131ms for a "cold start".
/// - `timeToInteractiveMs` is measured from the kernel's process-start stamp,
/// so it includes dyld, `main`, and everything before the data load. It is
/// omitted rather than faked when the kernel lookup fails.
func trackStartupTiming(
dbInitMs: Double, dataLoadMs: Double, hadUncleanShutdown: Bool,
databaseInitFailed: Bool,
timeToInteractiveMs: Double? = AppStartupTiming.millisecondsSinceProcessStart()
) {
guard !Self.isDevBuild else { return }
guard !didReportStartupTiming else { return }
didReportStartupTiming = true
var properties: [String: Any] = [
"db_init_ms": round(dbInitMs),
"data_load_ms": round(dataLoadMs),
"had_unclean_shutdown": hadUncleanShutdown,
"database_init_failed": databaseInitFailed,
]
if let timeToInteractiveMs {
properties["time_to_interactive_ms"] = round(timeToInteractiveMs)
}
// Also a Sentry breadcrumb so the numbers stay attached to a same-session
// crash report. Sentry is a per-issue view; it cannot answer "is startup
// getting slower across the fleet", which is why this is in PostHog too.
let breadcrumb = Breadcrumb(level: .info, category: "app.startup")
breadcrumb.message = "App Startup Timing"
breadcrumb.data = properties
SentrySDK.addBreadcrumb(breadcrumb)
PostHogManager.shared.track("App Startup Timing", properties: properties)
}
/// Track first launch with comprehensive system diagnostics
/// This only fires once per installation
func trackFirstLaunchIfNeeded() {
// Skip in dev builds
guard !Self.isDevBuild else { return }
let defaults = UserDefaults.standard
let hasLaunchedKey = "hasLaunchedBefore"
// Check if this is the first launch
guard !defaults.bool(forKey: hasLaunchedKey) else {
return
}
// Mark as launched so this only fires once
defaults.set(true, forKey: hasLaunchedKey)
// Collect system diagnostics
let diagnostics = collectSystemDiagnostics()
// Track in all analytics systems
PostHogManager.shared.firstLaunch(diagnostics: diagnostics)
log("Analytics: First launch diagnostics tracked")
}
/// Collect comprehensive system diagnostics for first launch event
private func collectSystemDiagnostics() -> [String: Any] {
var diagnostics: [String: Any] = [:]
// App version
diagnostics["app_version"] =
Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "unknown"
diagnostics["build_number"] =
Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "unknown"
// macOS version (detailed)
let osVersion = ProcessInfo.processInfo.operatingSystemVersion
diagnostics["os_version"] =
"\(osVersion.majorVersion).\(osVersion.minorVersion).\(osVersion.patchVersion)"
diagnostics["os_major_version"] = osVersion.majorVersion
diagnostics["os_minor_version"] = osVersion.minorVersion
diagnostics["os_patch_version"] = osVersion.patchVersion
diagnostics["os_version_string"] = ProcessInfo.processInfo.operatingSystemVersionString
// Architecture (Apple Silicon vs Intel)
#if arch(arm64)
diagnostics["architecture"] = "arm64"
diagnostics["is_apple_silicon"] = true
#elseif arch(x86_64)
diagnostics["architecture"] = "x86_64"
diagnostics["is_apple_silicon"] = false
#else
diagnostics["architecture"] = "unknown"
diagnostics["is_apple_silicon"] = false
#endif
// App bundle location - helps diagnose installation issues
if let bundlePath = Bundle.main.bundlePath as String? {
// Categorize the installation location
if bundlePath.hasPrefix("/Volumes/") {
diagnostics["install_location"] = "dmg_mounted"
} else if bundlePath.contains("/Downloads/") {
diagnostics["install_location"] = "downloads_folder"
} else if bundlePath.hasPrefix("/Applications/") {
diagnostics["install_location"] = "applications_system"
} else if bundlePath.contains("/Applications/") {
diagnostics["install_location"] = "applications_user"
} else if bundlePath.contains("DerivedData") || bundlePath.contains("Xcode") {
diagnostics["install_location"] = "xcode_build"
} else {
diagnostics["install_location"] = "other"
}
diagnostics["is_standard_install"] = bundlePath.hasPrefix("/Applications/")
}
// Device info
diagnostics["processor_count"] = ProcessInfo.processInfo.processorCount
diagnostics["physical_memory_gb"] = Int(ProcessInfo.processInfo.physicalMemory / 1_073_741_824)
// Locale info
diagnostics["locale"] = Locale.current.identifier
diagnostics["timezone"] = TimeZone.current.identifier
return diagnostics
}
// MARK: - Conversation Events
// Note: The event is named "Memory Created" in analytics for historical reasons,
// but it actually tracks when a conversation/recording is created, not a "memory".
func conversationCreated(conversationId: String, source: String, durationSeconds: Int? = nil) {
PostHogManager.shared.conversationCreated(
conversationId: conversationId, source: source, durationSeconds: durationSeconds)
}
func memoryDeleted(conversationId: String) {
PostHogManager.shared.memoryDeleted(conversationId: conversationId)
}
func memoryShareButtonClicked(conversationId: String) {
PostHogManager.shared.memoryShareButtonClicked(conversationId: conversationId)
}
func shareAction(category: String, properties: [String: Any] = [:]) {
var props = properties
props["category"] = category
PostHogManager.shared.track("Share Action", properties: props)
}
func memoryListItemClicked(conversationId: String) {
PostHogManager.shared.memoryListItemClicked(conversationId: conversationId)
}
// MARK: - Chat Events
func chatMessageSent(
messageLength: Int, hasSelectedAppContext: Bool = false, source: String,
countsAsQuestion: Bool = true, attemptID: String? = nil
) {
PostHogManager.shared.chatMessageSent(
messageLength: messageLength, hasSelectedAppContext: hasSelectedAppContext, source: source)
// Every chat surface funnels through here, which makes it the one place
// that can count "questions asked" for the rating-prompt trigger. Callers
// pass countsAsQuestion: false for sends that are not a NEW accepted
// question (retries of a failed turn, busy no-op paths) so the one-time
// prompt trigger counts each logical question exactly once.
guard countsAsQuestion else { return }
questionAsked(surface: .chatWindow, source: source, messageLength: messageLength, attemptID: attemptID)
}
func desktopRatingSubmitted(rating: Int, revision: Int? = nil) {
PostHogManager.shared.desktopRatingSubmitted(rating: rating, revision: revision)
}
func desktopPromptShown(promptId: String, promptType: String) {
PostHogManager.shared.track(
"Desktop Prompt Shown", properties: ["prompt_id": promptId, "prompt_type": promptType])
}
func desktopPromptAnswered(promptId: String, promptType: String, value: String) {
PostHogManager.shared.track(
"Desktop Prompt Answered",
properties: ["prompt_id": promptId, "prompt_type": promptType, "value": value])
}
func desktopPromptDismissed(promptId: String, promptType: String) {
PostHogManager.shared.track(
"Desktop Prompt Dismissed", properties: ["prompt_id": promptId, "prompt_type": promptType])
}
// MARK: - Settings Events
func settingsPageOpened() {
PostHogManager.shared.settingsPageOpened()
}
// MARK: - Page/Screen Views (PostHog specific, but tracked in both)
func pageViewed(_ pageName: String) {
PostHogManager.shared.pageViewed(pageName)
}
// MARK: - Account Events
func deleteAccountClicked() {
PostHogManager.shared.deleteAccountClicked()
}
func deleteAccountConfirmed() {
PostHogManager.shared.deleteAccountConfirmed()
}
func deleteAccountCancelled() {
PostHogManager.shared.deleteAccountCancelled()
}
// MARK: - Navigation Events
func tabChanged(tabName: String) {
PostHogManager.shared.tabChanged(tabName: tabName)
}
func conversationDetailOpened(conversationId: String) {
PostHogManager.shared.conversationDetailOpened(conversationId: conversationId)
}
// MARK: - Chat Events (Additional)
func chatAppSelected(appId: String?, appName: String?) {
PostHogManager.shared.chatAppSelected(appId: appId, appName: appName)
}
func chatCleared() {
PostHogManager.shared.chatCleared()
}
func chatSessionCreated() {
PostHogManager.shared.track("chat_session_created", properties: [:])
}
func chatSessionDeleted() {
PostHogManager.shared.track("chat_session_deleted", properties: [:])
}
func messageRated(rating: Int, surface: String = "text") {
let ratingString = rating == 1 ? "thumbs_up" : "thumbs_down"
// `source` splits the admin thumbs-ratio chart: "text" = main-window
// chat, "voice" = floating-bar responses. Events before this dimension
// existed chart as the combined series only.
PostHogManager.shared.track(
"message_rated", properties: ["rating": ratingString, "source": surface])
}
func initialMessageGenerated(hasApp: Bool) {
PostHogManager.shared.track("initial_message_generated", properties: ["has_app": hasApp])
}
func sessionTitleGenerated() {
PostHogManager.shared.track("session_title_generated", properties: [:])
}
func chatStarredFilterToggled(enabled: Bool) {
PostHogManager.shared.track("chat_starred_filter_toggled", properties: ["enabled": enabled])
}
func sessionRenamed() {
PostHogManager.shared.track("session_renamed", properties: [:])
}
// MARK: - Claude Agent Events
/// Sends a Chat-first event only after its closed, content-free mapper has
/// produced the payload. Views must use this typed entry point instead of a
/// generic PostHog event so rich controls cannot leak user text or IDs.
func chatFirst(_ event: ChatFirstAnalyticsEvent) {
let payload = event.analyticsPayload
PostHogManager.shared.track(
payload.eventName,
properties: payload.properties.mapValues { $0 as Any }
)
}
func chatQueryTelemetry(_ event: ChatQueryTelemetryEvent) {
let payload = event.analyticsPayload
PostHogManager.shared.track(payload.eventName, properties: payload.properties)
questionAnswered(forChatEvent: event)
if case .failed(_, _, let errorClass, _, _, _) = event {
DesktopDiagnosticsManager.shared.recordChatFailure(errorClass: errorClass.rawValue)
}
let diagnosticKeys = [
"duration_ms", "error_class", "cancel_reason", "partial_response",
"surface", "harness", "runtime_surface", "session_adapter_id", "watchdog_fired",
]
let diagnostics = diagnosticKeys.compactMap { key -> String? in
guard let value = payload.properties[key] else { return nil }