forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemoryExportDestinationSheet.swift
More file actions
1345 lines (1212 loc) · 47 KB
/
Copy pathMemoryExportDestinationSheet.swift
File metadata and controls
1345 lines (1212 loc) · 47 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 Combine
import OmiTheme
import SwiftUI
struct MemoryExportCatalogEntry: Identifiable {
let destination: MemoryExportDestination
let title: String?
let subtitle: String?
let description: String?
var id: String { destination.id }
var resolvedTitle: String { title ?? destination.title }
var resolvedSubtitle: String { subtitle ?? destination.subtitle }
var resolvedDescription: String { description ?? destination.description }
}
enum MemoryExportCatalog {
static let entries: [MemoryExportCatalogEntry] =
MemoryExportDestination.allCases.compactMap { destination in
switch destination {
case .claudeCode, .codex:
return nil
case .claude:
return MemoryExportCatalogEntry(
destination: .claude,
title: "Claude / Claude Code",
subtitle: nil,
description: "Claude Code (CLI) or Claude cloud — choose in setup."
)
case .chatgpt:
return MemoryExportCatalogEntry(
destination: .chatgpt,
title: "ChatGPT / Codex",
subtitle: "ChatGPT app or Codex CLI",
description: "Add Omi in ChatGPT or connect Codex locally — choose in setup."
)
default:
return MemoryExportCatalogEntry(
destination: destination, title: nil, subtitle: nil, description: nil)
}
}
static func matching(_ searchText: String) -> [MemoryExportCatalogEntry] {
let query = searchText.trimmingCharacters(in: .whitespacesAndNewlines)
guard !query.isEmpty else { return entries }
return
entries
.filter { entry in
[entry.resolvedTitle, entry.resolvedSubtitle, entry.resolvedDescription]
.contains { $0.localizedCaseInsensitiveContains(query) }
}
.sorted { matchRank($0, query: query) < matchRank($1, query: query) }
}
private static func matchRank(_ entry: MemoryExportCatalogEntry, query: String) -> Int {
if entry.resolvedTitle.localizedCaseInsensitiveCompare(query) == .orderedSame { return 0 }
if entry.resolvedTitle.range(
of: query, options: [.anchored, .caseInsensitive, .diacriticInsensitive]) != nil
{
return 1
}
return 2
}
}
struct ExportsSection: View {
let statuses: [MemoryExportDestination: MemoryExportStatus]
var searchText = ""
var title = "Exports"
var entriesOverride: [MemoryExportCatalogEntry]? = nil
let onSelectDestination: (MemoryExportDestination) -> Void
private var entries: [MemoryExportCatalogEntry] {
entriesOverride ?? MemoryExportCatalog.matching(searchText)
}
private func status(for destination: MemoryExportDestination) -> MemoryExportStatus {
let fallback = MemoryExportStatus(
exportedCount: 0,
lastExportedAt: nil,
detailText: nil,
isConfigured: false,
hasConnection: false)
switch destination {
case .claude:
return aggregateStatus(for: [.claude, .claudeCode], fallback: fallback)
case .chatgpt:
return aggregateStatus(for: [.chatgpt, .codex], fallback: fallback)
default:
return statuses[destination] ?? fallback
}
}
private func aggregateStatus(
for destinations: [MemoryExportDestination],
fallback: MemoryExportStatus
) -> MemoryExportStatus {
let values = destinations.map { statuses[$0] ?? fallback }
return MemoryExportStatus(
exportedCount: values.map(\.exportedCount).max() ?? 0,
lastExportedAt: values.compactMap(\.lastExportedAt).max(),
detailText: values.compactMap(\.detailText).first,
isConfigured: values.contains(where: \.hasConnection),
hasConnection: values.contains(where: \.hasConnection)
)
}
var body: some View {
VStack(alignment: .leading, spacing: OmiSpacing.md) {
Text(title)
.scaledFont(size: OmiType.subheading, weight: .semibold)
.foregroundColor(Ink.primary)
if entries.isEmpty {
Text("No exports match “\(searchText.trimmingCharacters(in: .whitespacesAndNewlines))”.")
.scaledFont(size: OmiType.body)
.foregroundStyle(Ink.secondary)
.padding(.vertical, OmiSpacing.md)
} else {
LazyVGrid(
columns: [GridItem(.adaptive(minimum: 260), spacing: OmiSpacing.md)],
alignment: .leading,
spacing: OmiSpacing.md
) {
ForEach(entries) { entry in
MemoryExportRow(
destination: entry.destination,
titleOverride: entry.title,
subtitleOverride: entry.subtitle,
descriptionOverride: entry.description,
status: status(for: entry.destination)
) {
onSelectDestination(entry.destination)
}
}
}
}
}
}
}
private struct MemoryExportRow: View {
let destination: MemoryExportDestination
var titleOverride: String? = nil
var subtitleOverride: String? = nil
var descriptionOverride: String? = nil
let status: MemoryExportStatus
let action: () -> Void
@State private var isHovering = false
private var actionTitle: String {
if destination.supportsAgentSetup {
return showsConnectedState ? "Connected" : "Connect"
}
if destination.supportsMCP {
return showsConnectedState ? "Connected" : "Connect"
}
switch destination {
case .obsidian:
return status.isConfigured ? "Sync" : "Connect"
case .notion, .chatgpt, .claude, .gemini, .agents, .claudeCode, .codex, .openclaw, .hermes:
return status.hasConnection ? "Open" : "Connect"
}
}
private var showsConnectedState: Bool {
guard destination.supportsMCP || destination.supportsAgentSetup else { return false }
return status.hasConnection
}
private var statusPrimaryText: String {
if status.exportedCount > 0 {
return "\(status.exportedCount.formatted()) memories exported"
}
return status.hasConnection ? "Connected" : "Not connected"
}
private var statusSecondaryText: String? {
if let lastExportedAt = status.lastExportedAt {
let relative = RelativeDateTimeFormatter().localizedString(for: lastExportedAt, relativeTo: Date())
return "Exported \(relative)"
}
return status.detailText
}
// Mirrors ImportConnectorCard so the Imports and Exports grids read as one
// system: identical icon block, description slot, and status/action footer.
var body: some View {
Button(action: action) {
VStack(alignment: .leading, spacing: OmiSpacing.sm) {
HStack(spacing: OmiSpacing.md) {
ConnectorBrandIcon(
brand: destination.brand, size: 50, cornerRadius: OmiChrome.smallControlRadius)
VStack(alignment: .leading, spacing: OmiSpacing.xxs) {
Text(titleOverride ?? destination.title)
.scaledFont(size: OmiType.body, weight: .medium)
.foregroundColor(Ink.primary)
.lineLimit(1)
Text(subtitleOverride ?? destination.subtitle)
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
.lineLimit(1)
}
Spacer()
}
Text(descriptionOverride ?? destination.description)
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
.lineLimit(2)
.multilineTextAlignment(.leading)
HStack {
VStack(alignment: .leading, spacing: OmiSpacing.hairline) {
Text(statusPrimaryText)
.scaledFont(size: OmiType.caption, weight: .medium)
.foregroundColor(
status.hasConnection || status.exportedCount > 0
? Ink.primary : Ink.secondary)
if let statusSecondaryText {
Text(statusSecondaryText)
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
.lineLimit(1)
}
}
Spacer()
ImportConnectorActionButton(
title: actionTitle, isConnected: showsConnectedState)
}
}
.padding(OmiSpacing.md)
.background(isHovering ? Ink.rowFillHover : Ink.rowFill)
.cornerRadius(OmiChrome.smallControlRadius)
.overlay(
RoundedRectangle(cornerRadius: OmiChrome.smallControlRadius)
.stroke(Ink.rowFillHover, lineWidth: 1)
)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.onHover { isHovering = $0 }
}
}
@MainActor
struct MemoryExportWorkspace {
var installedApplicationURL: (ConnectorBrand) -> URL?
var defaultApplicationURL: (URL) -> URL?
var openWithApplication: ([URL], URL, NSWorkspace.OpenConfiguration, @escaping @Sendable (Error?) -> Void) -> Void
var open: (URL) -> Void
static let live = Self(
installedApplicationURL: { $0.installedApplicationURL },
defaultApplicationURL: { NSWorkspace.shared.urlForApplication(toOpen: $0) },
openWithApplication: { urls, applicationURL, configuration, completion in
NSWorkspace.shared.open(urls, withApplicationAt: applicationURL, configuration: configuration) { _, error in
completion(error)
}
},
open: { NSWorkspace.shared.open($0) })
}
@MainActor
final class MemoryExportDestinationSheetModel: ObservableObject {
private let workspace: MemoryExportWorkspace
@Published var isRunning = false
@Published var statusMessage: String?
@Published var errorMessage: String?
@Published var notionToken = ""
@Published var notionParentPageID = ""
@Published var obsidianVaultPath = ""
@Published var mcpKey: String?
@Published var isLoadingMCPKey = false
@Published var isTestingAgentConnection = false
init(workspace: MemoryExportWorkspace = .live) {
self.workspace = workspace
}
func loadConfiguration() async {
obsidianVaultPath = await MemoryExportService.shared.obsidianVaultPath()
mcpKey = await MemoryExportService.shared.storedMCPKey()
}
func generateMCPKey() async {
errorMessage = nil
isLoadingMCPKey = true
defer { isLoadingMCPKey = false }
do {
mcpKey = try await MemoryExportService.shared.ensureMCPKey()
} catch {
errorMessage = "Couldn't create an MCP key: \(error.localizedDescription)"
}
}
func createNewAgentConnectionKey() async {
errorMessage = nil
statusMessage = nil
isLoadingMCPKey = true
defer { isLoadingMCPKey = false }
do {
let key = try await MemoryExportService.shared.createNewMCPKey()
_ = try LocalAgentAPISettings.createNewToken()
mcpKey = key
statusMessage = "New key created. Copy the prompt again when you're ready."
} catch {
errorMessage = "Couldn't create a new connection key: \(error.localizedDescription)"
}
}
func testAgentConnection() async {
errorMessage = nil
statusMessage = nil
isTestingAgentConnection = true
defer { isTestingAgentConnection = false }
do {
let key = try await MemoryExportService.shared.ensureMCPKey()
let localToken = try LocalAgentAPISettings.enable()
mcpKey = key
let result = try await MemoryExportService.shared.testAgentConnections(
hostedKey: key,
localToken: localToken)
statusMessage = result.summary
} catch {
errorMessage = "Omi couldn't test the connection: \(error.localizedDescription)"
}
}
func copyToPasteboard(_ text: String, label: String) {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(text, forType: .string)
statusMessage = "\(label) copied."
}
func copyAgentSetupPrompt() async -> MemoryExportStatus? {
errorMessage = nil
statusMessage = nil
isLoadingMCPKey = true
defer { isLoadingMCPKey = false }
do {
let key = try await MemoryExportService.shared.ensureMCPKey()
let localToken = try LocalAgentAPISettings.enable()
mcpKey = key
copyToPasteboard(
MemoryExportService.omiAgentSetupPrompt(
hostedKey: key,
localURL: LocalAgentAPISettings.serverURL,
localToken: localToken),
label: "Agent prompt")
statusMessage =
"Prompt copied. Only share it with an agent you trust; it includes Omi access keys."
return await MemoryExportService.shared.status(for: .agents)
} catch {
errorMessage = "Couldn't create the prompt: \(error.localizedDescription)"
return nil
}
}
func open(_ url: URL) {
NSWorkspace.shared.open(url)
}
@Published var isExecuting = false
/// Hand the whole setup to Omi: create a task and run it through the standard
/// execute flow (TasksStore.createTask + AgentPillsManager.spawn) — the same path
/// the floating-bar "Execute" button uses. No new execution flow.
func executeWithOmi(destination: MemoryExportDestination) async {
errorMessage = nil
isExecuting = true
defer { isExecuting = false }
do {
let outcome = try await MemoryExportExecutor.run(destination)
mcpKey = await MemoryExportService.shared.storedMCPKey()
switch outcome.mode {
case .autonomous:
statusMessage = "Omi is setting this up — follow along in the floating bar."
case .assisted:
statusMessage = outcome.taskTitle
case .completed:
// Deterministic local write — show the result directly.
statusMessage = outcome.taskTitle
}
} catch {
errorMessage = error.localizedDescription
}
}
func run(destination: MemoryExportDestination) async -> MemoryExportStatus? {
errorMessage = nil
statusMessage = nil
isRunning = true
defer { isRunning = false }
do {
switch destination {
case .notion:
if !NotionMCPConnector.shared.isConnected {
statusMessage = "Approve Omi in your browser…"
try await NotionMCPConnector.shared.connect()
}
let result = try await MemoryExportService.shared.exportToNotion()
await MainActor.run {
openDestination(for: destination, url: result.destinationURL)
}
statusMessage = "Wrote \(result.memoryCount.formatted()) memories into Notion."
case .obsidian:
let vaultURL: URL
if obsidianVaultPath.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
guard let pickedURL = selectObsidianVault() else {
return nil
}
obsidianVaultPath = pickedURL.path
vaultURL = pickedURL
} else {
vaultURL = URL(fileURLWithPath: obsidianVaultPath)
}
let result = try await MemoryExportService.shared.exportToObsidian(vaultURL: vaultURL)
await MainActor.run {
revealExportFile(from: result)
openDestination(for: destination, url: result.destinationURL)
}
statusMessage = "Wrote \(result.memoryCount.formatted()) memories into Obsidian."
case .chatgpt, .claude, .gemini:
let result = try await MemoryExportService.shared.prepareManualExport(for: destination)
await MainActor.run {
applyClipboard(from: result)
revealExportFile(from: result)
openDestination(for: destination, url: result.destinationURL)
}
statusMessage = "Memory pack ready for \(destination.title). Prompt and export copied."
case .agents, .claudeCode, .codex, .openclaw, .hermes:
// MCP-only destinations have no memory-pack run step.
return nil
}
return await MemoryExportService.shared.status(for: destination)
} catch {
errorMessage = error.localizedDescription
return nil
}
}
func pickObsidianVault() {
if let selectedURL = selectObsidianVault() {
obsidianVaultPath = selectedURL.path
}
}
private func selectObsidianVault() -> URL? {
let panel = NSOpenPanel()
panel.message = "Select your Obsidian vault."
panel.prompt = "Open"
panel.canChooseFiles = false
panel.canChooseDirectories = true
panel.allowsMultipleSelection = false
return panel.runModal() == .OK ? panel.url : nil
}
private func applyClipboard(from result: MemoryExportResult) {
guard let clipboardText = result.clipboardText, !clipboardText.isEmpty else { return }
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(clipboardText, forType: .string)
}
private func revealExportFile(from result: MemoryExportResult) {
guard let fileURL = result.fileURL else { return }
NSWorkspace.shared.activateFileViewerSelecting([fileURL])
}
func openDestination(for destination: MemoryExportDestination, url: URL?) {
guard let url else { return }
if let appURL = workspace.installedApplicationURL(destination.brand) {
let configuration = NSWorkspace.OpenConfiguration()
configuration.activates = true
workspace.openWithApplication([url], appURL, configuration) { [self] error in
if let error {
log(
"MemoryExportDestinationSheetModel: Failed opening \(destination.title) with installed app: \(error.localizedDescription)"
)
Self.performOnMainActor { [self] in
self.openInDefaultHandler(url)
}
}
}
return
}
openInDefaultHandler(url)
}
func openInDefaultHandler(_ url: URL) {
let configuration = NSWorkspace.OpenConfiguration()
configuration.activates = true
if let appURL = workspace.defaultApplicationURL(url) {
workspace.openWithApplication([url], appURL, configuration) { [workspace] error in
if let error {
log(
"MemoryExportDestinationSheetModel: Failed opening \(url.absoluteString): \(error.localizedDescription)"
)
Self.performOnMainActor {
workspace.open(url)
}
}
}
return
}
workspace.open(url)
}
nonisolated static func performOnMainActor(_ operation: @escaping @MainActor @Sendable () -> Void) {
Task { @MainActor in
operation()
}
}
}
struct MemoryExportDestinationSheet: View {
let destination: MemoryExportDestination
@Binding var statuses: [MemoryExportDestination: MemoryExportStatus]
let onDismiss: () -> Void
@StateObject private var model = MemoryExportDestinationSheetModel()
@State private var showManualSetup = false
@State private var permissionRefreshID = 0
@State private var isDisconnecting = false
private let permissionRefreshTimer = Timer.publish(every: 1.0, on: .main, in: .common)
.autoconnect()
var body: some View {
VStack(alignment: .leading, spacing: OmiSpacing.lg) {
HStack(alignment: .top, spacing: OmiSpacing.md) {
ConnectorBrandIcon(brand: destination.brand, size: 56, cornerRadius: OmiChrome.controlRadius)
VStack(alignment: .leading, spacing: OmiSpacing.xxs) {
Text(destination.title)
.scaledFont(size: OmiType.heading, weight: .semibold)
.foregroundColor(Ink.primary)
Text(destination.subtitle)
.scaledFont(size: OmiType.body)
.foregroundColor(Ink.secondary)
Text(destination.description)
.scaledFont(size: OmiType.body)
.foregroundColor(Ink.secondary)
.padding(.top, OmiSpacing.xxs)
}
Spacer()
DismissButton(action: onDismiss)
}
// Scrollable so the full connector flow (Execute + live-connection steps +
// memory pack) never clips inside the fixed-height sheet.
ScrollView {
VStack(alignment: .leading, spacing: OmiSpacing.lg) {
if let entry = IntegrationNudgeCatalog.exportEntry(destinationID: destination.rawValue) {
IntegrationValueSection(entry: entry)
}
content
if let statusMessage = model.statusMessage {
Text(statusMessage)
.scaledFont(size: OmiType.caption, weight: .medium)
.foregroundColor(Ink.listeningGreen)
}
if let errorMessage = model.errorMessage {
Text(errorMessage)
.scaledFont(size: OmiType.caption, weight: .medium)
.foregroundColor(PageGlass.warning)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
.padding(OmiSpacing.xxl)
.background(Ink.surface)
.glassContent()
.task {
await model.loadConfiguration()
statuses[destination] = await MemoryExportService.shared.refreshCloudGrantConnectionStatus(for: destination)
if destination.supportsMCP && destination.requiresHostedMCPKeyForSetup && model.mcpKey == nil {
await model.generateMCPKey()
}
}
.onReceive(permissionRefreshTimer) { _ in
refreshPermissionStateIfNeeded()
}
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
refreshPermissionStateIfNeeded()
refreshCloudGrantConnectionIfNeeded()
}
}
private func refreshPermissionStateIfNeeded() {
guard MemoryExportExecutor.requiresAccessibilityPreflight(destination) else { return }
permissionRefreshID += 1
}
private func refreshCloudGrantConnectionIfNeeded() {
guard destination.cloudOAuthClientID != nil else { return }
Task {
statuses[destination] = await MemoryExportService.shared.refreshCloudGrantConnectionStatus(for: destination)
}
}
@ViewBuilder
private var content: some View {
VStack(alignment: .leading, spacing: OmiSpacing.lg) {
if destination.supportsAgentSetup {
agentSetupSection
} else if destination.supportsMCP {
// Lead with the one action — "Do it for me". Everything manual (live
// MCP fields, memory pack) is tucked behind a collapsed disclosure so
// the default view stays simple.
executeBlock
manualSetupDisclosure
} else if destination.supportsMemoryPack {
methodHeader(
icon: "doc.on.clipboard.fill",
title: "Memory pack",
tag: "MANUAL",
tagColor: Ink.secondary,
subtitle: "Copy a one-time snapshot and paste it in yourself. Won't update on its own."
)
packSection
packActionButton
}
}
}
@ViewBuilder
private var manualSetupDisclosure: some View {
ManualInstallationDisclosure(
isExpanded: $showManualSetup,
title: destination == .chatgpt ? "Developer-mode fallback" : "Manual installation",
fontSize: 13
) {
VStack(alignment: .leading, spacing: OmiSpacing.lg) {
methodHeader(
icon: "bolt.fill",
title: destination == .chatgpt ? "Custom ChatGPT app" : "Live connection",
tag: destination == .chatgpt ? "ADVANCED" : "AUTOMATIC",
tagColor: destination == .chatgpt ? Ink.secondary : Ink.listeningGreen,
subtitle: destination == .chatgpt
? "Use only when your workspace requires a developer-mode custom app."
: "Set it once — \(destination.title) reads your memories live and stays in sync."
)
mcpSection
if destination.supportsMemoryPack {
Divider()
.background(Ink.rowFillHover)
.padding(.vertical, OmiSpacing.hairline)
methodHeader(
icon: "doc.on.clipboard.fill",
title: "Memory pack",
tag: "MANUAL",
tagColor: Ink.secondary,
subtitle: "Copy a one-time snapshot and paste it in yourself. Won't update on its own."
)
packSection
packActionButton
}
}
.padding(.top, OmiSpacing.sm)
}
}
private var agentSetupSection: some View {
VStack(alignment: .leading, spacing: OmiSpacing.lg) {
agentSetupHeader
VStack(alignment: .leading, spacing: OmiSpacing.sm) {
agentSetupBullet("Omi creates fresh connection keys for this prompt.")
agentSetupBullet(
"Your agent can read synced memories and conversations, then use this Mac for screen history, screenshots, recaps, files, and tasks."
)
agentSetupBullet(
"The included Omi guide helps your agent choose the right context and ask before changing memories."
)
}
HStack(spacing: OmiSpacing.sm) {
Button {
Task {
if let updatedStatus = await model.copyAgentSetupPrompt() {
statuses[destination] = updatedStatus
}
}
} label: {
Label(model.isLoadingMCPKey ? "Preparing…" : "Copy prompt", systemImage: "sparkles")
}
.buttonStyle(OmiButtonStyle(.primary, size: .compact))
.disabled(model.isLoadingMCPKey)
Button {
Task { await model.testAgentConnection() }
} label: {
Label(model.isTestingAgentConnection ? "Testing…" : "Test", systemImage: "checkmark.seal")
}
.buttonStyle(OmiButtonStyle(.secondary, size: .compact))
.disabled(model.isLoadingMCPKey || model.isTestingAgentConnection)
.help("Test hosted and local Omi access")
Button {
Task {
await model.createNewAgentConnectionKey()
statuses[destination] = await MemoryExportService.shared.status(for: destination)
}
} label: {
Label("New key", systemImage: "key")
}
.buttonStyle(OmiButtonStyle(.secondary, size: .compact))
.disabled(model.isLoadingMCPKey || model.isTestingAgentConnection)
.help("Create fresh hosted and local connection keys")
}
}
}
private var agentSetupHeader: some View {
VStack(alignment: .leading, spacing: OmiSpacing.xs) {
HStack(spacing: OmiSpacing.sm) {
Text("Let your agent do it")
.scaledFont(size: OmiType.subheading, weight: .semibold)
.foregroundColor(Ink.primary)
Text("MCP + CLI")
.scaledFont(size: OmiType.micro, weight: .bold)
.foregroundColor(Ink.listeningGreen)
.padding(.horizontal, OmiSpacing.xs)
.padding(.vertical, OmiSpacing.hairline)
.background(Capsule().fill(Ink.listeningGreen.opacity(0.15)))
}
Text(
"Copy one setup prompt for your agent. It connects Omi memories through MCP, turns on local Desktop access through the Omi CLI, and includes a short Omi guide the agent can keep."
)
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
.fixedSize(horizontal: false, vertical: true)
}
}
private func agentSetupBullet(_ text: String) -> some View {
HStack(alignment: .top, spacing: OmiSpacing.sm) {
Image(systemName: "checkmark.circle.fill")
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.listeningGreen)
.padding(.top, 1)
Text(text)
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
.fixedSize(horizontal: false, vertical: true)
}
}
private var executeButtonTitle: String {
let presentation = executePresentation
_ = permissionRefreshID
return presentation.primaryActionTitle ?? "Connected"
}
private var executePresentation: MemoryExportConnectionPresentation {
MemoryExportConnectionPresentation.make(
destination: destination,
status: statuses[destination],
isRunning: model.isExecuting,
accessibilityPreflightMissing: MemoryExportExecutor.accessibilityPreflightMissing(
for: destination)
)
}
private var executeBlockSubtitle: String {
switch destination.mcpExecuteKind {
case .directoryApp:
return
"Open Omi’s approved ChatGPT listing, then add Omi and authorize it in ChatGPT. Omi checks the connection when you return."
case .localAutonomous:
return
"Omi sets up \(destination.title) for you — it runs as an Omi task you can watch in the floating bar. If it gets stuck, use the manual steps below."
case .browserAutonomous:
if MemoryExportExecutor.accessibilityPreflightMissing(for: destination) {
return
"Omi needs Accessibility permission to use your signed-in browser for \(destination.title). If you prefer not to grant it, use the manual steps below."
} else {
return
"Omi uses your signed-in browser to set up \(destination.title). If sign-in or permissions block it, Omi will tell you exactly where it stopped."
}
case .assisted:
if destination.assistedOverlayHint != nil {
return
"Omi opens \(destination.title) and shows an on-screen card — copy each value with one click and paste it into the form."
}
return
"Omi opens \(destination.title) and copies your key, then you confirm the quick steps below."
}
}
/// "Execute" — hands the whole setup to Omi to run as a task.
private var executeBlock: some View {
VStack(alignment: .leading, spacing: OmiSpacing.sm) {
if let completion = executePresentation.completion {
setupCompleteBlock(completion)
} else {
HStack(spacing: OmiSpacing.sm) {
Image(systemName: "sparkles")
.scaledFont(size: OmiType.body, weight: .semibold)
.foregroundColor(Ink.secondary)
Text(destination.mcpExecuteKind == .directoryApp ? "Connect in ChatGPT" : "Let Omi do it")
.scaledFont(size: OmiType.subheading, weight: .semibold)
.foregroundColor(Ink.primary)
Text(destination.mcpExecuteKind == .directoryApp ? "ONE CLICK" : "FASTEST")
.scaledFont(size: OmiType.micro, weight: .bold)
.foregroundColor(Ink.listeningGreen)
.padding(.horizontal, OmiSpacing.xs)
.padding(.vertical, OmiSpacing.hairline)
.background(Capsule().fill(Ink.listeningGreen.opacity(0.15)))
}
Text(executeBlockSubtitle)
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
.fixedSize(horizontal: false, vertical: true)
Button {
Task {
await model.executeWithOmi(destination: destination)
statuses[destination] = await MemoryExportService.shared.refreshCloudGrantConnectionStatus(
for: destination)
// Assisted flow: the user pastes values by hand, so surface the
// field-by-field steps instead of leaving them collapsed.
if destination.mcpExecuteKind == .assisted, destination.assistedOverlayHint != nil {
showManualSetup = true
}
}
} label: {
ConnectionModalActionButton(
title: model.isExecuting ? "Starting Omi…" : executeButtonTitle,
isConnected: isConnected
)
}
.buttonStyle(.plain)
.disabled(model.isExecuting || isConnected)
}
}
}
private func setupCompleteBlock(_ completion: MCPSetupCompletionSummary) -> some View {
VStack(alignment: .leading, spacing: OmiSpacing.sm) {
HStack(alignment: .top, spacing: OmiSpacing.sm) {
Image(systemName: "checkmark.seal.fill")
.scaledFont(size: OmiType.subheading, weight: .semibold)
.foregroundColor(Ink.listeningGreen)
.padding(.top, 1)
VStack(alignment: .leading, spacing: OmiSpacing.xxs) {
Text(completion.title)
.scaledFont(size: OmiType.subheading, weight: .semibold)
.foregroundColor(Ink.primary)
if destination == .claudeCode {
ClaudeCodeRestartSubtitle()
} else {
Text(completion.subtitle)
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
.fixedSize(horizontal: false, vertical: true)
}
}
}
if destination.cloudOAuthClientID != nil {
Button(isDisconnecting ? "Disconnecting…" : "Disconnect") {
disconnectCloudConnection()
}
.buttonStyle(.plain)
.foregroundColor(Ink.secondary)
.scaledFont(size: OmiType.caption, weight: .medium)
.disabled(isDisconnecting)
}
}
.padding(OmiSpacing.md)
.frame(maxWidth: .infinity, alignment: .leading)
.background(
RoundedRectangle(cornerRadius: OmiChrome.smallControlRadius, style: .continuous)
.fill(Ink.rowFill)
.overlay(
RoundedRectangle(cornerRadius: OmiChrome.smallControlRadius, style: .continuous)
.stroke(Ink.listeningGreen.opacity(0.22), lineWidth: 1))
)
}
private func disconnectCloudConnection() {
guard !isDisconnecting else { return }
isDisconnecting = true
model.errorMessage = nil
model.statusMessage = nil
Task { @MainActor in
do {
statuses[destination] = try await MemoryExportService.shared
.disconnectCloudOAuthConnection(for: destination)
model.statusMessage = "Disconnected from \(destination.title)."
} catch {
model.errorMessage = "Couldn't disconnect \(destination.title). Try again."
}
isDisconnecting = false
}
}
private var isConnected: Bool {
guard destination.hasLocallyVerifiableLiveSetup else { return false }
return statuses[destination]?.hasConnection == true
}
/// Labeled header that makes the automatic (MCP) vs manual (pack) choice obvious.
private func methodHeader(
icon: String, title: String, tag: String, tagColor: Color, subtitle: String
) -> some View {
VStack(alignment: .leading, spacing: OmiSpacing.xxs) {
HStack(spacing: OmiSpacing.sm) {
Image(systemName: icon)
.scaledFont(size: OmiType.body, weight: .semibold)
.foregroundColor(tagColor)
Text(title)
.scaledFont(size: OmiType.subheading, weight: .semibold)
.foregroundColor(Ink.primary)
Text(tag)
.scaledFont(size: OmiType.micro, weight: .bold)
.foregroundColor(tagColor)
.padding(.horizontal, OmiSpacing.xs)
.padding(.vertical, OmiSpacing.hairline)
.background(
Capsule().fill(tagColor.opacity(0.15))
)
}
Text(subtitle)
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
.fixedSize(horizontal: false, vertical: true)
}
}
// MARK: - MCP connection
@ViewBuilder
private var mcpSection: some View {
let setup = destination.mcpSetup(key: model.mcpKey ?? "YOUR_OMI_KEY")
VStack(alignment: .leading, spacing: OmiSpacing.md) {
if destination == .claude {
claudeConnectorFields
} else if destination == .chatgpt {
chatGPTDeveloperModeFields
} else {
mcpCodeRow(
label: "Server URL", value: MemoryExportDestination.mcpServerURL, copyLabel: "Server URL")
if destination.requiresHostedMCPKeyForSetup {
mcpKeyRow
}
}
if let setup, let copyText = setup.copyText, let copyTitle = setup.copyTitle {
mcpSnippet(copyText, title: copyTitle, enabled: model.mcpKey != nil)
}
if let setup {
VStack(alignment: .leading, spacing: OmiSpacing.xs) {
ForEach(Array(setup.steps.enumerated()), id: \.offset) { index, step in
HStack(alignment: .top, spacing: OmiSpacing.sm) {
Text("\(index + 1).")
.scaledFont(size: OmiType.caption, weight: .semibold)
.foregroundColor(Ink.secondary)
Text(step)
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
.fixedSize(horizontal: false, vertical: true)
}