forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemoryGraphPage.swift
More file actions
1314 lines (1152 loc) · 45.5 KB
/
Copy pathMemoryGraphPage.swift
File metadata and controls
1314 lines (1152 loc) · 45.5 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 OmiSupport
import OmiTheme
import SceneKit
import SwiftUI
// MARK: - Memory Graph Page
/// One explicit compatibility boundary: the assertion-backed graph gets the atlas,
/// while the established graph remains a read-only historical projection.
enum MemoryGraphPresentationMode: Equatable {
case canonicalAtlas
case legacyBrainMap
/// The account's capability has not been established yet. Distinct from
/// `legacyBrainMap`: mounting either real surface here is a guess, and the
/// legacy graph is not an inert guess — it owns shared view-model state and
/// runs a rebuild bootstrap, both of which corrupt the surface that replaces
/// it a frame later.
case undetermined
/// Local QA can exercise the canonical-only surface without changing the
/// server-owned rollout state. Production bundles always remain gate-driven.
static var localQAOverrideEnabled: Bool {
AppBuild.isNonProduction
&& ProcessInfo.processInfo.environment["OMI_FORCE_CANONICAL_MEMORY_ATLAS"] == "1"
}
static func resolve(
canonicalLifecycleExposed: Bool,
forceCanonicalAtlasForLocalQA: Bool = false,
capabilityEstablished: Bool = true
) -> Self {
if forceCanonicalAtlasForLocalQA { return .canonicalAtlas }
guard capabilityEstablished else { return .undetermined }
return canonicalLifecycleExposed ? .canonicalAtlas : .legacyBrainMap
}
}
struct MemoryGraphPage: View {
@ObservedObject var viewModel: MemoryGraphViewModel
var searchText = ""
var body: some View {
ZStack {
if !viewModel.isEmpty {
MemoryGraphSceneView(viewModel: viewModel)
}
// Minimal floating controls — no boxes, no backgrounds. (The Brain Map is
// a Memory tab now, not a modal, so there's no close button.)
VStack {
HStack {
if !viewModel.isEmpty {
legacyGraphLegend
}
Spacer()
// Rebuild control: while rebuilding it just dims and disables — the
// single centered spinner below is the only progress indicator, so
// the header never shows a second spinner of its own.
Button {
Task { await viewModel.rebuildGraph() }
} label: {
PageQueryActionLabel(
icon: "arrow.clockwise",
title: viewModel.isRebuilding ? "Rebuilding…" : "Rebuild"
)
}
.buttonStyle(.plain)
.disabled(viewModel.isRebuilding)
.help("Rebuild graph")
}
.padding(.horizontal, OmiSpacing.sm)
.padding(.top, OmiSpacing.sm)
Spacer()
}
if shouldShowSearchEmptyState {
VStack(spacing: OmiSpacing.sm) {
Image(systemName: "magnifyingglass")
.scaledFont(size: OmiType.heading)
.foregroundStyle(Ink.surface)
Text("No entities match \u{201c}\(trimmedSearchText)\u{201d}")
.scaledFont(size: OmiType.body, weight: .semibold)
.foregroundStyle(Ink.surface)
Text("Try a different search or clear the search above.")
.scaledFont(size: OmiType.caption)
.foregroundStyle(Ink.surface.opacity(0.78))
}
.multilineTextAlignment(.center)
.allowsHitTesting(false)
.accessibilityElement(children: .combine)
.accessibilityLabel("No entities match \(trimmedSearchText)")
.accessibilityHint("Try a different search or clear the search above.")
}
// Exactly one status view: a single centered spinner while loading or
// rebuilding, otherwise an empty-state message — never a perpetual spinner
// (the empty case used to spin forever because there was no exit).
if viewModel.isLoading || viewModel.isRebuilding {
ProgressView()
.scaleEffect(1.2)
.tint(Ink.secondary)
} else if viewModel.isEmpty {
VStack(spacing: OmiSpacing.sm) {
Image(systemName: "brain")
.scaledFont(size: OmiType.heading)
.foregroundColor(Ink.secondary)
Text("Brain map will appear once enough linked memories are available.")
.scaledFont(size: 12.5)
.foregroundColor(Ink.secondary)
.multilineTextAlignment(.center)
}
.padding(OmiSpacing.lg)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.padding(OmiSpacing.xs)
.glassMediaMat(cornerRadius: PageGlass.cardRadius)
.padding(OmiSpacing.xs)
.task {
await viewModel.prepareGraph()
viewModel.applySearch(query: searchText)
}
.onChange(of: searchText) { _, query in
viewModel.applySearch(query: query)
}
}
private var trimmedSearchText: String {
searchText.trimmingCharacters(in: .whitespacesAndNewlines)
}
private var shouldShowSearchEmptyState: Bool {
!trimmedSearchText.isEmpty
&& viewModel.searchMatchCount == 0
&& !viewModel.isLoading
&& !viewModel.isRebuilding
&& !viewModel.isEmpty
}
private var legacyGraphLegend: some View {
let activeTypes = KnowledgeGraphNodeType.allCases.filter { type in
viewModel.graphResponse.nodes.contains { $0.nodeType == type }
}
return HStack(spacing: OmiSpacing.sm) {
Text("Legend")
.scaledFont(size: OmiType.caption, weight: .semibold)
.foregroundStyle(Ink.surface)
ForEach(activeTypes, id: \.self) { type in
HStack(spacing: OmiSpacing.xs) {
Circle()
.fill(type.color)
.frame(width: 6, height: 6)
Text(type.displayName)
.scaledFont(size: OmiType.caption)
.foregroundStyle(Ink.surface.opacity(0.84))
}
}
}
.accessibilityElement(children: .combine)
.accessibilityLabel("Brain Map legend")
.accessibilityValue(
activeTypes.map { "\($0.displayName), color coded" }.joined(separator: "; ")
)
.accessibilityHint("Legend only; these items are not interactive filters.")
}
}
// MARK: - SceneKit View
struct MemoryGraphSceneView: NSViewRepresentable {
@ObservedObject var viewModel: MemoryGraphViewModel
func makeNSView(context: Context) -> SCNView {
let scnView = SCNView()
scnView.scene = viewModel.scene
scnView.pointOfView = viewModel.cameraNode
scnView.allowsCameraControl = true
scnView.autoenablesDefaultLighting = false // We set up our own lights
scnView.backgroundColor = .clear
scnView.antialiasingMode = .multisampling2X // Lighter AA
scnView.preferredFramesPerSecond = 30 // Cap render rate
// Set up delegate for animation
scnView.delegate = context.coordinator
return scnView
}
func updateNSView(_ nsView: SCNView, context: Context) {
// Update scene if needed
}
func makeCoordinator() -> Coordinator {
Coordinator(viewModel: viewModel)
}
class Coordinator: NSObject, SCNSceneRendererDelegate {
let viewModel: MemoryGraphViewModel
private var lastUpdateTime: TimeInterval = 0
init(viewModel: MemoryGraphViewModel) {
self.viewModel = viewModel
}
func renderer(_ renderer: any SCNSceneRenderer, updateAtTime time: TimeInterval) {
// Throttle to ~30fps for physics updates
guard time - lastUpdateTime > 0.033 else { return }
lastUpdateTime = time
let vm = viewModel
Task { @MainActor in
vm.updateSimulation()
}
}
}
}
// MARK: - View Model
@MainActor
class MemoryGraphViewModel: ObservableObject {
typealias CanonicalGraphFetcher =
(RuntimeOwnerAuthorizationSnapshot) async throws -> KnowledgeGraphResponse
typealias OwnerNameProvider = () -> String?
@Published var isLoading = false
@Published var isRebuilding = false
@Published var isEmpty = true
@Published var selectedNodeId: String?
@Published private(set) var searchMatchCount: Int?
@Published private(set) var graphResponse = KnowledgeGraphResponse(nodes: [], edges: [])
/// Prepared off the main actor and retained for the complete lifetime of a
/// canonical graph revision. The SwiftUI Brain Map can re-render freely
/// without rebuilding the relationship layout or losing its gesture cache.
@Published private(set) var canonicalAtlasProjection: MemoryAtlasProjection?
/// False until a canonical fetch has returned, so the tab can show a loader
/// instead of a synthetic owner or a fake empty map. Failures stay in
/// loading and retry instead of counting as "attempted."
@Published private(set) var hasAttemptedCanonicalAtlasLoad = false
let scene = SCNScene()
let cameraNode = SCNNode()
private var simulation = ForceDirectedSimulation()
private var nodeSceneNodes: [String: SCNNode] = [:]
private var edgeSceneNodes: [String: SCNNode] = [:]
private var isAnimating = true
// Revisit guards: the VM is session-persistent (ViewModelContainer), so a
// page visit renders the existing scene instantly. Non-forced loads are
// TTL-throttled, single-flight, and skip the expensive re-simulation when
// the fetched graph is unchanged.
private var lastLoadedAt = Date.distantPast
private var isPreparing = false
private var hasLoadedCanonicalAtlas = false
private var hasRunEmptyBootstrap = false
private var loadedGraphSignature: Int?
private var activeSearchQuery = ""
private var sessionGeneration = 0
private let canonicalGraphFetcher: CanonicalGraphFetcher
private let ownerNameProvider: OwnerNameProvider
private static func hasAtlasContent(_ response: KnowledgeGraphResponse) -> Bool {
!response.atlasNodes.isEmpty || !(response.catalogNodes?.isEmpty ?? true)
}
init() {
canonicalGraphFetcher = { authorizationSnapshot in
try await APIClient.shared.getKnowledgeGraph(
authorizationSnapshot: authorizationSnapshot)
}
ownerNameProvider = Self.currentOwnerName
setupCamera()
setupLighting()
}
convenience init(
canonicalGraphFetcher: @escaping CanonicalGraphFetcher,
initialGraphResponse: KnowledgeGraphResponse
) {
self.init(
canonicalGraphFetcher: canonicalGraphFetcher,
initialGraphResponse: initialGraphResponse,
ownerNameProvider: Self.currentOwnerName)
}
init(
canonicalGraphFetcher: @escaping CanonicalGraphFetcher,
initialGraphResponse: KnowledgeGraphResponse,
ownerNameProvider: @escaping OwnerNameProvider
) {
self.canonicalGraphFetcher = canonicalGraphFetcher
self.ownerNameProvider = ownerNameProvider
graphResponse = initialGraphResponse
isEmpty = !Self.hasAtlasContent(initialGraphResponse)
setupCamera()
setupLighting()
}
private static func currentOwnerName() -> String? {
let givenName = AuthService.shared.givenName.trimmingCharacters(in: .whitespacesAndNewlines)
let displayName = AuthService.shared.displayName.trimmingCharacters(in: .whitespacesAndNewlines)
let ownerName = givenName.isEmpty ? displayName : givenName
return ownerName.isEmpty ? nil : ownerName
}
private func setupCamera() {
let camera = SCNCamera()
camera.zNear = 1
camera.zFar = 20000
camera.fieldOfView = 60
cameraNode.camera = camera
cameraNode.position = SCNVector3(0, 0, 2000) // Initial default, auto-adjusted after layout
scene.rootNode.addChildNode(cameraNode)
}
private func setupLighting() {
// Ambient light
let ambientLight = SCNLight()
ambientLight.type = .ambient
ambientLight.intensity = 500
ambientLight.color = NSColor.white
let ambientNode = SCNNode()
ambientNode.light = ambientLight
scene.rootNode.addChildNode(ambientNode)
// Directional light
let directionalLight = SCNLight()
directionalLight.type = .directional
directionalLight.intensity = 800
let directionalNode = SCNNode()
directionalNode.light = directionalLight
directionalNode.position = SCNVector3(0, 1000, 1000)
directionalNode.look(at: SCNVector3(0, 0, 0))
scene.rootNode.addChildNode(directionalNode)
}
// MARK: - Load Graph
func prepareGraph() async {
guard !isPreparing else { return }
let generation = sessionGeneration
isPreparing = true
defer {
if generation == sessionGeneration {
isPreparing = false
}
}
// A rendered scene within the cooldown is served as-is — visiting the
// page must not refetch, re-run the force layout, or reset the camera.
if !isEmpty,
!PollingConfig.shouldAllowActivationRefresh(lastRefresh: lastLoadedAt)
{
return
}
let didLoadAuthoritatively = await loadGraph(generation: generation)
guard generation == sessionGeneration else { return }
// `isEmpty` starts true and only a successful load clears it, so a failed
// or cancelled fetch is indistinguishable from a genuinely empty graph.
// Bootstrapping on that difference asked the backend to DELETE and rebuild
// a healthy graph because the view was torn down mid-fetch.
if didLoadAuthoritatively && isEmpty && !hasRunEmptyBootstrap {
// First-session bootstrap for sparse accounts: ask the backend to build
// the graph, then poll for it. Run once per session — not per visit.
guard await rebuildGraph(generation: generation) else { return }
hasRunEmptyBootstrap = true
for _ in 1...10 {
try? await Task.sleep(nanoseconds: 3_000_000_000)
guard generation == sessionGeneration else { return }
await loadGraph(generation: generation)
if !isEmpty { break }
}
}
}
/// Load graph data for the canonical atlas without invoking the legacy
/// empty-graph rebuild path or paying the SceneKit simulation cost.
func prepareCanonicalAtlas() async {
guard !isPreparing else { return }
let generation = sessionGeneration
if !hasLoadedCanonicalAtlas {
// The shared view model may still contain a local onboarding or legacy
// projection. Canonical Brain Map must remain empty until a complete
// server graph has been fetched.
graphResponse = KnowledgeGraphResponse(nodes: [], edges: [])
canonicalAtlasProjection = nil
isEmpty = true
isLoading = true
}
guard let authorizationSnapshot = RuntimeOwnerIdentity.captureAuthorizationSnapshot() else {
log("Memory atlas: canonical load skipped while owner authorization is unavailable")
return
}
isPreparing = true
defer {
if generation == sessionGeneration {
isPreparing = false
}
}
if hasLoadedCanonicalAtlas,
Self.hasAtlasContent(graphResponse),
!PollingConfig.shouldAllowActivationRefresh(lastRefresh: lastLoadedAt)
{
return
}
let showSpinner = !Self.hasAtlasContent(graphResponse)
if showSpinner { isLoading = true }
defer {
if showSpinner && generation == sessionGeneration {
isLoading = false
}
}
var lastError: Error?
for attempt in 1...3 {
guard isCanonicalLoadCurrent(generation: generation, authorizationSnapshot: authorizationSnapshot),
!Task.isCancelled
else { return }
do {
let response = try await canonicalGraphFetcher(authorizationSnapshot)
guard isCanonicalLoadCurrent(generation: generation, authorizationSnapshot: authorizationSnapshot) else {
return
}
let hasContent = Self.hasAtlasContent(response)
var projection: MemoryAtlasProjection?
if hasContent {
let ownerName = ownerNameProvider()
projection = await Task.detached(priority: .userInitiated) {
MemoryAtlasProjection(graph: response.atlasResponse, userName: ownerName)
}.value
guard isCanonicalLoadCurrent(generation: generation, authorizationSnapshot: authorizationSnapshot) else {
return
}
}
canonicalAtlasProjection = projection
graphResponse = response
isEmpty = !hasContent
hasLoadedCanonicalAtlas = true
hasAttemptedCanonicalAtlasLoad = true
lastLoadedAt = Date()
log("Memory atlas: \(response.atlasNodes.count) nodes, \(response.edges.count) edges")
return
} catch is CancellationError {
return
} catch {
lastError = error
if attempt < 3 {
try? await Task.sleep(nanoseconds: 800_000_000)
}
}
}
if let lastError {
log("Failed to load memory atlas: \(lastError.localizedDescription)")
}
}
/// Rebuild the canonical atlas graph, polling until the replacement appears.
///
/// The backend rebuild is a background task; a fixed 2-second sleep (as used
/// by the legacy `rebuildGraph`) receives an empty or stale graph whenever
/// processing the account takes longer. This polls until the new graph has
/// at least one node or the poll budget is exhausted.
@discardableResult
func rebuildCanonicalAtlas() async -> Bool {
let generation = sessionGeneration
guard let authorizationSnapshot = RuntimeOwnerIdentity.captureAuthorizationSnapshot() else {
log("Memory atlas: canonical rebuild skipped while owner authorization is unavailable")
return false
}
isRebuilding = true
defer {
if generation == sessionGeneration {
isRebuilding = false
}
}
do {
_ = try await APIClient.shared.rebuildKnowledgeGraph(
authorizationSnapshot: authorizationSnapshot)
// Poll for the replacement graph — the backend rebuild is async.
let maxAttempts = 10
for attempt in 1...maxAttempts {
try await Task.sleep(nanoseconds: 3_000_000_000)
guard isCanonicalLoadCurrent(generation: generation, authorizationSnapshot: authorizationSnapshot) else {
return false
}
let response = try await canonicalGraphFetcher(authorizationSnapshot)
guard isCanonicalLoadCurrent(generation: generation, authorizationSnapshot: authorizationSnapshot) else {
return false
}
if !response.atlasNodes.isEmpty || !(response.catalogNodes?.isEmpty ?? true) {
let ownerName = ownerNameProvider()
let projection = await Task.detached(priority: .userInitiated) {
MemoryAtlasProjection(graph: response.atlasResponse, userName: ownerName)
}.value
guard isCanonicalLoadCurrent(generation: generation, authorizationSnapshot: authorizationSnapshot) else {
return false
}
canonicalAtlasProjection = projection
graphResponse = response
isEmpty = !Self.hasAtlasContent(response)
hasLoadedCanonicalAtlas = true
lastLoadedAt = Date()
log("Memory atlas: rebuilt graph loaded after \(attempt) poll(s), \(response.atlasNodes.count) nodes")
return true
}
}
log("Memory atlas: rebuild poll budget exhausted, graph still empty after \(maxAttempts) attempts")
return false
} catch {
log("Failed to rebuild memory atlas: \(error.localizedDescription)")
return false
}
}
private func isCanonicalLoadCurrent(
generation: Int,
authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot
) -> Bool {
guard !Task.isCancelled, generation == sessionGeneration else { return false }
return RuntimeOwnerIdentity.isAuthorizationCurrent(authorizationSnapshot)
}
func loadGraph() async {
await loadGraph(generation: sessionGeneration)
}
/// Returns whether the graph was authoritatively loaded in this generation.
/// Callers that act on emptiness must not treat a failure as an empty graph.
@discardableResult
private func loadGraph(generation: Int) async -> Bool {
// Only surface the spinner while there's no scene to show — freshness
// checks over a rendered graph stay invisible.
let showSpinner = isEmpty
if showSpinner { isLoading = true }
defer {
if showSpinner && generation == sessionGeneration {
isLoading = false
}
}
do {
let response = try await fetchGraph()
guard generation == sessionGeneration else { return false }
log("Knowledge graph: \(response.nodes.count) nodes, \(response.edges.count) edges")
graphResponse = response
isEmpty = response.nodes.isEmpty
lastLoadedAt = Date()
guard !isEmpty else { return true }
// Same graph as last time → keep the settled scene. Re-simulating and
// recreating scene nodes for identical data is what made every page
// visit visibly "reload" the brain map.
let signature = Self.graphSignature(of: response)
if signature == loadedGraphSignature {
return true
}
loadedGraphSignature = signature
// Populate simulation with user node at center
let userName = AuthService.shared.displayName.isEmpty ? nil : AuthService.shared.givenName
log("User name for center node: \(userName ?? "nil")")
let populateStart = CFAbsoluteTimeGetCurrent()
simulation.populate(graphResponse: response, userNodeLabel: userName)
log(
"Simulation populated: \(simulation.nodes.count) nodes (including user), \(simulation.edges.count) edges"
)
logPerf(
"MemoryGraph: populate", duration: CFAbsoluteTimeGetCurrent() - populateStart)
// A settled layout for this exact graph renders instantly — restore it
// and skip both the physics run and the visual settle animation.
let layoutStart = CFAbsoluteTimeGetCurrent()
let restoredLayout =
loadCachedLayout(signature: signature).map { simulation.applyLayout($0) } ?? false
if !restoredLayout {
// Suppress the render-driven simulation.tick() while the off-main physics
// run mutates the same node positions/velocities. The SceneKit delegate
// enqueues updateSimulation() on the main actor every frame; without this
// it would tick() concurrently with runSync() off-main — an unsynchronized
// read/write of non-atomic SIMD3 node state (torn positions, corrupt
// layout/camera). The post-layout block below re-enables animation once the
// detached run has completed.
isAnimating = false
// Run initial layout off main thread for responsiveness
await Task.detached(priority: .userInitiated) { [simulation] in
simulation.runSync(ticks: 800)
}.value
guard generation == sessionGeneration else { return false }
saveLayoutCache(signature: signature)
}
logPerf(
"MemoryGraph: layout (restored=\(restoredLayout))",
duration: CFAbsoluteTimeGetCurrent() - layoutStart)
guard generation == sessionGeneration else { return false }
// Create scene nodes
let sceneStart = CFAbsoluteTimeGetCurrent()
createSceneNodes()
logPerf("MemoryGraph: scene build", duration: CFAbsoluteTimeGetCurrent() - sceneStart)
if restoredLayout {
isAnimating = false
} else {
// Brief animation to settle, then stop
isAnimating = true
Task {
try? await Task.sleep(nanoseconds: 3_000_000_000) // 3s of live physics
await MainActor.run { isAnimating = false }
}
}
return true
} catch {
log("Failed to load knowledge graph: \(error.localizedDescription)")
return false
}
}
private struct GraphLayoutCache: Codable {
let signature: Int
let positions: [String: [Float]]
}
private static func layoutCacheURL() -> URL? {
guard let userId = UserDefaults.standard.string(forKey: "auth_userId"), !userId.isEmpty
else { return nil }
let dir = DesktopLocalProfile.applicationSupportURL()
.appendingPathComponent("users", isDirectory: true)
.appendingPathComponent(userId, isDirectory: true)
do {
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
return dir.appendingPathComponent("memory-graph-layout.json")
} catch {
logError("MemoryGraph: failed to prepare layout cache directory", error: error)
return nil
}
}
private func loadCachedLayout(signature: Int) -> [String: SIMD3<Float>]? {
guard let url = Self.layoutCacheURL(), FileManager.default.fileExists(atPath: url.path)
else { return nil }
let cache: GraphLayoutCache
do {
let data = try Data(contentsOf: url)
cache = try JSONDecoder().decode(GraphLayoutCache.self, from: data)
} catch {
logError("MemoryGraph: failed to read layout cache", error: error)
return nil
}
guard cache.signature == signature else { return nil }
var positions: [String: SIMD3<Float>] = [:]
positions.reserveCapacity(cache.positions.count)
for (id, values) in cache.positions where values.count == 3 {
positions[id] = SIMD3<Float>(values[0], values[1], values[2])
}
return positions
}
private func saveLayoutCache(signature: Int) {
guard let url = Self.layoutCacheURL() else { return }
var positions: [String: [Float]] = [:]
for (id, position) in simulation.layoutPositions() {
positions[id] = [position.x, position.y, position.z]
}
let cache = GraphLayoutCache(signature: signature, positions: positions)
do {
let data = try JSONEncoder().encode(cache)
try data.write(to: url, options: .atomic)
} catch {
logError("MemoryGraph: failed to write layout cache", error: error)
}
}
/// Stable across launches — Swift's `Hasher` is per-process seeded, which
/// would silently invalidate the on-disk layout cache on every restart.
static func graphSignature(of response: KnowledgeGraphResponse) -> Int {
var hash: UInt64 = 0xcbf2_9ce4_8422_2325 // FNV-1a
func combine(_ string: String) {
for byte in string.utf8 {
hash ^= UInt64(byte)
hash = hash &* 0x0000_0100_0000_01b3
}
hash ^= 0xff
hash = hash &* 0x0000_0100_0000_01b3
}
combine(String(response.nodes.count))
combine(String(response.edges.count))
for node in response.nodes.sorted(by: { $0.id < $1.id }) {
combine(node.id)
combine(node.label)
combine(node.nodeType.rawValue)
}
for edge in response.edges.sorted(by: { $0.id < $1.id }) {
combine(edge.id)
combine(edge.sourceId)
combine(edge.targetId)
combine(edge.label)
}
return Int(bitPattern: UInt(truncatingIfNeeded: hash))
}
private func fetchGraph() async throws -> KnowledgeGraphResponse {
var response = await KnowledgeGraphStorage.shared.loadGraph()
if !response.nodes.isEmpty {
return response
}
for attempt in 0..<4 {
if AuthState.shared.isRestoringAuth {
try? await Task.sleep(nanoseconds: 500_000_000)
continue
}
do {
return try await APIClient.shared.getKnowledgeGraph()
} catch {
if case AuthError.notSignedIn = error,
AuthState.shared.isSignedIn || AuthState.shared.isRestoringAuth,
attempt < 3
{
try? await Task.sleep(nanoseconds: 1_000_000_000)
continue
}
throw error
}
}
response = await KnowledgeGraphStorage.shared.loadGraph()
return response
}
// MARK: - Rebuild Graph
@discardableResult
func rebuildGraph() async -> Bool {
await rebuildGraph(generation: sessionGeneration)
}
@discardableResult
private func rebuildGraph(generation: Int) async -> Bool {
isRebuilding = true
defer {
if generation == sessionGeneration {
isRebuilding = false
}
}
do {
_ = try await APIClient.shared.rebuildKnowledgeGraph()
// Wait a bit for the backend to process
try await Task.sleep(nanoseconds: 2_000_000_000)
guard generation == sessionGeneration else { return false }
// Reload the graph
await loadGraph(generation: generation)
return true
} catch {
log("Failed to rebuild knowledge graph: \(error.localizedDescription)")
return false
}
}
// MARK: - Incremental Graph Update
/// Add new graph data from storage incrementally (used during onboarding)
func addGraphFromStorage() async {
let generation = sessionGeneration
let response = await KnowledgeGraphStorage.shared.loadGraph()
guard generation == sessionGeneration else { return }
guard !response.nodes.isEmpty else { return }
isEmpty = false
let userName = AuthService.shared.displayName.isEmpty ? nil : AuthService.shared.givenName
simulation.addNodesAndEdges(graphResponse: response, userNodeLabel: userName)
// Suppress the render-driven tick() while this off-main physics burst mutates
// the (already-live) scene's node state — same main-vs-detached data race as
// loadGraph. Re-enabled for the settle animation below, after the detached run.
isAnimating = false
// Run a burst of physics to integrate new nodes
await Task.detached(priority: .userInitiated) { [simulation] in
simulation.runSync(ticks: 200)
}.value
guard generation == sessionGeneration else { return }
// Create scene nodes for new entries, animate them in
addNewSceneNodes()
applySearch(query: activeSearchQuery)
autoFitCamera(animated: true)
// Re-enable animation for settling
isAnimating = true
Task {
try? await Task.sleep(nanoseconds: 3_000_000_000)
await MainActor.run { isAnimating = false }
}
}
func resetSessionState() {
sessionGeneration += 1
clearGraphScene()
simulation = ForceDirectedSimulation()
isLoading = false
isRebuilding = false
isEmpty = true
selectedNodeId = nil
searchMatchCount = nil
activeSearchQuery = ""
graphResponse = KnowledgeGraphResponse(nodes: [], edges: [])
canonicalAtlasProjection = nil
isAnimating = false
lastLoadedAt = .distantPast
isPreparing = false
hasRunEmptyBootstrap = false
hasLoadedCanonicalAtlas = false
hasAttemptedCanonicalAtlasLoad = false
loadedGraphSignature = nil
cameraNode.position = SCNVector3(0, 0, 2000)
}
private func clearGraphScene() {
for (_, node) in nodeSceneNodes { node.removeFromParentNode() }
for (_, node) in edgeSceneNodes { node.removeFromParentNode() }
nodeSceneNodes.removeAll()
edgeSceneNodes.removeAll()
}
/// The compatibility graph keeps its SceneKit renderer, but participates in the same Brain search
/// contract by dimming non-matching entities and their connections in place.
func applySearch(query: String) {
let needle = query.trimmingCharacters(in: .whitespacesAndNewlines)
activeSearchQuery = needle
let matchingIDs = Set(
simulation.nodes.compactMap { node in
needle.isEmpty || node.label.localizedCaseInsensitiveContains(needle) ? node.id : nil
})
searchMatchCount = needle.isEmpty ? nil : matchingIDs.count
if !needle.isEmpty {
let resultsCount = matchingIDs.count
SearchAnalytics.scheduleQueryEntered(surface: .brainMap, query: needle) { resultsCount }
}
for (id, node) in nodeSceneNodes {
node.isHidden = !needle.isEmpty && !matchingIDs.contains(id)
}
for edge in simulation.edges {
edgeSceneNodes[edge.id]?.isHidden =
!needle.isEmpty
&& (!matchingIDs.contains(edge.sourceId) && !matchingIDs.contains(edge.targetId))
}
}
/// Create scene nodes only for simulation nodes/edges not yet in the scene
private func addNewSceneNodes() {
let billboardConstraint = SCNBillboardConstraint()
billboardConstraint.freeAxes = [.X, .Y]
// Add new edges
for edge in simulation.edges {
guard edgeSceneNodes[edge.id] == nil else { continue }
guard let source = simulation.nodeMap[edge.sourceId],
let target = simulation.nodeMap[edge.targetId]
else { continue }
let edgeColor = blendColors(source.nodeType.nsColor, target.nodeType.nsColor, alpha: 0.25)
let edgeMaterial = SCNMaterial()
edgeMaterial.diffuse.contents = edgeColor
edgeMaterial.emission.contents = edgeColor.withAlphaComponent(0.15)
edgeMaterial.lightingModel = .constant
let edgeNode = createEdgeNode(
from: source.position, to: target.position, material: edgeMaterial)
edgeNode.name = edge.id
edgeNode.opacity = 0
scene.rootNode.addChildNode(edgeNode)
edgeSceneNodes[edge.id] = edgeNode
// Fade in
SCNTransaction.begin()
SCNTransaction.animationDuration = 0.5
edgeNode.opacity = 1
SCNTransaction.commit()
}
// Add new node spheres
for node in simulation.nodes {
guard nodeSceneNodes[node.id] == nil else { continue }
let radius = nodeRadius(for: node)
let containerNode = SCNNode()
containerNode.position = SCNVector3(node.position)
containerNode.name = node.id
containerNode.scale = SCNVector3(0.01, 0.01, 0.01) // Start tiny for scale-in
// Core sphere
let sphere = SCNSphere(radius: radius)
sphere.segmentCount = node.isFixed ? 24 : 16
let mat = SCNMaterial()
if node.isFixed {
mat.diffuse.contents = NSColor.white
mat.emission.contents = NSColor.white.withAlphaComponent(0.8)
} else {
mat.diffuse.contents = node.nodeType.nsColor
mat.emission.contents = node.nodeType.nsColor.withAlphaComponent(0.5)
}
mat.lightingModel = .constant
sphere.materials = [mat]
let sphereNode = SCNNode(geometry: sphere)
containerNode.addChildNode(sphereNode)
// Glow halo
let glowRadius = radius * 2.5
let glowSphere = SCNSphere(radius: glowRadius)
glowSphere.segmentCount = 48
let glowMat = SCNMaterial()
let glowColor = node.isFixed ? NSColor.white : node.nodeType.nsColor
glowMat.diffuse.contents = glowColor.withAlphaComponent(0.03)
glowMat.emission.contents = glowColor.withAlphaComponent(0.025)
glowMat.lightingModel = .constant
glowMat.isDoubleSided = true
glowMat.blendMode = .add
glowSphere.materials = [glowMat]
let glowNode = SCNNode(geometry: glowSphere)
containerNode.addChildNode(glowNode)
// Text label
let labelNode = createLabelNode(text: node.label, nodeRadius: radius, isFixed: node.isFixed)
labelNode.constraints = [billboardConstraint]
containerNode.addChildNode(labelNode)
scene.rootNode.addChildNode(containerNode)
nodeSceneNodes[node.id] = containerNode
// Scale in from 0 with animation
SCNTransaction.begin()
SCNTransaction.animationDuration = 0.5
containerNode.scale = SCNVector3(1, 1, 1)
SCNTransaction.commit()
}
// Search can be entered before the first scene build completes. Re-apply the query after the
// nodes exist so a matching query never leaves an unfiltered graph behind on its first render.
applySearch(query: activeSearchQuery)
}
// MARK: - Scene Nodes
/// Compute node radius based on connection count (more connections = bigger)
private func nodeRadius(for node: GraphNode3D) -> CGFloat {
if node.isFixed { return 35 } // User node is largest
let base: CGFloat = 14
let connectionBonus = CGFloat(min(node.connectionCount, 10)) * 2.5
return base + connectionBonus
}
private func createSceneNodes() {
// Clear existing nodes
clearGraphScene()
// Billboard constraint for labels (always face camera)
let billboardConstraint = SCNBillboardConstraint()
billboardConstraint.freeAxes = [.X, .Y]
// Shared materials/geometry: nodes of the same type (and edges of the
// same type pair) are visually identical, so building one material per
// node/edge (~1,200 unique GPU objects for a mid-size graph) wasted both
// build time and draw-call batching. Cache by visual identity instead.
var edgeMaterialCache: [String: SCNMaterial] = [:]
var bodyMaterialCache: [String: SCNMaterial] = [:]
var glowMaterialCache: [String: SCNMaterial] = [:]
var sphereCache: [String: SCNSphere] = [:]
// Create edges first (behind nodes)
for edge in simulation.edges {
guard let source = simulation.nodeMap[edge.sourceId],
let target = simulation.nodeMap[edge.targetId]
else { continue }
let edgeKey = "\(source.nodeType.rawValue)|\(target.nodeType.rawValue)"