forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTaskTestRunnerWindow.swift
More file actions
646 lines (562 loc) · 20.2 KB
/
Copy pathTaskTestRunnerWindow.swift
File metadata and controls
646 lines (562 loc) · 20.2 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
import Cocoa
import OmiTheme
import SwiftUI
// MARK: - Test Result Model
struct TaskTestResult: Identifiable {
let id = UUID()
let index: Int
let timestamp: Date
let appName: String
let windowTitle: String?
let result: TaskExtractionResult?
let error: String?
let duration: TimeInterval
let searchCount: Int
}
// MARK: - SwiftUI View
struct TaskTestRunnerView: View {
@State private var periodFrom: Date = Calendar.current.date(byAdding: .hour, value: -24, to: Date()) ?? Date()
@State private var periodTo: Date = Date()
@State private var isRunning = false
@State private var results: [TaskTestResult] = []
@State private var progress: Double = 0
@State private var elapsedTime: TimeInterval = 0
@State private var statusMessage = "Ready"
@State private var cancellationRequested = false
@State private var totalContextSwitches = 0
var onClose: (() -> Void)?
private var tasksFound: Int {
results.filter { $0.result?.hasNewTask == true }.count
}
private var errorsCount: Int {
results.filter { $0.error != nil }.count
}
private var totalSearches: Int {
results.reduce(0) { $0 + $1.searchCount }
}
var body: some View {
VStack(spacing: 0) {
// Header
header
.padding(OmiSpacing.xl)
Divider()
// Column headers
columnHeaders
.padding(.horizontal, OmiSpacing.xl)
.padding(.vertical, OmiSpacing.xs)
.background(Ink.rowFill)
Divider()
// Results
ScrollViewReader { proxy in
ScrollView {
LazyVStack(spacing: OmiSpacing.hairline) {
ForEach(results) { result in
resultRow(result)
.id(result.id)
}
}
.padding(.vertical, OmiSpacing.sm)
}
.onChange(of: results.count) { _, _ in
if let last = results.last {
OmiMotion.withGated {
proxy.scrollTo(last.id, anchor: .bottom)
}
}
}
}
Divider()
// Footer
footer
.padding(OmiSpacing.lg)
}
.frame(width: 1400, height: 900)
.inkGlassPanel(cornerRadius: 0, shadow: nil)
}
// MARK: - Header
private var header: some View {
VStack(spacing: OmiSpacing.lg) {
HStack {
VStack(alignment: .leading, spacing: OmiSpacing.xxs) {
Text("Task Extraction Test Runner")
.scaledFont(size: OmiType.subheading, weight: .semibold)
.foregroundColor(.primary)
Text("Replay departing frames from context switches through the extraction pipeline")
.scaledFont(size: OmiType.caption)
.foregroundColor(.secondary)
}
Spacer()
Button(action: { onClose?() }) {
Image(systemName: "xmark.circle.fill")
.scaledFont(size: OmiType.subheading)
.foregroundColor(.secondary)
}
.buttonStyle(.plain)
}
HStack(spacing: OmiSpacing.lg) {
// Time range pickers
HStack(spacing: OmiSpacing.sm) {
Text("From:")
.scaledFont(size: OmiType.body)
.foregroundColor(.secondary)
DatePicker("", selection: $periodFrom, in: ...periodTo)
.labelsHidden()
.datePickerStyle(.field)
.frame(width: 180)
.disabled(isRunning)
Text("To:")
.scaledFont(size: OmiType.body)
.foregroundColor(.secondary)
DatePicker("", selection: $periodTo, in: periodFrom...Date())
.labelsHidden()
.datePickerStyle(.field)
.frame(width: 180)
.disabled(isRunning)
}
Spacer()
// Run / Stop button
if isRunning {
Button(action: { cancellationRequested = true }) {
HStack(spacing: OmiSpacing.xxs) {
Image(systemName: "stop.fill")
.scaledFont(size: OmiType.micro)
Text("Stop")
.scaledFont(size: OmiType.caption)
}
}
.buttonStyle(.bordered)
.controlSize(.small)
.tint(.red)
} else {
Button(action: runTest) {
HStack(spacing: OmiSpacing.xxs) {
Image(systemName: "play.fill")
.scaledFont(size: OmiType.micro)
Text("Run Test")
.scaledFont(size: OmiType.caption)
}
}
.buttonStyle(.borderedProminent)
.controlSize(.small)
}
}
// Progress bar
if isRunning {
VStack(spacing: OmiSpacing.xxs) {
ProgressView(value: progress)
.tint(.accentColor)
Text(statusMessage)
.scaledFont(size: OmiType.caption)
.foregroundColor(.secondary)
}
}
}
}
// MARK: - Column Headers
private var columnHeaders: some View {
HStack(spacing: OmiSpacing.lg) {
Text("#")
.frame(width: 28, alignment: .trailing)
Text("Time")
.frame(width: 90, alignment: .leading)
Text("App")
.frame(width: 100, alignment: .leading)
Text("Window")
.frame(width: 250, alignment: .leading)
Text("Decision")
.frame(width: 100, alignment: .leading)
Text("Search")
.frame(width: 40, alignment: .leading)
Text("Details")
Spacer()
Text("Conf")
.frame(width: 40, alignment: .trailing)
Text("Time")
.frame(width: 50, alignment: .trailing)
}
.scaledFont(size: OmiType.caption, weight: .medium)
.foregroundColor(.secondary.opacity(0.7))
}
// MARK: - Result Row
private func resultRow(_ testResult: TaskTestResult) -> some View {
HStack(spacing: OmiSpacing.lg) {
// Index
Text("\(testResult.index)")
.scaledFont(size: OmiType.caption, design: .monospaced)
.foregroundColor(.secondary)
.frame(width: 28, alignment: .trailing)
// Timestamp
Text(testResult.timestamp, format: .dateTime.hour().minute().second())
.scaledFont(size: OmiType.caption, design: .monospaced)
.foregroundColor(.secondary)
.frame(width: 90, alignment: .leading)
// App name
Text(testResult.appName)
.scaledFont(size: OmiType.caption)
.foregroundColor(.secondary)
.frame(width: 100, alignment: .leading)
.lineLimit(1)
// Window title
Text(testResult.windowTitle ?? "—")
.scaledFont(size: OmiType.caption)
.foregroundColor(.secondary)
.frame(width: 250, alignment: .leading)
.fixedSize(horizontal: false, vertical: true)
// Decision column
decisionBadge(for: testResult)
.frame(width: 100, alignment: .leading)
// Search count indicator
if testResult.searchCount > 0 {
HStack(spacing: OmiSpacing.hairline) {
Image(systemName: "magnifyingglass")
.scaledFont(size: OmiType.micro)
Text("×\(testResult.searchCount)")
.scaledFont(size: OmiType.caption, design: .monospaced)
}
.foregroundColor(.secondary)
.frame(width: 40, alignment: .leading)
} else {
Text("")
.frame(width: 40)
}
// Task title or context summary
if let error = testResult.error {
Text(error)
.scaledFont(size: OmiType.caption)
.foregroundColor(.orange)
.lineLimit(2)
} else if let result = testResult.result {
if result.hasNewTask, let task = result.task {
VStack(alignment: .leading, spacing: OmiSpacing.hairline) {
Text(task.title)
.scaledFont(size: OmiType.caption, weight: .medium)
.foregroundColor(.primary)
.lineLimit(2)
HStack(spacing: OmiSpacing.sm) {
Text(task.priority.rawValue)
.scaledFont(size: OmiType.micro, weight: .medium)
.foregroundColor(.white)
.padding(.horizontal, OmiSpacing.xs)
.padding(.vertical, OmiSpacing.hairline)
.background(priorityColor(task.priority))
.cornerRadius(OmiChrome.stripRadius)
Text("\(task.sourceCategory)/\(task.sourceSubcategory)")
.scaledFont(size: OmiType.micro, weight: .medium)
.foregroundColor(.white)
.padding(.horizontal, OmiSpacing.xs)
.padding(.vertical, OmiSpacing.hairline)
.background(Color.teal.opacity(0.7))
.cornerRadius(OmiChrome.stripRadius)
Text(task.tags.joined(separator: ", "))
.scaledFont(size: OmiType.micro)
.foregroundColor(.secondary)
}
}
} else {
Text(result.contextSummary)
.scaledFont(size: OmiType.caption)
.foregroundColor(.secondary)
.lineLimit(2)
}
}
Spacer()
// Confidence (only for tasks)
if let result = testResult.result, result.hasNewTask, let task = result.task {
Text("\(Int(task.confidence * 100))%")
.scaledFont(size: OmiType.caption, weight: .medium, design: .monospaced)
.foregroundColor(.green)
.frame(width: 40, alignment: .trailing)
} else {
Text("")
.frame(width: 40)
}
// Duration
Text(String(format: "%.1fs", testResult.duration))
.scaledFont(size: OmiType.caption, design: .monospaced)
.foregroundColor(.secondary.opacity(0.7))
.frame(width: 50, alignment: .trailing)
}
.padding(.horizontal, OmiSpacing.xl)
.padding(.vertical, OmiSpacing.sm)
.background(testResult.result?.hasNewTask == true ? Color.green.opacity(0.05) : Color.clear)
}
private func decisionBadge(for testResult: TaskTestResult) -> some View {
Group {
if testResult.error != nil {
HStack(spacing: OmiSpacing.xxs) {
Image(systemName: "exclamationmark.triangle.fill")
.scaledFont(size: OmiType.micro)
Text("Error")
.scaledFont(size: OmiType.caption, weight: .medium)
}
.foregroundColor(.orange)
} else if let result = testResult.result {
if result.hasNewTask {
HStack(spacing: OmiSpacing.xxs) {
Image(systemName: "plus.circle.fill")
.scaledFont(size: OmiType.micro)
Text("New Task")
.scaledFont(size: OmiType.caption, weight: .medium)
}
.foregroundColor(.green)
} else {
HStack(spacing: OmiSpacing.xxs) {
Image(systemName: "minus.circle")
.scaledFont(size: OmiType.micro)
Text("No Task")
.scaledFont(size: OmiType.caption, weight: .medium)
}
.foregroundColor(.secondary)
}
}
}
}
private func priorityColor(_ priority: TaskPriority) -> Color {
switch priority {
case .high: return .red
case .medium: return .orange
case .low: return .blue
}
}
// MARK: - Footer
private var footer: some View {
HStack {
if !results.isEmpty {
HStack(spacing: OmiSpacing.lg) {
Label("\(results.count)/\(totalContextSwitches)", systemImage: "arrow.triangle.swap")
.scaledFont(size: OmiType.caption)
.foregroundColor(.secondary)
Label("\(tasksFound) tasks", systemImage: "checkmark.circle")
.scaledFont(size: OmiType.caption)
.foregroundColor(tasksFound > 0 ? .green : .secondary)
Label("\(totalSearches) searches", systemImage: "magnifyingglass")
.scaledFont(size: OmiType.caption)
.foregroundColor(totalSearches > 0 ? .blue : .secondary)
if errorsCount > 0 {
Label("\(errorsCount) errors", systemImage: "exclamationmark.triangle")
.scaledFont(size: OmiType.caption)
.foregroundColor(.orange)
}
if elapsedTime > 0 {
Label(String(format: "%.1fs total", elapsedTime), systemImage: "clock")
.scaledFont(size: OmiType.caption)
.foregroundColor(.secondary)
}
}
} else {
Text("Select a time range and click Run Test")
.scaledFont(size: OmiType.caption)
.foregroundColor(.secondary.opacity(0.7))
}
Spacer()
Button("Done") {
onClose?()
}
.keyboardShortcut(.return, modifiers: .command)
.buttonStyle(.borderedProminent)
.controlSize(.small)
}
}
// MARK: - Test Execution
private func runTest() {
log("TaskTestRunner: runTest() called")
isRunning = true
results = []
progress = 0
elapsedTime = 0
totalContextSwitches = 0
cancellationRequested = false
statusMessage = "Finding context switches..."
Task {
log("TaskTestRunner: Starting test task")
let startTime = Date()
let periodStart = periodFrom
let now = periodTo
// Get TaskAssistant from coordinator
log("TaskTestRunner: Looking up task-extraction assistant")
let assistant = await MainActor.run(body: {
AssistantCoordinator.shared.assistant(withIdentifier: "task-extraction")
})
log("TaskTestRunner: Assistant lookup result: \(assistant != nil ? "found" : "nil")")
guard let taskAssistant = assistant as? TaskAssistant else {
log("TaskTestRunner: ERROR - Task Assistant not available or wrong type")
await MainActor.run {
statusMessage = "Task Assistant not available"
isRunning = false
}
return
}
log("TaskTestRunner: Task Assistant successfully retrieved")
// Build filter parameters from current settings
let (allowedApps, browserApps, browserPatterns) = await MainActor.run {
() -> (Set<String>, Set<String>, [String]) in
let settings = TaskAssistantSettings.shared
return (settings.allowedApps, TaskAssistantSettings.browserApps, settings.browserKeywords)
}
log("TaskTestRunner: allowedApps = \(allowedApps)")
log("TaskTestRunner: browserApps = \(browserApps)")
log("TaskTestRunner: browserPatterns count = \(browserPatterns.count)")
// Fetch all filtered screenshots chronologically from selected range
log("TaskTestRunner: Fetching screenshots from \(periodStart) to \(now) with filters")
let allScreenshots: [Screenshot]
do {
allScreenshots = try await RewindDatabase.shared.getScreenshotsFiltered(
from: periodStart,
to: now,
allowedApps: allowedApps,
browserApps: browserApps,
browserWindowPatterns: browserPatterns,
limit: 100_000
).reversed() // getScreenshotsFiltered returns desc, we want chronological
} catch {
log("TaskTestRunner: ERROR - Failed to load screenshots: \(error)")
await MainActor.run {
statusMessage = "Failed to load screenshots: \(error.localizedDescription)"
isRunning = false
}
return
}
// Filter out Rewind privacy-excluded apps (password managers, keychains)
let filteredScreenshots = allScreenshots.filter { !RewindSettings.shared.isAppExcluded($0.appName) }
log(
"TaskTestRunner: Loaded \(allScreenshots.count) screenshots, \(filteredScreenshots.count) after Rewind privacy filter"
)
guard filteredScreenshots.count >= 2 else {
log("TaskTestRunner: ERROR - Not enough screenshots (\(filteredScreenshots.count) < 2)")
await MainActor.run {
statusMessage = "Not enough screenshots in selected range to detect context switches"
isRunning = false
}
return
}
// Walk through chronologically and find departing frames at context switches
var departingFrames: [Screenshot] = []
for i in 0..<(filteredScreenshots.count - 1) {
let current = filteredScreenshots[i]
let next = filteredScreenshots[i + 1]
if ContextDetection.didContextChange(
fromApp: current.appName,
fromWindowTitle: current.windowTitle,
toApp: next.appName,
toWindowTitle: next.windowTitle
) {
departingFrames.append(current)
}
}
guard !departingFrames.isEmpty else {
await MainActor.run {
statusMessage = "No context switches found in \(filteredScreenshots.count) screenshots from selected range"
isRunning = false
}
return
}
let sampled = departingFrames
await MainActor.run {
totalContextSwitches = sampled.count
statusMessage = "Found \(sampled.count) context switches, testing all..."
}
// Process each departing frame
for (i, screenshot) in sampled.enumerated() {
if cancellationRequested { break }
await MainActor.run {
statusMessage = "Processing \(i + 1)/\(sampled.count)..."
}
do {
// Load JPEG from video chunk
let jpegData = try await RewindStorage.shared.loadScreenshotData(for: screenshot)
// Run extraction pipeline
let analyzeStart = Date()
let (allResults, searchCount) = try await taskAssistant.testAnalyze(
jpegData: jpegData, appName: screenshot.appName)
let duration = Date().timeIntervalSince(analyzeStart)
// Pick the first task-bearing result for display; fall back to the first
// result (e.g. no_task_found terminator) when nothing was extracted.
let result: TaskExtractionResult? = allResults.first(where: { $0.hasNewTask }) ?? allResults.first
await MainActor.run {
results.append(
TaskTestResult(
index: i + 1,
timestamp: screenshot.timestamp,
appName: screenshot.appName,
windowTitle: screenshot.windowTitle,
result: result,
error: nil,
duration: duration,
searchCount: searchCount
))
progress = Double(i + 1) / Double(sampled.count)
}
} catch {
await MainActor.run {
results.append(
TaskTestResult(
index: i + 1,
timestamp: screenshot.timestamp,
appName: screenshot.appName,
windowTitle: screenshot.windowTitle,
result: nil,
error: error.localizedDescription,
duration: 0,
searchCount: 0
))
progress = Double(i + 1) / Double(sampled.count)
}
}
}
let totalElapsed = Date().timeIntervalSince(startTime)
await MainActor.run {
elapsedTime = totalElapsed
statusMessage = cancellationRequested ? "Stopped" : "Complete"
isRunning = false
}
}
}
}
// MARK: - NSWindow Subclass
class TaskTestRunnerWindow: NSWindow {
private static var sharedWindow: TaskTestRunnerWindow?
static func show() {
if let existingWindow = sharedWindow {
existingWindow.makeKeyAndOrderFront(nil)
NSApp.activate()
return
}
let window = TaskTestRunnerWindow()
sharedWindow = window
window.makeKeyAndOrderFront(nil)
NSApp.activate()
}
static func close() {
sharedWindow?.close()
sharedWindow = nil
}
private init() {
let contentRect = NSRect(x: 0, y: 0, width: 1400, height: 900)
super.init(
contentRect: contentRect,
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
backing: .buffered,
defer: false
)
self.title = "Task Extraction Test Runner"
self.isReleasedWhenClosed = false
// The inside of a titled window is glass: transparent, light-pinned, and shadowed by its own
// frame (`WindowGlass.Kind.titled`). Without the pin the title bar and the traffic lights stay in
// the machine's appearance — a dark title bar on a white sheet on a Dark Mac.
WindowGlass.wear(self, as: .titled)
self.delegate = self
self.minSize = NSSize(width: 900, height: 600)
self.center()
let runnerView = TaskTestRunnerView(onClose: { [weak self] in
self?.close()
})
let hostingView = NSHostingView(rootView: runnerView)
self.contentView = hostingView
}
}
// MARK: - NSWindowDelegate
extension TaskTestRunnerWindow: NSWindowDelegate {
func windowWillClose(_ notification: Notification) {
TaskTestRunnerWindow.sharedWindow = nil
}
}