Something went wrong. Try again.
A small AI buddy that lives in the bottom right-hand corner of your Mac that wakes when you press a keybind.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142import AppKit
/// Watches the user do a task and writes it down as plain-language steps: each click as the control/// that was clicked, each run of typing as one step. Passwords are never written down.@MainActorfinal class LessonRecorder { private(set) var steps: [String] = [] var onChange: ((Int) -> Void)?
private var monitors: [Any] = [] private var typed = "" private var typedInto = "" private var skippedSecret = false
private static let namedKeys: [UInt16: String] = [ 36: "Return", 76: "Return", 48: "Tab", 53: "Escape", 117: "Forward Delete", 126: "Up arrow", 125: "Down arrow", 123: "Left arrow", 124: "Right arrow", ]
func start() { steps = [] typed = "" skippedSecret = false let click = NSEvent.addGlobalMonitorForEvents(matching: .leftMouseDown) { [weak self] event in guard let point = event.cgEvent?.location else { return } MainActor.assumeIsolated { self?.recordClick(at: point) } } let key = NSEvent.addGlobalMonitorForEvents(matching: .keyDown) { [weak self] event in if event.cgEvent?.getIntegerValueField(.eventSourceUserData) == ActionExecutor.syntheticEventMarker { return } let code = event.keyCode, flags = event.modifierFlags let characters = event.charactersIgnoringModifiers ?? "", typedCharacters = event.characters ?? "" MainActor.assumeIsolated { self?.recordKey(code: code, flags: flags, characters: characters, typed: typedCharacters) } } monitors = [click, key].compactMap { $0 } }
/// Stops watching and returns the steps. @discardableResult func stop() -> [String] { monitors.forEach(NSEvent.removeMonitor) monitors = [] flushTyped() return steps }
private func recordClick(at point: CGPoint) { flushTyped() skippedSecret = false guard let target = ScreenObserver.target(at: point), target.pid != ProcessInfo.processInfo.processIdentifier else { return } add(target.label.isEmpty ? "Click in \(target.app)" : "Click \(target.role) \"\(target.label)\" in \(target.app)") }
private func recordKey(code: UInt16, flags: NSEvent.ModifierFlags, characters: String, typed text: String) { if flags.contains(.command) || flags.contains(.control) { flushTyped() let symbols = (flags.contains(.control) ? "⌃" : "") + (flags.contains(.option) ? "⌥" : "") + (flags.contains(.shift) ? "⇧" : "") + (flags.contains(.command) ? "⌘" : "") add("Press \(symbols)\(characters.uppercased())") } else if code == 51 { if typed.isEmpty { add("Press Delete") } else { typed.removeLast() } } else if let name = Self.namedKeys[code] { flushTyped() add("Press \(name)") } else if !text.isEmpty, text.unicodeScalars.allSatisfy({ !CharacterSet.controlCharacters.contains($0) && $0.value < 0xF700 }) { if typed.isEmpty { let field = ScreenObserver.focusedField() if field?.isSecure == true { if !skippedSecret { add("Type the password (not recorded)") } skippedSecret = true return } typedInto = field?.label.isEmpty == false ? "\(field!.role) \"\(field!.label)\"" : "" } guard !skippedSecret else { return } typed += text } }
private func flushTyped() { guard !typed.isEmpty else { return } add("Type \"\(typed.prefix(200))\"" + (typedInto.isEmpty ? "" : " into \(typedInto)")) typed = "" typedInto = "" }
private func add(_ step: String) { steps.append(step) onChange?(steps.count) }}
extension ScreenObserver { struct ClickTarget { let app: String let pid: pid_t let role: String let label: String }
/// The control under a point (global, top-left origin), named by its own label or the nearest labeled parent. static func target(at point: CGPoint) -> ClickTarget? { var hit: AXUIElement? guard AXUIElementCopyElementAtPosition(AXUIElementCreateSystemWide(), Float(point.x), Float(point.y), &hit) == .success, let start = hit else { return nil } var pid: pid_t = 0 AXUIElementGetPid(start, &pid) let app = NSRunningApplication(processIdentifier: pid)?.localizedName ?? "an app"
var node: AXUIElement? = start for _ in 0..<4 { guard let element = node else { break } let axRole = copy(element, kAXRoleAttribute) as? String ?? "" let isText = textRoles.contains(axRole) let label = firstNonEmpty( copy(element, kAXTitleAttribute) as? String, copy(element, kAXDescriptionAttribute) as? String, isText ? nil : copy(element, kAXValueAttribute) as? String, copy(element, kAXPlaceholderValueAttribute) as? String ) ?? descendantText(of: element, depth: 2) if let label { return ClickTarget(app: app, pid: pid, role: roleNames[axRole] ?? "item", label: String(label.prefix(80))) } node = copy(element, kAXParentAttribute) as! AXUIElement? } return ClickTarget(app: app, pid: pid, role: "", label: "") }
/// The field that has the keyboard focus, system-wide. static func focusedField() -> (role: String, label: String, isSecure: Bool)? { guard let value = copy(AXUIElementCreateSystemWide(), kAXFocusedUIElementAttribute) else { return nil } let element = value as! AXUIElement let axRole = copy(element, kAXRoleAttribute) as? String ?? "" let subrole = copy(element, kAXSubroleAttribute) as? String let label = firstNonEmpty( copy(element, kAXTitleAttribute) as? String, copy(element, kAXDescriptionAttribute) as? String, copy(element, kAXPlaceholderValueAttribute) as? String ) ?? "" return (roleNames[subrole == "AXSearchField" ? "AXSearchField" : axRole] ?? "field", String(label.prefix(80)), subrole == "AXSecureTextField") }}