forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSettingsContentView+BillingHelpers.swift
More file actions
1179 lines (1062 loc) · 40.3 KB
/
Copy pathSettingsContentView+BillingHelpers.swift
File metadata and controls
1179 lines (1062 loc) · 40.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 OmiTheme
import Sparkle
import SwiftUI
import UniformTypeIdentifiers
import WebKit
/// Single edit point for the Operator price quoted in the deprecation-banner
/// fallback (used only when the backend omits `deprecationMessage`).
let operatorDeprecationFallbackPrice = "$49/mo"
enum SubscriptionPlanPresentation {
static func selectionLabel(planTitle: String, startingPrice: String?) -> String {
guard let startingPrice, !startingPrice.isEmpty else {
return "Select \(planTitle)"
}
return "Select \(planTitle) · \(startingPrice)"
}
}
extension SettingsContentView {
var hasPaidSubscription: Bool {
guard let subscription = userSubscription?.subscription else { return false }
if subscription.features.contains("byok") { return false }
return subscription.plan.hasPaidCapability && subscription.status == .active
}
var shouldShowPlanPurchaseOptions: Bool {
!subscriptionPlansForDisplay.isEmpty
}
var subscriptionPlansForDisplay: [SubscriptionPlanOption] {
// Operator (mass-market, green) on the left, Architect (premium, white accent)
// on the right. Hide the user's current plan — they already see it above.
// Neo ($20) | Operator ($49) | Architect ($200) — cheapest to premium
let order = ["unlimited": 0, "operator": 1, "architect": 2]
return
mergedPlanCatalog
.filter { !isCurrentSubscriptionPlan($0) }
.sorted { lhs, rhs in
let lhsOrder = order[lhs.id, default: Int.max]
let rhsOrder = order[rhs.id, default: Int.max]
if lhsOrder != rhsOrder {
return lhsOrder < rhsOrder
}
return lhs.title < rhs.title
}
}
var currentPlanTitle: String {
guard let subscription = userSubscription?.subscription else {
return isLoadingSubscription ? "Loading plan..." : "Free"
}
// BYOK users: the backend returns plan=unlimited to turn off metering
// but that's an implementation detail — to the user, they're on the
// free plan because they pay the providers directly, not Omi.
if subscription.features.contains("byok") {
return "Free (BYOK)"
}
switch subscription.plan {
case .basic:
return "Free"
case .plus:
return "Plus"
case .unlimited:
// Backend serializes Operator subscribers as plan="unlimited" for
// backward compat with old mobile builds that don't know the
// `operator` enum. Distinguish by matching current_price_id against
// an Operator-titled plan in the catalog.
if isCurrentSubscriptionOperator() {
return "Operator"
}
return "Neo"
case .unlimitedV2:
return "Unlimited"
case .architect, .pro:
return "Architect"
case .operator:
return "Operator"
case .unknown:
return subscription.plan.displayName
}
}
/// Returns true when the user's current Stripe price maps to a plan the
/// backend is calling "Operator". Protects against the wire-level
/// Operator→Unlimited remapping in `/v1/users/me/subscription`.
func isCurrentSubscriptionOperator() -> Bool {
guard let subscription = userSubscription?.subscription,
let currentPriceId = subscription.currentPriceId
else { return false }
for plan in mergedPlanCatalog {
guard plan.title == "Operator" else { continue }
if plan.prices.contains(where: { $0.id == currentPriceId }) {
return true
}
}
return false
}
var currentPlanSubtitle: String {
if isLoadingSubscription {
return "Fetching subscription details from omi."
}
if let detail = currentPlanBillingDetail {
return detail
}
if hasPaidSubscription {
return "Your paid plan is active."
}
return "You are currently on the free tier."
}
var currentPlanBillingDetail: String? {
guard hasPaidSubscription,
let subscription = userSubscription?.subscription,
let currentPriceId = subscription.currentPriceId
else {
return nil
}
for plan in mergedPlanCatalog {
if let price = plan.prices.first(where: { $0.id == currentPriceId }) {
return "\(plan.title) \(price.title) • \(price.priceString)"
}
}
return nil
}
var currentPlanPeriodText: String? {
guard let subscription = userSubscription?.subscription else { return nil }
guard hasPaidSubscription, let periodEnd = subscription.currentPeriodEnd else { return nil }
let date = Date(timeIntervalSince1970: TimeInterval(periodEnd))
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .none
let prefix = subscription.cancelAtPeriodEnd ? "Access ends" : "Renews"
return "\(prefix) on \(formatter.string(from: date))"
}
static func planSubtitle(for planId: String) -> String? {
switch planId {
case "unlimited":
return "200 questions per month"
case "operator":
return "500 questions per month"
case "architect":
return "Power-user AI — thousands of chats + agentic automations"
default:
return nil
}
}
func planAccentColor(for planId: String) -> Color {
// Architect is the premium white-accent tier; Operator + legacy Unlimited
// are the mass-market green tier.
planId == "architect" ? Ink.accent : Ink.listeningGreen
}
func planSummaryText(for plan: SubscriptionPlanOption) -> String {
preferredStartingPrice(for: plan)?.priceString ?? ""
}
func planSelectionLabel(for plan: SubscriptionPlanOption) -> String {
SubscriptionPlanPresentation.selectionLabel(
planTitle: plan.title,
startingPrice: preferredStartingPrice(for: plan)?.priceString
)
}
func preferredStartingPrice(for plan: SubscriptionPlanOption) -> SubscriptionPriceOption? {
let prices = sortedPrices(for: plan)
if let monthly = prices.first(where: { price in
let title = price.title.lowercased()
return title.contains("month")
}) {
return monthly
}
return prices.first
}
static func planEyebrow(for planId: String) -> String {
switch planId {
case "unlimited":
return "Starter"
case "operator":
return "Most popular"
case "architect":
return "Automation + coding"
default:
return "Plan"
}
}
static func planDescription(for planId: String) -> String {
switch planId {
case "unlimited":
return "200 chat questions per month. Shared with mobile and web."
case "operator":
return "500 chat questions per month. Shared with mobile and web."
case "architect":
return "Power-user AI for heavy agentic workflows and vibe coding."
default:
return ""
}
}
func sortedPrices(for plan: SubscriptionPlanOption) -> [SubscriptionPriceOption] {
plan.prices.sorted { lhs, rhs in
let lhsIsMonthly = lhs.title.lowercased().contains("month")
let rhsIsMonthly = rhs.title.lowercased().contains("month")
if lhsIsMonthly != rhsIsMonthly {
return lhsIsMonthly && !rhsIsMonthly
}
return lhs.title < rhs.title
}
}
func isCurrentSubscriptionPlan(_ plan: SubscriptionPlanOption) -> Bool {
guard hasPaidSubscription, let currentPlan = userSubscription?.subscription.plan else {
return false
}
if currentPlan == .operator && plan.id == "unlimited" {
return true
}
if currentPlan == .unlimited && plan.id == "operator" && isCurrentSubscriptionOperator() {
return true
}
return currentPlan.rawValue == plan.id
}
var mergedPlanCatalog: [SubscriptionPlanOption] {
mergePlanCatalog(primary: userSubscription?.availablePlans ?? [], fallback: fallbackPlanCatalog)
}
func mergePlanCatalog(
primary: [SubscriptionPlanOption],
fallback: [SubscriptionPlanOption]
) -> [SubscriptionPlanOption] {
SubscriptionPlanCatalogMerger.merge(primary: primary, fallback: fallback)
}
static func fallbackFeatures(for planId: String) -> [String] {
switch planId {
case "architect":
return [
"Automations and vibe coding",
"Unlimited listening, memories, and insights",
"Priority desktop AI features",
"~$400 of monthly AI compute included (fair-use cap)",
]
case "operator":
return [
"500 chat questions per month",
"Unlimited listening and transcription",
"Unlimited memories and insights",
"Shared with mobile and web",
]
case "unlimited":
return [
"200 chat questions per month",
"Unlimited listening and transcription",
"Unlimited memories and insights",
"Shared with mobile and web",
]
default:
return []
}
}
func normalizedPlanId(from title: String) -> String? {
let normalized = title.lowercased()
// Match the three plan families by title keyword. Neo is the post-rename
// display name for the legacy "unlimited" plan and still maps to that id
// because Stripe/backend PlanType enum is unchanged.
if normalized.contains("unlimited") || normalized.contains("neo") {
return "unlimited"
}
if normalized.contains("operator") {
return "operator"
}
if normalized.contains("architect") || normalized.contains("pro") {
return "architect"
}
return nil
}
func planCatalog(from prices: [AvailablePlanPriceOption]) -> [SubscriptionPlanOption] {
let groupedPrices = Dictionary(grouping: prices) { price in
normalizedPlanId(from: price.title) ?? "unknown"
}
return groupedPrices.compactMap { planId, options in
guard planId != "unknown" else { return nil }
let title: String
switch planId {
case "unlimited":
title = "Neo"
case "operator":
title = "Operator"
case "architect":
title = "Architect"
default:
title = options.first?.title ?? "Plan"
}
let mappedPrices = options.map { option in
SubscriptionPriceOption(
id: option.id,
title: option.interval.lowercased().contains("year") ? "Annual" : "Monthly",
description: option.description,
priceString: option.priceString
)
}
return SubscriptionPlanOption(
id: planId,
title: title,
features: Self.fallbackFeatures(for: planId),
prices: mappedPrices
)
}
}
@ViewBuilder
func subscriptionPlanCard(_ plan: SubscriptionPlanOption) -> some View {
let isSelected = selectedPlanIdForCheckout == plan.id
let accent = planAccentColor(for: plan.id)
let isCurrentPlan = isCurrentSubscriptionPlan(plan)
let isArchitectUser =
userSubscription?.subscription.plan == .architect
|| userSubscription?.subscription.plan == .pro
let isDowngrade = isArchitectUser && plan.id == "unlimited"
let canPurchase = !isCurrentPlan && !isDowngrade
VStack(alignment: .leading, spacing: OmiSpacing.lg) {
HStack(alignment: .top, spacing: OmiSpacing.md) {
VStack(alignment: .leading, spacing: OmiSpacing.xs) {
// The tint is the disc, not the word — the same measurement `SettingsStatusChip`
// documents. These are *named system colours* on a light panel: `systemGreen` sets a
// 10 pt bold eyebrow at ≈1.6:1 against this card and `systemBlue` at ≈2.4:1, so the
// plan's colour was there and the plan's name could not be read. Moving the hue to a
// 6 pt disc keeps the tier legible at a glance *and* legible as words.
HStack(spacing: 5) {
Circle()
.fill(accent)
.frame(width: 6, height: 6)
Text((plan.eyebrow ?? Self.planEyebrow(for: plan.id)).uppercased())
.scaledFont(size: OmiType.micro, weight: .bold)
.foregroundColor(Ink.secondary)
.tracking(0.8)
}
Text(plan.title)
.scaledFont(size: OmiType.heading, weight: .bold)
.foregroundColor(Ink.primary)
if let subtitle = plan.subtitle ?? Self.planSubtitle(for: plan.id) {
Text(subtitle)
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
}
}
Spacer()
// Selection is carried by the tile's own fill and border, so the price does not also change
// colour to say it. The selected branch of both of these used to tint the copy — and at
// `accent.opacity(0.8)` on a selected card that was the faintest text on the pane, i.e. the
// state that most wanted reading was the one hardest to read.
VStack(alignment: .trailing, spacing: OmiSpacing.hairline) {
Text(planSummaryText(for: plan))
.scaledFont(size: OmiType.subheading, weight: .bold)
.foregroundColor(Ink.primary)
.lineLimit(1)
.minimumScaleFactor(0.72)
Text("starting price")
.scaledFont(size: OmiType.micro, weight: .medium)
.foregroundColor(Ink.secondary)
}
.fixedSize(horizontal: true, vertical: false)
}
Text(plan.description ?? Self.planDescription(for: plan.id))
.scaledFont(size: OmiType.body)
.foregroundColor(Ink.secondary)
VStack(alignment: .leading, spacing: OmiSpacing.sm) {
ForEach(plan.features.prefix(4), id: \.self) { feature in
HStack(spacing: OmiSpacing.sm) {
ZStack {
Circle()
.fill(accent.opacity(0.16))
.frame(width: 18, height: 18)
// The disc carries the tint; the mark on it is ink. A `systemGreen` glyph on a 16%
// `systemGreen` disc is the same sub-2:1 pair the eyebrow had.
Image(systemName: "checkmark")
.scaledFont(size: OmiType.micro, weight: .bold)
.foregroundColor(Ink.primary)
}
Text(feature)
.scaledFont(size: OmiType.body, weight: .medium)
.foregroundColor(Ink.secondary)
}
}
}
if isSelected && canPurchase {
GlassSeparator()
VStack(alignment: .leading, spacing: OmiSpacing.sm) {
VStack(alignment: .leading, spacing: OmiSpacing.xs) {
Button(action: {
OmiMotion.withGated(.easeInOut(duration: 0.2)) {
isPromoCodeExpanded.toggle()
}
}) {
HStack(spacing: OmiSpacing.xs) {
Image(systemName: "tag")
.scaledFont(size: OmiType.caption)
Text("Promo code")
.scaledFont(size: OmiType.caption)
Image(systemName: isPromoCodeExpanded ? "chevron.up" : "chevron.down")
.scaledFont(size: OmiType.micro)
}
.foregroundColor(Ink.secondary)
}
.buttonStyle(.plain)
if isPromoCodeExpanded {
VStack(alignment: .leading, spacing: OmiSpacing.xs) {
TextField("Enter promo code", text: $upgradePromotionCode)
.settingsTextInputStyle()
.disabled(activeCheckoutPriceId != nil)
.onChange(of: upgradePromotionCode) {
subscriptionError = nil
}
if let error = subscriptionError {
HStack(spacing: OmiSpacing.xxs) {
Image(systemName: "exclamationmark.circle")
.scaledFont(size: OmiType.caption)
Text(error)
.scaledFont(size: OmiType.caption)
}
.foregroundColor(SettingsInk.notice)
}
}
.transition(.opacity.combined(with: .move(edge: .top)))
}
}
Text("Choose billing")
.scaledFont(size: OmiType.caption, weight: .semibold)
.foregroundColor(Ink.secondary)
HStack(spacing: OmiSpacing.sm) {
ForEach(sortedPrices(for: plan)) { price in
Button(action: {
startCheckout(for: price.id)
}) {
Group {
if activeCheckoutPriceId == price.id {
ProgressView()
.controlSize(.small)
.frame(maxWidth: .infinity)
} else {
VStack(spacing: OmiSpacing.hairline) {
Text(price.title)
.scaledFont(size: OmiType.caption, weight: .bold)
Text(price.priceString)
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
}
.frame(maxWidth: .infinity)
}
}
}
.buttonStyle(OmiButtonStyle(.secondary, size: .compact))
.disabled(activeCheckoutPriceId != nil)
}
}
}
} else if isCurrentPlan {
HStack {
Text("Current Plan")
.scaledFont(size: OmiType.caption, weight: .bold)
.foregroundColor(Ink.primary)
Spacer()
// The glyph keeps the tint — it is a graphical object, which is a 3:1 bar rather than a
// 4.5:1 one — and the words next to it stop being set in a hue that cannot clear either.
Image(systemName: "checkmark.circle.fill")
.scaledFont(size: OmiType.caption)
.foregroundColor(accent)
}
.padding(.vertical, OmiSpacing.sm)
} else {
Button(action: {
selectedPlanIdForCheckout = plan.id
}) {
HStack {
Text(planSelectionLabel(for: plan))
.scaledFont(size: OmiType.caption, weight: .bold)
Spacer()
Image(systemName: "arrow.right")
.scaledFont(size: OmiType.caption, weight: .bold)
}
.frame(maxWidth: .infinity)
}
.buttonStyle(OmiButtonStyle(.secondary, size: .compact))
}
}
.padding(OmiSpacing.xxl)
.frame(maxWidth: .infinity, alignment: .leading)
// The tile is now the pane's *only* card here rather than content inside one, so at rest it is
// exactly the card every other pane draws — `Ink.rowFill` behind an `Ink.separator` hairline.
// It was `Ink.wash` behind `Ink.hairline`, which are the well and control-outline tokens: right
// for something sitting on a card, a shade too heavy once it *is* the card.
.background(
RoundedRectangle(cornerRadius: SettingsGlassMetrics.cardRadius, style: .continuous)
.fill(isSelected ? accent.opacity(0.12) : Ink.rowFill)
.overlay(
RoundedRectangle(cornerRadius: SettingsGlassMetrics.cardRadius, style: .continuous)
.stroke(
isSelected ? accent.opacity(0.85) : Ink.separator,
lineWidth: isSelected ? 1.5 : 1)
)
)
.contentShape(RoundedRectangle(cornerRadius: SettingsGlassMetrics.cardRadius, style: .continuous))
.onTapGesture {
guard canPurchase else { return }
selectedPlanIdForCheckout = plan.id
}
}
// MARK: - Language Helpers
/// Whether the selected language supports auto-detect mode
var autoDetectSupported: Bool {
AssistantSettings.supportsAutoDetect(transcriptionLanguage)
}
/// Subtitle text for auto-detect toggle
var autoDetectSubtitle: String {
if autoDetectSupported {
return "Automatically detect spoken language"
} else {
return "Not available for \(languageName(for: transcriptionLanguage))"
}
}
/// Get display name for a language code
func languageName(for code: String) -> String {
AssistantSettings.supportedLanguages.first { $0.code == code }?.name ?? code
}
// MARK: - Slider Index Helpers
// Each of these was `options.firstIndex(of: stored) ?? 0`. See
// `SettingsControlMetrics.nearestLadderIndex` for what that `?? 0` did to a stored value the
// slider does not offer, and why the handle now snaps to the nearest step instead. When it is only
// an approximation, `offLadderStepNote` says so under the slider.
var analysisDelaySliderIndex: Int {
SettingsControlMetrics.nearestLadderIndex(of: analysisDelay, in: analysisDelayOptions)
}
var taskIntervalSliderIndex: Int {
SettingsControlMetrics.nearestLadderIndex(
of: taskExtractionInterval, in: extractionIntervalOptions)
}
var insightIntervalSliderIndex: Int {
SettingsControlMetrics.nearestLadderIndex(
of: insightExtractionInterval, in: extractionIntervalOptions)
}
var memoryIntervalSliderIndex: Int {
SettingsControlMetrics.nearestLadderIndex(
of: memoryExtractionInterval, in: extractionIntervalOptions)
}
// MARK: - Helpers
func toggleMonitoring(enabled: Bool) {
if enabled && !ProactiveAssistantsPlugin.shared.hasScreenRecordingPermission {
permissionError = "Screen recording permission required"
isMonitoring = false
ScreenCaptureService.requestScreenRecordingAccessAndOpenSettings()
return
}
permissionError = nil
isToggling = true
// Track setting change
AnalyticsManager.shared.settingToggled(setting: "monitoring", enabled: enabled)
if enabled {
ProactiveAssistantsPlugin.shared.startMonitoring { success, error in
DispatchQueue.main.async {
isToggling = false
if !success {
permissionError = error ?? "Failed to start monitoring"
isMonitoring = false
}
}
}
} else {
ProactiveAssistantsPlugin.shared.stopMonitoring()
isToggling = false
}
// Persist the setting
AssistantSettings.shared.screenAnalysisEnabled = enabled
}
func startGlowPreview() {
isPreviewRunning = true
// Show the demo window and get its frame
let demoWindow = GlowDemoWindow.show()
let windowFrame = demoWindow.frame
// Phase 1: Show focused (green) glow after a small delay
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
GlowDemoWindow.setPhase(.focused)
OverlayService.shared.showGlow(around: windowFrame, colorMode: .focused, isPreview: true)
}
// Phase 2: Show distracted (red) glow
DispatchQueue.main.asyncAfter(deadline: .now() + 3.3) {
GlowDemoWindow.setPhase(.distracted)
OverlayService.shared.showGlow(around: windowFrame, colorMode: .distracted, isPreview: true)
}
// End preview and close demo window
DispatchQueue.main.asyncAfter(deadline: .now() + 7.0) {
GlowDemoWindow.close()
isPreviewRunning = false
}
}
func deleteCurrentAIProfile() {
guard let id = aiProfileId else { return }
Task {
let previous = await AIUserProfileService.shared.deleteProfile(id: id)
await MainActor.run {
if let previous {
aiProfileId = previous.id
aiProfileText = previous.profileText
aiProfileGeneratedAt = previous.generatedAt
aiProfileDataSourcesUsed = previous.dataSourcesUsed
} else {
aiProfileId = nil
aiProfileText = nil
aiProfileGeneratedAt = nil
aiProfileDataSourcesUsed = 0
}
}
}
}
func regenerateAIProfile() {
isGeneratingAIProfile = true
Task {
do {
let result = try await AIUserProfileService.shared.generateProfile()
await MainActor.run {
aiProfileId = result.id
aiProfileText = result.profileText
aiProfileGeneratedAt = result.generatedAt
aiProfileDataSourcesUsed = result.dataSourcesUsed
isGeneratingAIProfile = false
}
} catch {
log("Settings: AI profile generation failed: \(error.localizedDescription)")
await MainActor.run {
isGeneratingAIProfile = false
}
}
}
}
func formatMinutes(_ minutes: Int) -> String {
if minutes == 1 {
return "1 minute"
} else if minutes < 60 {
return "\(minutes) minutes"
} else {
return "1 hour"
}
}
func formatAnalysisDelay(_ seconds: Int) -> String {
if seconds == 0 {
return "Instant"
} else if seconds < 60 {
return "\(seconds) seconds"
} else if seconds == 60 {
return "1 minute"
} else {
return "\(seconds / 60) minutes"
}
}
func formatExtractionInterval(_ seconds: Double) -> String {
if seconds < 60 {
return "\(Int(seconds)) seconds"
} else if seconds < 3600 {
let minutes = Int(seconds / 60)
return minutes == 1 ? "1 minute" : "\(minutes) minutes"
} else {
let hours = Int(seconds / 3600)
return hours == 1 ? "1 hour" : "\(hours) hours"
}
}
func formatHour(_ hour: Int) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "h:00 a"
var components = DateComponents()
components.hour = hour
if let date = Calendar.current.date(from: components) {
return formatter.string(from: date)
}
return "\(hour):00"
}
// MARK: - Backend Settings
func loadBackendSettings() {
guard !isLoadingSettings else { return }
isLoadingSettings = true
// Load local transcription settings first (these are used immediately)
transcriptionLanguage = AssistantSettings.shared.transcriptionLanguage
transcriptionAutoDetect = AssistantSettings.shared.transcriptionAutoDetect
vocabularyList = AssistantSettings.shared.transcriptionVocabulary
let transcriptionVocabularyRevisionAtLoadStart =
AssistantSettings.shared.transcriptionVocabularyRevision
vadGateEnabled = AssistantSettings.shared.vadGateEnabled
Task {
do {
// Load all settings in parallel
async let dailySummaryTask = APIClient.shared.getDailySummarySettings()
async let notificationsReconcile: Void = NotificationSettingsSyncCoordinator.shared.reconcile()
async let languageTask = APIClient.shared.getUserLanguage()
async let recordingTask = APIClient.shared.getRecordingPermission()
async let cloudSyncTask = APIClient.shared.getPrivateCloudSync()
async let transcriptionTask = APIClient.shared.getTranscriptionPreferences()
// Sync assistant settings from server in parallel
async let assistantSyncTask: () = SettingsSyncManager.shared.syncFromServer()
let (dailySummary, _, language, recording, cloudSync, transcription, _) = try await (
dailySummaryTask,
notificationsReconcile,
languageTask,
recordingTask,
cloudSyncTask,
transcriptionTask,
assistantSyncTask
)
await MainActor.run {
dailySummaryEnabled = dailySummary.enabled
dailySummaryHour = dailySummary.hour
dailySummaryTime = SettingsControlMetrics.dailySummaryDate(
forHour: dailySummary.hour, referenceDate: Date())
// Local UserDefaults remain the gate. The coordinator owns GET/hydrate/retry.
notificationsEnabled = NotificationService.areNotificationsEnabled()
notificationFrequency = NotificationService.currentFrequencyLevel()
userLanguage = language.language
recordingPermissionEnabled = recording.enabled
privateCloudSyncEnabled = cloudSync.enabled
singleLanguageMode = transcription.singleLanguageMode
// Do not let a GET that began before a local/PATCH mutation overwrite
// the newer vocabulary when it finally completes.
if AssistantSettings.shared.shouldApplyTranscriptionVocabularyHydration(
startedAtRevision: transcriptionVocabularyRevisionAtLoadStart
) {
vocabularyList = transcription.vocabulary
AssistantSettings.shared.transcriptionVocabulary = transcription.vocabulary
} else {
vocabularyList = AssistantSettings.shared.transcriptionVocabulary
}
// Sync backend language to local if different (backend is source of truth for language)
let normalizedLanguage = AssistantSettings.normalizeTranscriptionLanguageCode(language.language)
if !language.language.isEmpty && normalizedLanguage != transcriptionLanguage {
transcriptionLanguage = normalizedLanguage
AssistantSettings.shared.transcriptionLanguage = normalizedLanguage
}
// Sync single language mode from backend (inverted to auto-detect)
// Only update if we got a valid response and it differs
let backendAutoDetect =
!transcription.singleLanguageMode && AssistantSettings.supportsAutoDetect(normalizedLanguage)
if backendAutoDetect != transcriptionAutoDetect {
transcriptionAutoDetect = backendAutoDetect
AssistantSettings.shared.transcriptionAutoDetect = backendAutoDetect
}
isLoadingSettings = false
viewModel.markBackendSettingsLoaded()
}
} catch {
logError("Failed to load backend settings", error: error)
await MainActor.run {
isLoadingSettings = false
}
}
}
}
func loadSubscriptionInfo() {
guard !isLoadingSubscription else { return }
isLoadingSubscription = true
subscriptionError = nil
refreshPlanUsageDetails()
Task {
do {
let subscription = try await APIClient.shared.getUserSubscription()
let availablePlans = try? await APIClient.shared.getAvailablePlans()
await MainActor.run {
userSubscription = subscription
subscriptionError = nil
fallbackPlanCatalog = availablePlans.map { planCatalog(from: $0.plans) } ?? []
if let selectedPlanIdForCheckout,
subscription.subscription.plan.rawValue == selectedPlanIdForCheckout
{
self.selectedPlanIdForCheckout = nil
}
// Clear the sticky paywall flag whenever the subscription endpoint
// reports a non-basic active plan. Catches the case where a paid user
// hit the paywall once (e.g. WS connected before payment cleared
// the trial cache) — without this they'd stay paywalled until the
// next app restart even after their Operator/Architect plan is active.
if subscription.subscription.plan.hasPaidCapability,
subscription.subscription.status == .active,
AppState.current?.isPaywalled == true
{
AppState.current?.isPaywalled = false
log("Paywall: cleared sticky flag — subscription \(subscription.subscription.plan.rawValue) is active")
}
isLoadingSubscription = false
viewModel.markBillingRefreshed()
}
} catch {
logError("Failed to load subscription", error: error)
await MainActor.run {
subscriptionError = "Failed to load plan information."
isLoadingSubscription = false
}
}
}
}
func refreshPlanUsageDetails() {
planUsageDetailsRequestID += 1
let requestID = planUsageDetailsRequestID
isLoadingChatUsage = true
isLoadingOverage = true
chatUsageQuota = nil
overageInfo = nil
Task {
async let quota = APIClient.shared.fetchChatUsageQuota()
async let overageInfo = fetchOverageInfoForPlanUsage()
let (quotaValue, overageInfoValue) = await (quota, overageInfo)
applyPlanUsageDetails(
requestID: requestID,
quota: quotaValue,
overageInfo: overageInfoValue
)
}
}
func fetchOverageInfoForPlanUsage() async -> OverageInfoResponse? {
do {
return try await APIClient.shared.getOverageInfo()
} catch {
logError("Failed to load overage info", error: error)
return nil
}
}
@MainActor
func applyPlanUsageDetails(
requestID: Int,
quota: APIClient.ChatUsageQuota?,
overageInfo: OverageInfoResponse?
) {
guard requestID == planUsageDetailsRequestID else { return }
chatUsageQuota = quota
if let quota {
FloatingBarUsageLimiter.shared.applyQuota(quota)
}
self.overageInfo = overageInfo
isLoadingChatUsage = false
isLoadingOverage = false
}
func applySuccessfulSubscriptionRefresh(_ subscription: UserSubscriptionResponse) {
userSubscription = subscription
subscriptionError = nil
pendingSubscriptionPriceId = nil
pendingCheckoutSessionId = nil
selectedPlanIdForCheckout = nil
FloatingBarUsageLimiter.shared.applyPlan(
plan: subscription.subscription.plan,
status: subscription.subscription.status,
desktopGrandfatherUntil: subscription.desktopGrandfatherUntil
)
if subscription.subscription.plan.hasPaidCapability,
subscription.subscription.status == .active,
AppState.current?.isPaywalled == true
{
AppState.current?.isPaywalled = false
log("Paywall: cleared sticky flag — subscription \(subscription.subscription.plan.rawValue) is active")
}
refreshPlanUsageDetails()
}
func startCheckout(for priceId: String) {
guard activeCheckoutPriceId == nil else { return }
activeCheckoutPriceId = priceId
pendingSubscriptionPriceId = priceId
subscriptionError = nil
let promotionCode = upgradePromotionCode.trimmingCharacters(in: .whitespacesAndNewlines)
let promoToSend: String? = promotionCode.isEmpty ? nil : promotionCode
// If user already has an active paid subscription (not canceled), use upgrade endpoint
// to schedule the plan change at end of billing period (no double-charging)
if hasPaidSubscription,
let subscription = userSubscription?.subscription,
!subscription.cancelAtPeriodEnd
{
Task {
do {
_ = try await APIClient.shared.upgradeSubscription(
priceId: priceId, promotionCode: promoToSend)
await MainActor.run {
activeCheckoutPriceId = nil
pendingSubscriptionPriceId = nil
subscriptionError = nil
self.upgradePromotionCode = ""
loadSubscriptionInfo()
}
} catch let apiError as APIError {
await MainActor.run {
activeCheckoutPriceId = nil
pendingSubscriptionPriceId = nil
subscriptionError = apiError.detail ?? "Failed to schedule plan change."
}
} catch {
logError("Failed to schedule plan change", error: error)
await MainActor.run {
activeCheckoutPriceId = nil
pendingSubscriptionPriceId = nil
subscriptionError = "Failed to schedule plan change."
}
}
}
return
}
Task {
do {
let response = try await APIClient.shared.createCheckoutSession(
priceId: priceId, promotionCode: promoToSend)
let apiBaseURL = await APIClient.shared.baseURL
await MainActor.run {
activeCheckoutPriceId = nil
pendingCheckoutSessionId = response.sessionId
}
if response.status == "reactivated" {
await MainActor.run {
subscriptionError = nil
pendingSubscriptionPriceId = nil
pendingCheckoutSessionId = nil
loadSubscriptionInfo()
}
} else if let urlString = response.url, let url = URL(string: urlString) {
let normalizedBaseURL = apiBaseURL.hasSuffix("/") ? apiBaseURL : apiBaseURL + "/"
await MainActor.run {
activeBillingWebFlow = BillingWebFlow(
title: "Complete Your Upgrade",
url: url,
completionURLs: [