forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDesktopAutomationBridge.swift
More file actions
5004 lines (4744 loc) · 199 KB
/
Copy pathDesktopAutomationBridge.swift
File metadata and controls
5004 lines (4744 loc) · 199 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 AppKit
import CryptoKit
import Foundation
import Network
import OmiSupport
import OmiTheme
import VoiceTurnDomain
enum DesktopAutomationLaunchOptions {
static let enableFlag = "--automation-bridge"
static let portPrefix = "--automation-port="
static let captureRootPrefix = "--automation-capture-root="
static let uiPresentationPrefix = "--automation-ui="
static let uiPresentationEnvironmentKey = "OMI_AUTOMATION_UI_MODE"
static let defaultPort: UInt16 = 47777
static let tokenEnvironmentKey = "OMI_AUTOMATION_TOKEN"
static let tokenFileEnvironmentKey = "OMI_AUTOMATION_TOKEN_FILE"
private static let generatedToken =
"omi_auto_\(UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased())"
static var isEnabled: Bool {
isEnabled(
allowsLocalAutomation: AppBuild.allowsLocalAutomation,
arguments: CommandLine.arguments,
environment: ProcessInfo.processInfo.environment
)
}
static func isEnabled(
allowsLocalAutomation: Bool,
arguments: [String],
environment: [String: String]
) -> Bool {
guard allowsLocalAutomation else {
return false
}
// Explicit opt-out always wins, so a dev build can be run "clean" if needed.
if environment["OMI_DISABLE_LOCAL_AUTOMATION"] == "1" {
return false
}
// Auto-enable on local bundles (Omi Dev + every `omi-*` named test bundle) so agents
// can drive the app without remembering a launch flag. Published previews are excluded
// by `allowsLocalAutomation` above even if their process environment is contaminated.
return arguments.contains(enableFlag)
|| environment["OMI_ENABLE_LOCAL_AUTOMATION"] == "1"
|| allowsLocalAutomation
}
static var port: UInt16 {
for argument in CommandLine.arguments {
guard argument.hasPrefix(portPrefix) else { continue }
let rawValue = String(argument.dropFirst(portPrefix.count))
if let parsed = UInt16(rawValue) {
return parsed
}
}
if let rawValue = ProcessInfo.processInfo.environment["OMI_AUTOMATION_PORT"],
let parsed = UInt16(rawValue)
{
return parsed
}
return defaultPort
}
static var uiPresentationMode: DesktopAutomationUIPresentationMode {
uiPresentationMode(
allowsLocalAutomation: AppBuild.allowsLocalAutomation,
arguments: CommandLine.arguments,
environment: ProcessInfo.processInfo.environment)
}
static func uiPresentationMode(
allowsLocalAutomation: Bool,
arguments: [String],
environment: [String: String]
) -> DesktopAutomationUIPresentationMode {
guard allowsLocalAutomation else { return .normal }
for argument in arguments where argument.hasPrefix(uiPresentationPrefix) {
let rawValue = String(argument.dropFirst(uiPresentationPrefix.count)).lowercased()
return DesktopAutomationUIPresentationMode(rawValue: rawValue) ?? .normal
}
let rawValue = environment[uiPresentationEnvironmentKey]?.trimmingCharacters(in: .whitespacesAndNewlines)
.lowercased()
return rawValue.flatMap(DesktopAutomationUIPresentationMode.init(rawValue:)) ?? .normal
}
static var token: String {
let env = ProcessInfo.processInfo.environment[tokenEnvironmentKey] ?? ""
let trimmed = env.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? generatedToken : trimmed
}
static var tokenFileURL: URL {
if let rawValue = ProcessInfo.processInfo.environment[tokenFileEnvironmentKey],
!rawValue.isEmpty
{
return URL(fileURLWithPath: rawValue).standardizedFileURL
}
return URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent("omi-automation-\(port).token")
.standardizedFileURL
}
static func writeTokenFileIfNeeded() {
guard isEnabled else { return }
let url = tokenFileURL
do {
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
try token.write(to: url, atomically: true, encoding: .utf8)
chmod(url.path, S_IRUSR | S_IWUSR)
} catch {
logError("DesktopAutomationBridge: failed to write automation token file", error: error)
}
}
static var captureRoot: URL {
for argument in CommandLine.arguments {
guard argument.hasPrefix(captureRootPrefix) else { continue }
let rawValue = String(argument.dropFirst(captureRootPrefix.count))
if !rawValue.isEmpty {
return URL(fileURLWithPath: rawValue).standardizedFileURL
}
}
if let rawValue = ProcessInfo.processInfo.environment["OMI_AUTOMATION_CAPTURE_ROOT"],
!rawValue.isEmpty
{
return URL(fileURLWithPath: rawValue).standardizedFileURL
}
return URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent("omi-harness", isDirectory: true)
.standardizedFileURL
}
}
struct DesktopAutomationSnapshot: Codable, Sendable {
/// The app has one shell. Flows and the navigation-visibility policy still read
/// `shellVariant`, so it is pinned here rather than removed from the contract.
static let singleShellVariant = "chat_first"
var bridgeEnabled: Bool
var bridgePort: UInt16
var bundleIdentifier: String
var appState: String
var selectedTab: String?
var selectedTabIndex: Int?
var selectedSettingsSection: String?
var highlightedSettingId: String?
/// Home stage mode: `hub`, `chat`, or `connect`. `DashboardPage` was the only view that ever
/// rendered that stage and it no longer exists, so this is now always nil. Kept in the snapshot
/// so an older flow reading it sees "no stage" rather than a missing key.
var homeMode: String?
/// Always `chat_first` on a mounted shell: the app has exactly one. Nil only before the shell has
/// reported state. Never a local preference.
var shellVariant: String?
/// Stable typed route for the one shell.
var chatFirstRoute: String?
/// Set only by the mounted Chat-first destination after it has appeared. This
/// keeps a successful navigation response equivalent to the target being
/// visible, rather than merely accepted by the root reducer.
var visibleChatFirstRoute: String?
/// Shape-only focus telemetry for route acknowledgement; entity IDs stay local.
var pendingFocusKind: String?
var acknowledgedFocusKind: String?
/// The focused entity is available only through the local non-production
/// bridge so named-bundle probes can prove the acknowledgement target. It is
/// never an analytics dimension or a persisted navigation value.
var focusedEntityID: String?
var isFocusedEntityAcknowledged: Bool
/// Retained for snapshot compatibility; the legacy sidebar shell is gone, so it is always false.
var showsPrimarySidebar: Bool
var isSidebarCollapsed: Bool
var hasCompletedOnboarding: Bool
var isSignedIn: Bool
var isRestoringAuth: Bool
var isAppActive: Bool
var mainWindowTitle: String?
var floatingBarVisible: Bool
/// True when the chat-first Chat route is selected, so the main-window composer is the typed Ask Omi surface.
var askOmiOpen: Bool
/// True when that composer’s text view is first responder.
var askOmiFocused: Bool
var floatingBarFrame: String?
var floatingBarVoiceListening: Bool
/// The current hold has been recognised as a dictation (the notch's red tint).
var floatingBarVoiceDictating: Bool
var floatingBarVoiceResponseActive: Bool
var floatingBarUsesNotchIsland: Bool
var updatedAt: String
/// True when the live MainActor refresh timed out and this is the last cached
/// snapshot instead — e.g. the main thread is wedged on a blocking Keychain
/// read during sign-in. The bridge still answers `/state` so harnesses don't
/// hang; callers can detect that the live fields may be stale.
var snapshotStale: Bool = false
}
struct DesktopAutomationOpenConversationRequest: Codable {
let conversationId: String
let showTranscript: Bool?
let activateApp: Bool?
let settleMs: Int?
}
struct DesktopAutomationVisualExportRequest: Codable {
let path: String
let target: String?
}
struct DesktopAutomationVisualExportResult: Codable {
let path: String
let width: Int
let height: Int
}
struct DesktopAutomationExecuteExportRequest: Codable {
let destination: String
}
struct DesktopAutomationOpenImportRequest: Codable {
let connector: String
}
/// Describes a semantic action exposed over `GET /actions` so an agent can discover
/// what it can drive without inspecting the UI tree.
struct DesktopAutomationActionDescriptor: Codable {
let name: String
let summary: String
/// Names of params the handler reads (hints for the caller; not enforced).
let params: [String]
/// Coarse grouping for scanners and harness UIs.
let category: String
/// Screens or app surfaces this action is meant to replace AX interaction on.
let surfaces: [String]
/// Agent-facing risk label; the bridge is still non-production only.
let safety: String
/// Plain-language effects so callers can prefer read-only probes before clicks.
let sideEffects: [String]
/// Copy-pasteable examples for `scripts/omi-ctl action ...`.
let examples: [String]
/// Semantic bridge actions should be preferred over `agent-swift` clicks when covered.
let preferSemantic: Bool
init(
name: String,
summary: String,
params: [String] = [],
category: String? = nil,
surfaces: [String]? = nil,
safety: String? = nil,
sideEffects: [String]? = nil,
examples: [String] = [],
preferSemantic: Bool = true
) {
self.name = name
self.summary = summary
self.params = params
self.category = category ?? Self.inferCategory(name)
self.surfaces = surfaces ?? Self.inferSurfaces(name)
self.safety = safety ?? Self.inferSafety(name)
self.sideEffects = sideEffects ?? Self.inferSideEffects(name)
self.examples = examples.isEmpty ? [Self.commandExample(name: name, params: params)] : examples
self.preferSemantic = preferSemantic
}
private static func inferCategory(_ name: String) -> String {
if name.contains("snapshot") || name.contains("probe") || name.contains("state")
|| name.contains("tail") || name.contains("evidence") || name.contains("qa_export")
{
return "read"
}
if name.hasPrefix("capture") {
return "capture"
}
if name.contains("coordinator") {
return "coordinator"
}
if name.contains("ask") || name.contains("chat") || name.contains("omni") {
return "chat"
}
if name.contains("spatial_overlay") || name.contains("debug_bar") || name.contains("subagent") {
return "visual"
}
if name.contains("transcription") || name.contains("refresh") {
return "app_control"
}
return "general"
}
private static func inferSurfaces(_ name: String) -> [String] {
if name.hasPrefix("capture_main_window") {
return ["main_window"]
}
if name.hasPrefix("capture_floating_bar") || name.contains("debug_bar") {
return ["floating_bar"]
}
if name.contains("main_chat") {
return ["main_chat"]
}
if name.contains("ask_omi") || name == "ask" || name.contains("floating") || name.contains("subagent") {
return ["floating_bar", "ask_omi"]
}
if name.contains("coordinator") {
return ["coordinator"]
}
if name.contains("spatial_overlay") || name.contains("cloud_connector") {
return ["cloud_connector_guidance"]
}
if name.contains("calendar") {
return ["calendar_connector"]
}
if name.contains("gmail") {
return ["gmail_connector"]
}
if name.contains("apple_notes") || name.contains("local_file") {
return ["import_connectors"]
}
return ["app"]
}
private static func inferSafety(_ name: String) -> String {
if name.contains("delete") {
return "remote_write"
}
if name.contains("snapshot") || name.contains("probe") || name.contains("state")
|| name.contains("tail") || name.contains("evidence") || name.contains("qa_export")
{
return "read_only"
}
if name.hasPrefix("capture") {
return "local_artifact"
}
if name.contains("ask") || name.contains("omni") || name.contains("import") {
return "network_or_model"
}
return "local_ui_state"
}
private static func inferSideEffects(_ name: String) -> [String] {
if name.contains("delete") {
return ["may mutate remote user data"]
}
if name.hasPrefix("capture") {
return ["writes local artifact file"]
}
if name.contains("ask") || name.contains("omni") {
return ["may call model/backend services"]
}
if name.contains("import") {
return ["may read local connector data", "may save imported memory data"]
}
if name.contains("toggle") || name.contains("debug") || name.contains("open") || name.contains("close")
|| name.contains("seed") || name.contains("swap") || name.contains("clear")
{
return ["mutates non-production app state"]
}
return []
}
private static func commandExample(name: String, params: [String]) -> String {
var pieces = ["./scripts/omi-ctl", "action", name]
for param in params {
pieces.append("\(param)=<value>")
}
return pieces.joined(separator: " ")
}
}
/// Returned by `POST /action`: what ran, any handler detail, and the resulting state.
struct DesktopAutomationActionResult: Codable {
let action: String
let detail: [String: String]?
let state: DesktopAutomationSnapshot
}
struct DesktopAutomationCapabilities: Codable {
let schemaVersion: Int
let routes: [String]
let lanes: [String]
let waits: [String]
let assertions: [String]
let artifactTypes: [String]
let actions: [DesktopAutomationActionDescriptor]
}
private struct DesktopAutomationHealth: Codable {
let ok: Bool
let name: String
let bundleIdentifier: String
let processID: Int32
let logFilePath: String
let logLaunchID: String
let bridgePort: UInt16
let requiresAuth: Bool
let backendEnvironment: String
let pythonBackendURL: String
let rustBackendURL: String
let agentRuntimeRunning: Bool
let agentRuntimeExpectedProtocolVersion: Int
let agentRuntimeProtocolVersion: Int?
let agentRuntimeVersion: String?
}
struct DesktopAutomationRouteTrace: Codable {
let method: String
let path: String
let statusCode: Int
let durationMs: Double
let finishedAt: String
}
enum DesktopAutomationActionError: LocalizedError {
case unknownAction(String)
case invalidParams(String)
var errorDescription: String? {
switch self {
case .unknownAction(let name): return "unknown_action: \(name)"
case .invalidParams(let detail): return "invalid_params: \(detail)"
}
}
}
enum DesktopAutomationRevisionComparator {
static func matchesAtMillisecondPrecision(_ lhs: Date?, _ rhs: Date?) -> Bool {
guard let lhs, let rhs else { return lhs == nil && rhs == nil }
let lhsMilliseconds = Int64((lhs.timeIntervalSince1970 * 1_000).rounded())
let rhsMilliseconds = Int64((rhs.timeIntervalSince1970 * 1_000).rounded())
return lhsMilliseconds == rhsMilliseconds
}
}
private func automationSafeErrorDetail(_ raw: String) -> String {
var detail = raw.replacingOccurrences(of: #"[\r\n\t]+"#, with: " ", options: .regularExpression)
let redactions: [(String, String)] = [
(#"eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+"#, "[redacted-jwt]"),
(#"(?i)bearer\s+[A-Za-z0-9._~+/=-]{8,}"#, "Bearer [redacted]"),
(#"sk-[A-Za-z0-9_-]{20,}"#, "sk-[redacted]"),
]
for (pattern, replacement) in redactions {
detail = detail.replacingOccurrences(of: pattern, with: replacement, options: .regularExpression)
}
return String(detail.prefix(500))
}
private func automationActionErrorDescription(_ error: Error) -> String {
if case APIError.httpError(let statusCode, let detail) = error {
let suffix = detail.map { " detail=\(automationSafeErrorDetail($0))" } ?? ""
return "api_http_error status=\(statusCode)\(suffix)"
}
return automationSafeErrorDetail(error.localizedDescription)
}
private struct DesktopAutomationResponse<T: Codable>: Codable {
let ok: Bool
let result: T?
let error: String?
}
final class DesktopAutomationStateStore {
nonisolated(unsafe) static let shared = DesktopAutomationStateStore()
private let lock = NSLock()
private var snapshot = DesktopAutomationSnapshot(
bridgeEnabled: DesktopAutomationLaunchOptions.isEnabled,
bridgePort: DesktopAutomationLaunchOptions.port,
bundleIdentifier: Bundle.main.bundleIdentifier ?? "unknown",
appState: "launching",
selectedTab: nil,
selectedTabIndex: nil,
selectedSettingsSection: nil,
highlightedSettingId: nil,
homeMode: nil,
shellVariant: nil,
chatFirstRoute: nil,
visibleChatFirstRoute: nil,
pendingFocusKind: nil,
acknowledgedFocusKind: nil,
focusedEntityID: nil,
isFocusedEntityAcknowledged: false,
showsPrimarySidebar: false,
isSidebarCollapsed: true,
hasCompletedOnboarding: false,
isSignedIn: false,
isRestoringAuth: true,
isAppActive: false,
mainWindowTitle: nil,
floatingBarVisible: false,
askOmiOpen: false,
askOmiFocused: false,
floatingBarFrame: nil,
floatingBarVoiceListening: false,
floatingBarVoiceDictating: false,
floatingBarVoiceResponseActive: false,
floatingBarUsesNotchIsland: false,
updatedAt: ISO8601DateFormatter().string(from: Date())
)
func update(_ snapshot: DesktopAutomationSnapshot) {
lock.lock()
defer { lock.unlock() }
self.snapshot = snapshot
}
func updateLiveFields(_ update: (inout DesktopAutomationSnapshot) -> Void) -> DesktopAutomationSnapshot {
lock.lock()
defer { lock.unlock() }
update(&snapshot)
return snapshot
}
func current() -> DesktopAutomationSnapshot {
lock.lock()
defer { lock.unlock() }
return snapshot
}
}
/// How long `/state` waits for the live MainActor refresh before serving the last
/// cached snapshot instead. Generous enough not to false-trip under normal load,
/// small enough that a wedged main thread can't stall the harness.
private let liveSnapshotMainActorTimeout: Duration = .seconds(3)
/// Single-resume guard for a continuation raced between two unstructured tasks.
private final class TimeoutRaceBox<T>: @unchecked Sendable {
private var resumed = false
private let lock = NSLock()
private let continuation: CheckedContinuation<T?, Never>
init(_ continuation: CheckedContinuation<T?, Never>) {
self.continuation = continuation
}
func resume(_ value: sending T?) {
lock.lock()
defer { lock.unlock() }
guard !resumed else { return }
resumed = true
continuation.resume(returning: value)
}
}
/// Await `operation`, but give up after `timeout` and return `nil`.
///
/// The automation bridge uses this so a wedged MainActor — e.g. a blocking
/// Keychain read on the main thread during sign-in (`AuthService.storedIdToken`
/// → `SecItemCopyMatching`) — can't hang `/state`. Crucially the operation runs
/// in an *unstructured* task, not a `withTaskGroup` child: a task group awaits all
/// children at scope exit, so a non-cancellable wedged `MainActor.run` would hang
/// the timeout itself. Here we resume on whichever finishes first and leave the
/// abandoned operation task to complete (harmlessly) on its own later. Pure and
/// self-contained, so it is hermetically testable.
func awaitWithTimeout<T: Sendable>(
_ timeout: Duration,
operation: @escaping @Sendable () async -> T
) async -> T? {
await withCheckedContinuation { (continuation: CheckedContinuation<T?, Never>) in
let box = TimeoutRaceBox<T>(continuation)
let operationTask = Task { box.resume(await operation()) }
Task {
try? await Task.sleep(for: timeout)
box.resume(nil)
operationTask.cancel()
}
}
}
func liveAutomationSnapshot() async -> DesktopAutomationSnapshot {
// Bound the MainActor hop: if the main thread is wedged (blocking Keychain read
// during sign-in), fall back to the last cached snapshot so `/state` still
// answers instead of hanging the whole bridge. See awaitWithTimeout.
guard let live = await awaitWithTimeout(liveSnapshotMainActorTimeout, operation: liveAutomationSnapshotFromMainActor)
else {
log("DesktopAutomationBridge: live /state refresh timed out (main thread busy); serving cached snapshot")
var stale = await cachedAutomationSnapshot()
stale.snapshotStale = true
return stale
}
return live
}
@Sendable
private func liveAutomationSnapshotFromMainActor() async -> DesktopAutomationSnapshot {
let floating = await MainActor.run {
let floating = FloatingControlBarManager.shared.automationState
return (
isVisible: floating.isVisible,
isAskOmiOpen: OpenAskOmiAutomation.isComposerPresented(),
isAskOmiFocused: OpenAskOmiAutomation.isComposerFocused(),
frame: floating.frame,
isVoiceListening: floating.isVoiceListening,
isVoiceDictating: floating.isVoiceDictating,
isVoiceResponseActive: floating.isVoiceResponseActive,
usesNotchIsland: floating.usesNotchIsland,
isAppActive: NSApp.isActive
)
}
return DesktopAutomationStateStore.shared.updateLiveFields { snapshot in
snapshot.floatingBarVisible = floating.isVisible
snapshot.askOmiOpen = floating.isAskOmiOpen
snapshot.askOmiFocused = floating.isAskOmiFocused
snapshot.floatingBarFrame = floating.frame
snapshot.floatingBarVoiceListening = floating.isVoiceListening
snapshot.floatingBarVoiceDictating = floating.isVoiceDictating
snapshot.floatingBarVoiceResponseActive = floating.isVoiceResponseActive
snapshot.floatingBarUsesNotchIsland = floating.usesNotchIsland
snapshot.isAppActive = floating.isAppActive
snapshot.updatedAt = ISO8601DateFormatter().string(from: Date())
snapshot.snapshotStale = false
}
}
func cachedAutomationSnapshot() async -> DesktopAutomationSnapshot {
var snapshot = DesktopAutomationStateStore.shared.current()
snapshot.updatedAt = ISO8601DateFormatter().string(from: Date())
return snapshot
}
actor DesktopAutomationTraceStore {
static let shared = DesktopAutomationTraceStore()
private var traces: [DesktopAutomationRouteTrace] = []
private let formatter = ISO8601DateFormatter()
func record(method: String, path: String, statusCode: Int, durationMs: Double) {
traces.append(
DesktopAutomationRouteTrace(
method: method,
path: path,
statusCode: statusCode,
durationMs: durationMs,
finishedAt: formatter.string(from: Date())
)
)
if traces.count > 200 {
traces.removeFirst(traces.count - 200)
}
}
func recent(limit: Int = 50) -> [DesktopAutomationRouteTrace] {
Array(traces.suffix(max(1, min(limit, 200))))
}
func clear() {
traces.removeAll(keepingCapacity: true)
}
}
/// In-process registry of semantic, cursor-free actions the automation bridge can
/// run. Handlers invoke the app's real code (notifications, services) directly, so
/// no synthetic mouse events are ever generated — this is the deterministic
/// "command channel" equivalent of the Flutter app's Marionette driver.
///
/// Built-ins are registered at bridge startup. Feature code can register more via
/// `register(name:summary:params:handler:)` (e.g. from a view model's lifecycle) and
/// remove them with `unregister(_:)`.
@MainActor
private func ensureConversationsTabVisibleForAutomation() async throws {
NotificationCenter.default.post(
name: .navigateToSidebarItem,
object: nil,
userInfo: ["rawValue": SidebarNavItem.conversations.rawValue]
)
// Propagate cancellation instead of swallowing it with try? — if the
// automation task is cancelled during the settle sleep, the caller should
// not continue to post further notifications.
try await Task.sleep(nanoseconds: 150_000_000)
}
private func requestAutomationConversationOpen(conversationId: String, showTranscript: Bool) async {
await MainActor.run {
ConversationDetailAutomationState.shared.requestOpen(
conversationId: conversationId,
showTranscript: showTranscript
)
NotificationCenter.default.post(name: .desktopAutomationOpenConversationRequested, object: nil)
}
}
@MainActor
final class DesktopAutomationActionRegistry {
static let shared = DesktopAutomationActionRegistry()
/// Handler runs on the main actor and returns optional string detail for the caller.
typealias Handler = (_ params: [String: String]) async throws -> [String: String]?
private struct Entry {
let descriptor: DesktopAutomationActionDescriptor
let run: Handler
}
/// A 1x1 PNG, for the hermetic half of `screen_frame_quick_look_probe`. Literal bytes rather
/// than a rendered image so the probe has no dependency on capture history, a backend, or AppKit
/// drawing — the thing it is verifying is the panel, not the picture.
static let onePixelPNGBase64 =
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
private var entries: [String: Entry] = [:]
private var didRegisterBuiltins = false
/// Non-prod harness latch so race probes stay busy without relying on LLM latency.
private var harnessBusyUntil: Date?
/// The current typed floating-bar submission and its pre-submit timeline size.
/// The wait action must observe this turn before it may accept an idle state.
private var pendingFloatingBarSubmission: (generation: Int, baselineMessageCount: Int)?
private var floatingBarSubmissionGeneration = 0
private func harnessBusyLatchActive(now: Date = Date()) -> Bool {
guard let until = harnessBusyUntil else { return false }
if now >= until {
harnessBusyUntil = nil
return false
}
return true
}
private func clearHarnessBusyLatch() {
harnessBusyUntil = nil
}
private func armHarnessBusyLatch(holdBusyMs: Int) {
let ms = max(0, holdBusyMs)
guard ms > 0 else { return }
harnessBusyUntil = Date().addingTimeInterval(Double(ms) / 1000.0)
}
func register(
name: String,
summary: String,
params: [String] = [],
category: String? = nil,
surfaces: [String]? = nil,
safety: String? = nil,
sideEffects: [String]? = nil,
examples: [String] = [],
preferSemantic: Bool = true,
handler: @escaping Handler
) {
entries[name] = Entry(
descriptor: DesktopAutomationActionDescriptor(
name: name,
summary: summary,
params: params,
category: category,
surfaces: surfaces,
safety: safety,
sideEffects: sideEffects,
examples: examples,
preferSemantic: preferSemantic
),
run: handler)
}
func unregister(_ name: String) { entries[name] = nil }
func descriptors() -> [DesktopAutomationActionDescriptor] {
entries.values.map(\.descriptor).sorted { $0.name < $1.name }
}
func perform(_ name: String, params: [String: String]) async throws -> [String: String]? {
guard let entry = entries[name] else {
throw DesktopAutomationActionError.unknownAction(name)
}
return try await entry.run(params)
}
/// Register the always-available actions that don't need any view's `@State` —
/// they post the same notifications / hit the same services as the real controls,
/// so they exercise the genuine code paths. Idempotent.
func registerBuiltins() {
guard !didRegisterBuiltins else { return }
didRegisterBuiltins = true
registerOpenOmiShortcutActionsForQA()
register(
name: "set_automation_ui_presentation",
summary:
"Park automation windows quietly, reveal them briefly for Accessibility, or restore normal user presentation",
params: ["mode", "activate"],
category: "app_control",
surfaces: ["app"],
safety: "local_ui_state",
sideEffects: ["changes non-production window placement and input handling"],
examples: [
"./scripts/omi-ctl ui quiet",
"./scripts/omi-ctl ui interactive --activate",
"./scripts/omi-ctl ui normal --activate",
]
) { params in
// This registry is reachable only through DesktopAutomationBridge, whose listener cannot start
// for production-family or published-preview bundles. Keep the handler itself exercisable in a
// hermetic test instead of duplicating the bridge's stronger process boundary here.
guard let requested = params["mode"]?.lowercased() else {
return [
"mode": DesktopAutomationWindowPresentation.currentMode.rawValue,
"available_modes": DesktopAutomationUIPresentationMode.allCases.map(\.rawValue).joined(
separator: ","),
]
}
guard let mode = DesktopAutomationUIPresentationMode(rawValue: requested) else {
throw DesktopAutomationActionError.invalidParams(
"mode must be normal, quiet, or interactive")
}
let activate = boolParam(params["activate"], default: false)
let previous = DesktopAutomationWindowPresentation.setMode(mode, activate: activate)
return [
"previous_mode": previous.rawValue,
"mode": DesktopAutomationWindowPresentation.currentMode.rawValue,
"activated": activate ? "true" : "false",
]
}
// Cursor-free Home-stage and first-use-popup drivers: see their own files for the shared failure mode.
registerHomeStageActions()
registerActivationActions()
registerOpenAskOmiActions()
registerCloseAskOmiActions()
registerPTTRecoveryActions()
registerFirstUsePopupActions()
register(
name: "refresh_all_data",
summary: "Refresh conversations, chat, tasks, and memories (same as Cmd+R)"
) { _ in
NotificationCenter.default.post(name: .refreshAllData, object: nil)
return nil
}
// Posts a real keyDown+keyUp pair through the app's own event queue, so local
// NSEvent monitors and SwiftUI key equivalents see it exactly like a physical
// keypress — lets a headless harness drive keyboard navigation without
// Accessibility permission or a frontmost window. Non-prod only.
register(
name: "post_key",
summary:
"Post a keyDown+keyUp NSEvent through the app event queue (e.g. key_code=124 for right arrow). Non-prod only.",
params: ["key_code", "modifiers"]
) { params in
guard AppBuild.isNonProduction else {
return ["error": "post_key is disabled on production bundles"]
}
guard let codeText = params["key_code"], let keyCode = UInt16(codeText) else {
throw DesktopAutomationActionError.invalidParams("key_code must be a numeric macOS key code")
}
var modifiers: NSEvent.ModifierFlags = []
for token in (params["modifiers"] ?? "").split(separator: ",") {
switch token.trimmingCharacters(in: .whitespaces).lowercased() {
case "command", "cmd": modifiers.insert(.command)
case "shift": modifiers.insert(.shift)
case "option", "alt": modifiers.insert(.option)
case "control", "ctrl": modifiers.insert(.control)
case "function", "fn": modifiers.insert(.function)
case "": break
default:
throw DesktopAutomationActionError.invalidParams("unknown modifier '\(token)'")
}
}
// Arrow keys carry their function-key character and the flags a physical
// press would have, so consumers that look at characters/flags match too.
let arrowCharacters: [UInt16: String] = [
123: "\u{F702}", 124: "\u{F703}", 125: "\u{F701}", 126: "\u{F700}",
]
let characters = arrowCharacters[keyCode] ?? ""
if arrowCharacters[keyCode] != nil {
modifiers.formUnion([.function, .numericPad])
}
let window = NSApp.keyWindow ?? NSApp.mainWindow
var posted = 0
for phase in [NSEvent.EventType.keyDown, .keyUp] {
if let event = NSEvent.keyEvent(
with: phase, location: .zero, modifierFlags: modifiers,
timestamp: ProcessInfo.processInfo.systemUptime,
windowNumber: window?.windowNumber ?? 0, context: nil,
characters: characters, charactersIgnoringModifiers: characters,
isARepeat: false, keyCode: keyCode)
{
NSApp.postEvent(event, atStart: false)
posted += 1
}
}
return [
"posted_events": "\(posted)",
"key_code": "\(keyCode)",
"window": window.map { $0.title.isEmpty ? "untitled" : $0.title } ?? "none",
]
}
// CHAT-05: read the free-tier monthly chat usage-limiter state so a harness can
// prove the counter is deterministic without spending LLM calls. Read-only.
register(
name: "usage_limiter_snapshot",
summary: "Read the free-tier monthly chat usage-limiter state (deterministic counter) — CHAT-05 harness read."
) { _ in
await MainActor.run {
let limiter = FloatingBarUsageLimiter.shared
let banner = ChatQuotaBanner.current(
quota: limiter.serverQuota,
optimisticDelta: limiter.optimisticDelta,
dismissed: ChatQuotaBannerDismissals.shared.dismissed)
return [
"is_limit_reached": limiter.isLimitReached ? "true" : "false",
"remaining_queries": "\(limiter.remainingQueries)",
"limit_description": limiter.limitDescription,
"banner_threshold": banner.map { "\($0.threshold)" } ?? "none",
"rendered_banner_threshold": ChatQuotaBannerPresentation.shared.rendered
.map { "\($0.threshold)" } ?? "none",
"rendered_banner_title": ChatQuotaBannerPresentation.shared.rendered?.title ?? "",
"banner_title": banner?.title ?? "",
"banner_message": banner?.message ?? "",
]
}
}
// CHAT-05: reset the usage-limiter counter so a harness can prove it is
// dev-resettable (the criterion's second half) without driving real LLM usage.
register(
name: "reset_usage_limiter",
summary: "Reset the free-tier monthly chat usage-limiter counter (dev-resettable proof) — CHAT-05. Non-prod only."
) { _ in
guard AppBuild.isNonProduction else {
return ["error": "reset_usage_limiter is disabled on production bundles"]
}
return await MainActor.run {
let limiter = FloatingBarUsageLimiter.shared
limiter.reset()
return [
"reset": "true",
"is_limit_reached": limiter.isLimitReached ? "true" : "false",
"remaining_queries": "\(limiter.remainingQueries)",
]
}
}
// Seeds the quota snapshot the chat-quota warnings key off, so a harness can
// walk 90/100 without spending a month of real questions. Non-prod only.
register(
name: "apply_usage_quota",
summary: "Seed the chat usage-quota snapshot (threshold-warning harness). Non-prod only.",
params: ["used", "limit", "plan", "unit", "is_overage_plan", "reset_at"]
) { params in
guard AppBuild.isNonProduction else {
return ["error": "apply_usage_quota is disabled on production bundles"]
}
guard let used = params["used"].flatMap(Double.init) else {
throw DesktopAutomationActionError.invalidParams("used must be a number")
}
var json: [String: Any] = [
"plan": params["plan"] ?? "Operator",
"plan_type": "operator",
"unit": params["unit"] ?? "questions",
"used": used,
"percent": 0,
"allowed": true,
]
if let limit = params["limit"].flatMap(Double.init) {
json["limit"] = limit
json["allowed"] = used < limit
}
if let resetAt = params["reset_at"].flatMap(Int.init) { json["reset_at"] = resetAt }
if let overage = params["is_overage_plan"] { json["is_overage_plan"] = overage == "true" }
let data = try JSONSerialization.data(withJSONObject: json)
let quota = try JSONDecoder().decode(APIClient.ChatUsageQuota.self, from: data)
return await MainActor.run {
let limiter = FloatingBarUsageLimiter.shared
limiter.applyQuota(quota)
// Seeding a cycle must produce the banner it asks for; a dismissal left
// over from an earlier run would silently suppress it.
ChatQuotaBannerDismissals.shared.reset()
return [
"applied": "true",
"used": "\(quota.used)",
"limit": "\(quota.limit ?? -1)",
"is_limit_reached": limiter.isLimitReached ? "true" : "false",
]
}
}
register(
name: "task_capture_fixture",
summary: "Evaluate canonical screen-capture policy facts without screenshot bytes",
params: ["facts_json"]
) { params in
guard let json = params["facts_json"], let data = json.data(using: .utf8) else {
throw DesktopAutomationActionError.invalidParams("facts_json must be canonical capture facts JSON")
}
guard let payload = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
throw DesktopAutomationActionError.invalidParams("facts_json must be a JSON object")
}
func value<T>(_ camel: String, _ snake: String, default fallback: T) -> T {
payload[camel] as? T ?? payload[snake] as? T ?? fallback
}
let facts = ScreenCaptureFacts(
explicitCommand: value("explicitCommand", "explicit_command", default: false),
clearCommitment: value("clearCommitment", "clear_commitment", default: false),
concreteDeliverable: value("concreteDeliverable", "concrete_deliverable", default: false),
directRequest: value("directRequest", "direct_request", default: false),
inferredNextStep: value("inferredNextStep", "inferred_next_step", default: false),
owner: value("owner", "owner", default: "unknown"),
publicBroadcast: value("publicBroadcast", "public_broadcast", default: false),
directMention: value("directMention", "direct_mention", default: false),
alreadyDone: value("alreadyDone", "already_done", default: false),
duplicateOf: payload["duplicateOf"] as? String ?? payload["duplicate_of"] as? String,
refinesTask: payload["refinesTask"] as? String ?? payload["refines_task"] as? String,
captureConfidence: value("captureConfidence", "capture_confidence", default: 0.5),