forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBrowserExtensionSetup.swift
More file actions
680 lines (609 loc) · 22.9 KB
/
Copy pathBrowserExtensionSetup.swift
File metadata and controls
680 lines (609 loc) · 22.9 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
import OmiTheme
import SwiftUI
/// Standalone multi-phase onboarding view for setting up the Playwright MCP browser extension.
/// Can be presented as a sheet, overlay, or full page from any context.
struct BrowserExtensionSetup: View {
var onComplete: () -> Void
var onSkip: (() -> Void)? = nil
var onDismiss: (() -> Void)? = nil
/// Optional ChatProvider for running the connection test.
/// When nil, Phase 3 is skipped (token is saved and we go straight to Done).
var chatProvider: ChatProvider? = nil
enum Phase: Int, CaseIterable {
case welcome = 0
case connect = 1
case verify = 2
case done = 3
}
@State private var phase: Phase = .welcome
@State private var tokenInput: String = ""
@State private var tokenError: String? = nil
@State private var isVerifying = false
@State private var verifyError: String? = nil
@State private var verifySuccess = false
@State private var selectedTarget =
BrowserAutomationTargetResolver.preferredTarget() ?? BrowserAutomationTargetResolver.knownTargets[0]
@State private var browserInstalled = false
@State private var extensionStepDone = false
@State private var tokenStepDone = false
@State private var browserCheckTimer: Timer? = nil
@State private var extensionCheckTimer: Timer? = nil
var body: some View {
VStack(spacing: 0) {
// Top bar: progress dots + dismiss button
HStack {
Spacer()
// Progress dots
HStack(spacing: OmiSpacing.sm) {
ForEach(Phase.allCases, id: \.rawValue) { p in
Circle()
.fill(p.rawValue <= phase.rawValue ? Ink.accent : Ink.hairline)
.frame(width: 8, height: 8)
}
}
Spacer()
// Dismiss button (always visible)
DismissButton(action: dismissSheet, showBackground: false)
}
.padding(.top, OmiSpacing.lg)
.padding(.horizontal, OmiSpacing.lg)
.padding(.bottom, OmiSpacing.md)
// Phase content
Group {
switch phase {
case .welcome:
welcomePhase
case .connect:
connectPhase
case .verify:
verifyPhase
case .done:
donePhase
}
}
.frame(maxWidth: .infinity)
Spacer()
// Bottom buttons
VStack(spacing: OmiSpacing.sm) {
Button(action: handlePrimaryAction) {
Text(primaryButtonTitle)
.frame(maxWidth: .infinity)
.padding(.vertical, OmiSpacing.sm)
}
.buttonStyle(.borderedProminent)
.controlSize(.large)
.disabled(isPrimaryDisabled)
if let onSkip = onSkip, phase == .welcome {
Button(action: onSkip) {
Text("Skip for now")
.scaledFont(size: OmiType.body)
.foregroundColor(Ink.secondary)
}
.buttonStyle(.plain)
}
}
.padding(.horizontal, OmiSpacing.page)
.padding(.bottom, OmiSpacing.xxl)
}
.frame(width: phase == .connect ? 880 : 480, height: phase == .connect ? 520 : 420)
.background(
RoundedRectangle(cornerRadius: SettingsGlassMetrics.cardRadius, style: .continuous)
.fill(Ink.wash)
.overlay(
RoundedRectangle(cornerRadius: SettingsGlassMetrics.cardRadius, style: .continuous)
.stroke(Ink.separator, lineWidth: 1)
)
)
.omiAnimation(.easeInOut(duration: 0.3), value: phase)
}
// MARK: - Phase Views
private var welcomePhase: some View {
VStack(spacing: OmiSpacing.lg) {
Image(systemName: "globe")
.scaledFont(size: 48)
.foregroundColor(Ink.primary)
Text("Set up browser access")
.scaledFont(size: OmiType.heading, weight: .semibold)
.foregroundColor(Ink.primary)
Text(
"This lets the AI use your signed-in browser session — search the web, fill forms, and interact with sites on your behalf."
)
.scaledFont(size: OmiType.body)
.foregroundColor(Ink.secondary)
.multilineTextAlignment(.center)
.padding(.horizontal, OmiSpacing.page)
VStack(alignment: .leading, spacing: OmiSpacing.sm) {
featureRow(icon: "checkmark.shield", text: "Uses a Chromium browser extension for secure access")
featureRow(icon: "key", text: "One-time auth token setup")
featureRow(icon: "bolt", text: "No more Allow/Reject popups")
}
.padding(.horizontal, OmiSpacing.page)
.padding(.top, OmiSpacing.sm)
}
.padding(.horizontal, OmiSpacing.xl)
}
/// Which GIF to show based on the current active step.
private var activeGifName: String? {
if !browserInstalled { return nil }
if !extensionStepDone { return "installing_extension" }
return "enabling_token"
}
private var connectPhase: some View {
HStack(spacing: OmiSpacing.lg) {
// Left side: steps
VStack(spacing: OmiSpacing.lg) {
Text("Connect the extension")
.scaledFont(size: OmiType.heading, weight: .semibold)
.foregroundColor(Ink.primary)
browserPicker
// Step 1: Install the selected browser
HStack(alignment: .top, spacing: OmiSpacing.md) {
stepBadge("1", done: browserInstalled)
VStack(alignment: .leading, spacing: OmiSpacing.xs) {
Text(browserInstalled ? "\(selectedTarget.name) is installed" : "Install \(selectedTarget.name)")
.scaledFont(size: OmiType.body, weight: .medium)
.foregroundColor(browserInstalled ? Ink.secondary : Ink.primary)
if !browserInstalled {
Button(action: {
if let url = selectedTarget.installURL {
NSWorkspace.shared.open(url)
}
startBrowserCheckTimer()
}) {
HStack(spacing: OmiSpacing.xxs) {
Image(systemName: "arrow.down.circle")
.scaledFont(size: OmiType.caption)
Text("Download \(selectedTarget.name)")
.scaledFont(size: OmiType.caption)
}
}
.buttonStyle(.bordered)
.controlSize(.small)
}
}
}
.frame(maxWidth: .infinity, alignment: .leading)
// Step 2: Install extension from the browser's extension store
HStack(alignment: .top, spacing: OmiSpacing.md) {
stepBadge("2", done: extensionStepDone)
VStack(alignment: .leading, spacing: OmiSpacing.xs) {
Text("Install the Playwright MCP Bridge extension")
.scaledFont(size: OmiType.body, weight: .medium)
.foregroundColor(extensionStepDone ? Ink.secondary : Ink.primary)
Button(action: {
if let url = selectedTarget.extensionInstallURL() {
BrowserAutomationTargetResolver.open(url, in: selectedTarget)
}
startExtensionCheckTimer()
}) {
HStack(spacing: OmiSpacing.xxs) {
Image(systemName: extensionStepDone ? "checkmark" : "arrow.up.right.square")
.scaledFont(size: OmiType.caption)
Text(extensionStepDone ? "Installed" : "Add Extension")
.scaledFont(size: OmiType.caption)
}
}
.buttonStyle(.bordered)
.controlSize(.small)
.disabled(!browserInstalled || extensionStepDone)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
// Step 3: Open extension settings & copy token
HStack(alignment: .top, spacing: OmiSpacing.md) {
stepBadge("3", done: tokenStepDone)
VStack(alignment: .leading, spacing: OmiSpacing.xs) {
Text("Open the extension and copy the auth token")
.scaledFont(size: OmiType.body, weight: .medium)
.foregroundColor(tokenStepDone ? Ink.secondary : Ink.primary)
Button(action: {
if let url = selectedTarget.extensionStatusURL() {
BrowserAutomationTargetResolver.open(url, in: selectedTarget)
}
OmiMotion.withGated(.easeInOut(duration: 0.2)) {
tokenStepDone = true
}
}) {
HStack(spacing: OmiSpacing.xxs) {
Image(systemName: tokenStepDone ? "checkmark" : "key")
.scaledFont(size: OmiType.caption)
Text(tokenStepDone ? "Opened" : "Open Extension Settings")
.scaledFont(size: OmiType.caption)
}
}
.buttonStyle(.bordered)
.controlSize(.small)
.disabled(!browserInstalled)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
// Step 4: Paste token
HStack(alignment: .top, spacing: OmiSpacing.md) {
stepBadge("4", done: isTokenValid)
VStack(alignment: .leading, spacing: OmiSpacing.xs) {
Text("Paste it here")
.scaledFont(size: OmiType.body, weight: .medium)
.foregroundColor(isTokenValid ? Ink.secondary : Ink.primary)
TextField("Paste token here...", text: $tokenInput)
.textFieldStyle(.plain)
.scaledFont(size: OmiType.body)
.foregroundColor(Ink.primary)
.padding(OmiSpacing.sm)
.background(
RoundedRectangle(cornerRadius: SettingsGlassMetrics.controlRadius, style: .continuous)
.fill(Ink.wash)
.overlay(
RoundedRectangle(cornerRadius: SettingsGlassMetrics.controlRadius, style: .continuous)
.stroke(
tokenError != nil
? Ink.errorRed.opacity(0.5)
: isTokenValid ? Ink.listeningGreen.opacity(0.5) : Ink.hairline,
lineWidth: 1
)
)
)
.disabled(!browserInstalled)
.onChange(of: tokenInput) { _, _ in
tokenError = nil
}
if let error = tokenError {
Text(error)
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.errorRed)
}
}
}
.frame(maxWidth: .infinity, alignment: .leading)
}
.padding(.leading, OmiSpacing.page)
.padding(.trailing, OmiSpacing.sm)
.frame(maxWidth: .infinity)
// Right side: GIF guide
guidePanel
.frame(maxWidth: .infinity)
.padding(.trailing, OmiSpacing.xxl)
}
.onAppear {
refreshBrowserState()
}
.onDisappear {
browserCheckTimer?.invalidate()
browserCheckTimer = nil
extensionCheckTimer?.invalidate()
extensionCheckTimer = nil
}
}
private var browserPicker: some View {
HStack(alignment: .center, spacing: OmiSpacing.sm) {
Text("Browser")
.scaledFont(size: OmiType.caption, weight: .medium)
.foregroundColor(Ink.secondary)
Picker("", selection: $selectedTarget) {
ForEach(BrowserAutomationTargetResolver.knownTargets) { target in
Text(target.name).tag(target)
}
}
.labelsHidden()
.controlSize(.small)
.onChange(of: selectedTarget) { _, target in
BrowserAutomationTargetStore.select(target)
resetConnectionStateForSelectedBrowser()
refreshBrowserState()
}
Spacer()
if let defaultTarget = BrowserAutomationTargetResolver.defaultTarget(),
defaultTarget.bundleIdentifier == selectedTarget.bundleIdentifier
{
Text("Default")
.scaledFont(size: OmiType.caption, weight: .medium)
.foregroundColor(Ink.listeningGreen)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
}
/// Right-side guide panel showing the appropriate GIF for the current step.
private var guidePanel: some View {
VStack(spacing: OmiSpacing.md) {
if let gifName = activeGifName {
AnimatedGIFView(gifName: gifName)
.id(gifName)
.clipShape(RoundedRectangle(cornerRadius: SettingsGlassMetrics.controlRadius, style: .continuous))
.overlay(
RoundedRectangle(cornerRadius: SettingsGlassMetrics.controlRadius, style: .continuous)
.stroke(Ink.hairline, lineWidth: 1)
)
} else if !browserInstalled {
VStack(spacing: OmiSpacing.md) {
Image(systemName: "desktopcomputer")
.scaledFont(size: OmiType.hero)
.foregroundColor(Ink.secondary)
Text("Install \(selectedTarget.name) to get started")
.scaledFont(size: OmiType.body)
.foregroundColor(Ink.secondary)
.multilineTextAlignment(.center)
}
.frame(maxWidth: .infinity)
}
}
.padding(.vertical, OmiSpacing.sm)
.background(
RoundedRectangle(cornerRadius: SettingsGlassMetrics.cardRadius, style: .continuous)
.fill(Ink.wash)
)
}
private var verifyPhase: some View {
VStack(spacing: OmiSpacing.lg) {
if isVerifying {
ProgressView()
.scaleEffect(1.5)
.frame(height: 48)
Text("Testing connection...")
.scaledFont(size: OmiType.heading, weight: .semibold)
.foregroundColor(Ink.primary)
Text("Sending a test request to verify the extension is working.")
.scaledFont(size: OmiType.body)
.foregroundColor(Ink.secondary)
.multilineTextAlignment(.center)
.padding(.horizontal, OmiSpacing.page)
} else if verifySuccess {
Image(systemName: "checkmark.circle.fill")
.scaledFont(size: 48)
.foregroundColor(Ink.listeningGreen)
Text("Connected")
.scaledFont(size: OmiType.heading, weight: .semibold)
.foregroundColor(Ink.primary)
Text("The browser extension is working. The AI can now use \(selectedTarget.name).")
.scaledFont(size: OmiType.body)
.foregroundColor(Ink.secondary)
.multilineTextAlignment(.center)
.padding(.horizontal, OmiSpacing.page)
} else if let error = verifyError {
Image(systemName: "exclamationmark.triangle.fill")
.scaledFont(size: 48)
.foregroundColor(SettingsInk.notice)
Text("Connection failed")
.scaledFont(size: OmiType.heading, weight: .semibold)
.foregroundColor(Ink.primary)
Text(error)
.scaledFont(size: OmiType.body)
.foregroundColor(Ink.secondary)
.multilineTextAlignment(.center)
.padding(.horizontal, OmiSpacing.page)
Text("Make sure \(selectedTarget.name) is open and the extension page shows \"Connected\".")
.scaledFont(size: OmiType.caption)
.foregroundColor(Ink.secondary)
.multilineTextAlignment(.center)
.padding(.horizontal, OmiSpacing.page)
}
}
.padding(.horizontal, OmiSpacing.xl)
}
private var donePhase: some View {
VStack(spacing: OmiSpacing.lg) {
Image(systemName: "checkmark.circle.fill")
.scaledFont(size: 48)
.foregroundColor(Ink.listeningGreen)
Text("All set")
.scaledFont(size: OmiType.heading, weight: .semibold)
.foregroundColor(Ink.primary)
Text(
"Browser access is configured. The AI can now browse the web, fill forms, and interact with sites using your \(selectedTarget.name) sessions."
)
.scaledFont(size: OmiType.body)
.foregroundColor(Ink.secondary)
.multilineTextAlignment(.center)
.padding(.horizontal, OmiSpacing.page)
}
.padding(.horizontal, OmiSpacing.xl)
}
// MARK: - Helpers
private func featureRow(icon: String, text: String) -> some View {
HStack(spacing: OmiSpacing.sm) {
Image(systemName: icon)
.scaledFont(size: OmiType.body)
.foregroundColor(Ink.secondary)
.frame(width: 20)
Text(text)
.scaledFont(size: OmiType.body)
.foregroundColor(Ink.secondary)
}
}
/// The numbered disc beside a setup step, in the same two shapes `PermissionsPage`'s
/// `instructionStep` uses — this sheet and that page are the same instruction, and they were
/// drawn differently.
///
/// The pending disc set `Ink.surface` on `Ink.hairline`: a white numeral on `labelColor` at 0.22,
/// which over the light panel is a pale grey disc with nothing legible on it. `Ink.surface` is the
/// *inverted* label and it is only ever correct over an `Ink.primary` fill. The done disc had the
/// same shape of problem one step milder — white on `systemGreen` measures about 2:1 — so both
/// now compose the ground from the tint the way `SettingsStatusChip` does, which keeps the fill
/// and the label a pair rather than two independent choices.
private func stepBadge(_ number: String, done: Bool = false) -> some View {
let tint = done ? Ink.listeningGreen : Ink.primary
return Group {
if done {
Image(systemName: "checkmark")
.scaledFont(size: OmiType.caption, weight: .bold)
} else {
Text(number)
.scaledFont(size: OmiType.caption, weight: .bold)
}
}
.foregroundColor(tint)
.frame(width: 22, height: 22)
.background(Circle().fill(tint.opacity(0.14)))
}
/// Strip the "PLAYWRIGHT_MCP_EXTENSION_TOKEN=" prefix if the user copied the full env var line.
static func parseToken(_ input: String) -> String {
var token = input.trimmingCharacters(in: .whitespacesAndNewlines)
if let eqIndex = token.firstIndex(of: "="), token.hasPrefix("PLAYWRIGHT") {
token = String(token[token.index(after: eqIndex)...])
}
return token
}
/// Validate that a parsed token looks like a real extension auth token.
/// Returns an error message if invalid, nil if valid.
static func validateToken(_ token: String) -> String? {
if token.isEmpty {
return "Please paste the token from the extension page."
}
if token.count < 20 {
return "Token is too short. Copy the full token from the extension page."
}
// Extension tokens are base64url: alphanumeric + hyphen + underscore
let allowed = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-_"))
if token.unicodeScalars.contains(where: { !allowed.contains($0) }) {
return "Token contains invalid characters. Copy the token value only, not the surrounding text."
}
return nil
}
private func resetConnectionStateForSelectedBrowser() {
tokenInput = ""
tokenError = nil
tokenStepDone = false
verifyError = nil
verifySuccess = false
}
private func refreshBrowserState() {
browserInstalled = BrowserAutomationTargetResolver.isInstalled(selectedTarget)
extensionStepDone = BrowserAutomationTargetResolver.isExtensionInstalled(in: selectedTarget)
}
/// Poll every 2 seconds to detect selected browser installation.
private func startBrowserCheckTimer() {
guard browserCheckTimer == nil else { return }
browserCheckTimer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { _ in
MainActor.assumeIsolated {
if BrowserAutomationTargetResolver.isInstalled(selectedTarget) {
OmiMotion.withGated(.easeInOut(duration: 0.2)) {
browserInstalled = true
}
browserCheckTimer?.invalidate()
browserCheckTimer = nil
}
}
}
}
/// Poll every 2 seconds to detect extension installation.
private func startExtensionCheckTimer() {
guard extensionCheckTimer == nil else { return }
extensionCheckTimer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { _ in
MainActor.assumeIsolated {
if BrowserAutomationTargetResolver.isExtensionInstalled(in: selectedTarget) {
OmiMotion.withGated(.easeInOut(duration: 0.2)) {
extensionStepDone = true
}
extensionCheckTimer?.invalidate()
extensionCheckTimer = nil
}
}
}
}
private func dismissSheet() {
if let onDismiss = onDismiss {
onDismiss()
} else {
onComplete()
}
}
// MARK: - Button Logic
private var primaryButtonTitle: String {
switch phase {
case .welcome:
return "Set Up"
case .connect:
return "Continue"
case .verify:
if isVerifying { return "Testing..." }
if verifySuccess { return "Continue" }
return "Try Again"
case .done:
return "Done"
}
}
/// Whether the current token input parses and validates successfully.
private var isTokenValid: Bool {
let token = Self.parseToken(tokenInput)
return Self.validateToken(token) == nil
}
private var isPrimaryDisabled: Bool {
switch phase {
case .connect:
return tokenInput.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
case .verify:
return isVerifying
default:
return false
}
}
private func handlePrimaryAction() {
switch phase {
case .welcome:
OmiMotion.withGated(.easeInOut(duration: 0.2)) {
phase = .connect
}
case .connect:
let token = Self.parseToken(tokenInput)
if let error = Self.validateToken(token) {
tokenError = error
return
}
UserDefaults.standard.set(token, forKey: "playwrightExtensionToken")
log("BrowserExtensionSetup: Token saved (\(token.prefix(8))...)")
if chatProvider != nil {
OmiMotion.withGated(.easeInOut(duration: 0.2)) {
phase = .verify
}
runConnectionTest()
} else {
// No provider available — skip verification, go to done
OmiMotion.withGated(.easeInOut(duration: 0.2)) {
phase = .done
}
}
case .verify:
if verifySuccess {
OmiMotion.withGated(.easeInOut(duration: 0.2)) {
phase = .done
}
} else {
// Try again
runConnectionTest()
}
case .done:
onComplete()
}
}
private func runConnectionTest() {
guard let provider = chatProvider else { return }
isVerifying = true
verifyError = nil
verifySuccess = false
Task {
do {
let connected = try await provider.testPlaywrightConnection()
await MainActor.run {
isVerifying = false
if connected {
verifySuccess = true
log("BrowserExtensionSetup: Connection test succeeded")
} else {
verifyError = "Could not connect to the extension. Make sure \(selectedTarget.name) is open and try again."
log("BrowserExtensionSetup: Connection test returned false")
}
}
} catch {
await MainActor.run {
isVerifying = false
let msg = error.localizedDescription
if msg.contains("timeout") || msg.contains("Extension connection timeout") {
verifyError =
"Connection timed out. Make sure \(selectedTarget.name) is running and the extension is installed, then try again."
} else {
verifyError = UserFacingErrorPresentation.message(for: error, while: .browserExtension)
}
log("BrowserExtensionSetup: Connection test error: \(error)")
}
}
}
}
}