-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathSettingsStore.swift
More file actions
3951 lines (3511 loc) · 154 KB
/
SettingsStore.swift
File metadata and controls
3951 lines (3511 loc) · 154 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 ApplicationServices
import Combine
import Foundation
import ServiceManagement
import SwiftUI
#if canImport(FluidAudio)
import FluidAudio
#endif
// swiftlint:disable type_body_length
final class SettingsStore: ObservableObject {
static let shared = SettingsStore()
static let transcriptionPreviewCharLimitRange: ClosedRange<Int> = 50...800
static let transcriptionPreviewCharLimitStep = 50
static let defaultTranscriptionPreviewCharLimit = 150
private let defaults = UserDefaults.standard
private let keychain = KeychainService.shared
private(set) var launchAtStartupEnabled = false
private(set) var launchAtStartupErrorMessage: String?
private(set) var launchAtStartupStatusMessage =
"FluidVoice reflects the actual macOS login item state. Unsigned or development builds may fail to enable this."
private init() {
self.migrateTranscriptionStartSoundIfNeeded()
self.ensureDebugLoggingDefaults()
self.migrateProviderAPIKeysIfNeeded()
self.scrubSavedProviderAPIKeys()
self.migrateDictationPromptProfilesIfNeeded()
self.migrateLegacyDictationAIPreferenceIfNeeded()
self.normalizePromptSelectionsIfNeeded()
self.migrateOverlayBottomOffsetTo50IfNeeded()
self.refreshLaunchAtStartupStatus(clearError: true, logMismatch: false)
}
// MARK: - Prompt Profiles (Unified)
enum PromptMode: String, Codable, CaseIterable, Identifiable {
case dictate
case edit
case write // legacy persisted value (decoded as .edit)
case rewrite // legacy persisted value (decoded as .edit)
var id: String {
self.rawValue
}
static var visiblePromptModes: [PromptMode] {
[.dictate, .edit]
}
var normalized: PromptMode {
switch self {
case .dictate:
return .dictate
case .edit, .write, .rewrite:
return .edit
}
}
var displayName: String {
switch self.normalized {
case .dictate:
return "Dictate"
case .edit:
return "Edit"
case .write, .rewrite:
return "Edit"
}
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let raw = (try? container.decode(String.self).lowercased()) ?? Self.dictate.rawValue
switch raw {
case "dictate":
self = .dictate
case "edit", "write", "rewrite":
self = .edit
default:
self = .dictate
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.normalized.rawValue)
}
}
enum DictationShortcutSlot: String, Codable, CaseIterable, Identifiable {
case primary
case secondary
var id: String { self.rawValue }
var displayName: String {
switch self {
case .primary:
return "Primary Dictation Shortcut"
case .secondary:
return "Secondary Dictation Shortcut"
}
}
}
enum DictationPromptSelection: Equatable {
case off
case `default`
case profile(String)
}
struct DictationPromptProfile: Codable, Identifiable, Hashable {
let id: String
var name: String
var prompt: String
var mode: PromptMode
var includeContext: Bool
var createdAt: Date
var updatedAt: Date
private enum CodingKeys: String, CodingKey {
case id
case name
case prompt
case mode
case includeContext
case createdAt
case updatedAt
}
init(
id: String = UUID().uuidString,
name: String,
prompt: String,
mode: PromptMode = .dictate,
includeContext: Bool = false,
createdAt: Date = Date(),
updatedAt: Date = Date()
) {
self.id = id
self.name = name
self.prompt = prompt
self.mode = mode
self.includeContext = includeContext
self.createdAt = createdAt
self.updatedAt = updatedAt
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
self.name = try container.decode(String.self, forKey: .name)
self.prompt = try container.decode(String.self, forKey: .prompt)
self.mode = try (container.decodeIfPresent(PromptMode.self, forKey: .mode) ?? .dictate).normalized
self.includeContext = try container.decodeIfPresent(Bool.self, forKey: .includeContext) ?? false
self.createdAt = try container.decode(Date.self, forKey: .createdAt)
self.updatedAt = try container.decode(Date.self, forKey: .updatedAt)
}
}
struct AppPromptBinding: Codable, Identifiable, Hashable {
let id: String
var mode: PromptMode
var appBundleID: String
var appName: String
var promptID: String?
var createdAt: Date
var updatedAt: Date
private enum CodingKeys: String, CodingKey {
case id
case mode
case appBundleID
case appName
case promptID
case createdAt
case updatedAt
}
init(
id: String = UUID().uuidString,
mode: PromptMode,
appBundleID: String,
appName: String,
promptID: String?,
createdAt: Date = Date(),
updatedAt: Date = Date()
) {
self.id = id
self.mode = mode.normalized
self.appBundleID = Self.normalizeBundleID(appBundleID)
let trimmedName = appName.trimmingCharacters(in: .whitespacesAndNewlines)
self.appName = trimmedName.isEmpty ? self.appBundleID : trimmedName
let trimmedPromptID = promptID?.trimmingCharacters(in: .whitespacesAndNewlines)
self.promptID = (trimmedPromptID?.isEmpty == true) ? nil : trimmedPromptID
self.createdAt = createdAt
self.updatedAt = updatedAt
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
self.mode = try (container.decodeIfPresent(PromptMode.self, forKey: .mode) ?? .dictate).normalized
let rawBundleID = try container.decodeIfPresent(String.self, forKey: .appBundleID) ?? ""
self.appBundleID = Self.normalizeBundleID(rawBundleID)
let rawName = try container.decodeIfPresent(String.self, forKey: .appName) ?? ""
let trimmedName = rawName.trimmingCharacters(in: .whitespacesAndNewlines)
self.appName = trimmedName.isEmpty ? self.appBundleID : trimmedName
let rawPromptID = try container.decodeIfPresent(String.self, forKey: .promptID)
let trimmedPromptID = rawPromptID?.trimmingCharacters(in: .whitespacesAndNewlines)
self.promptID = (trimmedPromptID?.isEmpty == true) ? nil : trimmedPromptID
self.createdAt = try container.decodeIfPresent(Date.self, forKey: .createdAt) ?? Date()
self.updatedAt = try container.decodeIfPresent(Date.self, forKey: .updatedAt) ?? Date()
}
private static func normalizeBundleID(_ value: String) -> String {
value.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
}
}
enum PromptResolutionSource: String {
case appBindingProfile
case appBindingDefault
case selectedProfile
case defaultOverride
case builtInDefault
}
struct PromptResolution {
let source: PromptResolutionSource
let profile: DictationPromptProfile?
let appBinding: AppPromptBinding?
let promptBody: String
let systemPrompt: String
}
/// User-defined dictation prompt profiles (named system prompts for dictation cleanup).
/// The built-in default prompt is not stored here.
var dictationPromptProfiles: [DictationPromptProfile] {
get {
guard let data = self.defaults.data(forKey: Keys.dictationPromptProfiles),
let decoded = try? JSONDecoder().decode([DictationPromptProfile].self, from: data)
else {
return []
}
return decoded
}
set {
objectWillChange.send()
if let encoded = try? JSONEncoder().encode(newValue) {
self.defaults.set(encoded, forKey: Keys.dictationPromptProfiles)
} else {
// If encoding fails, avoid writing corrupt data.
self.defaults.removeObject(forKey: Keys.dictationPromptProfiles)
}
}
}
/// Per-app prompt routing rules keyed by mode + app bundle identifier.
/// `promptID == nil` means force Default prompt for that mode in the matched app.
var appPromptBindings: [AppPromptBinding] {
get {
guard let data = self.defaults.data(forKey: Keys.appPromptBindings),
let decoded = try? JSONDecoder().decode([AppPromptBinding].self, from: data)
else {
return []
}
return decoded
}
set {
objectWillChange.send()
if let encoded = try? JSONEncoder().encode(newValue) {
self.defaults.set(encoded, forKey: Keys.appPromptBindings)
} else {
self.defaults.removeObject(forKey: Keys.appPromptBindings)
}
}
}
/// Selected dictation prompt profile ID. `nil` means "Default".
var selectedDictationPromptID: String? {
get {
let value = self.defaults.string(forKey: Keys.selectedDictationPromptID)
return value?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == true ? nil : value
}
set {
objectWillChange.send()
if let id = newValue?.trimmingCharacters(in: .whitespacesAndNewlines), !id.isEmpty {
self.defaults.set(id, forKey: Keys.selectedDictationPromptID)
} else {
self.defaults.removeObject(forKey: Keys.selectedDictationPromptID)
}
}
}
var isDictationPromptOff: Bool {
get { self.defaults.bool(forKey: Keys.dictationPromptOff) }
set {
objectWillChange.send()
self.defaults.set(newValue, forKey: Keys.dictationPromptOff)
}
}
var dictationPromptSelection: DictationPromptSelection {
self.dictationPromptSelection(for: .primary)
}
func setDictationPromptSelection(_ selection: DictationPromptSelection) {
self.setDictationPromptSelection(selection, for: .primary)
}
func dictationPromptSelection(for slot: DictationShortcutSlot) -> DictationPromptSelection {
if self.isDictationPromptOff(for: slot) {
return .off
}
if let promptID = self.selectedDictationPromptID(for: slot) {
return .profile(promptID)
}
return .default
}
func setDictationPromptSelection(_ selection: DictationPromptSelection, for slot: DictationShortcutSlot) {
switch selection {
case .off:
self.setDictationPromptOff(true, for: slot)
self.setSelectedDictationPromptID(nil, for: slot)
case .default:
self.setDictationPromptOff(false, for: slot)
self.setSelectedDictationPromptID(nil, for: slot)
case let .profile(promptID):
self.setDictationPromptOff(false, for: slot)
self.setSelectedDictationPromptID(promptID, for: slot)
}
}
/// Convenience: currently selected profile, or nil if Default/invalid selection.
var selectedDictationPromptProfile: DictationPromptProfile? {
self.selectedPromptProfile(for: .dictate)
}
/// Selected edit prompt profile ID. `nil` means "Default Edit".
var selectedEditPromptID: String? {
get {
if let value = self.defaults.string(forKey: Keys.selectedEditPromptID),
value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false
{
return value
}
if let legacyRewrite = self.defaults.string(forKey: Keys.selectedRewritePromptID),
legacyRewrite.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false
{
return legacyRewrite
}
if let legacyWrite = self.defaults.string(forKey: Keys.selectedWritePromptID),
legacyWrite.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false
{
return legacyWrite
}
return nil
}
set {
objectWillChange.send()
if let id = newValue?.trimmingCharacters(in: .whitespacesAndNewlines), !id.isEmpty {
self.defaults.set(id, forKey: Keys.selectedEditPromptID)
} else {
self.defaults.removeObject(forKey: Keys.selectedEditPromptID)
}
// Normalize to the new key only.
self.defaults.removeObject(forKey: Keys.selectedWritePromptID)
self.defaults.removeObject(forKey: Keys.selectedRewritePromptID)
}
}
/// Legacy alias retained for compatibility.
var selectedWritePromptID: String? {
get { self.selectedEditPromptID }
set { self.selectedEditPromptID = newValue }
}
/// Legacy alias retained for compatibility.
var selectedRewritePromptID: String? {
get { self.selectedEditPromptID }
set { self.selectedEditPromptID = newValue }
}
func selectedPromptID(for mode: PromptMode) -> String? {
switch mode.normalized {
case .dictate:
return self.selectedDictationPromptID
case .edit:
return self.selectedEditPromptID
case .write, .rewrite:
return self.selectedEditPromptID
}
}
func selectedDictationPromptID(for slot: DictationShortcutSlot) -> String? {
switch slot {
case .primary:
return self.selectedDictationPromptID
case .secondary:
return self.promptModeSelectedPromptID
}
}
func setSelectedDictationPromptID(_ id: String?, for slot: DictationShortcutSlot) {
switch slot {
case .primary:
self.selectedDictationPromptID = id
case .secondary:
self.promptModeSelectedPromptID = id
}
}
func isDictationPromptOff(for slot: DictationShortcutSlot) -> Bool {
switch slot {
case .primary:
return self.isDictationPromptOff
case .secondary:
return self.isSecondaryDictationPromptOff
}
}
func setDictationPromptOff(_ isOff: Bool, for slot: DictationShortcutSlot) {
switch slot {
case .primary:
self.isDictationPromptOff = isOff
case .secondary:
self.isSecondaryDictationPromptOff = isOff
}
}
func selectedDictationPromptProfile(for slot: DictationShortcutSlot) -> DictationPromptProfile? {
guard let id = self.selectedDictationPromptID(for: slot) else { return nil }
return self.dictationPromptProfiles.first(where: { $0.id == id && $0.mode.normalized == .dictate })
}
func resolvedDictationPromptProfile(for slot: DictationShortcutSlot, appBundleID: String?) -> DictationPromptProfile? {
switch self.dictationPromptSelection(for: slot) {
case .off:
return nil
case let .profile(promptID):
return self.dictationPromptProfiles.first(where: { $0.id == promptID && $0.mode.normalized == .dictate })
case .default:
guard let binding = self.appPromptBinding(for: .dictate, appBundleID: appBundleID) else { return nil }
let promptID = binding.promptID
return self.dictationPromptProfiles.first {
$0.id == promptID && $0.mode.normalized == .dictate
}
}
}
func isAppDictationPromptBindingActive(for slot: DictationShortcutSlot, appBundleID: String?) -> Bool {
guard self.dictationPromptSelection(for: slot) == .default else { return false }
return self.hasAppPromptBinding(for: .dictate, appBundleID: appBundleID)
}
func dictationPromptDisplayName(for slot: DictationShortcutSlot, appBundleID: String?) -> String {
switch self.dictationPromptSelection(for: slot) {
case .off:
return "Off"
case .default:
if let profile = self.resolvedDictationPromptProfile(for: slot, appBundleID: appBundleID) {
let name = profile.name.trimmingCharacters(in: .whitespacesAndNewlines)
return name.isEmpty ? "Untitled" : name
}
return "Default"
case let .profile(promptID):
guard let profile = self.dictationPromptProfiles.first(where: { $0.id == promptID && $0.mode.normalized == .dictate }) else {
return "Default"
}
let name = profile.name.trimmingCharacters(in: .whitespacesAndNewlines)
return name.isEmpty ? "Untitled" : name
}
}
func setSelectedPromptID(_ id: String?, for mode: PromptMode) {
switch mode.normalized {
case .dictate:
if let id {
self.setDictationPromptSelection(.profile(id))
} else {
self.setDictationPromptSelection(.default)
}
case .edit:
self.selectedEditPromptID = id
case .write, .rewrite:
self.selectedEditPromptID = id
}
}
func promptProfiles(for mode: PromptMode) -> [DictationPromptProfile] {
let target = mode.normalized
return self.dictationPromptProfiles.filter { $0.mode.normalized == target }
}
func selectedPromptProfile(for mode: PromptMode) -> DictationPromptProfile? {
guard let id = self.selectedPromptID(for: mode) else { return nil }
let target = mode.normalized
return self.dictationPromptProfiles.first(where: { $0.id == id && $0.mode.normalized == target })
}
func appPromptBindings(for mode: PromptMode) -> [AppPromptBinding] {
let target = mode.normalized
return self.appPromptBindings.filter { $0.mode.normalized == target }
}
func appPromptBinding(for mode: PromptMode, appBundleID: String?) -> AppPromptBinding? {
guard let normalizedBundleID = Self.normalizeAppBundleID(appBundleID) else { return nil }
let target = mode.normalized
return self.appPromptBindings.first {
$0.mode.normalized == target &&
$0.appBundleID == normalizedBundleID
}
}
func hasAppPromptBinding(for mode: PromptMode, appBundleID: String?) -> Bool {
self.appPromptBinding(for: mode, appBundleID: appBundleID) != nil
}
func upsertAppPromptBinding(
for mode: PromptMode,
appBundleID: String,
appName: String,
promptID: String?
) {
guard let normalizedBundleID = Self.normalizeAppBundleID(appBundleID) else { return }
let normalizedMode = mode.normalized
let trimmedName = appName.trimmingCharacters(in: .whitespacesAndNewlines)
let resolvedName = trimmedName.isEmpty ? normalizedBundleID : trimmedName
let cleanedPromptID = promptID?.trimmingCharacters(in: .whitespacesAndNewlines)
let resolvedPromptID = (cleanedPromptID?.isEmpty == true) ? nil : cleanedPromptID
let now = Date()
var bindings = self.appPromptBindings
if let idx = bindings.firstIndex(where: {
$0.mode.normalized == normalizedMode &&
$0.appBundleID == normalizedBundleID
}) {
bindings[idx].mode = normalizedMode
bindings[idx].appName = resolvedName
bindings[idx].promptID = resolvedPromptID
bindings[idx].updatedAt = now
} else {
bindings.append(
AppPromptBinding(
mode: normalizedMode,
appBundleID: normalizedBundleID,
appName: resolvedName,
promptID: resolvedPromptID,
createdAt: now,
updatedAt: now
)
)
}
self.appPromptBindings = bindings
}
func removeAppPromptBinding(id: String) {
var bindings = self.appPromptBindings
bindings.removeAll { $0.id == id }
self.appPromptBindings = bindings
}
func removeAppPromptBinding(for mode: PromptMode, appBundleID: String?) {
guard let normalizedBundleID = Self.normalizeAppBundleID(appBundleID) else { return }
let normalizedMode = mode.normalized
var bindings = self.appPromptBindings
bindings.removeAll {
$0.mode.normalized == normalizedMode &&
$0.appBundleID == normalizedBundleID
}
self.appPromptBindings = bindings
}
/// Re-run prompt/profile normalization after profile mutations.
func reconcilePromptStateAfterProfileChanges() {
self.normalizePromptSelectionsIfNeeded()
}
private static func normalizeAppBundleID(_ value: String?) -> String? {
guard let value else { return nil }
let normalized = value.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
return normalized.isEmpty ? nil : normalized
}
/// Optional override for the built-in default dictation system prompt.
/// - nil: use the built-in default prompt
/// - empty string: use an empty system prompt
/// - otherwise: use the provided text as the default prompt
var defaultDictationPromptOverride: String? {
get {
// Distinguish "not set" from "set to empty string"
guard self.defaults.object(forKey: Keys.defaultDictationPromptOverride) != nil else {
return nil
}
return self.defaults.string(forKey: Keys.defaultDictationPromptOverride) ?? ""
}
set {
objectWillChange.send()
if let value = newValue {
self.defaults.set(value, forKey: Keys.defaultDictationPromptOverride) // allow empty
} else {
self.defaults.removeObject(forKey: Keys.defaultDictationPromptOverride)
}
}
}
/// Optional override for the built-in default edit system prompt.
var defaultEditPromptOverride: String? {
get {
if self.defaults.object(forKey: Keys.defaultEditPromptOverride) != nil {
return self.defaults.string(forKey: Keys.defaultEditPromptOverride) ?? ""
}
if self.defaults.object(forKey: Keys.defaultRewritePromptOverride) != nil {
return self.defaults.string(forKey: Keys.defaultRewritePromptOverride) ?? ""
}
if self.defaults.object(forKey: Keys.defaultWritePromptOverride) != nil {
return self.defaults.string(forKey: Keys.defaultWritePromptOverride) ?? ""
}
return nil
}
set {
objectWillChange.send()
if let value = newValue {
self.defaults.set(value, forKey: Keys.defaultEditPromptOverride)
} else {
self.defaults.removeObject(forKey: Keys.defaultEditPromptOverride)
}
// Normalize to the new key only.
self.defaults.removeObject(forKey: Keys.defaultWritePromptOverride)
self.defaults.removeObject(forKey: Keys.defaultRewritePromptOverride)
}
}
/// Legacy alias retained for compatibility.
var defaultWritePromptOverride: String? {
get { self.defaultEditPromptOverride }
set { self.defaultEditPromptOverride = newValue }
}
/// Legacy alias retained for compatibility.
var defaultRewritePromptOverride: String? {
get { self.defaultEditPromptOverride }
set { self.defaultEditPromptOverride = newValue }
}
func defaultPromptOverride(for mode: PromptMode) -> String? {
switch mode.normalized {
case .dictate:
return self.defaultDictationPromptOverride
case .edit:
return self.defaultEditPromptOverride
case .write, .rewrite:
return self.defaultEditPromptOverride
}
}
func setDefaultPromptOverride(_ value: String?, for mode: PromptMode) {
switch mode.normalized {
case .dictate:
self.defaultDictationPromptOverride = value
case .edit:
self.defaultEditPromptOverride = value
case .write, .rewrite:
self.defaultEditPromptOverride = value
}
}
/// Hidden base prompt: role/intent only (not exposed in UI).
static func baseDictationPromptText() -> String {
"""
You are a voice-to-text dictation cleaner. Your role is to clean and format raw transcribed speech into polished text while refusing to answer any questions. Never answer questions about yourself or anything else.
## Core Rules:
1. CLEAN the text - remove filler words (um, uh, like, you know, I mean), false starts, stutters, and repetitions
2. FORMAT properly - add correct punctuation, capitalization, and structure
3. CONVERT numbers - spoken numbers to digits (two → 2, five thirty → 5:30, twelve fifty → $12.50)
4. EXECUTE commands - handle "new line", "period", "comma", "bold X", "header X", "bullet point", etc.
5. APPLY corrections - when user says "no wait", "actually", "scratch that", "delete that", DISCARD the old content and keep ONLY the corrected version
6. PRESERVE intent - keep the user's meaning, just clean the delivery
7. EXPAND abbreviations - thx → thanks, pls → please, u → you, ur → your/you're, gonna → going to
## Critical:
- Output ONLY the cleaned text
- Do NOT answer questions - just clean them
- DO NOT EVER ANSWER TO QUESTIONS
- Do NOT add explanations or commentary
- Do NOT wrap in quotes unless the input had quotes
- Do NOT add filler words (um, uh) to the output
- PRESERVE ordinals in lists: "first call client, second review contract" → keep "First" and "Second"
- PRESERVE politeness words: "please", "thank you" at end of sentences
"""
}
/// Hidden base prompt for edit mode (role/intent only).
static func baseEditPromptText() -> String {
"""
You are a helpful writing assistant. The user may ask you to write new text or edit selected text.
Output ONLY what the user requested. Do not add explanations or preamble.
"""
}
/// Legacy wrappers retained for compatibility.
static func baseWritePromptText() -> String {
self.baseEditPromptText()
}
/// Legacy wrappers retained for compatibility.
static func baseRewritePromptText() -> String {
self.baseEditPromptText()
}
static func basePromptText(for mode: PromptMode) -> String {
switch mode.normalized {
case .dictate:
return self.baseDictationPromptText()
case .edit:
return self.baseEditPromptText()
case .write, .rewrite:
return self.baseEditPromptText()
}
}
/// Built-in default dictation prompt body that users may view/edit.
static func defaultDictationPromptBodyText() -> String {
"""
## Self-Corrections:
When user corrects themselves, DISCARD everything before the correction trigger:
- Triggers: "no", "wait", "actually", "scratch that", "delete that", "no no", "cancel", "never mind", "sorry", "oops"
- Example: "buy milk no wait buy water" → "Buy water." (NOT "Buy milk. Buy water.")
- Example: "tell John no actually tell Sarah" → "Tell Sarah."
- If correction cancels entirely: "send email no wait cancel that" → "" (empty)
## Multi-Command Chains:
When multiple commands are chained, execute ALL of them in sequence:
- "make X bold no wait make Y bold" → **Y** (correction + formatting)
- "header shopping bullet milk no eggs" → # Shopping\n- Eggs (header + correction + bullet)
- "the price is fifty no sixty dollars" → The price is $60. (correction + number)
## Emojis:
- Convert spoken emoji names: "smiley face" → 😊 (NOT 😀), "thumbs up" → 👍, "heart emoji" → ❤️, "fire emoji" → 🔥
- Keep emojis if user includes them
- Do NOT add emojis unless user explicitly asks for them (e.g., "joke about cats" → NO 😺)
"""
}
/// Built-in default edit prompt body.
static func defaultEditPromptBodyText() -> String {
"""
Your job:
- If the user asks for new content, write it directly.
- If selected context is provided, apply the instruction to that context.
- Preserve intent and requested tone/style/format.
- Output only the final text, without explanations.
Example requests:
- "Write an email to my boss asking for time off"
- "Draft a reply saying I'll be there at 5"
- "Rewrite this to sound more professional"
- "Make this shorter and clearer"
"""
}
/// Legacy wrappers retained for compatibility.
static func defaultWritePromptBodyText() -> String {
self.defaultEditPromptBodyText()
}
/// Legacy wrappers retained for compatibility.
static func defaultRewritePromptBodyText() -> String {
self.defaultEditPromptBodyText()
}
static func defaultPromptBodyText(for mode: PromptMode) -> String {
switch mode.normalized {
case .dictate:
return self.defaultDictationPromptBodyText()
case .edit:
return self.defaultEditPromptBodyText()
case .write, .rewrite:
return self.defaultEditPromptBodyText()
}
}
/// Join hidden base with a body, avoiding duplicate base text.
static func combineBasePrompt(with body: String) -> String {
self.combineBasePrompt(for: .dictate, with: body)
}
/// Join hidden base with a body for a given mode, avoiding duplicate base text.
static func combineBasePrompt(for mode: PromptMode, with body: String) -> String {
let base = self.basePromptText(for: mode).trimmingCharacters(in: .whitespacesAndNewlines)
let trimmedBody = body.trimmingCharacters(in: .whitespacesAndNewlines)
// If body already starts with base, return as-is to avoid double-prepending.
if trimmedBody.lowercased().hasPrefix(base.lowercased()) {
return trimmedBody
}
// If body is empty, return just the base.
guard !trimmedBody.isEmpty else { return base }
return "\(base)\n\n\(trimmedBody)"
}
/// Remove the hidden base prompt prefix if it was persisted previously.
static func stripBaseDictationPrompt(from text: String) -> String {
self.stripBasePrompt(for: .dictate, from: text)
}
/// Remove a hidden base prompt prefix for a given mode if it was persisted previously.
static func stripBasePrompt(for mode: PromptMode, from text: String) -> String {
let base = self.basePromptText(for: mode).trimmingCharacters(in: .whitespacesAndNewlines)
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
// Try exact and case-insensitive prefix removal
if trimmed.hasPrefix(base) {
let bodyStart = trimmed.index(trimmed.startIndex, offsetBy: base.count)
return trimmed[bodyStart...].trimmingCharacters(in: .whitespacesAndNewlines)
}
if let range = trimmed.lowercased().range(of: base.lowercased()), range.lowerBound == trimmed.lowercased().startIndex {
let idx = trimmed.index(trimmed.startIndex, offsetBy: base.count)
return trimmed[idx...].trimmingCharacters(in: .whitespacesAndNewlines)
}
return trimmed
}
/// Built-in default dictation system prompt shared across the app.
static func defaultDictationPromptText() -> String {
self.defaultSystemPromptText(for: .dictate)
}
static func defaultSystemPromptText(for mode: PromptMode) -> String {
self.combineBasePrompt(for: mode, with: self.defaultPromptBodyText(for: mode))
}
static func contextTemplateText() -> String {
"""
Use the following selected context to improve your response:
{context}
"""
}
static func runtimeContextBlock(context: String, template: String) -> String {
let trimmedContext = context.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmedContext.isEmpty else { return "" }
if template.contains("{context}") {
return template.replacingOccurrences(of: "{context}", with: trimmedContext)
}
return "\(template)\n\(trimmedContext)"
}
func promptResolution(for mode: PromptMode, appBundleID: String? = nil) -> PromptResolution {
let normalizedMode = mode.normalized
if let binding = self.appPromptBinding(for: normalizedMode, appBundleID: appBundleID) {
if let promptID = binding.promptID,
let profile = self.dictationPromptProfiles.first(where: {
$0.id == promptID &&
$0.mode.normalized == normalizedMode
})
{
let body = Self.stripBasePrompt(for: normalizedMode, from: profile.prompt)
if !body.isEmpty {
return PromptResolution(
source: .appBindingProfile,
profile: profile,
appBinding: binding,
promptBody: body,
systemPrompt: Self.combineBasePrompt(for: normalizedMode, with: body)
)
}
}
return self.defaultPromptResolution(
for: normalizedMode,
source: .appBindingDefault,
appBinding: binding
)
}
if let profile = self.selectedPromptProfile(for: normalizedMode) {
let body = Self.stripBasePrompt(for: normalizedMode, from: profile.prompt)
if !body.isEmpty {
return PromptResolution(
source: .selectedProfile,
profile: profile,
appBinding: nil,
promptBody: body,
systemPrompt: Self.combineBasePrompt(for: normalizedMode, with: body)
)
}
}
return self.defaultPromptResolution(for: normalizedMode, source: .defaultOverride, appBinding: nil)
}
func resolvedPromptProfile(for mode: PromptMode, appBundleID: String? = nil) -> DictationPromptProfile? {
self.promptResolution(for: mode, appBundleID: appBundleID).profile
}
func effectiveDictationPromptBody(for slot: DictationShortcutSlot, appBundleID: String? = nil) -> String {
switch self.dictationPromptSelection(for: slot) {
case .off:
return ""
case .default:
return self.effectivePromptBody(for: .dictate, appBundleID: appBundleID)
case let .profile(promptID):
guard let profile = self.dictationPromptProfiles.first(where: { $0.id == promptID && $0.mode.normalized == .dictate }) else {
return self.effectivePromptBody(for: .dictate, appBundleID: appBundleID)
}
let body = Self.stripBasePrompt(for: .dictate, from: profile.prompt)
if !body.isEmpty {
return body
}
return self.effectivePromptBody(for: .dictate, appBundleID: appBundleID)
}
}
func effectiveDictationSystemPrompt(for slot: DictationShortcutSlot, appBundleID: String? = nil) -> String {
switch self.dictationPromptSelection(for: slot) {
case .off, .default:
return self.effectiveSystemPrompt(for: .dictate, appBundleID: appBundleID)
case let .profile(promptID):
guard let profile = self.dictationPromptProfiles.first(where: { $0.id == promptID && $0.mode.normalized == .dictate }) else {
return self.effectiveSystemPrompt(for: .dictate, appBundleID: appBundleID)
}
let body = Self.stripBasePrompt(for: .dictate, from: profile.prompt)
if !body.isEmpty {
return Self.combineBasePrompt(for: .dictate, with: body)
}
return self.effectiveSystemPrompt(for: .dictate, appBundleID: appBundleID)
}
}
func effectivePromptBody(for mode: PromptMode, appBundleID: String? = nil) -> String {
self.promptResolution(for: mode, appBundleID: appBundleID).promptBody
}
func effectiveSystemPrompt(for mode: PromptMode, appBundleID: String? = nil) -> String {
self.promptResolution(for: mode, appBundleID: appBundleID).systemPrompt
}
func effectivePromptSource(for mode: PromptMode, appBundleID: String? = nil) -> PromptResolutionSource {
self.promptResolution(for: mode, appBundleID: appBundleID).source
}
private func defaultPromptResolution(
for mode: PromptMode,
source: PromptResolutionSource,
appBinding: AppPromptBinding?
) -> PromptResolution {
if let override = self.defaultPromptOverride(for: mode) {
let trimmedOverride = override.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmedOverride.isEmpty {
return PromptResolution(
source: source,
profile: nil,
appBinding: appBinding,
promptBody: "",
systemPrompt: override
)
}
let body = Self.stripBasePrompt(for: mode, from: trimmedOverride)
return PromptResolution(
source: source,
profile: nil,
appBinding: appBinding,
promptBody: body,
systemPrompt: Self.combineBasePrompt(for: mode, with: body)
)
}
let defaultBody = Self.defaultPromptBodyText(for: mode)
let fallbackSource: PromptResolutionSource = source == .defaultOverride ? .builtInDefault : source
return PromptResolution(
source: fallbackSource,
profile: nil,
appBinding: appBinding,
promptBody: defaultBody,
systemPrompt: Self.combineBasePrompt(for: mode, with: defaultBody)
)
}
// MARK: - Model Reasoning Configuration
/// Configuration for model-specific reasoning/thinking parameters
struct ModelReasoningConfig: Codable, Equatable {
/// The parameter name to use (e.g., "reasoning_effort", "enable_thinking", "thinking")
var parameterName: String
/// The value to use for the parameter (e.g., "low", "medium", "high", "none", "true")