synheart-sensor-agent 0.2.2

Privacy-first PC background sensor for behavioral research
Documentation
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
//! macOS implementation of event collection using CGEvent tap.
//!
//! This module captures keyboard and mouse events at the system level using
//! macOS's Core Graphics event tap API. It requires Input Monitoring permission.

use crate::collector::types::{
    KeyboardEvent, KeyboardEventType, MouseEvent, SensorEvent, ShortcutEvent, ShortcutType,
};
use core_foundation::runloop::{kCFRunLoopCommonModes, CFRunLoop};
use core_graphics::event::{
    CGEvent, CGEventTap, CGEventTapLocation, CGEventTapOptions, CGEventTapPlacement, CGEventType,
    CallbackResult,
};
use crossbeam_channel::{bounded, Receiver, Sender};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread::{self, JoinHandle};

/// Configuration for which event sources to capture.
#[derive(Debug, Clone)]
pub struct CollectorConfig {
    /// Whether to capture keyboard events (timing only, not key content).
    pub capture_keyboard: bool,
    /// Whether to capture mouse events (speed/magnitude only, not coordinates).
    pub capture_mouse: bool,
}

impl Default for CollectorConfig {
    fn default() -> Self {
        Self {
            capture_keyboard: true,
            capture_mouse: true,
        }
    }
}

/// The macOS event collector using CGEvent tap.
pub struct MacOSCollector {
    config: CollectorConfig,
    sender: Sender<SensorEvent>,
    receiver: Receiver<SensorEvent>,
    running: Arc<AtomicBool>,
    thread_handle: Option<JoinHandle<()>>,
}

impl MacOSCollector {
    /// Create a new macOS collector with the given configuration.
    pub fn new(config: CollectorConfig) -> Self {
        // Use a bounded channel to prevent unbounded memory growth
        let (sender, receiver) = bounded(10_000);

        Self {
            config,
            sender,
            receiver,
            running: Arc::new(AtomicBool::new(false)),
            thread_handle: None,
        }
    }

    /// Start capturing events in a background thread.
    ///
    /// Returns an error if:
    /// - The collector is already running
    /// - Input Monitoring permission is not granted
    pub fn start(&mut self) -> Result<(), CollectorError> {
        if self.running.load(Ordering::SeqCst) {
            return Err(CollectorError::AlreadyRunning);
        }

        self.running.store(true, Ordering::SeqCst);

        let sender = self.sender.clone();
        let running = self.running.clone();
        let config = self.config.clone();

        let handle = thread::spawn(move || {
            if let Err(e) = run_event_loop(sender, running.clone(), config) {
                eprintln!("Event loop error: {e:?}");
            }
            running.store(false, Ordering::SeqCst);
        });

        self.thread_handle = Some(handle);
        Ok(())
    }

    /// Stop capturing events.
    pub fn stop(&mut self) {
        self.running.store(false, Ordering::SeqCst);
        if let Some(handle) = self.thread_handle.take() {
            // The thread should exit when running becomes false
            let _ = handle.join();
        }
    }

    /// Check if the collector is currently running.
    pub fn is_running(&self) -> bool {
        self.running.load(Ordering::SeqCst)
    }

    /// Get the receiver for sensor events.
    pub fn receiver(&self) -> &Receiver<SensorEvent> {
        &self.receiver
    }

    /// Try to receive an event without blocking.
    pub fn try_recv(&self) -> Option<SensorEvent> {
        self.receiver.try_recv().ok()
    }
}

impl Drop for MacOSCollector {
    fn drop(&mut self) {
        self.stop();
    }
}

/// Errors that can occur during event collection.
#[derive(Debug)]
pub enum CollectorError {
    /// The collector is already running and cannot be started again.
    AlreadyRunning,
    /// Input Monitoring permission has not been granted by the user.
    PermissionDenied,
    /// Failed to create a CGEvent tap (Core Graphics).
    TapCreationFailed,
    /// Failed to create a run-loop source from the event tap.
    RunLoopSourceFailed,
}

impl std::fmt::Display for CollectorError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CollectorError::AlreadyRunning => write!(f, "Collector is already running"),
            CollectorError::PermissionDenied => {
                write!(f, "Input Monitoring permission not granted")
            }
            CollectorError::TapCreationFailed => write!(f, "Failed to create CGEvent tap"),
            CollectorError::RunLoopSourceFailed => {
                write!(f, "Failed to create run loop source")
            }
        }
    }
}

impl std::error::Error for CollectorError {}

/// Build a list of event types to capture based on configuration.
fn build_event_types(config: &CollectorConfig) -> Vec<CGEventType> {
    let mut types = Vec::new();

    if config.capture_keyboard {
        types.push(CGEventType::KeyDown);
        types.push(CGEventType::KeyUp);
        types.push(CGEventType::FlagsChanged);
    }

    if config.capture_mouse {
        types.push(CGEventType::MouseMoved);
        types.push(CGEventType::LeftMouseDown);
        types.push(CGEventType::LeftMouseUp);
        types.push(CGEventType::RightMouseDown);
        types.push(CGEventType::RightMouseUp);
        types.push(CGEventType::LeftMouseDragged);
        types.push(CGEventType::RightMouseDragged);
        types.push(CGEventType::ScrollWheel);
    }

    types
}

/// Run the Core Graphics event loop.
fn run_event_loop(
    sender: Sender<SensorEvent>,
    running: Arc<AtomicBool>,
    config: CollectorConfig,
) -> Result<(), CollectorError> {
    // Build the list of event types to capture
    let event_types = build_event_types(&config);

    // Store sender in a thread-local for the callback
    // Note: We need to use a different approach since the callback can't capture variables
    thread_local! {
        static EVENT_SENDER: std::cell::RefCell<Option<Sender<SensorEvent>>> = const { std::cell::RefCell::new(None) };
    }

    EVENT_SENDER.with(|s| {
        *s.borrow_mut() = Some(sender);
    });

    // Callback function for CGEvent tap
    fn event_callback(
        _proxy: core_graphics::event::CGEventTapProxy,
        event_type: CGEventType,
        event: &CGEvent,
    ) -> CallbackResult {
        thread_local! {
            static EVENT_SENDER: std::cell::RefCell<Option<Sender<SensorEvent>>> = const { std::cell::RefCell::new(None) };
        }

        // Try to get the sender and process the event
        EVENT_SENDER.with(|sender_cell| {
            if let Some(ref sender) = *sender_cell.borrow() {
                if let Some(sensor_event) = process_cg_event(event_type, event) {
                    // Don't block if the channel is full - just drop the event
                    let _ = sender.try_send(sensor_event);
                }
            }
        });

        // Return the event unchanged (we're passive observers)
        CallbackResult::Keep
    }

    // Create the event tap
    let tap = CGEventTap::new(
        CGEventTapLocation::Session,
        CGEventTapPlacement::HeadInsertEventTap,
        CGEventTapOptions::ListenOnly,
        event_types,
        event_callback,
    )
    .map_err(|_| CollectorError::TapCreationFailed)?;

    // Create the run loop source
    let source = tap
        .mach_port()
        .create_runloop_source(0)
        .map_err(|_| CollectorError::RunLoopSourceFailed)?;

    // Add source to the run loop
    let run_loop = CFRunLoop::get_current();
    unsafe {
        run_loop.add_source(&source, kCFRunLoopCommonModes);
    }

    // Enable the tap
    tap.enable();

    // Run the loop until stopped
    while running.load(Ordering::SeqCst) {
        // Run the loop for a short interval, then check if we should stop
        CFRunLoop::run_in_mode(
            unsafe { kCFRunLoopCommonModes },
            std::time::Duration::from_millis(100),
            false,
        );
    }

    // The tap is automatically disabled when dropped
    Ok(())
}

/// Classify a keyboard event based on key code.
///
/// Privacy: The key code is used only for classification and is immediately discarded.
/// The actual key code value is never stored or transmitted. Only the category
/// (typing, navigation, backspace, etc.) is recorded.
pub(crate) fn classify_keyboard_event(event: &CGEvent) -> KeyboardEventType {
    let keycode =
        event.get_integer_value_field(core_graphics::event::EventField::KEYBOARD_EVENT_KEYCODE);

    classify_keycode(keycode)
}

/// Classify a keycode into a KeyboardEventType category.
///
/// Privacy: The key code is used only for classification and is immediately discarded.
pub(crate) fn classify_keycode(keycode: i64) -> KeyboardEventType {
    // macOS virtual key codes
    // Navigation keys
    const KEY_LEFT_ARROW: i64 = 123;
    const KEY_RIGHT_ARROW: i64 = 124;
    const KEY_DOWN_ARROW: i64 = 125;
    const KEY_UP_ARROW: i64 = 126;
    const KEY_PAGE_UP: i64 = 116;
    const KEY_PAGE_DOWN: i64 = 121;
    const KEY_HOME: i64 = 115;
    const KEY_END: i64 = 119;

    // Special keys
    const KEY_BACKSPACE: i64 = 51;
    const KEY_DELETE: i64 = 117;
    const KEY_RETURN: i64 = 36;
    const KEY_TAB: i64 = 48;
    const KEY_ESCAPE: i64 = 53;

    // Function keys F1-F12
    const KEY_F1: i64 = 122;
    const KEY_F2: i64 = 120;
    const KEY_F3: i64 = 99;
    const KEY_F4: i64 = 118;
    const KEY_F5: i64 = 96;
    const KEY_F6: i64 = 97;
    const KEY_F7: i64 = 98;
    const KEY_F8: i64 = 100;
    const KEY_F9: i64 = 101;
    const KEY_F10: i64 = 109;
    const KEY_F11: i64 = 103;
    const KEY_F12: i64 = 111;

    match keycode {
        KEY_LEFT_ARROW | KEY_RIGHT_ARROW | KEY_DOWN_ARROW | KEY_UP_ARROW | KEY_PAGE_UP
        | KEY_PAGE_DOWN | KEY_HOME | KEY_END => KeyboardEventType::NavigationKey,
        KEY_BACKSPACE => KeyboardEventType::Backspace,
        KEY_DELETE => KeyboardEventType::Delete,
        KEY_RETURN => KeyboardEventType::Enter,
        KEY_TAB => KeyboardEventType::Tab,
        KEY_ESCAPE => KeyboardEventType::Escape,
        KEY_F1 | KEY_F2 | KEY_F3 | KEY_F4 | KEY_F5 | KEY_F6 | KEY_F7 | KEY_F8 | KEY_F9
        | KEY_F10 | KEY_F11 | KEY_F12 => KeyboardEventType::FunctionKey,
        _ => KeyboardEventType::TypingTap,
    }
}

/// Detect if a key event with modifier flags represents a known shortcut.
///
/// Privacy: The key code is used only for shortcut detection and is immediately discarded.
/// Only the shortcut category (copy, paste, etc.) is recorded, never the specific keys.
fn detect_shortcut(event: &CGEvent) -> Option<ShortcutType> {
    use core_graphics::event::CGEventFlags;

    let flags = event.get_flags();
    let keycode =
        event.get_integer_value_field(core_graphics::event::EventField::KEYBOARD_EVENT_KEYCODE);

    // Check if Command (macOS) or Control modifier is held
    let has_cmd = flags.contains(CGEventFlags::CGEventFlagCommand);
    if !has_cmd {
        return None;
    }

    let has_shift = flags.contains(CGEventFlags::CGEventFlagShift);

    // macOS virtual key codes for shortcut keys
    const KEY_C: i64 = 8;
    const KEY_V: i64 = 9;
    const KEY_X: i64 = 7;
    const KEY_Z: i64 = 6;
    const KEY_A: i64 = 0;
    const KEY_S: i64 = 1;

    match keycode {
        KEY_C => Some(ShortcutType::Copy),
        KEY_V => Some(ShortcutType::Paste),
        KEY_X => Some(ShortcutType::Cut),
        KEY_Z if has_shift => Some(ShortcutType::Redo),
        KEY_Z => Some(ShortcutType::Undo),
        KEY_A => Some(ShortcutType::SelectAll),
        KEY_S => Some(ShortcutType::Save),
        _ => None,
    }
}

/// Process a CGEvent and convert it to a SensorEvent.
///
/// Privacy: This function ONLY extracts timing and magnitude information,
/// never key codes, characters, or absolute coordinates. Key codes are used
/// internally only to classify events as navigation vs typing, then discarded.
fn process_cg_event(event_type: CGEventType, event: &CGEvent) -> Option<SensorEvent> {
    use core_graphics::event::CGEventType::*;

    match event_type {
        // Keyboard events - capture timing and classification only, NO key codes stored
        KeyDown => {
            // Check for shortcut first - emit Shortcut event INSTEAD of keyboard event
            if let Some(shortcut_type) = detect_shortcut(event) {
                return Some(SensorEvent::Shortcut(ShortcutEvent {
                    timestamp: chrono::Utc::now(),
                    shortcut_type,
                }));
            }
            let event_class = classify_keyboard_event(event);
            Some(SensorEvent::Keyboard(KeyboardEvent::with_type(
                true,
                event_class,
            )))
        }
        KeyUp => {
            let event_class = classify_keyboard_event(event);
            Some(SensorEvent::Keyboard(KeyboardEvent::with_type(
                false,
                event_class,
            )))
        }
        FlagsChanged => {
            // Modifier key change - classify as ModifierKey
            // We can't easily determine down/up for modifiers, so we just record it as down
            Some(SensorEvent::Keyboard(KeyboardEvent::with_type(
                true,
                KeyboardEventType::ModifierKey,
            )))
        }

        // Mouse movement - capture delta magnitude only, NO absolute position
        MouseMoved | LeftMouseDragged | RightMouseDragged => {
            // Get the delta (movement amount), not the absolute position
            let delta_x =
                event.get_double_value_field(core_graphics::event::EventField::MOUSE_EVENT_DELTA_X);
            let delta_y =
                event.get_double_value_field(core_graphics::event::EventField::MOUSE_EVENT_DELTA_Y);

            Some(SensorEvent::Mouse(MouseEvent::movement(delta_x, delta_y)))
        }

        // Click events - left button
        LeftMouseDown => Some(SensorEvent::Mouse(MouseEvent::click(true))),
        LeftMouseUp => None, // We only count the down event as a "click"

        // Click events - right button
        RightMouseDown => Some(SensorEvent::Mouse(MouseEvent::click(false))),
        RightMouseUp => None, // We only count the down event as a "click"

        // Scroll events
        ScrollWheel => {
            let delta_x = event.get_double_value_field(
                core_graphics::event::EventField::SCROLL_WHEEL_EVENT_POINT_DELTA_AXIS_2,
            );
            let delta_y = event.get_double_value_field(
                core_graphics::event::EventField::SCROLL_WHEEL_EVENT_POINT_DELTA_AXIS_1,
            );

            Some(SensorEvent::Mouse(MouseEvent::scroll(delta_x, delta_y)))
        }

        // Ignore other event types
        _ => None,
    }
}

/// Get the bundle identifier of the current frontmost application.
///
/// Privacy: Only the bundle identifier (e.g. "com.apple.Safari") is captured.
/// No window titles, file names, URLs, or document content is ever accessed.
#[allow(unexpected_cfgs)]
pub fn get_frontmost_app_id() -> Option<String> {
    use objc::runtime::{Class, Object};
    use objc::{msg_send, sel, sel_impl};
    use std::ffi::CStr;

    unsafe {
        let cls = Class::get("NSWorkspace")?;

        let workspace: *mut Object = msg_send![cls, sharedWorkspace];
        if workspace.is_null() {
            return None;
        }

        let app: *mut Object = msg_send![workspace, frontmostApplication];
        if app.is_null() {
            return None;
        }

        let bundle_id: *mut Object = msg_send![app, bundleIdentifier];
        if bundle_id.is_null() {
            return None;
        }

        let c_str: *const std::os::raw::c_char = msg_send![bundle_id, UTF8String];
        if c_str.is_null() {
            return None;
        }

        Some(CStr::from_ptr(c_str).to_string_lossy().into_owned())
    }
}

/// Check if the application has Input Monitoring permission.
///
/// Note: This doesn't actually check the permission - macOS doesn't provide
/// a direct API for that. Instead, attempting to create the tap will fail
/// if permission is not granted.
pub fn check_permission() -> bool {
    // On macOS 10.15+, we can try to create a passive tap to check permission
    // If it fails, permission is likely not granted
    let result = CGEventTap::new(
        CGEventTapLocation::Session,
        CGEventTapPlacement::HeadInsertEventTap,
        CGEventTapOptions::ListenOnly,
        vec![CGEventType::KeyDown],
        |_proxy, _type, _event| CallbackResult::Keep,
    );

    result.is_ok()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_collector_config_default() {
        let config = CollectorConfig::default();
        assert!(config.capture_keyboard);
        assert!(config.capture_mouse);
    }

    #[test]
    fn test_collector_creation() {
        let collector = MacOSCollector::new(CollectorConfig::default());
        assert!(!collector.is_running());
    }

    #[test]
    fn test_classify_keycode_navigation() {
        assert_eq!(classify_keycode(123), KeyboardEventType::NavigationKey); // Left arrow
        assert_eq!(classify_keycode(124), KeyboardEventType::NavigationKey); // Right arrow
        assert_eq!(classify_keycode(125), KeyboardEventType::NavigationKey); // Down arrow
        assert_eq!(classify_keycode(126), KeyboardEventType::NavigationKey); // Up arrow
        assert_eq!(classify_keycode(116), KeyboardEventType::NavigationKey); // Page Up
        assert_eq!(classify_keycode(121), KeyboardEventType::NavigationKey); // Page Down
        assert_eq!(classify_keycode(115), KeyboardEventType::NavigationKey); // Home
        assert_eq!(classify_keycode(119), KeyboardEventType::NavigationKey); // End
    }

    #[test]
    fn test_classify_keycode_special_keys() {
        assert_eq!(classify_keycode(51), KeyboardEventType::Backspace);
        assert_eq!(classify_keycode(117), KeyboardEventType::Delete);
        assert_eq!(classify_keycode(36), KeyboardEventType::Enter);
        assert_eq!(classify_keycode(48), KeyboardEventType::Tab);
        assert_eq!(classify_keycode(53), KeyboardEventType::Escape);
    }

    #[test]
    fn test_classify_keycode_function_keys() {
        assert_eq!(classify_keycode(122), KeyboardEventType::FunctionKey); // F1
        assert_eq!(classify_keycode(120), KeyboardEventType::FunctionKey); // F2
        assert_eq!(classify_keycode(99), KeyboardEventType::FunctionKey); // F3
        assert_eq!(classify_keycode(118), KeyboardEventType::FunctionKey); // F4
        assert_eq!(classify_keycode(96), KeyboardEventType::FunctionKey); // F5
        assert_eq!(classify_keycode(97), KeyboardEventType::FunctionKey); // F6
        assert_eq!(classify_keycode(98), KeyboardEventType::FunctionKey); // F7
        assert_eq!(classify_keycode(100), KeyboardEventType::FunctionKey); // F8
        assert_eq!(classify_keycode(101), KeyboardEventType::FunctionKey); // F9
        assert_eq!(classify_keycode(109), KeyboardEventType::FunctionKey); // F10
        assert_eq!(classify_keycode(103), KeyboardEventType::FunctionKey); // F11
        assert_eq!(classify_keycode(111), KeyboardEventType::FunctionKey); // F12
    }

    #[test]
    fn test_classify_keycode_typing() {
        // Regular letter keys should be typing taps
        assert_eq!(classify_keycode(0), KeyboardEventType::TypingTap); // A
        assert_eq!(classify_keycode(1), KeyboardEventType::TypingTap); // S
        assert_eq!(classify_keycode(13), KeyboardEventType::TypingTap); // W
        assert_eq!(classify_keycode(49), KeyboardEventType::TypingTap); // Space
    }

    #[test]
    fn test_get_frontmost_app_id() {
        // Should return Some(...) when running in a GUI environment on macOS
        let app_id = get_frontmost_app_id();
        // Can be None in headless CI, so just check it doesn't panic
        if let Some(ref id) = app_id {
            assert!(!id.is_empty());
        }
    }
}