forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatLabView.swift
More file actions
1166 lines (1014 loc) · 40.7 KB
/
Copy pathChatLabView.swift
File metadata and controls
1166 lines (1014 loc) · 40.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import OmiTheme
import SwiftUI
// MARK: - Data Models
struct LabQuestion: Identifiable {
let id = UUID()
var text: String
var contextType: String // memories, conversations, screen, search, tasks
}
struct LabEvaluation: Identifiable {
let id = UUID()
let questionText: String
var response: String = ""
var aiScore: Int = 0
var aiComment: String = ""
var humanScore: Int = 0
var humanComment: String = ""
var isRunning: Bool = false
}
struct LabPromptVersion: Identifiable {
let id = UUID()
var name: String
var floatingPrefix: String
var mainPrompt: String
var evaluations: [LabEvaluation] = []
var avgAIScore: Double {
evaluations.isEmpty ? 0 : Double(evaluations.map(\.aiScore).reduce(0, +)) / Double(evaluations.count)
}
var avgHumanScore: Double {
evaluations.isEmpty ? 0 : Double(evaluations.map(\.humanScore).reduce(0, +)) / Double(evaluations.count)
}
}
/// A historical prompt version with production rating data
struct PromptHistoryEntry: Identifiable {
let id = UUID()
let version: Int
let date: String // "Apr 7"
let commitMsg: String
let commitHash: String
var thumbsUp: Int = 0
var thumbsDown: Int = 0
var promptSnippet: String = "" // First ~200 chars of the prompt at that version
var fullPrompt: String = ""
/// Satisfaction ratio: likes / (likes + dislikes). 1.0 = perfect, 0.0 = all dislikes.
var satisfactionRatio: Double {
let total = thumbsUp + thumbsDown
guard total > 0 else { return 0 }
return Double(thumbsUp) / Double(total)
}
/// Formatted as percentage
var satisfactionPct: String {
let total = thumbsUp + thumbsDown
guard total > 0 else { return "—" }
return "\(Int(satisfactionRatio * 100))%"
}
}
// MARK: - View Model
@MainActor
class ChatLabViewModel: ObservableObject {
@Published var questions: [LabQuestion] = []
@Published var versions: [LabPromptVersion] = []
@Published var selectedVersionIndex: Int = 0
@Published var isRunningAll = false
@Published var isGenerating = false
@Published var editingFloatingPrefix = ""
@Published var editingMainPrompt = ""
@Published var promptHistory: [PromptHistoryEntry] = []
@Published var isLoadingHistory = false
@Published var expandedHistoryVersion: Int? = nil
let chatProvider: ChatProvider
/// User must provide their own Anthropic API key for ChatLab.
/// Persisted in UserDefaults so they don't have to re-enter each session.
@Published var userApiKey: String {
didSet { UserDefaults.standard.set(userApiKey, forKey: "chatlab_anthropic_api_key") }
}
private var anthropicKey: String {
userApiKey.trimmingCharacters(in: .whitespacesAndNewlines)
}
init(chatProvider: ChatProvider) {
self.chatProvider = chatProvider
self.userApiKey = UserDefaults.standard.string(forKey: "chatlab_anthropic_api_key") ?? ""
loadDefaultQuestions()
loadCurrentPrompt()
// Load history in background — don't block the UI
Task.detached(priority: .background) { [weak self] in
guard let self else { return }
await self.loadPromptHistory()
}
}
func loadDefaultQuestions() {
questions = [
LabQuestion(text: "what should I focus on today?", contextType: "tasks"),
LabQuestion(text: "summarize my last conversation", contextType: "conversations"),
LabQuestion(text: "what do you know about me?", contextType: "memories"),
LabQuestion(text: "how old am I?", contextType: "memories"),
LabQuestion(text: "what apps did I use most today?", contextType: "tasks"),
LabQuestion(text: "what did I talk about with my team?", contextType: "conversations"),
LabQuestion(text: "which option should I pick?", contextType: "screen"),
LabQuestion(text: "compare these two for me", contextType: "search"),
LabQuestion(text: "create a task to follow up with John", contextType: "tasks"),
LabQuestion(text: "what meetings do I have tomorrow?", contextType: "conversations"),
]
}
// MARK: - Production Prompt History
/// Load prompt version history by checking git commits that modified the prompt files,
/// then fetch ratings from the Omi backend API and attribute them to each version.
func loadPromptHistory() async {
isLoadingHistory = true
// 1. Get git log of prompt-changing commits
let versions = await getPromptVersionsFromGit()
// 2. Fetch all rated messages from the backend
let ratings = await fetchRatingsFromBackend()
// 3. Attribute ratings to versions by date range
var history = versions
for i in 0..<history.count {
let versionDate = history[i].date
let nextDate = i + 1 < history.count ? history[i + 1].date : nil
for (dateStr, up, down) in ratings {
// Check if this rating falls within this version's date range
if dateStr >= versionDate && (nextDate == nil || dateStr < nextDate!) {
history[i].thumbsUp += up
history[i].thumbsDown += down
}
}
}
promptHistory = history
isLoadingHistory = false
}
/// Locate the repository root by walking up from this source file until a
/// `.git` directory is found. Returns nil in a shipped `.app` (or a moved
/// checkout) where the compile-time source path no longer exists — the
/// prompt-history feature then degrades to empty rather than shelling out
/// against a foreign hardcoded path.
private func repoRootFromSource() -> String? {
var dir = URL(fileURLWithPath: #filePath).deletingLastPathComponent()
for _ in 0..<12 {
if FileManager.default.fileExists(atPath: dir.appendingPathComponent(".git").path) {
return dir.path
}
let parent = dir.deletingLastPathComponent()
if parent.path == dir.path { break }
dir = parent
}
return nil
}
/// Parse git log for commits that changed ChatPrompts.swift or ChatProvider's floating prefix
private func getPromptVersionsFromGit() async -> [PromptHistoryEntry] {
// Resolve the repo root from the source location instead of a hardcoded
// developer path; bail cleanly when it can't be found (e.g. shipped app).
guard let repoPath = repoRootFromSource() else {
log("ChatLab: repo root not found from source path; skipping git prompt history")
return []
}
let promptFile = "desktop/macos/Desktop/Sources/Chat/ChatPrompts.swift"
let providerFile = "desktop/macos/Desktop/Sources/Providers/ChatProvider.swift"
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/git")
process.arguments = [
"-C", repoPath, "log", "--format=%H|%ci|%s", "-n", "30", "origin/main", "--", promptFile, providerFile,
]
let pipe = Pipe()
process.standardOutput = pipe
process.standardError = Pipe()
do {
try process.run()
// Timeout after 10 seconds
let deadline = Date().addingTimeInterval(10)
while process.isRunning && Date() < deadline {
try? await Task.sleep(nanoseconds: 100_000_000)
}
if process.isRunning { process.terminate() }
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8) ?? ""
let lines = output.components(separatedBy: "\n").filter { !$0.isEmpty }
// Deduplicate by date and take last 10
var seenDates = Set<String>()
var entries: [PromptHistoryEntry] = []
for line in lines {
let parts = line.components(separatedBy: "|")
guard parts.count >= 3 else { continue }
let hash = parts[0]
let dateRaw = String(parts[1].prefix(10)) // "2026-04-09"
let msg = parts[2]
// Only one version per day
guard !seenDates.contains(dateRaw) else { continue }
seenDates.insert(dateRaw)
// Get the prompt content at this commit
let promptContent = getFileAtCommit(repoPath: repoPath, hash: hash, file: promptFile)
let snippet = String(promptContent.prefix(200))
entries.append(
PromptHistoryEntry(
version: 0,
date: dateRaw,
commitMsg: msg,
commitHash: String(hash.prefix(8)),
promptSnippet: snippet.isEmpty ? "—" : snippet + "...",
fullPrompt: promptContent
))
if entries.count >= 10 { break }
}
// Number versions in reverse (most recent = highest)
for i in 0..<entries.count {
entries[i] = PromptHistoryEntry(
version: entries.count - i,
date: entries[i].date,
commitMsg: entries[i].commitMsg,
commitHash: entries[i].commitHash,
promptSnippet: entries[i].promptSnippet,
fullPrompt: entries[i].fullPrompt
)
}
return entries.reversed() // oldest first
} catch {
log("ChatLab: git log failed: \(error)")
return []
}
}
private func getFileAtCommit(repoPath: String, hash: String, file: String) -> String {
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/git")
process.arguments = ["-C", repoPath, "show", "\(hash):\(file)"]
let pipe = Pipe()
process.standardOutput = pipe
process.standardError = Pipe() // suppress errors
do {
try process.run()
process.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
return String(data: data, encoding: .utf8) ?? ""
} catch {
return ""
}
}
/// Fetch rated messages from the Omi backend, return (date, ups, downs) tuples
private func fetchRatingsFromBackend() async -> [(String, Int, Int)] {
do {
let authHeader = try await AuthService.shared.getAuthHeader()
// Fetch messages with ratings from the last 60 days
let baseURL = await APIClient.shared.baseURL
let url = URL(string: "\(baseURL)v2/messages?limit=500")!
var request = URLRequest(url: url)
request.setValue(authHeader, forHTTPHeaderField: "Authorization")
let (data, _) = try await URLSession.shared.data(for: request)
let messages = try JSONSerialization.jsonObject(with: data) as? [[String: Any]] ?? []
// Group by date
var byDate: [String: (up: Int, down: Int)] = [:]
let dateFmt = DateFormatter()
dateFmt.dateFormat = "yyyy-MM-dd"
for msg in messages {
guard let rating = msg["rating"] as? Int, rating != 0 else { continue }
let createdAt = msg["created_at"] as? String ?? ""
let dateStr = String(createdAt.prefix(10))
guard !dateStr.isEmpty else { continue }
var entry = byDate[dateStr] ?? (up: 0, down: 0)
if rating > 0 { entry.up += 1 } else { entry.down += 1 }
byDate[dateStr] = entry
}
return byDate.map { ($0.key, $0.value.up, $0.value.down) }
.sorted { $0.0 < $1.0 }
} catch {
log("ChatLab: Failed to fetch ratings: \(error)")
return []
}
}
private func inferContextType(_ text: String) -> String {
let lower = text.lowercased()
if lower.contains("task") || lower.contains("focus") || lower.contains("todo") || lower.contains("create a") {
return "tasks"
}
if lower.contains("talk") || lower.contains("conversation") || lower.contains("meeting") || lower.contains("call")
|| lower.contains("said")
{
return "conversations"
}
if lower.contains("screen") || lower.contains("option") || lower.contains("pick") || lower.contains("which")
|| lower.contains("see")
{
return "screen"
}
if lower.contains("compare") || lower.contains("search") || lower.contains("find") || lower.contains("look up") {
return "search"
}
return "memories"
}
func loadCurrentPrompt() {
let floatingPrefix = ChatProvider.floatingBarSystemPromptPrefix
let mainPrompt = ChatPromptBuilder.buildDesktopChat(
userName: "{user_name}",
memoriesSection: "{memories_section}",
goalSection: "{goal_section}",
tasksSection: "{tasks_section}",
aiProfileSection: "{ai_profile_section}",
databaseSchema: "{database_schema}"
)
editingFloatingPrefix = floatingPrefix
editingMainPrompt = mainPrompt
if versions.isEmpty {
versions.append(
LabPromptVersion(
name: "v1 (current)",
floatingPrefix: floatingPrefix,
mainPrompt: mainPrompt
))
}
}
func runAllQuestions() async {
isRunningAll = true
let vIdx = selectedVersionIndex
guard vIdx < versions.count else {
isRunningAll = false
return
}
var evals: [LabEvaluation] = []
for q in questions {
evals.append(LabEvaluation(questionText: q.text))
}
versions[vIdx].evaluations = evals
for i in 0..<questions.count {
let q = questions[i]
versions[vIdx].evaluations[i].isRunning = true
// Build the real system prompt — same as ChatProvider does
let systemPrompt = buildRealSystemPrompt(version: versions[vIdx])
// Run through the real agent bridge (with tools, real context)
let response = await runThroughBridge(
question: q.text,
systemPrompt: systemPrompt,
labSessionId: "chat-lab-\(vIdx)-\(i)"
)
versions[vIdx].evaluations[i].response = response
// AI-grade the response
let (aiScore, aiComment) = await gradeResponse(question: q.text, response: response)
versions[vIdx].evaluations[i].aiScore = aiScore
versions[vIdx].evaluations[i].aiComment = aiComment
versions[vIdx].evaluations[i].isRunning = false
}
isRunningAll = false
}
/// Build a system prompt using the version's template with real user context.
/// Uses ChatProvider's public labBuildSystemPrompt() for the real context injection.
private func buildRealSystemPrompt(version: LabPromptVersion) -> String {
let chatProvider = chatProvider
return chatProvider.labBuildSystemPrompt(
floatingPrefix: version.floatingPrefix,
mainTemplate: version.mainPrompt
)
}
/// Send a question through the real agent bridge (same path as floating bar / main chat).
/// Falls back to direct API if bridge isn't available.
private func runThroughBridge(question: String, systemPrompt: String, labSessionId: String) async -> String {
let chatProvider = chatProvider
let result = await chatProvider.labRunQuestion(
question: question,
systemPrompt: systemPrompt,
labSessionId: labSessionId
)
return result
}
func generateNextVersion() async {
guard !anthropicKey.isEmpty else { return }
isGenerating = true
let currentVersion = versions[selectedVersionIndex]
let evalSummary = currentVersion.evaluations.map { e in
"Q: \(e.questionText)\nResponse: \(e.response.prefix(200))\nAI Score: \(e.aiScore)/5 (\(e.aiComment))\nHuman Score: \(e.humanScore)/5 (\(e.humanComment))"
}.joined(separator: "\n---\n")
let metaPrompt = """
You are an expert prompt engineer. Below is a system prompt for an AI assistant called Omi, and the evaluation results from testing it with real user questions.
CURRENT FLOATING BAR PREFIX:
\(currentVersion.floatingPrefix)
CURRENT MAIN PROMPT:
\(currentVersion.mainPrompt)
EVALUATION RESULTS:
\(evalSummary)
Based on the evaluation results, generate an IMPROVED version of the prompt. Focus on:
- Questions that scored low — what context or instruction was missing?
- Making responses more personalized and specific
- Reducing generic/vague answers
- Keeping responses concise (1-3 sentences for floating bar)
Return ONLY the improved main prompt (not the floating bar prefix — keep that as-is). Do not explain your changes, just output the new prompt.
"""
let (newPrompt, _, _) = await callClaude(
systemPrompt: "You are a prompt engineering expert.", userMessage: metaPrompt)
if !newPrompt.isEmpty {
let newVersion = LabPromptVersion(
name: "v\(versions.count + 1)",
floatingPrefix: currentVersion.floatingPrefix,
mainPrompt: newPrompt
)
versions.append(newVersion)
selectedVersionIndex = versions.count - 1
editingFloatingPrefix = newVersion.floatingPrefix
editingMainPrompt = newVersion.mainPrompt
}
isGenerating = false
}
func saveAsNewVersion(name: String) {
let newVersion = LabPromptVersion(
name: name,
floatingPrefix: editingFloatingPrefix,
mainPrompt: editingMainPrompt
)
versions.append(newVersion)
selectedVersionIndex = versions.count - 1
}
private func callClaude(systemPrompt: String, userMessage: String) async -> (String, Int, String) {
guard !anthropicKey.isEmpty else { return ("No API key", 0, "") }
do {
let url = URL(string: "https://api.anthropic.com/v1/messages")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(anthropicKey, forHTTPHeaderField: "x-api-key")
request.setValue("2023-06-01", forHTTPHeaderField: "anthropic-version")
let body: [String: Any] = [
"model": ModelQoS.Claude.chatLabQuery,
"max_tokens": 1024,
"system": systemPrompt.prefix(50000),
"messages": [["role": "user", "content": userMessage]],
]
request.httpBody = try JSONSerialization.data(withJSONObject: body)
let (data, _) = try await URLSession.shared.data(for: request)
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
let content = json?["content"] as? [[String: Any]]
let responseText = content?.first?["text"] as? String ?? "No response"
// Grade the response
let (aiScore, aiComment) = await gradeResponse(question: userMessage, response: responseText)
return (responseText, aiScore, aiComment)
} catch {
log("ChatLab: Claude API error: \(error)")
return ("Error: \(error.localizedDescription)", 0, "")
}
}
private func gradeResponse(question: String, response: String) async -> (Int, String) {
do {
let url = URL(string: "https://api.anthropic.com/v1/messages")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(anthropicKey, forHTTPHeaderField: "x-api-key")
request.setValue("2023-06-01", forHTTPHeaderField: "anthropic-version")
let gradePrompt = """
Rate this AI assistant response on a 0-5 scale. Consider:
- Relevance to the question
- Personalization (does it use user context?)
- Conciseness (is it brief and direct?)
- Helpfulness (does it actually help?)
Question: \(question)
Response: \(response)
Reply with ONLY a JSON object: {"score": N, "comment": "brief reason"}
"""
let body: [String: Any] = [
"model": ModelQoS.Claude.chatLabGrade,
"max_tokens": 200,
"messages": [["role": "user", "content": gradePrompt]],
]
request.httpBody = try JSONSerialization.data(withJSONObject: body)
let (data, _) = try await URLSession.shared.data(for: request)
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
let content = json?["content"] as? [[String: Any]]
let text = content?.first?["text"] as? String ?? ""
// Parse JSON from response
if let jsonData = text.data(using: .utf8),
let grade = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any]
{
let score = grade["score"] as? Int ?? 0
let comment = grade["comment"] as? String ?? ""
return (score, comment)
}
return (0, "Failed to parse grade")
} catch {
return (0, "Grading error")
}
}
}
// MARK: - Chat Lab View
struct ChatLabView: View {
let chatProvider: ChatProvider
@StateObject private var vm: ChatLabViewModel
@State private var showSaveDialog = false
@State private var newVersionName = ""
init(chatProvider: ChatProvider) {
self.chatProvider = chatProvider
_vm = StateObject(wrappedValue: ChatLabViewModel(chatProvider: chatProvider))
}
var body: some View {
ScrollView {
VStack(spacing: OmiSpacing.xxl) {
promptHistorySection
promptEditorSection
evaluationSection
versionComparisonSection
}
.padding(OmiSpacing.xxl)
}
.frame(minWidth: 900, minHeight: 600)
// No ground of its own: the glass window owns it. `glassContent()` also pins the panel's light
// appearance, without which `Ink`'s ladder resolves up on a Dark Mac and the page goes blank.
.glassContent()
}
// MARK: - Production Prompt History
private var promptHistorySection: some View {
VStack(alignment: .leading, spacing: OmiSpacing.lg) {
HStack {
Text("Prompt Version History")
.scaledFont(size: OmiType.heading, weight: .semibold)
.foregroundColor(Ink.primary)
Spacer()
Button(action: {
Task { await vm.loadPromptHistory() }
}) {
HStack(spacing: OmiSpacing.xxs) {
if vm.isLoadingHistory {
ProgressView().scaleEffect(0.6).frame(width: 12, height: 12)
} else {
Image(systemName: "arrow.clockwise").scaledFont(size: OmiType.caption)
}
Text("Refresh").scaledFont(size: OmiType.caption, weight: .medium)
}
.foregroundColor(Ink.secondary)
}
.buttonStyle(.plain)
}
if vm.isLoadingHistory && vm.promptHistory.isEmpty {
HStack {
Spacer()
ProgressView()
Text("Loading git history & ratings...")
.scaledFont(size: OmiType.body)
.foregroundColor(Ink.secondary)
Spacer()
}
.padding(.vertical, OmiSpacing.page)
} else if vm.promptHistory.isEmpty {
Text("No prompt history found")
.scaledFont(size: OmiType.body)
.foregroundColor(Ink.secondary)
.frame(maxWidth: .infinity)
.padding(.vertical, OmiSpacing.page)
} else {
// Table header
HStack(spacing: 0) {
Text("V")
.frame(width: 30, alignment: .center)
Text("Date")
.frame(width: 70, alignment: .leading)
Text("Change")
.frame(maxWidth: .infinity, alignment: .leading)
Text("👍")
.frame(width: 40, alignment: .center)
Text("👎")
.frame(width: 40, alignment: .center)
Text("Score")
.frame(width: 60, alignment: .center)
}
.scaledFont(size: OmiType.caption, weight: .semibold)
.foregroundColor(Ink.secondary)
.padding(.horizontal, OmiSpacing.md)
.padding(.vertical, OmiSpacing.xs)
GlassSeparator()
ForEach(vm.promptHistory) { entry in
VStack(spacing: 0) {
Button(action: {
// Every animation in the glass system goes through `InkReduceMotion`, and the duration
// comes off the motion table rather than being typed here.
InkReduceMotion.perform(.easeInOut(duration: InkMotion.stepTransition)) {
vm.expandedHistoryVersion = vm.expandedHistoryVersion == entry.version ? nil : entry.version
}
}) {
HStack(spacing: 0) {
Text("v\(entry.version)")
.scaledFont(size: OmiType.body, weight: .semibold)
.foregroundColor(Ink.accent)
.frame(width: 30, alignment: .center)
Text(formatHistoryDate(entry.date))
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
.frame(width: 70, alignment: .leading)
Text(entry.commitMsg)
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.primary)
.lineLimit(1)
.frame(maxWidth: .infinity, alignment: .leading)
let total = entry.thumbsUp + entry.thumbsDown
Text("\(entry.thumbsUp)")
.scaledFont(size: OmiType.body, weight: .medium)
.foregroundColor(Ink.listeningGreen)
.frame(width: 40, alignment: .center)
Text("\(entry.thumbsDown)")
.scaledFont(size: OmiType.body, weight: .medium)
.foregroundColor(Ink.errorRed)
.frame(width: 40, alignment: .center)
// Satisfaction score: single number
Group {
if total == 0 {
Text("—")
.foregroundColor(Ink.secondary)
} else {
Text(entry.satisfactionPct)
.foregroundColor(satisfactionColor(entry.satisfactionRatio))
}
}
.scaledFont(size: OmiType.body, weight: .bold)
.frame(width: 60, alignment: .center)
Image(systemName: vm.expandedHistoryVersion == entry.version ? "chevron.up" : "chevron.down")
.scaledFont(size: OmiType.micro)
.foregroundColor(Ink.secondary)
.frame(width: 20)
}
.padding(.horizontal, OmiSpacing.md)
.padding(.vertical, OmiSpacing.sm)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
// Expanded: show full prompt
if vm.expandedHistoryVersion == entry.version {
VStack(alignment: .leading, spacing: OmiSpacing.sm) {
Text("Commit: \(entry.commitHash)")
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
ScrollView {
Text(entry.fullPrompt.isEmpty ? "Prompt not available" : entry.fullPrompt)
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(maxHeight: 300)
.padding(OmiSpacing.md)
.glassField()
}
.padding(.horizontal, OmiSpacing.lg)
.padding(.bottom, OmiSpacing.md)
.transition(.opacity.combined(with: .move(edge: .top)))
}
if entry.version < vm.promptHistory.last?.version ?? 0 {
GlassSeparator().padding(.horizontal, OmiSpacing.md)
}
}
}
}
}
.padding(OmiSpacing.xl)
.glassCard()
}
private func formatHistoryDate(_ dateStr: String) -> String {
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd"
guard let date = fmt.date(from: dateStr) else { return dateStr }
let display = DateFormatter()
display.dateFormat = "MMM d"
return display.string(from: date)
}
private func satisfactionColor(_ ratio: Double) -> Color {
if ratio >= 0.75 { return Ink.listeningGreen }
if ratio >= 0.50 { return PageGlass.warning }
return Ink.errorRed
}
// MARK: - Prompt Editor
private var promptEditorSection: some View {
VStack(alignment: .leading, spacing: OmiSpacing.lg) {
HStack {
Text("Prompt Editor")
.scaledFont(size: OmiType.heading, weight: .semibold)
.foregroundColor(Ink.primary)
Spacer()
// Version picker
Picker("", selection: $vm.selectedVersionIndex) {
ForEach(vm.versions.indices, id: \.self) { i in
Text(vm.versions[i].name).tag(i)
}
}
.pickerStyle(.menu)
.frame(width: 180)
.onChange(of: vm.selectedVersionIndex) { _, idx in
if idx < vm.versions.count {
vm.editingFloatingPrefix = vm.versions[idx].floatingPrefix
vm.editingMainPrompt = vm.versions[idx].mainPrompt
}
}
}
// Anthropic API key (user must provide their own)
VStack(alignment: .leading, spacing: OmiSpacing.xs) {
Text("Anthropic API Key")
.scaledFont(size: OmiType.caption, weight: .medium)
.foregroundColor(Ink.secondary)
SecureField("sk-ant-...", text: $vm.userApiKey)
.textFieldStyle(.plain)
.font(.system(size: 12, design: .monospaced))
.foregroundColor(Ink.primary)
.padding(OmiSpacing.sm)
.glassField()
if vm.userApiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
Text("Enter your own Anthropic API key to use ChatLab evaluation features.")
.scaledFont(size: OmiType.caption)
.foregroundColor(PageGlass.warning)
}
}
// Floating prefix
VStack(alignment: .leading, spacing: OmiSpacing.xs) {
Text("Floating Bar Prefix")
.scaledFont(size: OmiType.caption, weight: .medium)
.foregroundColor(Ink.secondary)
TextEditor(text: $vm.editingFloatingPrefix)
.font(.system(size: 12, design: .monospaced))
.foregroundColor(Ink.primary)
// A `TextEditor` paints an opaque ground of its own, which on glass is a grey slab.
.scrollContentBackground(.hidden)
.frame(height: 100)
.padding(OmiSpacing.sm)
.glassField()
}
// Main prompt
VStack(alignment: .leading, spacing: OmiSpacing.xs) {
Text("Main Prompt")
.scaledFont(size: OmiType.caption, weight: .medium)
.foregroundColor(Ink.secondary)
TextEditor(text: $vm.editingMainPrompt)
.font(.system(size: 12, design: .monospaced))
.foregroundColor(Ink.primary)
// A `TextEditor` paints an opaque ground of its own, which on glass is a grey slab.
.scrollContentBackground(.hidden)
.frame(height: 200)
.padding(OmiSpacing.sm)
.glassField()
}
HStack(spacing: OmiSpacing.md) {
Button(action: { showSaveDialog = true }) {
HStack(spacing: OmiSpacing.xs) {
Image(systemName: "square.and.arrow.down")
.scaledFont(size: OmiType.caption)
Text("Save as New Version")
}
}
.buttonStyle(OmiButtonStyle(.primary, size: .compact))
Button(action: {
Task { await vm.generateNextVersion() }
}) {
HStack(spacing: OmiSpacing.xs) {
if vm.isGenerating {
ProgressView()
.scaleEffect(0.6)
.frame(width: 14, height: 14)
} else {
Image(systemName: "sparkles")
.scaledFont(size: OmiType.caption)
}
Text("Generate Next Version")
}
}
.buttonStyle(OmiButtonStyle(.secondary, size: .compact))
.disabled(vm.isGenerating)
}
}
.padding(OmiSpacing.xl)
.glassCard()
.alert("Save as New Version", isPresented: $showSaveDialog) {
TextField("Version name", text: $newVersionName)
Button("Save") {
if !newVersionName.isEmpty {
vm.saveAsNewVersion(name: newVersionName)
newVersionName = ""
}
}
Button("Cancel", role: .cancel) { newVersionName = "" }
}
}
// MARK: - Evaluation Section
private var evaluationSection: some View {
VStack(alignment: .leading, spacing: OmiSpacing.lg) {
HStack {
Text("Evaluation")
.scaledFont(size: OmiType.heading, weight: .semibold)
.foregroundColor(Ink.primary)
Spacer()
Button(action: {
Task { await vm.runAllQuestions() }
}) {
HStack(spacing: OmiSpacing.xs) {
if vm.isRunningAll {
ProgressView()
.scaleEffect(0.6)
.frame(width: 14, height: 14)
} else {
Image(systemName: "play.fill")
.scaledFont(size: OmiType.caption)
}
Text("Run All Questions")
}
}
// `disabled` is the whole "running" treatment now: the style dims a disabled button, so a
// second grey fill for the same state was two ways of saying it and one of them could rot.
.buttonStyle(OmiButtonStyle(.primary, size: .compact))
.disabled(vm.isRunningAll)
}
// Questions table
VStack(spacing: 0) {
// Header
HStack {
Text("Question")
.scaledFont(size: OmiType.caption, weight: .semibold)
.foregroundColor(Ink.secondary)
.frame(width: 200, alignment: .leading)
Text("Context")
.scaledFont(size: OmiType.caption, weight: .semibold)
.foregroundColor(Ink.secondary)
.frame(width: 80)
Text("Response")
.scaledFont(size: OmiType.caption, weight: .semibold)
.foregroundColor(Ink.secondary)
.frame(maxWidth: .infinity, alignment: .leading)
Text("AI")
.scaledFont(size: OmiType.caption, weight: .semibold)
.foregroundColor(Ink.secondary)
.frame(width: 40)
Text("You")
.scaledFont(size: OmiType.caption, weight: .semibold)
.foregroundColor(Ink.secondary)
.frame(width: 80)
}
.padding(.horizontal, OmiSpacing.md)
.padding(.vertical, OmiSpacing.sm)
GlassSeparator()
// Rows
let evals =
vm.selectedVersionIndex < vm.versions.count
? vm.versions[vm.selectedVersionIndex].evaluations
: []
ForEach(vm.questions.indices, id: \.self) { qi in
let q = vm.questions[qi]
let eval = qi < evals.count ? evals[qi] : nil
HStack(alignment: .top) {
Text(q.text)
.scaledFont(size: OmiType.body)
.foregroundColor(Ink.primary)
.frame(width: 200, alignment: .leading)
.lineLimit(3)
contextBadge(q.contextType)
.frame(width: 80)
if let eval = eval {
if eval.isRunning {
HStack(spacing: OmiSpacing.xs) {
ProgressView().scaleEffect(0.6)
Text("Running...")
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
}
.frame(maxWidth: .infinity, alignment: .leading)
} else if eval.response.isEmpty {
Text("Not evaluated")
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
.frame(maxWidth: .infinity, alignment: .leading)
} else {
Text(eval.response)
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
.frame(maxWidth: .infinity, alignment: .leading)
.textSelection(.enabled)
}
// AI score
Text("\(eval.aiScore)")
.scaledFont(size: OmiType.body, weight: .semibold)
.foregroundColor(scoreColor(eval.aiScore))
.frame(width: 40)
// Human rating stars
starRating(
score: Binding(