forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileIndexingView.swift
More file actions
612 lines (526 loc) · 21 KB
/
Copy pathFileIndexingView.swift
File metadata and controls
612 lines (526 loc) · 21 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
import OmiTheme
import SceneKit
import SwiftUI
/// Standalone file indexing view: loading → brainMap.
/// Works in two contexts:
/// 1. Embedded in OnboardingView step 4 (new users)
/// 2. Shown as a dismissable overlay on app launch in DesktopHomeView (existing users)
struct FileIndexingView: View {
enum Phase { case loading, brainMap }
@State private var phase: Phase = .loading
@State private var scanningFolder: String = ""
@State private var totalFilesScanned: Int = 0
@State private var progress: Double = 0.0
@State private var statusText: String = "Scanning your files..."
@State private var showInfoPopover: Bool = false
@State private var chatMessages: [String] = []
@State private var pipelineStarted = false
@StateObject private var graphViewModel = MemoryGraphViewModel()
@ObservedObject var chatProvider: ChatProvider
/// Tells the parent when brainMap phase is active (for full-bleed layout)
var isBrainMapPhase: Binding<Bool>? = nil
/// Called when user completes (with file count) or skips (with 0)
var onComplete: (Int) -> Void
var body: some View {
VStack(spacing: 0) {
switch phase {
case .loading:
loadingView
case .brainMap:
brainMapView
}
}
.onAppear {
if !pipelineStarted {
pipelineStarted = true
startLoadingPipeline()
}
}
}
// MARK: - Loading Phase
private var loadingView: some View {
VStack(spacing: 0) {
Spacer()
// Animation
OnboardingLoadingAnimation(progress: progress)
.padding(.bottom, OmiSpacing.xl)
// Title
Text(statusText)
.scaledFont(size: OmiType.subheading, weight: .medium)
.foregroundColor(Ink.primary)
.multilineTextAlignment(.center)
.padding(.bottom, OmiSpacing.xs)
// Subtitle — folder being scanned or general message
if !scanningFolder.isEmpty {
Text(
"Scanning ~/\(scanningFolder)"
+ (totalFilesScanned > 0 ? " · \(totalFilesScanned.formatted()) files found" : "")
)
.scaledFont(size: OmiType.body)
.foregroundColor(Ink.secondary)
.multilineTextAlignment(.center)
.omiAnimation(.easeInOut(duration: 0.2), value: scanningFolder)
} else if totalFilesScanned > 0 {
Text("\(totalFilesScanned.formatted()) files indexed")
.scaledFont(size: OmiType.body)
.foregroundColor(Ink.secondary)
.multilineTextAlignment(.center)
} else {
Text("All data is secure and belongs to you. Open-source verified.")
.scaledFont(size: OmiType.body)
.foregroundColor(Ink.secondary)
.multilineTextAlignment(.center)
}
// Progress bar
VStack(spacing: OmiSpacing.xs) {
GeometryReader { geo in
ZStack(alignment: .leading) {
RoundedRectangle(cornerRadius: OmiChrome.stripRadius, style: .continuous)
.fill(Ink.rowFill)
.frame(height: 6)
RoundedRectangle(cornerRadius: OmiChrome.stripRadius, style: .continuous)
.fill(Ink.primary)
.frame(width: max(0, geo.size.width * progress), height: 6)
.omiAnimation(.easeOut(duration: 0.3), value: progress)
}
}
.frame(height: 6)
Text("\(Int(progress * 100))%")
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
.monospacedDigit()
}
.padding(.horizontal, OmiSpacing.page)
.padding(.top, OmiSpacing.xl)
// Skip
Button(action: skip) {
Text("Skip")
.scaledFont(size: OmiType.body)
.foregroundColor(Ink.secondary)
}
.buttonStyle(.plain)
.padding(.top, OmiSpacing.lg)
Spacer()
}
}
// MARK: - Info Popover
private var infoPopoverContent: some View {
VStack(alignment: .leading, spacing: OmiSpacing.sm) {
HStack {
Text("Behind the scenes")
.scaledFont(size: OmiType.body, weight: .semibold)
.foregroundColor(Ink.primary)
Spacer()
}
if !scanningFolder.isEmpty {
HStack(spacing: OmiSpacing.xs) {
Image(systemName: "folder")
.scaledFont(size: OmiType.micro)
.foregroundColor(Ink.secondary)
Text("Scanning ~/\(scanningFolder)")
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
}
}
if totalFilesScanned > 0 {
Text("\(totalFilesScanned.formatted()) files indexed")
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
}
// Live chat messages from the AI exploration
let aiMessages = chatProvider.messages.filter { $0.sender == .ai }
if !aiMessages.isEmpty {
Divider()
ScrollView {
VStack(alignment: .leading, spacing: OmiSpacing.sm) {
ForEach(Array(aiMessages.enumerated()), id: \.offset) { _, msg in
Text(msg.text)
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
.lineSpacing(3)
.textSelection(.enabled)
}
}
}
.frame(maxHeight: 300)
}
}
.padding(OmiSpacing.md)
.frame(width: 340)
}
// MARK: - Brain Map Phase
/// This phase has **two different grounds**, and that is what every colour in it turns on:
/// with a graph, `MemoryGraphSceneView` renders its own black scene edge to edge; without one,
/// there is no scene and the ground is the window's light glass. The white type here was written
/// for the scene and survived onto the empty state, where it was white on a near-white panel —
/// the headline, the placeholder and its glyph were all invisible in the one state a first-run
/// user is most likely to land in.
private var hasGraph: Bool { !graphViewModel.isEmpty }
private var brainMapView: some View {
ZStack {
if hasGraph {
// 3D graph — SceneKit renders its own black background
MemoryGraphSceneView(viewModel: graphViewModel)
} else {
// Empty fallback, on the light panel: the ladder, not the scene's white.
VStack(spacing: OmiSpacing.md) {
Image(systemName: "brain")
.scaledFont(size: OmiType.hero)
.foregroundColor(Ink.hairline)
Text("Your knowledge graph will grow as omi learns more about you")
.scaledFont(size: OmiType.body)
.foregroundColor(Ink.secondary)
.multilineTextAlignment(.center)
.padding(.horizontal, OmiSpacing.page)
}
}
// Floating title + continue button
VStack {
Text("Here's what I know about you")
.font(.system(size: 22, weight: .bold))
.foregroundColor(hasGraph ? Ink.glow : Ink.primary)
// The shadows are how white type stays readable over a moving scene. Over the light
// panel there is nothing to lift the type off, and a dark halo under dark type is just
// smudge, so they go with the scene.
.shadow(color: .black.opacity(hasGraph ? 0.7 : 0), radius: 12, x: 0, y: 2)
.shadow(color: .black.opacity(hasGraph ? 0.4 : 0), radius: 24, x: 0, y: 4)
.padding(.top, OmiSpacing.page)
Spacer()
Button(action: { onComplete(totalFilesScanned) }) {
Text("Continue")
.font(.system(size: 15, weight: .semibold))
.foregroundColor(Ink.surface)
.frame(maxWidth: 220)
.padding(.vertical, OmiSpacing.md)
.background(Ink.primary)
.cornerRadius(SettingsGlassMetrics.cardRadius)
.shadow(color: .black.opacity(0.18), radius: 12, x: 0, y: 3)
}
.buttonStyle(.plain)
.keyboardShortcut(.defaultAction)
.padding(.bottom, OmiSpacing.page)
}
// Graph shortcut hints — bottom-left corner. Only over the scene: every gesture they name
// (rotate, pan, zoom, reset) belongs to a graph that is not there in the empty state, and the
// plate they sit on is a dark scrim sized for the scene's black, not for the light panel.
if hasGraph {
VStack {
Spacer()
HStack {
graphShortcutsHint
.padding(.leading, OmiSpacing.xl)
.padding(.bottom, OmiSpacing.xl)
Spacer()
}
}
}
}
}
// MARK: - Graph Shortcuts Hint
private var graphShortcutsHint: some View {
VStack(alignment: .leading, spacing: OmiSpacing.xxs) {
shortcutRow(icon: "cursorarrow.rays", label: "Drag to rotate")
shortcutRow(icon: "arrow.up.and.down.and.arrow.left.and.right", label: "Right-drag to pan")
shortcutRow(icon: "plus.magnifyingglass", label: "Scroll to zoom")
shortcutRow(icon: "arrow.counterclockwise", label: "Double-click to reset")
}
.padding(.horizontal, OmiSpacing.sm)
.padding(.vertical, OmiSpacing.sm)
.background(
RoundedRectangle(cornerRadius: SettingsGlassMetrics.controlRadius, style: .continuous)
.fill(.black.opacity(0.45))
)
}
private func shortcutRow(icon: String, label: String) -> some View {
HStack(spacing: OmiSpacing.xs) {
Image(systemName: icon)
.font(.system(size: 10, weight: .medium))
.foregroundColor(.white.opacity(0.5))
.frame(width: 14)
Text(label)
.font(.system(size: 11))
.foregroundColor(.white.opacity(0.5))
}
}
// MARK: - Pipeline
private func startLoadingPipeline() {
totalFilesScanned = 0
progress = 0.0
// Set flag immediately so DesktopHomeView won't spawn a duplicate sheet
// when onboarding completes mid-pipeline
UserDefaults.standard.set(true, forKey: "hasCompletedFileIndexing")
Task {
// Stage 1: File Scanning (0% → 60%)
await runFileScanning()
// Stage 2: AI Exploration (60% → 90%)
await runAIExploration()
// Stage 3: Knowledge Graph Build (90% → 100%)
await runKnowledgeGraphBuild()
// Transition to brain map
await MainActor.run {
OmiMotion.withGated(.easeInOut(duration: 0.5)) {
phase = .brainMap
isBrainMapPhase?.wrappedValue = true
}
}
}
}
/// Stage 1: Scan folders, progress 0% → 60%
private func runFileScanning() async {
// Check if files were already indexed (e.g., during onboarding chat via scan_files tool)
let existingCount = await FileIndexerService.shared.getIndexedFileCount()
if existingCount > 0 {
log("FileIndexingView: Skipping file scan — \(existingCount) files already indexed")
await MainActor.run {
totalFilesScanned = existingCount
progress = 0.6
statusText = "Analyzing your files..."
}
return
}
await MainActor.run {
statusText = "Scanning your files..."
}
let home = FileManager.default.homeDirectoryForCurrentUser
let folders = [
("Downloads", home.appendingPathComponent("Downloads")),
("Documents", home.appendingPathComponent("Documents")),
("Desktop", home.appendingPathComponent("Desktop")),
("Developer", home.appendingPathComponent("Developer")),
("Projects", home.appendingPathComponent("Projects")),
("Code", home.appendingPathComponent("Code")),
("src", home.appendingPathComponent("src")),
("repos", home.appendingPathComponent("repos")),
("Sites", home.appendingPathComponent("Sites")),
]
let fm = FileManager.default
let existingFolders = folders.filter { fm.fileExists(atPath: $0.1.path) }
let folderCount = existingFolders.count + 1 // +1 for Applications
var completedFolders = 0
for (name, url) in existingFolders {
await MainActor.run {
scanningFolder = name
}
let count = await FileIndexerService.shared.scanFolders([url])
completedFolders += 1
await MainActor.run {
totalFilesScanned += count
progress = Double(completedFolders) / Double(folderCount) * 0.6
}
}
// Also index installed app names from /Applications
let appCount = await scanApplicationNames()
await MainActor.run {
totalFilesScanned += appCount
progress = 0.6
scanningFolder = ""
}
}
/// Stage 2: AI exploration chat in background, progress 60% → 90%
private func runAIExploration() async {
await MainActor.run {
statusText = "Analyzing your files..."
}
// Start progress animation (ease-out curve over ~30s)
let progressTask = Task {
let startTime = Date()
let duration: Double = 30.0
while !Task.isCancelled {
let elapsed = Date().timeIntervalSince(startTime)
let t = min(elapsed / duration, 1.0)
// Ease-out: fast at start, slow at end
let eased = 1.0 - pow(1.0 - t, 3.0)
let newProgress = 0.6 + eased * 0.3 // 60% → 90%
await MainActor.run {
progress = min(newProgress, 0.89) // Cap at 89% until AI finishes
}
try? await Task.sleep(nanoseconds: 200_000_000) // 200ms
}
}
// Run AI exploration in background — don't wait for it to complete
Task { await startExplorationChat() }
// Just wait a fixed time for the exploration to make progress, then move on
try? await Task.sleep(nanoseconds: 45_000_000_000) // 45s
log("FileIndexingView: AI exploration timeout reached, moving to knowledge graph build")
// Cancel progress animation and jump to 90%
progressTask.cancel()
await MainActor.run {
progress = 0.9
}
}
/// Stage 3: Load knowledge graph, progress 90% → 100%
/// The AI exploration session populates the local graph via save_knowledge_graph tool.
/// We poll the local SQLite briefly, then fall back to API if needed.
private func runKnowledgeGraphBuild() async {
await MainActor.run {
statusText = "Building your knowledge graph..."
scanningFolder = ""
progress = 0.92
}
AnalyticsManager.shared.knowledgeGraphBuildStarted(
filesIndexed: totalFilesScanned,
hadExistingGraph: false
)
// Poll local SQLite — the exploration chat is still running and will call
// save_knowledge_graph when it finishes extracting entities
let maxAttempts = 20 // 20 × 2s = 40s max
for attempt in 1...maxAttempts {
try? await Task.sleep(nanoseconds: 2_000_000_000)
let localEmpty = await KnowledgeGraphStorage.shared.isEmpty()
if !localEmpty {
log("FileIndexingView: Local graph ready after \(attempt) polls")
await graphViewModel.loadGraph()
AnalyticsManager.shared.knowledgeGraphBuildCompleted(
nodeCount: 0,
edgeCount: 0,
pollAttempts: attempt,
hadExistingGraph: false
)
await MainActor.run {
progress = 1.0
statusText = "Done"
}
try? await Task.sleep(nanoseconds: 500_000_000)
return
}
// Update progress smoothly 92% → 98%
let p = 0.92 + Double(attempt) / Double(maxAttempts) * 0.06
await MainActor.run { progress = p }
log("FileIndexingView: Local graph poll \(attempt)/\(maxAttempts), still empty")
}
// Local graph still empty — try loading from API (user may have one from mobile)
log("FileIndexingView: Local graph empty after polling, trying API")
await graphViewModel.loadGraph()
if graphViewModel.isEmpty {
AnalyticsManager.shared.knowledgeGraphBuildFailed(
reason: "local_empty_api_empty",
pollAttempts: maxAttempts,
filesIndexed: totalFilesScanned
)
} else {
AnalyticsManager.shared.knowledgeGraphBuildCompleted(
nodeCount: 0,
edgeCount: 0,
pollAttempts: maxAttempts,
hadExistingGraph: true
)
}
await MainActor.run {
progress = 1.0
statusText = "Done"
}
// Brief pause to show 100%
try? await Task.sleep(nanoseconds: 500_000_000)
}
// MARK: - Helpers
/// Scan /Applications and ~/Applications for app names
private func scanApplicationNames() async -> Int {
await MainActor.run {
scanningFolder = "Applications"
}
let home = FileManager.default.homeDirectoryForCurrentUser
let appDirs = [
URL(fileURLWithPath: "/Applications"),
home.appendingPathComponent("Applications"),
]
var count = 0
for dir in appDirs {
let scanned = await FileIndexerService.shared.scanFolders([dir])
count += scanned
}
return count
}
/// Send the exploration prompt to the chat
private func startExplorationChat() async {
// Multi-chat users get a dedicated session; single-chat users stay in default chat
if chatProvider.multiChatEnabled {
let session = await chatProvider.createNewSession(skipGreeting: true)
guard session != nil else {
log("FileIndexingView: Failed to create session for file exploration")
return
}
}
let prompt = """
I just indexed \(totalFilesScanned) files on your computer. Explore them to learn about me, then build my knowledge graph.
Use execute_sql to query the indexed_files table (columns: path, filename, fileExtension, fileType, sizeBytes, folder, depth, createdAt, modifiedAt). Do 3-5 queries:
1. Overview: file types, folders, project indicators (package.json, Cargo.toml, etc.)
2. Recently modified files to see what I'm working on now
3. Dig into interesting patterns — tech stack, recurring themes
CRITICAL RESPONSE FORMAT:
- Each message to me: MAX 1-2 sentences. No essays, no bullet lists, no headers.
- Just quick observations like "You've got 3 active Rust projects and heavy VS Code usage."
- Save the detailed analysis for the knowledge graph — don't dump it in chat.
After exploring, call save_knowledge_graph with all entities and relationships you found. Extract:
- People (me, collaborators, companies I work with)
- Organizations (companies, teams, services)
- Things (projects, repos, tools, languages, frameworks)
- Concepts (domains, interests, skills)
- Relationships between them (uses, works_on, built_with, part_of, etc.)
Aim for 15-40 nodes and meaningful edges connecting them.
After saving the graph, end with ONE sentence summarizing what you found about me overall.
"""
await chatProvider.sendMessage(prompt)
// Track chat messages for info popover
await MainActor.run {
chatMessages = chatProvider.messages
.filter { $0.sender == .ai }
.map { String($0.text.prefix(200)) }
}
// Append the AI's exploration response to the user's AI profile
// and inject a collapsible discovery card into the chat
await appendExplorationToProfile()
// Inject discovery card with the full profile text
await injectDiscoveryCard()
// Follow up: concise actionable suggestion
await chatProvider.sendMessage("What's one specific thing you could help me finish right now? One sentence.")
}
/// Append the AI's file exploration response to the latest AI user profile
private func appendExplorationToProfile() async {
// Get the last AI message (the exploration response)
guard let lastAIMessage = chatProvider.messages.last(where: { $0.sender == .ai }),
!lastAIMessage.text.isEmpty
else {
log("FileIndexingView: No AI response to append to profile")
return
}
let service = AIUserProfileService.shared
let existingProfile = await service.getLatestProfile()
if let existing = existingProfile, let profileId = existing.id {
// Append to existing profile
let updated = existing.profileText + "\n\n--- File Exploration Insights ---\n" + lastAIMessage.text
let success = await service.updateProfileText(id: profileId, newText: updated)
log("FileIndexingView: Appended exploration to AI profile (success=\(success))")
} else {
// No profile exists yet — create one via generation, or save directly
// For now, trigger a full generation which will pick up the new data
log("FileIndexingView: No existing AI profile, triggering generation")
_ = try? await service.generateProfile()
}
}
/// Inject a collapsible discovery card into the chat with the full AI exploration text
private func injectDiscoveryCard() async {
// Collect all AI messages from the exploration as the full profile text
let aiMessages = chatProvider.messages
.filter { $0.sender == .ai }
.map { $0.text.trimmingCharacters(in: .whitespacesAndNewlines) }
.filter { !$0.isEmpty }
guard !aiMessages.isEmpty else { return }
let fullText = aiMessages.joined(separator: "\n\n")
// Build a short summary from the last AI message
let lastMsg = aiMessages.last ?? ""
let summary = lastMsg.count > 120 ? String(lastMsg.prefix(120)) + "..." : lastMsg
await MainActor.run {
chatProvider.appendDiscoveryCard(
title: "Your Digital Profile",
summary: summary,
fullText: fullText
)
}
log("FileIndexingView: Injected discovery card into chat")
}
private func skip() {
log("FileIndexingView: User skipped file indexing")
UserDefaults.standard.set(true, forKey: "hasCompletedFileIndexing")
onComplete(0)
}
}