Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

Vision Streaming (#1110)

Ezra Ellette21f46284ba20
diff --git a/screenpipe-server/src/auto_destruct.rs b/screenpipe-server/src/auto_destruct.rs
index 80a7d802e..553f9c82b 100644
--- a/screenpipe-server/src/auto_destruct.rs
+++ b/screenpipe-server/src/auto_destruct.rs
@@ -1,12 +1,15 @@
use std::process::Command;
use std::time::Duration;
use tokio::time::sleep;
-
-use tracing::{debug, info};
+#[cfg(target_os = "windows")]
+use tracing::debug;
+use tracing::info;
#[cfg(target_os = "windows")]
use windows::Win32::Foundation::{CloseHandle, HANDLE, STILL_ACTIVE};
#[cfg(target_os = "windows")]
-use windows::Win32::System::Threading::{OpenProcess, PROCESS_QUERY_INFORMATION, GetExitCodeProcess};
+use windows::Win32::System::Threading::{
+ GetExitCodeProcess, OpenProcess, PROCESS_QUERY_INFORMATION,
+};
#[cfg(target_os = "windows")]
fn is_process_alive(pid: u32) -> bool {
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index afaea086f..57494f7f3 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -457,10 +457,14 @@ async fn main() -> anyhow::Result<()> {
let audio_chunk_duration = Duration::from_secs(cli.audio_chunk_duration);
let (realtime_transcription_sender, _) = tokio::sync::broadcast::channel(1000);
let realtime_transcription_sender_clone = realtime_transcription_sender.clone();
+ let (realtime_vision_sender, _) = tokio::sync::broadcast::channel(1000);
+ let realtime_vision_sender = Arc::new(realtime_vision_sender.clone());
+ let realtime_vision_sender_clone = realtime_vision_sender.clone();
let handle = {
let runtime = &tokio::runtime::Handle::current();
runtime.spawn(async move {
loop {
+ let realtime_vision_sender_clone = realtime_vision_sender.clone();
let vad_engine_clone = vad_engine.clone(); // Clone it here for each iteration
let mut shutdown_rx = shutdown_tx_clone.subscribe();
let realtime_transcription_sender_clone = realtime_transcription_sender.clone(); // Clone inside the loop
@@ -491,6 +495,7 @@ async fn main() -> anyhow::Result<()> {
cli.enable_realtime_audio_transcription,
Arc::new(cli.realtime_audio_transcription_engine.clone().into()),
Arc::new(realtime_transcription_sender_clone), // Use the cloned sender
+ realtime_vision_sender_clone,
);
let result = tokio::select! {
@@ -530,6 +535,8 @@ async fn main() -> anyhow::Result<()> {
// Track search requests
}
};
+
+ let realtime_vision_sender_clone = realtime_vision_sender_clone.clone();
// TODO: Add SSE stream for realtime audio transcription
let server = Server::new(
db_server,
@@ -543,6 +550,7 @@ async fn main() -> anyhow::Result<()> {
cli.enable_ui_monitoring,
cli.enable_realtime_audio_transcription,
realtime_transcription_sender_clone,
+ realtime_vision_sender_clone.clone(),
);
// print screenpipe in gradient
@@ -892,7 +900,7 @@ async fn main() -> anyhow::Result<()> {
loop {
tokio::select! {
- result = run_ui() => {
+ result = run_ui(realtime_vision_sender_clone.clone()) => {
match result {
Ok(_) => break,
Err(e) => {
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index 6e9b5c3d6..87cedd5d6 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -14,6 +14,7 @@ use screenpipe_audio::{
use screenpipe_audio::{start_realtime_recording, AudioStream};
use screenpipe_core::pii_removal::remove_pii;
use screenpipe_core::Language;
+use screenpipe_vision::core::{RealtimeVisionEvent, WindowOcr};
use screenpipe_vision::OcrEngine;
use std::collections::HashMap;
use std::path::PathBuf;
@@ -51,6 +52,7 @@ pub async fn start_continuous_recording(
realtime_audio_enabled: bool,
realtime_transcription_engine: Arc<AudioTranscriptionEngine>,
realtime_transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,
+ realtime_vision_sender: Arc<tokio::sync::broadcast::Sender<RealtimeVisionEvent>>,
) -> Result<()> {
debug!("Starting video recording for monitor {:?}", monitor_ids);
let video_tasks = if !vision_disabled {
@@ -63,6 +65,7 @@ pub async fn start_continuous_recording(
let ocr_engine = Arc::clone(&ocr_engine);
let ignored_windows_video = ignored_windows.to_vec();
let include_windows_video = include_windows.to_vec();
+ let realtime_vision_sender_clone = realtime_vision_sender.clone();
let languages = languages.clone();
@@ -81,6 +84,7 @@ pub async fn start_continuous_recording(
video_chunk_duration,
languages.clone(),
capture_unfocused_windows,
+ realtime_vision_sender_clone,
)
.await
})
@@ -186,6 +190,7 @@ async fn record_video(
video_chunk_duration: Duration,
languages: Vec<Language>,
capture_unfocused_windows: bool,
+ realtime_vision_sender: Arc<tokio::sync::broadcast::Sender<RealtimeVisionEvent>>,
) -> Result<()> {
debug!("record_video: Starting");
let db_chunk_callback = Arc::clone(&db);
@@ -237,6 +242,17 @@ async fn record_video(
} else {
&window_result.text
};
+
+ let _ = realtime_vision_sender.send(RealtimeVisionEvent::Ocr(WindowOcr {
+ image: Some(frame.image.clone()),
+ text: text.clone(),
+ text_json: window_result.text_json.clone(),
+ app_name: window_result.app_name.clone(),
+ window_name: window_result.window_name.clone(),
+ focused: window_result.focused,
+ confidence: window_result.confidence,
+ timestamp: frame.timestamp,
+ }));
if let Err(e) = db
.insert_ocr_text(
frame_id,
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 91ba53b4a..6eb866ba1 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -30,8 +30,8 @@ use screenpipe_audio::{
default_input_device, default_output_device, list_audio_devices,
realtime::RealtimeTranscriptionEvent, AudioDevice, DeviceControl, DeviceType,
};
-use screenpipe_vision::monitor::list_monitors;
use screenpipe_vision::OcrEngine;
+use screenpipe_vision::{core::RealtimeVisionEvent, monitor::list_monitors};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{json, Value};
use std::{
@@ -73,6 +73,7 @@ pub struct AppState {
pub realtime_transcription_enabled: bool,
pub realtime_transcription_sender:
Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,
+ pub realtime_vision_sender: Arc<tokio::sync::broadcast::Sender<RealtimeVisionEvent>>,
}
// Update the SearchQuery struct
@@ -807,6 +808,7 @@ pub struct Server {
ui_monitoring_enabled: bool,
realtime_transcription_enabled: bool,
realtime_transcription_sender: tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>,
+ realtime_vision_sender: Arc<tokio::sync::broadcast::Sender<RealtimeVisionEvent>>,
}
impl Server {
@@ -823,6 +825,7 @@ impl Server {
ui_monitoring_enabled: bool,
realtime_transcription_enabled: bool,
realtime_transcription_sender: tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>,
+ realtime_vision_sender: Arc<tokio::sync::broadcast::Sender<RealtimeVisionEvent>>,
) -> Self {
Server {
db,
@@ -836,6 +839,7 @@ impl Server {
ui_monitoring_enabled,
realtime_transcription_enabled,
realtime_transcription_sender,
+ realtime_vision_sender,
}
}
@@ -870,6 +874,7 @@ impl Server {
},
realtime_transcription_enabled: self.realtime_transcription_enabled,
realtime_transcription_sender: Arc::new(self.realtime_transcription_sender),
+ realtime_vision_sender: self.realtime_vision_sender,
});
let app = create_router()
@@ -1606,6 +1611,54 @@ async fn sse_transcription_handler(
))
}
+#[derive(Deserialize)]
+struct VisionSSEQuery {
+ images: Option<bool>,
+}
+
+async fn sse_vision_handler(
+ Query(query): Query<VisionSSEQuery>,
+ State(state): State<Arc<AppState>>,
+) -> Result<
+ Sse<impl Stream<Item = Result<Event, Infallible>>>,
+ (StatusCode, JsonResponse<serde_json::Value>),
+> {
+ if state.vision_disabled {
+ return Err((
+ StatusCode::FORBIDDEN,
+ JsonResponse(json!({"error": "Vision streaming is disabled"})),
+ ));
+ }
+ // Get a new subscription - this won't affect the sender
+ let rx = state.realtime_vision_sender.subscribe();
+
+ let include_images = query.images.unwrap_or(false);
+
+ let stream = async_stream::stream! {
+ let mut rx = rx; // Create a new mutable reference to the receiver
+ while let Ok(event) = rx.recv().await {
+ match event {
+ RealtimeVisionEvent::Ocr(mut frame) => {
+ if !include_images {
+ frame.image = None; // Remove the image data if not enabled
+ }
+ yield Ok(Event::default().data(serde_json::to_string(&frame).unwrap_or_default()));
+ }
+ _ => {
+ yield Ok(Event::default().data(serde_json::to_string(&event).unwrap_or_default()));
+ }
+ }
+ }
+ // Even if this stream ends, the sender remains active
+ };
+
+ Ok(Sse::new(stream).keep_alive(
+ axum::response::sse::KeepAlive::new()
+ .interval(Duration::from_secs(1))
+ .text("keep-alive-text"),
+ ))
+}
+
pub fn create_router() -> Router<Arc<AppState>> {
let cors = CorsLayer::new()
.allow_origin(Any)
@@ -1648,6 +1701,7 @@ pub fn create_router() -> Router<Arc<AppState>> {
.route("/experimental/frames/merge", post(merge_frames_handler))
.route("/experimental/validate/media", get(validate_media_handler))
.route("/sse/transcriptions", get(sse_transcription_handler))
+ .route("/sse/vision", get(sse_vision_handler))
.layer(cors);
#[cfg(feature = "experimental")]
diff --git a/screenpipe-server/tests/endpoint_test.rs b/screenpipe-server/tests/endpoint_test.rs
index 6b5c6f65a..af6825867 100644
--- a/screenpipe-server/tests/endpoint_test.rs
+++ b/screenpipe-server/tests/endpoint_test.rs
@@ -47,6 +47,7 @@ mod tests {
ui_monitoring_enabled: false,
realtime_transcription_sender: Arc::new(tokio::sync::broadcast::channel(1000).0),
realtime_transcription_enabled: false,
+ realtime_vision_sender: Arc::new(tokio::sync::broadcast::channel(1000).0),
});
let router = create_router();
diff --git a/screenpipe-server/tests/tags_test.rs b/screenpipe-server/tests/tags_test.rs
index 3d737079f..69d6f05ee 100644
--- a/screenpipe-server/tests/tags_test.rs
+++ b/screenpipe-server/tests/tags_test.rs
@@ -42,6 +42,7 @@ async fn setup_test_app() -> (Router, Arc<AppState>) {
ui_monitoring_enabled: false,
realtime_transcription_sender: Arc::new(tokio::sync::broadcast::channel(1000).0),
realtime_transcription_enabled: false,
+ realtime_vision_sender: Arc::new(tokio::sync::broadcast::channel(1000).0),
});
let app = create_router().with_state(app_state.clone());
diff --git a/screenpipe-vision/Cargo.toml b/screenpipe-vision/Cargo.toml
index 1cc874af9..262637789 100644
--- a/screenpipe-vision/Cargo.toml
+++ b/screenpipe-vision/Cargo.toml
@@ -43,6 +43,8 @@ which = "6.0"
serde = "1.0.200"
once_cell = { workspace = true }
+chrono = { version = "0.4.39", features = ["serde"] }
+base64 = "0.22.1"
[dev-dependencies]
tempfile = "3.3.0"
@@ -57,7 +59,6 @@ memory-stats = "1.2.0"
futures-util = "0.3"
tokio-tungstenite = "0.20"
serde = "1.0.200"
-base64 = "0.22.1"
[build-dependencies]
cc = "1.0"
@@ -87,7 +88,12 @@ path = "examples/websocket.rs"
[target.'cfg(target_os = "windows")'.dependencies]
-windows = { version = "0.58", features = ["Graphics_Imaging", "Media_Ocr", "Storage", "Storage_Streams"] }
+windows = { version = "0.58", features = [
+ "Graphics_Imaging",
+ "Media_Ocr",
+ "Storage",
+ "Storage_Streams",
+] }
xcap = "0.0.12"
[target.'cfg(target_os = "macos")'.dependencies]
diff --git a/screenpipe-vision/bin/ui_monitor b/screenpipe-vision/bin/ui_monitor
index 81d3479e3..c18230ba8 100755
Binary files a/screenpipe-vision/bin/ui_monitor and b/screenpipe-vision/bin/ui_monitor differ
diff --git a/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin b/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin
index 27dc6d78e..c18230ba8 100755
Binary files a/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin and b/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin differ
diff --git a/screenpipe-vision/build.rs b/screenpipe-vision/build.rs
index 815594d99..3e680de75 100644
--- a/screenpipe-vision/build.rs
+++ b/screenpipe-vision/build.rs
@@ -1,5 +1,5 @@
#[cfg(target_os = "macos")]
-use std::{env, process::Command, path::PathBuf};
+use std::{env, path::PathBuf, process::Command};
fn main() {
#[cfg(target_os = "macos")]
@@ -20,29 +20,39 @@ fn main() {
let binary_path = bin_path.join(binary_name);
println!("cargo:rerun-if-changed=src/ui_monitoring_macos.swift");
-
+
let status = Command::new("swiftc")
- .args(&[
+ .args([
"-O",
"-whole-module-optimization",
"-enforce-exclusivity=unchecked",
- "-num-threads", "8",
- "-target", if cfg!(target_arch = "aarch64") {
- "arm64-apple-macos11.0"
- } else {
- "x86_64-apple-macos11.0"
+ "-num-threads",
+ "8",
+ "-target",
+ if cfg!(target_arch = "aarch64") {
+ "arm64-apple-macos11.0"
+ } else {
+ "x86_64-apple-macos11.0"
},
- "-o", binary_path.to_str().unwrap(),
+ "-o",
+ binary_path.to_str().unwrap(),
"src/ui_monitoring_macos.swift",
- "-framework", "Cocoa",
- "-framework", "ApplicationServices",
- "-framework", "Foundation",
+ "-framework",
+ "Cocoa",
+ "-framework",
+ "ApplicationServices",
+ "-framework",
+ "Foundation",
])
.status()
.expect("failed to compile Swift executable");
-
+
if !status.success() {
panic!("failed to compile ui_monitor executable");
}
+
+ let bin_path = PathBuf::from(&manifest_dir).join("bin");
+ let new_path = bin_path.join("ui_monitor");
+ std::fs::copy(&binary_path, &new_path).expect("failed to copy ui_monitor executable");
}
}
diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rs
index 516665881..90e236273 100644
--- a/screenpipe-vision/src/core.rs
+++ b/screenpipe-vision/src/core.rs
@@ -9,19 +9,27 @@ use crate::tesseract::perform_ocr_tesseract;
use crate::utils::OcrEngine;
use crate::utils::{capture_screenshot, compare_with_previous_image};
use anyhow::{anyhow, Result};
+use base64::{engine::general_purpose, Engine as _};
#[cfg(target_os = "macos")]
use cidre::ns;
+use image::codecs::jpeg::JpegEncoder;
use image::DynamicImage;
use log::{debug, error};
use screenpipe_core::Language;
use screenpipe_integrations::unstructured_ocr::perform_ocr_cloud;
+use serde::Deserialize;
+use serde::Deserializer;
+use serde::Serialize;
+use serde::Serializer;
use serde_json;
use std::sync::Arc;
use std::{
collections::HashMap,
- time::{Duration, Instant},
sync::OnceLock,
+ time::{Duration, Instant, UNIX_EPOCH},
};
+use tokio::fs::File;
+use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::sync::mpsc::Sender;
use tokio::time::sleep;
@@ -34,6 +42,74 @@ use xcap::Monitor;
#[cfg(target_os = "macos")]
static APPLE_LANGUAGE_MAP: OnceLock<HashMap<Language, &'static str>> = OnceLock::new();
+fn serialize_image<S>(image: &Option<DynamicImage>, serializer: S) -> Result<S::Ok, S::Error>
+where
+ S: serde::Serializer,
+{
+ if let Some(image) = image {
+ let mut webp_buffer = Vec::new();
+ let mut cursor = std::io::Cursor::new(&mut webp_buffer);
+
+ let mut encoder = JpegEncoder::new_with_quality(&mut cursor, 80);
+
+ // Encode the image as WebP
+ encoder
+ .encode_image(image)
+ .map_err(serde::ser::Error::custom)?;
+
+ // Base64 encode the WebP data
+ let base64_string = general_purpose::STANDARD.encode(webp_buffer);
+
+ // Serialize the base64 string
+ serializer.serialize_str(&base64_string)
+ } else {
+ serializer.serialize_none()
+ }
+}
+
+fn deserialize_image<'de, D>(deserializer: D) -> Result<Option<DynamicImage>, D::Error>
+where
+ D: serde::Deserializer<'de>,
+{
+ // Deserialize the base64 string
+ let base64_string: String = serde::Deserialize::deserialize(deserializer)?;
+
+ // Check if the base64 string is empty or invalid
+ if base64_string.trim().is_empty() {
+ return Ok(None);
+ }
+
+ // Decode base64 to bytes
+ let image_bytes = general_purpose::STANDARD
+ .decode(&base64_string)
+ .map_err(serde::de::Error::custom)?;
+
+ // Create a cursor to read from the bytes
+ let cursor = std::io::Cursor::new(image_bytes);
+
+ // Decode the JPEG data back into an image
+ let image = image::load(cursor, image::ImageFormat::Jpeg).map_err(serde::de::Error::custom)?;
+ Ok(Some(image))
+}
+
+fn serialize_instant<S>(instant: &Instant, serializer: S) -> Result<S::Ok, S::Error>
+where
+ S: Serializer,
+{
+ let duration_since_epoch = UNIX_EPOCH.elapsed().map_err(serde::ser::Error::custom)?;
+ let instant_duration = duration_since_epoch - instant.elapsed();
+ let millis = instant_duration.as_millis();
+ serializer.serialize_u128(millis)
+}
+
+fn deserialize_instant<'de, D>(deserializer: D) -> Result<Instant, D::Error>
+where
+ D: Deserializer<'de>,
+{
+ let millis: u128 = Deserialize::deserialize(deserializer)?;
+ Ok(Instant::now() - Duration::from_millis(millis as u64))
+}
+
pub struct CaptureResult {
pub image: DynamicImage,
pub frame_number: u64,
@@ -266,6 +342,13 @@ pub async fn process_ocr_task(
};
if let Err(e) = result_tx.send(capture_result).await {
+ if e.to_string().contains("channel closed") {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::Other,
+ "Channel closed",
+ ));
+ }
+
error!("Failed to send OCR result: {}", e);
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
@@ -334,3 +417,64 @@ pub fn get_apple_languages(languages: Vec<screenpipe_core::Language>) -> Vec<Str
.filter_map(|lang| map.get(lang).map(|&s| s.to_string()))
.collect()
}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub enum RealtimeVisionEvent {
+ Ocr(WindowOcr),
+ Ui(UIFrame),
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct WindowOcr {
+ #[serde(
+ serialize_with = "serialize_image",
+ deserialize_with = "deserialize_image"
+ )]
+ pub image: Option<DynamicImage>,
+ pub window_name: String,
+ pub app_name: String,
+ pub text: String,
+ pub text_json: Vec<HashMap<String, String>>, // Change this line
+ pub focused: bool,
+ pub confidence: f64,
+ #[serde(
+ serialize_with = "serialize_instant",
+ deserialize_with = "deserialize_instant"
+ )]
+ pub timestamp: Instant,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct UIFrame {
+ pub window: String,
+ pub app: String,
+ pub text_output: String,
+ pub initial_traversal_at: String,
+}
+
+impl UIFrame {
+ pub async fn read_from_pipe(reader: &mut BufReader<File>) -> Result<Self> {
+ let window = UIFrame::read_string(reader).await?;
+ let app = UIFrame::read_string(reader).await?;
+ let text_output = UIFrame::read_string(reader).await?;
+ let initial_traversal_at = UIFrame::read_string(reader).await?;
+
+ Ok(UIFrame {
+ window,
+ app,
+ text_output,
+ initial_traversal_at,
+ })
+ }
+
+ async fn read_string(reader: &mut BufReader<File>) -> Result<String> {
+ let mut buffer = Vec::new();
+ loop {
+ let result = reader.read_until(b'\0', &mut buffer).await?;
+ if result > 0 {
+ buffer.pop(); // Remove the null terminator
+ return Ok(String::from_utf8_lossy(&buffer).to_string());
+ }
+ }
+ }
+}
diff --git a/screenpipe-vision/src/lib.rs b/screenpipe-vision/src/lib.rs
index 7d26c1566..700087dd2 100644
--- a/screenpipe-vision/src/lib.rs
+++ b/screenpipe-vision/src/lib.rs
@@ -1,18 +1,19 @@
#[cfg(target_os = "macos")]
pub mod apple;
pub mod core;
-pub mod run_ui_monitoring_macos;
#[cfg(target_os = "windows")]
pub mod microsoft;
pub mod monitor;
+pub mod run_ui_monitoring_macos;
pub mod tesseract;
pub mod utils;
#[cfg(target_os = "macos")]
pub use apple::perform_ocr_apple;
-pub use core::{continuous_capture, process_ocr_task, CaptureResult};
+pub use core::{continuous_capture, process_ocr_task, CaptureResult, RealtimeVisionEvent, UIFrame};
+// pub use types::CaptureResult;
pub use utils::OcrEngine;
pub mod capture_screenshot_by_window;
-pub use run_ui_monitoring_macos::run_ui;
#[cfg(target_os = "windows")]
pub use microsoft::perform_ocr_windows;
+pub use run_ui_monitoring_macos::run_ui;
pub use tesseract::perform_ocr_tesseract;
diff --git a/screenpipe-vision/src/run_ui_monitoring_macos.rs b/screenpipe-vision/src/run_ui_monitoring_macos.rs
index 04ad532b1..044a2f84c 100644
--- a/screenpipe-vision/src/run_ui_monitoring_macos.rs
+++ b/screenpipe-vision/src/run_ui_monitoring_macos.rs
@@ -1,13 +1,24 @@
use anyhow::Result;
use log::{debug, error, info, warn};
+use std::fs;
+use std::io;
use std::path::PathBuf;
use std::process::Stdio;
-use tokio::io::{AsyncBufReadExt, BufReader};
+use std::sync::atomic::AtomicBool;
+use std::sync::Arc;
+use tokio::fs::{File, OpenOptions};
+use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
use tokio::process::Command;
-use tokio::time::{sleep, Duration};
+use tokio::signal;
+use tokio::time::{sleep, timeout, Duration};
use which::which;
-pub async fn run_ui() -> Result<()> {
+use crate::core::RealtimeVisionEvent;
+use crate::UIFrame;
+
+pub async fn run_ui(
+ realtime_vision_sender: Arc<tokio::sync::broadcast::Sender<RealtimeVisionEvent>>,
+) -> Result<()> {
info!("starting ui monitoring service...");
let binary_name = "ui_monitor";
@@ -49,9 +60,105 @@ pub async fn run_ui() -> Result<()> {
info!("ui_monitor path: {}", ui_monitor_path.display());
- loop {
+ let named_pipe = setup_ipc_queue().await?;
+
+ let named_pipe_clone = named_pipe.clone();
+ let is_running = Arc::new(AtomicBool::new(true));
+ let is_running_clone = is_running.clone();
+ let (is_running_sender, mut is_running_receiver) = tokio::sync::broadcast::channel(1);
+ tokio::spawn(async move {
+ let mut terminate_signal =
+ signal::unix::signal(signal::unix::SignalKind::terminate()).unwrap();
+ tokio::select! {
+ _ = signal::ctrl_c() => {
+ debug!("ctrl-c received");
+ }
+ _ = terminate_signal.recv() => {
+ debug!("terminate signal received");
+ }
+ }
+
+ if fs::metadata(&named_pipe_clone.path).is_ok() {
+ if let Err(e) = fs::remove_file(&named_pipe_clone.path) {
+ eprintln!("Failed to remove named pipe: {:?}", e);
+ }
+ }
+ is_running_clone.store(false, std::sync::atomic::Ordering::Relaxed);
+ let _ = is_running_sender.send(false);
+ });
+
+ let named_pipe_clone = named_pipe.clone();
+ tokio::spawn(async move {
+ // add loop and timeout for opening the file
+ let mut file: Option<File> = None;
+ let mut attempts = 0;
+
+ while attempts < 10 {
+ match timeout(Duration::from_secs(5), named_pipe_clone.open()).await {
+ Ok(Ok(opened_file)) => {
+ // Successfully opened the file
+ file = Some(opened_file);
+ break;
+ }
+ Ok(Err(e)) => {
+ error!("failed to open named pipe: {}", e);
+ attempts += 1;
+ sleep(Duration::from_secs(1)).await;
+ }
+ Err(_) => {
+ error!("timeout while trying to open named pipe");
+ attempts += 1;
+ sleep(Duration::from_secs(1)).await;
+ }
+ }
+ }
+
+ let file = match file {
+ Some(f) => f,
+ None => {
+ return Err(anyhow::anyhow!(
+ "failed to open named pipe after multiple attempts"
+ ))
+ }
+ };
+
+ let mut reader = BufReader::new(file);
+
+ loop {
+ tokio::select! {
+ _ = is_running_receiver.recv() => {
+ info!("ui_monitor is shutting down");
+ return Ok(());
+ }
+ frame = UIFrame::read_from_pipe(&mut reader) => {
+ match frame {
+ Ok(frame) => {
+ let _ = realtime_vision_sender.send(RealtimeVisionEvent::Ui(frame));
+ }
+ Err(e) => {
+ if let Some(io_err) = e.downcast_ref::<io::Error>() {
+ if io_err.kind() == io::ErrorKind::WouldBlock {
+ // Resource temporarily unavailable, retry after a short delay
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ } else {
+ error!("failed to read line from ui_monitor: {}", e);
+ }
+ } else {
+ error!("failed to read line from ui_monitor: {}", e);
+ }
+ }
+ }
+ }
+ }
+ }
+ });
+
+ let named_pipe_clone = named_pipe.clone();
+
+ while is_running.load(std::sync::atomic::Ordering::Relaxed) {
// Clone the PathBuf for each iteration
let mut child = Command::new(&ui_monitor_path)
+ .arg(named_pipe_clone.path.clone())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
@@ -102,4 +209,51 @@ pub async fn run_ui() -> Result<()> {
}
}
}
+
+ Ok(())
+}
+
+async fn setup_ipc_queue() -> Result<NamedPipe> {
+ // create random /dev/shm/screenpipe-ipc-queue-<random-string>
+ // read 16 bytes from /dev/urandom
+ let mut random_bytes = [0u8; 16];
+ let mut file = File::open("/dev/urandom").await?;
+ file.read_exact(&mut random_bytes).await?;
+ let mut path: String = String::from("/tmp/screenpipe-ui-ipc-queue-");
+ for byte in random_bytes {
+ path.push_str(&format!("{:02x}", byte));
+ }
+
+ NamedPipe::new(path).await
+}
+
+#[derive(Debug, Clone)]
+struct NamedPipe {
+ pub path: String,
+}
+
+impl NamedPipe {
+ async fn new(path: String) -> Result<Self> {
+ // Create the named pipe
+ let c_path = std::ffi::CString::new(path.clone()).expect("CString::new failed");
+ let result = unsafe { libc::mkfifo(c_path.as_ptr(), libc::S_IRUSR | libc::S_IWUSR) };
+ if result != 0 {
+ panic!(
+ "Failed to create named pipe: {:?}",
+ std::io::Error::last_os_error()
+ );
+ }
+
+ Ok(NamedPipe { path })
+ }
+
+ async fn open(&self) -> Result<File> {
+ let file = OpenOptions::new()
+ .read(true)
+ .custom_flags(libc::O_NONBLOCK) // Open in non-blocking mode
+ .open(self.path.clone())
+ .await?;
+
+ Ok(file)
+ }
}
diff --git a/screenpipe-vision/src/ui_monitoring_macos.swift b/screenpipe-vision/src/ui_monitoring_macos.swift
index 75acf50cc..956a244ba 100644
--- a/screenpipe-vision/src/ui_monitoring_macos.swift
+++ b/screenpipe-vision/src/ui_monitoring_macos.swift
@@ -1,5 +1,5 @@
-import Cocoa
import ApplicationServices
+import Cocoa
import Foundation
import SQLite3
@@ -29,6 +29,34 @@ struct WindowState {
}
}
+struct UIFrame {
+ let window: String
+ let app: String
+ let text_output: String
+ let initial_traversal_at: String
+}
+
+extension UIFrame {
+ func toBytes() -> [UInt8] {
+ var bytes = [UInt8]()
+
+ // Convert each string to bytes and append to the array
+ bytes.append(contentsOf: window.utf8)
+ bytes.append(0) // Null-terminate the string
+
+ bytes.append(contentsOf: app.utf8)
+ bytes.append(0) // Null-terminate the string
+
+ bytes.append(contentsOf: text_output.utf8)
+ bytes.append(0) // Null-terminate the string
+
+ bytes.append(contentsOf: initial_traversal_at.utf8)
+ bytes.append(0) // Null-terminate the string
+
+ return bytes
+ }
+}
+
// Global state
var globalElementValues = [String: [String: WindowState]]() // [App: [Window: WindowState]]
var currentObserver: AXObserver? {
@@ -83,7 +111,7 @@ let notificationsToObserve: [(String, String)] = [
("AXSelectedCellsChanged", kAXSelectedCellsChangedNotification as String),
("AXWindowResized", kAXWindowResizedNotification as String),
("AXWindowMoved", kAXWindowMovedNotification as String),
- ("AXCreated", kAXCreatedNotification as String)
+ ("AXCreated", kAXCreatedNotification as String),
]
// Struct to hold element attributes including hierarchy and position
@@ -98,7 +126,7 @@ struct ElementAttributes {
var height: CGFloat
var children: [ElementAttributes]
var timestamp: Date
-
+
// Add computed property for unique identifier
var identifier: String {
// Combine path with sorted attributes to create a stable identifier
@@ -108,9 +136,11 @@ struct ElementAttributes {
return "\(path)#\(attributesString)"
}
- init(element: String, path: String, attributes: [String: String], depth: Int,
- x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, children: [ElementAttributes],
- timestamp: Date = Date()) {
+ init(
+ element: String, path: String, attributes: [String: String], depth: Int,
+ x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, children: [ElementAttributes],
+ timestamp: Date = Date()
+ ) {
self.element = element
self.path = path
self.attributes = attributes
@@ -148,7 +178,7 @@ var isCleaningUp = false
// JSON state structure
struct UIMonitoringState: Codable {
var ignoredApps: [String]
-
+
init(ignoredApps: [String] = []) {
self.ignoredApps = ignoredApps
}
@@ -158,45 +188,43 @@ struct UIMonitoringState: Codable {
func getStateFilePath() -> String {
let paths = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
let appSupportDir = paths[0].appendingPathComponent("screenpipe")
-
+
// Create directory if it doesn't exist
try? FileManager.default.createDirectory(at: appSupportDir, withIntermediateDirectories: true)
-
+
return appSupportDir.appendingPathComponent("uiMonitoringLogs.json").path
}
// Function to load or create state
func loadOrCreateState() -> UIMonitoringState {
let path = getStateFilePath()
-
+
if let data = try? Data(contentsOf: URL(fileURLWithPath: path)),
- let state = try? JSONDecoder().decode(UIMonitoringState.self, from: data) {
+ let state = try? JSONDecoder().decode(UIMonitoringState.self, from: data)
+ {
return state
}
-
+
// Create default state with TablePlus ignored
let defaultState = UIMonitoringState(ignoredApps: ["tableplus"])
-
+
// Save default state
if let encoded = try? JSONEncoder().encode(defaultState) {
try? encoded.write(to: URL(fileURLWithPath: path))
}
-
+
return defaultState
}
-// Start monitoring
-startMonitoring()
-
func startMonitoring() {
print("entering startMonitoring()")
-
+
// Check permissions first
if !checkAccessibilityPermissions() {
print("error: accessibility permissions not granted")
exit(1)
}
-
+
// Set up signal handling
signal(SIGINT) { _ in
print("received SIGINT, cleaning up...")
@@ -204,12 +232,28 @@ func startMonitoring() {
exit(0)
}
+ // get args
+ let args = CommandLine.arguments
+ let namedPipePath = args[1]
+
+ if namedPipePath.isEmpty {
+ print("error: named pipe path is empty")
+ exit(1)
+ }
+
+ // create handle
+ let handle = open(namedPipePath, O_WRONLY)
+ if handle == -1 {
+ print("error: failed to open named pipe")
+ exit(1)
+ }
+
setupDatabase()
print("loaded ui_monitoring logs state")
-
+
print("setting up application observer...")
setupApplicationChangeObserver()
-
+
print("monitoring current application...")
monitorCurrentFrontmostApplication()
@@ -228,54 +272,54 @@ func setupDatabase() {
do {
screenPipeDb = try ScreenPipeDB()
print("database connected successfully")
-
+
// Create table if not exists (original schema)
let createTableSQL = """
- CREATE TABLE IF NOT EXISTS ui_monitoring (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- timestamp TEXT,
- app TEXT,
- window TEXT,
- text_output TEXT
- );
- CREATE INDEX IF NOT EXISTS idx_timestamp ON ui_monitoring(timestamp);
- CREATE UNIQUE INDEX IF NOT EXISTS idx_app_window ON ui_monitoring(app, window);
- """
-
+ CREATE TABLE IF NOT EXISTS ui_monitoring (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ timestamp TEXT,
+ app TEXT,
+ window TEXT,
+ text_output TEXT
+ );
+ CREATE INDEX IF NOT EXISTS idx_timestamp ON ui_monitoring(timestamp);
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_app_window ON ui_monitoring(app, window);
+ """
+
if sqlite3_exec(screenPipeDb?.db, createTableSQL, nil, nil, nil) != SQLITE_OK {
let error = String(cString: sqlite3_errmsg(screenPipeDb?.db))
print("error creating table: \(error)")
return
}
-
+
// Add initial_traversal_at column if it doesn't exist
let addColumnSQL = """
- SELECT COUNT(*) FROM pragma_table_info('ui_monitoring')
- WHERE name='initial_traversal_at';
- """
-
+ SELECT COUNT(*) FROM pragma_table_info('ui_monitoring')
+ WHERE name='initial_traversal_at';
+ """
+
var stmt: OpaquePointer?
var columnExists = false
-
+
if sqlite3_prepare_v2(screenPipeDb?.db, addColumnSQL, -1, &stmt, nil) == SQLITE_OK {
if sqlite3_step(stmt) == SQLITE_ROW {
columnExists = sqlite3_column_int(stmt, 0) > 0
}
}
sqlite3_finalize(stmt)
-
+
if !columnExists {
print("adding initial_traversal_at column...")
let alterTableSQL = """
- ALTER TABLE ui_monitoring
- ADD COLUMN initial_traversal_at TEXT;
-
- -- Set initial_traversal_at to timestamp for existing records
- UPDATE ui_monitoring
- SET initial_traversal_at = timestamp
- WHERE initial_traversal_at IS NULL;
- """
-
+ ALTER TABLE ui_monitoring
+ ADD COLUMN initial_traversal_at TEXT;
+
+ -- Set initial_traversal_at to timestamp for existing records
+ UPDATE ui_monitoring
+ SET initial_traversal_at = timestamp
+ WHERE initial_traversal_at IS NULL;
+ """
+
if sqlite3_exec(screenPipeDb?.db, alterTableSQL, nil, nil, nil) != SQLITE_OK {
let error = String(cString: sqlite3_errmsg(screenPipeDb?.db))
print("error adding column: \(error)")
@@ -283,7 +327,7 @@ func setupDatabase() {
print("added initial_traversal_at column successfully")
}
}
-
+
print("database setup completed")
} catch {
print("error setting up database: \(error)")
@@ -335,7 +379,8 @@ func monitorCurrentFrontmostApplication() {
// Get window name BEFORE initializing structures
var windowName = "unknown window"
var windowValue: AnyObject?
- let result = AXUIElementCopyAttributeValue(axApp, kAXFocusedWindowAttribute as CFString, &windowValue)
+ let result = AXUIElementCopyAttributeValue(
+ axApp, kAXFocusedWindowAttribute as CFString, &windowValue)
if result == .success, let window = windowValue as! AXUIElement? {
if let titleValue = getAttributeValue(window, forAttribute: kAXTitleAttribute) as? String {
// Sanitize window name immediately when we get it
@@ -347,7 +392,9 @@ func monitorCurrentFrontmostApplication() {
// Check if we already have recent data for this window
let windowExists = globalElementValues[appName]?[windowName] != nil
- let isWindowRecent = globalElementValues[appName]?[windowName]?.timestamp.timeIntervalSinceNow ?? -Double.infinity > -300 // 5 minutes
+ let isWindowRecent =
+ globalElementValues[appName]?[windowName]?.timestamp.timeIntervalSinceNow ?? -Double
+ .infinity > -300 // 5 minutes
// Initialize app and window in the structure if needed
if globalElementValues[appName] == nil {
@@ -367,7 +414,8 @@ func monitorCurrentFrontmostApplication() {
}
// Always set up notifications
- setupAccessibilityNotifications(pid: pid, axApp: axApp, appName: appName, windowName: windowName)
+ setupAccessibilityNotifications(
+ pid: pid, axApp: axApp, appName: appName, windowName: windowName)
print("monitoring changes for \(appName), window: \(windowName)...")
}
@@ -421,9 +469,11 @@ func traverseAndStoreUIElements(_ element: AXUIElement, appName: String, windowN
let unwantedLabels = [
"window", "application", "group", "button", "image", "text",
"pop up button", "region", "notifications", "table", "column",
- "html content"
+ "html content",
+ ]
+ let attributesToCheck = [
+ "AXDescription", "AXValue", "AXLabel", "AXRoleDescription", "AXHelp",
]
- let attributesToCheck = ["AXDescription", "AXValue", "AXLabel", "AXRoleDescription", "AXHelp"]
// Add character count tracking
var totalCharacterCount = 0
@@ -431,7 +481,8 @@ func traverseAndStoreUIElements(_ element: AXUIElement, appName: String, windowN
func traverse(_ element: AXUIElement, depth: Int) -> ElementAttributes? {
// Add check for AXMenuBar at the start
if let role = getAttributeValue(element, forAttribute: "AXRole") as? String,
- role == "AXMenuBar" {
+ role == "AXMenuBar"
+ {
return nil
}
@@ -457,25 +508,32 @@ func traverseAndStoreUIElements(_ element: AXUIElement, appName: String, windowN
var attributeNames: CFArray?
let result = AXUIElementCopyAttributeNames(element, &attributeNames)
- guard result == .success, let attributes = attributeNames as? [String] else { return nil }
+ guard result == .success, let attributes = attributeNames as? [String] else {
+ return nil
+ }
var position: CGPoint = .zero
var size: CGSize = .zero
// Get position
- if let positionValue = getAttributeValue(element, forAttribute: kAXPositionAttribute) as! AXValue?,
- AXValueGetType(positionValue) == .cgPoint {
+ if let positionValue = getAttributeValue(element, forAttribute: kAXPositionAttribute)
+ as! AXValue?,
+ AXValueGetType(positionValue) == .cgPoint
+ {
AXValueGetValue(positionValue, .cgPoint, &position)
}
// Get size
- if let sizeValue = getAttributeValue(element, forAttribute: kAXSizeAttribute) as! AXValue?,
- AXValueGetType(sizeValue) == .cgSize {
+ if let sizeValue = getAttributeValue(element, forAttribute: kAXSizeAttribute)
+ as! AXValue?,
+ AXValueGetType(sizeValue) == .cgSize
+ {
AXValueGetValue(sizeValue, .cgSize, &size)
}
// Get element description
- let elementDesc = (getAttributeValue(element, forAttribute: "AXRole") as? String) ?? "Unknown"
+ let elementDesc =
+ (getAttributeValue(element, forAttribute: "AXRole") as? String) ?? "Unknown"
// Get path
let (path, depth) = getElementPath(element)
@@ -500,10 +558,9 @@ func traverseAndStoreUIElements(_ element: AXUIElement, appName: String, windowN
if attributesToCheck.contains(attr) {
if let value = getAttributeValue(element, forAttribute: attr) {
let valueStr = describeValue(value)
- if !valueStr.isEmpty &&
- !unwantedValues.contains(valueStr) &&
- valueStr.count > 1 &&
- !unwantedLabels.contains(valueStr.lowercased()) {
+ if !valueStr.isEmpty && !unwantedValues.contains(valueStr)
+ && valueStr.count > 1 && !unwantedLabels.contains(valueStr.lowercased())
+ {
// Store attribute and its value
elementAttributes.attributes[attr] = valueStr
hasRelevantValue = true
@@ -542,9 +599,10 @@ func traverseAndStoreUIElements(_ element: AXUIElement, appName: String, windowN
totalCharacterCount += value.count
}
}
-
+
// Store the element with its attributes using identifier as key
- globalElementValues[appName]?[windowName]?.elements[elementAttributes.identifier] = elementAttributes
+ globalElementValues[appName]?[windowName]?.elements[elementAttributes.identifier] =
+ elementAttributes
return elementAttributes
} else {
return nil
@@ -563,6 +621,14 @@ func traverseAndStoreUIElements(_ element: AXUIElement, appName: String, windowN
hasChanges = true
changedWindows.insert(WindowIdentifier(app: appName, window: windowName))
+ let uiFrame = UIFrame(
+ window: windowName,
+ app: appName,
+ text_output: "",
+ initial_traversal_at: ISO8601DateFormatter().string(from: Date())
+ )
+ try! writeToPipe(uiFrame: uiFrame)
+
// Update timestamp after traversal
globalElementValues[appName]?[windowName]?.timestamp = Date()
@@ -582,16 +648,15 @@ func getRelevantValue(_ element: AXUIElement) -> String? {
let unwantedLabels = [
"window", "application", "group", "button", "image", "text",
"pop up button", "region", "notifications", "table", "column",
- "html content"
+ "html content",
]
for attr in attributesToCheck {
if let value = getAttributeValue(element, forAttribute: attr) {
let valueStr = describeValue(value)
- if !valueStr.isEmpty &&
- !unwantedValues.contains(valueStr) &&
- valueStr.count > 1 &&
- !unwantedLabels.contains(valueStr.lowercased()) {
+ if !valueStr.isEmpty && !unwantedValues.contains(valueStr) && valueStr.count > 1
+ && !unwantedLabels.contains(valueStr.lowercased())
+ {
return valueStr
}
}
@@ -602,40 +667,44 @@ func getRelevantValue(_ element: AXUIElement) -> String? {
func updateElementAndChildren(
_ element: AXUIElement,
- appName: String,
+ appName: String,
windowName: String,
visitedElements: inout Set<AXUIElementWrapper>
) -> Bool {
// Add check for AXMenuBar at the start
if let role = getAttributeValue(element, forAttribute: "AXRole") as? String,
- role == "AXMenuBar" {
+ role == "AXMenuBar"
+ {
return false
}
let elementWrapper = AXUIElementWrapper(element: element)
if visitedElements.contains(elementWrapper) { return false }
visitedElements.insert(elementWrapper)
-
+
var hasUpdates = false
-
+
// Get position and size
var position: CGPoint = .zero
var size: CGSize = .zero
-
- if let positionValue = getAttributeValue(element, forAttribute: kAXPositionAttribute) as! AXValue?,
- AXValueGetType(positionValue) == .cgPoint {
+
+ if let positionValue = getAttributeValue(element, forAttribute: kAXPositionAttribute)
+ as! AXValue?,
+ AXValueGetType(positionValue) == .cgPoint
+ {
AXValueGetValue(positionValue, .cgPoint, &position)
}
-
+
if let sizeValue = getAttributeValue(element, forAttribute: kAXSizeAttribute) as! AXValue?,
- AXValueGetType(sizeValue) == .cgSize {
+ AXValueGetType(sizeValue) == .cgSize
+ {
AXValueGetValue(sizeValue, .cgSize, &size)
}
-
+
// Get element description and full path with depth
let elementDesc = (getAttributeValue(element, forAttribute: "AXRole") as? String) ?? "unknown"
let (path, depth) = getElementPath(element)
-
+
// Check if element has relevant value
if let newValue = getRelevantValue(element) {
let tempAttributes = ElementAttributes(
@@ -651,31 +720,38 @@ func updateElementAndChildren(
timestamp: Date()
)
let identifier = tempAttributes.identifier
-
+
if globalElementValues[appName]?[windowName]?.elements[identifier] == nil {
// New element - create and store it directly
globalElementValues[appName]?[windowName]?.elements[identifier] = tempAttributes
hasUpdates = true
- } else if globalElementValues[appName]?[windowName]?.elements[identifier]?.attributes["Value"] != newValue {
+ } else if globalElementValues[appName]?[windowName]?.elements[identifier]?.attributes[
+ "Value"] != newValue
+ {
// Existing element with changed value
- globalElementValues[appName]?[windowName]?.elements[identifier]?.attributes["Value"] = newValue
+ globalElementValues[appName]?[windowName]?.elements[identifier]?.attributes["Value"] =
+ newValue
hasUpdates = true
}
}
-
+
// Traverse children
- if let children = getAttributeValue(element, forAttribute: kAXChildrenAttribute) as? [AXUIElement] {
+ if let children = getAttributeValue(element, forAttribute: kAXChildrenAttribute)
+ as? [AXUIElement]
+ {
if children.count > 1000 {
let (path, _) = getElementPath(element)
print("element at path \(path) has \(children.count) children")
}
for child in children {
- if updateElementAndChildren(child, appName: appName, windowName: windowName, visitedElements: &visitedElements) {
+ if updateElementAndChildren(
+ child, appName: appName, windowName: windowName, visitedElements: &visitedElements)
+ {
hasUpdates = true
}
}
}
-
+
return hasUpdates
}
@@ -693,7 +769,7 @@ func handleFocusedWindowChange(element: AXUIElement) {
// Check if this is actually a new window
let isNewWindow = currentContext?.windowName != windowName
-
+
// Update the context
currentContext = MonitoringContext(appName: appName, windowName: windowName)
@@ -701,7 +777,7 @@ func handleFocusedWindowChange(element: AXUIElement) {
if globalElementValues[appName] == nil {
globalElementValues[appName] = [:]
}
-
+
// If it's a new window, create fresh state
if isNewWindow {
globalElementValues[appName]?[windowName] = WindowState()
@@ -713,23 +789,27 @@ func handleFocusedWindowChange(element: AXUIElement) {
hasChanges = true
}
-
-func axObserverCallback(observer: AXObserver, element: AXUIElement, notification: CFString, refcon: UnsafeMutableRawPointer?) {
+func axObserverCallback(
+ observer: AXObserver, element: AXUIElement, notification: CFString,
+ refcon: UnsafeMutableRawPointer?
+) {
autoreleasepool {
guard !isCleaningUp else { return }
guard CFGetTypeID(element) == AXUIElementGetTypeID() else { return }
-
+
synchronizationQueue.async {
// Check for window-related notifications
let notificationStr = notification as String
- if notificationStr == kAXFocusedWindowChangedNotification as String ||
- notificationStr == kAXMainWindowChangedNotification as String ||
- notificationStr == kAXTitleChangedNotification as String {
-
+ if notificationStr == kAXFocusedWindowChangedNotification as String
+ || notificationStr == kAXMainWindowChangedNotification as String
+ || notificationStr == kAXTitleChangedNotification as String
+ {
+
// For title changes, we need to check if it's a window
if notificationStr == kAXTitleChangedNotification as String {
if let role = getAttributeValue(element, forAttribute: "AXRole") as? String,
- role == "AXWindow" {
+ role == "AXWindow"
+ {
handleFocusedWindowChange(element: element)
return
}
@@ -748,20 +828,20 @@ func axObserverCallback(observer: AXObserver, element: AXUIElement, notification
if let parent = parent {
grandparent = getAttributeValue(parent, forAttribute: "AXParent") as! AXUIElement?
}
-
+
// Start from highest available ancestor
let startElement = grandparent ?? parent ?? element
-
+
// Get the depth of the startElement
let (_, depth) = getElementPath(startElement)
-
+
// Add to pending notifications
pendingNotifications.append((startElement: startElement, depth: depth))
-
+
// Reset debounce timer
debounceTimer?.cancel()
debounceTimer = nil
-
+
// Start a new debounce timer
debounceTimer = DispatchSource.makeTimerSource(queue: synchronizationQueue)
debounceTimer?.schedule(deadline: .now() + .milliseconds(200))
@@ -773,44 +853,58 @@ func axObserverCallback(observer: AXObserver, element: AXUIElement, notification
}
}
-
func processPendingNotifications() {
if isCleaningUp || isTraversing { return }
guard let context = currentContext else { return }
-
+
let startTime = DispatchTime.now()
-
+
autoreleasepool {
// Find the notification with the startElement of least depth
- guard let selectedNotification = pendingNotifications.min(by: { $0.depth < $1.depth }) else {
+ guard let selectedNotification = pendingNotifications.min(by: { $0.depth < $1.depth })
+ else {
pendingNotifications.removeAll()
return
}
-
+
let startElement = selectedNotification.startElement
var visitedElements = Set<AXUIElementWrapper>()
-
+
// Always add to timestamp update set
- windowsNeedingTimestampUpdate.insert(WindowIdentifier(app: context.appName, window: context.windowName))
-
- if updateElementAndChildren(startElement, appName: context.appName, windowName: context.windowName, visitedElements: &visitedElements) {
+ windowsNeedingTimestampUpdate.insert(
+ WindowIdentifier(app: context.appName, window: context.windowName))
+
+ if updateElementAndChildren(
+ startElement, appName: context.appName, windowName: context.windowName,
+ visitedElements: &visitedElements)
+ {
hasChanges = true
- changedWindows.insert(WindowIdentifier(app: context.appName, window: context.windowName))
+ changedWindows.insert(
+ WindowIdentifier(app: context.appName, window: context.windowName))
+
+ let uiFrame = UIFrame(
+ window: context.windowName,
+ app: context.appName,
+ text_output: "",
+ initial_traversal_at: ISO8601DateFormatter().string(from: Date())
+ )
+
+ try! writeToPipe(uiFrame: uiFrame)
}
}
-
+
let endTime = DispatchTime.now()
let timeInterval = Double(endTime.uptimeNanoseconds - startTime.uptimeNanoseconds) / 1_000_000
print("\(String(format: "%.2f", timeInterval))ms - processed pending notifications")
-
+
// Clear pending notifications and reset debounceTimer
pendingNotifications.removeAll()
debounceTimer = nil
}
-
-
-func setupAccessibilityNotifications(pid: pid_t, axApp: AXUIElement, appName: String, windowName: String) {
+func setupAccessibilityNotifications(
+ pid: pid_t, axApp: AXUIElement, appName: String, windowName: String
+) {
// Add safety check for invalid pid
if pid <= 0 {
print("invalid pid: \(pid)")
@@ -864,7 +958,9 @@ func setupAccessibilityNotifications(pid: pid_t, axApp: AXUIElement, appName: St
}
} else {
// If we can't get windows, try to register with the main window
- if let mainWindow = getAttributeValue(axApp, forAttribute: kAXMainWindowAttribute) as! AXUIElement? {
+ if let mainWindow = getAttributeValue(axApp, forAttribute: kAXMainWindowAttribute)
+ as! AXUIElement?
+ {
registerNotificationsRecursively(element: mainWindow, observer: axObserver)
}
}
@@ -883,7 +979,9 @@ func registerNotificationsRecursively(element: AXUIElement, observer: AXObserver
}
// Get children and recursively register notifications
- if let children = getAttributeValue(element, forAttribute: kAXChildrenAttribute) as? [AXUIElement] {
+ if let children = getAttributeValue(element, forAttribute: kAXChildrenAttribute)
+ as? [AXUIElement]
+ {
for child in children {
registerNotificationsRecursively(element: child, observer: observer, depth: depth + 1)
}
@@ -951,7 +1049,9 @@ func getElementPath(_ element: AXUIElement) -> (path: String, depth: Int) {
while current != nil {
if let role = getAttributeValue(current!, forAttribute: "AXRole") as? String {
var elementDesc = role
- if let title = getAttributeValue(current!, forAttribute: "AXTitle") as? String, !title.isEmpty {
+ if let title = getAttributeValue(current!, forAttribute: "AXTitle") as? String,
+ !title.isEmpty
+ {
elementDesc += "[\(title)]"
}
path.append(elementDesc)
@@ -969,38 +1069,38 @@ func getElementPath(_ element: AXUIElement) -> (path: String, depth: Int) {
func buildTextOutput(from windowState: WindowState) -> String {
var textOutput = ""
var processedElements = Set<String>()
- var seenTexts = Set<String>() // Track unique text values
-
+ var seenTexts = Set<String>() // Track unique text values
+
// Helper function to process text values
func processText(_ text: String) -> String {
if seenTexts.contains(text) {
- return "" // Return empty string for duplicate text
+ return "" // Return empty string for duplicate text
}
seenTexts.insert(text)
return "[\(text)]"
}
-
+
// Process hierarchical elements
func processElement(_ elementAttributes: ElementAttributes, indentLevel: Int) {
// One space per level
let indentStr = String(repeating: " ", count: indentLevel)
-
+
// Process each attribute value and join with spaces
let text = elementAttributes.attributes.values
.filter { !seenTexts.contains($0) }
- .map {
+ .map {
seenTexts.insert($0)
return "[\($0)]"
}
.joined(separator: " ")
-
+
if !text.isEmpty {
textOutput += "\(indentStr)\(text)\n"
}
-
+
// Mark as processed using identifier
processedElements.insert(elementAttributes.identifier)
-
+
// Recursively process children
let sortedChildren = elementAttributes.children.sorted { (e1, e2) -> Bool in
if abs(e1.y - e2.y) < 10 {
@@ -1008,12 +1108,12 @@ func buildTextOutput(from windowState: WindowState) -> String {
}
return e1.y < e2.y
}
-
+
for child in sortedChildren {
processElement(child, indentLevel: indentLevel + 1)
}
}
-
+
// Process root elements first (hierarchical)
let rootElements = windowState.elements.values.filter { $0.depth == 0 }
let sortedRootElements = rootElements.sorted { (e1, e2) -> Bool in
@@ -1022,16 +1122,16 @@ func buildTextOutput(from windowState: WindowState) -> String {
}
return e1.y < e2.y
}
-
+
for rootElement in sortedRootElements {
processElement(rootElement, indentLevel: 0)
}
-
+
// Then process any orphaned elements
let orphanElements = windowState.elements.filter { !processedElements.contains($0.key) }
if !orphanElements.isEmpty {
textOutput += "\n---\n"
-
+
// Sort orphans by timestamp first (oldest first), then position if timestamps are equal
let sortedOrphans = orphanElements.values.sorted { (e1, e2) -> Bool in
if e1.timestamp == e2.timestamp {
@@ -1042,24 +1142,24 @@ func buildTextOutput(from windowState: WindowState) -> String {
}
return e1.timestamp < e2.timestamp
}
-
+
for element in sortedOrphans {
// One space per depth level
let indentStr = String(repeating: " ", count: element.depth)
let text = element.attributes.values
.filter { !seenTexts.contains($0) }
- .map {
+ .map {
seenTexts.insert($0)
return "[\($0)]"
}
.joined(separator: " ")
-
+
if !text.isEmpty {
textOutput += "\(indentStr)\(text)\n"
}
}
}
-
+
return textOutput
}
@@ -1068,11 +1168,11 @@ func saveToDatabase(windowId: WindowIdentifier, newTextOutput: String, timestamp
print("database not initialized")
return
}
-
+
let startTime = DispatchTime.now()
let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
let MAX_CHARS = 300_000
-
+
// Sanitize window name by removing invisible characters
let sanitizedWindow = windowId.window
.components(separatedBy: CharacterSet.controlCharacters).joined()
@@ -1080,17 +1180,26 @@ func saveToDatabase(windowId: WindowIdentifier, newTextOutput: String, timestamp
let sanitizedApp = windowId.app
.components(separatedBy: CharacterSet.controlCharacters).joined()
.trimmingCharacters(in: .whitespacesAndNewlines)
-
+
+ let uiFrame = UIFrame(
+ window: windowId.window,
+ app: windowId.app,
+ text_output: newTextOutput,
+ initial_traversal_at: timestamp
+ )
+
+ try! writeToPipe(uiFrame: uiFrame)
+
// First, get existing text_output and check if record exists
var existingText = ""
var recordExists = false
let selectSQL = "SELECT text_output FROM ui_monitoring WHERE app = ? AND window = ?;"
var selectStmt: OpaquePointer?
-
+
if sqlite3_prepare_v2(db, selectSQL, -1, &selectStmt, nil) == SQLITE_OK {
sqlite3_bind_text(selectStmt, 1, sanitizedApp, -1, SQLITE_TRANSIENT)
sqlite3_bind_text(selectStmt, 2, sanitizedWindow, -1, SQLITE_TRANSIENT)
-
+
if sqlite3_step(selectStmt) == SQLITE_ROW {
recordExists = true
if let text = sqlite3_column_text(selectStmt, 0) {
@@ -1099,7 +1208,7 @@ func saveToDatabase(windowId: WindowIdentifier, newTextOutput: String, timestamp
}
sqlite3_finalize(selectStmt)
}
-
+
// Split and clean lines - only trim trailing whitespace, preserve leading
let existingLines = existingText.components(separatedBy: "\n")
.map { $0.trimmingCharacters(in: .whitespaces.subtracting(.init(charactersIn: " "))) }
@@ -1107,35 +1216,38 @@ func saveToDatabase(windowId: WindowIdentifier, newTextOutput: String, timestamp
let newLines = newTextOutput.components(separatedBy: "\n")
.map { $0.trimmingCharacters(in: .whitespaces.subtracting(.init(charactersIn: " "))) }
.filter { !$0.isEmpty }
-
+
var extensionsFound = 0
var exactMatchesFound = 0
var newCharsCount = 0
-
+
let uniqueNewLines = newLines.filter { newLine in
let strippedNewLine = newLine.trimmingCharacters(in: CharacterSet(charactersIn: "[]"))
.trimmingCharacters(in: .whitespaces)
return !existingLines.contains { existingLine in
- let strippedExistingLine = existingLine.trimmingCharacters(in: CharacterSet(charactersIn: "[]"))
- .trimmingCharacters(in: .whitespaces)
-
+ let strippedExistingLine = existingLine.trimmingCharacters(
+ in: CharacterSet(charactersIn: "[]")
+ )
+ .trimmingCharacters(in: .whitespaces)
+
if strippedExistingLine == strippedNewLine {
exactMatchesFound += 1
return true
}
-
- if strippedExistingLine.count < strippedNewLine.count &&
- strippedNewLine.contains(strippedExistingLine) {
+
+ if strippedExistingLine.count < strippedNewLine.count
+ && strippedNewLine.contains(strippedExistingLine)
+ {
extensionsFound += 1
// Count additional characters in the extension
newCharsCount += (strippedNewLine.count - strippedExistingLine.count)
return true
}
-
+
return false
}
}
-
+
// Skip if no unique lines or extensions found
if uniqueNewLines.isEmpty && extensionsFound == 0 {
// Update timestamp only
@@ -1145,7 +1257,7 @@ func saveToDatabase(windowId: WindowIdentifier, newTextOutput: String, timestamp
sqlite3_bind_text(updateStmt, 1, timestamp, -1, SQLITE_TRANSIENT)
sqlite3_bind_text(updateStmt, 2, sanitizedApp, -1, SQLITE_TRANSIENT)
sqlite3_bind_text(updateStmt, 3, sanitizedWindow, -1, SQLITE_TRANSIENT)
-
+
if sqlite3_step(updateStmt) != SQLITE_DONE {
print("error updating timestamp")
}
@@ -1157,39 +1269,39 @@ func saveToDatabase(windowId: WindowIdentifier, newTextOutput: String, timestamp
// Add characters from unique new lines
newCharsCount += uniqueNewLines.reduce(0) { $0 + $1.count }
-
+
// Process only if we have unique lines
let allLines = existingLines + uniqueNewLines
-
+
// Trim older lines if total length exceeds limit
var totalChars = 0
var startIndex = 0
-
+
for (index, line) in allLines.enumerated().reversed() {
- totalChars += line.count + 1 // +1 for newline
+ totalChars += line.count + 1 // +1 for newline
if totalChars > MAX_CHARS {
startIndex = index + 1
break
}
}
-
+
let finalText = allLines[startIndex...].joined(separator: "\n")
-
+
// Update database with different SQL based on whether record exists
if recordExists {
let updateSQL = """
- UPDATE ui_monitoring
- SET timestamp = ?, text_output = ?
- WHERE app = ? AND window = ?;
- """
-
+ UPDATE ui_monitoring
+ SET timestamp = ?, text_output = ?
+ WHERE app = ? AND window = ?;
+ """
+
var updateStmt: OpaquePointer?
if sqlite3_prepare_v2(db, updateSQL, -1, &updateStmt, nil) == SQLITE_OK {
sqlite3_bind_text(updateStmt, 1, timestamp, -1, SQLITE_TRANSIENT)
sqlite3_bind_text(updateStmt, 2, finalText, -1, SQLITE_TRANSIENT)
sqlite3_bind_text(updateStmt, 3, sanitizedApp, -1, SQLITE_TRANSIENT)
sqlite3_bind_text(updateStmt, 4, sanitizedWindow, -1, SQLITE_TRANSIENT)
-
+
if sqlite3_step(updateStmt) != SQLITE_DONE {
print("error updating row")
}
@@ -1197,19 +1309,19 @@ func saveToDatabase(windowId: WindowIdentifier, newTextOutput: String, timestamp
}
} else {
let insertSQL = """
- INSERT INTO ui_monitoring (
- timestamp, initial_traversal_at, app, window, text_output
- ) VALUES (?, ?, ?, ?, ?);
- """
-
+ INSERT INTO ui_monitoring (
+ timestamp, initial_traversal_at, app, window, text_output
+ ) VALUES (?, ?, ?, ?, ?);
+ """
+
var insertStmt: OpaquePointer?
if sqlite3_prepare_v2(db, insertSQL, -1, &insertStmt, nil) == SQLITE_OK {
sqlite3_bind_text(insertStmt, 1, timestamp, -1, SQLITE_TRANSIENT)
- sqlite3_bind_text(insertStmt, 2, timestamp, -1, SQLITE_TRANSIENT) // Set initial_traversal_at same as timestamp for new records
+ sqlite3_bind_text(insertStmt, 2, timestamp, -1, SQLITE_TRANSIENT) // Set initial_traversal_at same as timestamp for new records
sqlite3_bind_text(insertStmt, 3, sanitizedApp, -1, SQLITE_TRANSIENT)
sqlite3_bind_text(insertStmt, 4, sanitizedWindow, -1, SQLITE_TRANSIENT)
sqlite3_bind_text(insertStmt, 5, finalText, -1, SQLITE_TRANSIENT)
-
+
if sqlite3_step(insertStmt) != SQLITE_DONE {
print("error inserting row")
}
@@ -1219,40 +1331,44 @@ func saveToDatabase(windowId: WindowIdentifier, newTextOutput: String, timestamp
let endTime = DispatchTime.now()
let timeInterval = Double(endTime.uptimeNanoseconds - startTime.uptimeNanoseconds) / 1_000_000
- print("\(String(format: "%.2f", timeInterval))ms - saved to db for \(windowId.app)/\(String(windowId.window.prefix(30)))... (\(uniqueNewLines.count) new lines, \(extensionsFound) extensions, \(newCharsCount) new chars), skipped \(exactMatchesFound) exact matches")
+ print(
+ "\(String(format: "%.2f", timeInterval))ms - saved to db for \(windowId.app)/\(String(windowId.window.prefix(30)))... (\(uniqueNewLines.count) new lines, \(extensionsFound) extensions, \(newCharsCount) new chars), skipped \(exactMatchesFound) exact matches"
+ )
}
func saveElementValues() {
// Check both sets
- if (changedWindows.isEmpty && windowsNeedingTimestampUpdate.isEmpty) { return }
-
+ if changedWindows.isEmpty && windowsNeedingTimestampUpdate.isEmpty { return }
+
let timestamp = ISO8601DateFormatter().string(from: Date())
var totalChars = 0
-
+
sqlite3_exec(screenPipeDb?.db, "BEGIN TRANSACTION", nil, nil, nil)
-
+
// Process windows with content changes
for windowId in changedWindows {
- guard let windowState = globalElementValues[windowId.app]?[windowId.window] else { continue }
-
+ guard let windowState = globalElementValues[windowId.app]?[windowId.window] else {
+ continue
+ }
+
// Build text output
let textOutput = buildTextOutput(from: windowState)
totalChars += textOutput.count
-
+
// Store the formatted text output in the window state
globalElementValues[windowId.app]?[windowId.window]?.textOutput = textOutput
-
+
// Save to database
saveToDatabase(windowId: windowId, newTextOutput: textOutput, timestamp: timestamp)
}
-
+
// Process windows that only need timestamp updates
for windowId in windowsNeedingTimestampUpdate where !changedWindows.contains(windowId) {
saveToDatabase(windowId: windowId, newTextOutput: "", timestamp: timestamp)
}
-
+
sqlite3_exec(screenPipeDb?.db, "COMMIT", nil, nil, nil)
-
+
// Clear the changed windows set
changedWindows.removeAll()
windowsNeedingTimestampUpdate.removeAll()
@@ -1266,6 +1382,8 @@ func cleanup() {
isCleaningUp = true
}
+ close(handle)
+
// Remove observer from run loop
if let observer = currentObserver {
CFRunLoopRemoveSource(
@@ -1287,10 +1405,10 @@ func cleanup() {
func pruneGlobalState() {
let MAX_SIZE_MB = 10.0
let MAX_SIZE_BYTES = MAX_SIZE_MB * 1024 * 1024 / 2 // Divide by 2 since String uses 2 bytes per char
-
+
var totalSize = 0
var elementsByTimestamp: [(app: String, window: String, timestamp: Date, size: Int)] = []
-
+
// Calculate sizes and collect timestamps
for (app, windows) in globalElementValues {
for (window, windowState) in windows {
@@ -1302,34 +1420,40 @@ func pruneGlobalState() {
elementsByTimestamp.append((app, window, windowState.timestamp, windowSize))
}
}
-
+
// If we're under the limit, no need to prune
if Double(totalSize) <= MAX_SIZE_BYTES {
return
}
-
- print("pruning global state: current size \(String(format: "%.2f", Double(totalSize) * 2 / 1024 / 1024))mb")
-
+
+ print(
+ "pruning global state: current size \(String(format: "%.2f", Double(totalSize) * 2 / 1024 / 1024))mb"
+ )
+
// Sort by timestamp (oldest first)
elementsByTimestamp.sort { $0.timestamp < $1.timestamp }
-
+
// Remove oldest entries until we're under the limit
var removedSize = 0
for entry in elementsByTimestamp {
if Double(totalSize - removedSize) <= MAX_SIZE_BYTES {
break
}
-
+
globalElementValues[entry.app]?[entry.window] = nil
if globalElementValues[entry.app]?.isEmpty == true {
globalElementValues.removeValue(forKey: entry.app)
}
-
+
removedSize += entry.size
- print("pruned \(entry.app)/\(entry.window): \(String(format: "%.2f", Double(entry.size) * 2 / 1024))kb")
+ print(
+ "pruned \(entry.app)/\(entry.window): \(String(format: "%.2f", Double(entry.size) * 2 / 1024))kb"
+ )
}
-
- print("pruned global state to \(String(format: "%.2f", Double(totalSize - removedSize) * 2 / 1024 / 1024))mb")
+
+ print(
+ "pruned global state to \(String(format: "%.2f", Double(totalSize - removedSize) * 2 / 1024 / 1024))mb"
+ )
}
func measureGlobalElementValuesSize() {
@@ -1341,13 +1465,15 @@ func measureGlobalElementValuesSize() {
for (_, windowState) in windows {
totalElements += windowState.elements.count
totalAttributes += windowState.elements.values.reduce(0) { $0 + $1.attributes.count }
- totalStringLength += windowState.elements.values.reduce(0) { $0 + $1.attributes.values.reduce(0) { $0 + $1.count } }
+ totalStringLength += windowState.elements.values.reduce(0) {
+ $0 + $1.attributes.values.reduce(0) { $0 + $1.count }
+ }
}
}
let mbSize = Double(totalStringLength) * 2 / 1024.0 / 1024.0
print("global state size: \(String(format: "%.3f", mbSize))mb")
-
+
// Add pruning check
if mbSize > 10.0 {
pruneGlobalState()
@@ -1357,42 +1483,42 @@ func measureGlobalElementValuesSize() {
public class UIMonitor {
private static var shared: UIMonitor?
private var isRunning = false
-
+
public static func getInstance() -> UIMonitor {
if shared == nil {
shared = UIMonitor()
}
return shared!
}
-
+
// Start monitoring in background
public func start() {
if isRunning { return }
isRunning = true
-
+
DispatchQueue.global(qos: .background).async {
startMonitoring()
}
}
-
+
// Stop monitoring
public func stop() {
if !isRunning { return }
cleanup()
isRunning = false
}
-
+
// Get current text output for specific app/window
public func getCurrentOutput(app: String, window: String? = nil) -> String? {
let appName = app.lowercased()
-
+
if let windowName = window?.lowercased() {
if let windowState = globalElementValues[appName]?[windowName] {
return buildTextOutput(from: windowState)
}
return nil
}
-
+
// If no window specified, return all windows' output concatenated
var outputs: [String] = []
if let windows = globalElementValues[appName] {
@@ -1403,12 +1529,12 @@ public class UIMonitor {
}
return outputs.isEmpty ? nil : outputs.joined(separator: "\n---\n")
}
-
+
// Get all current apps being monitored
public func getMonitoredApps() -> [String] {
return Array(globalElementValues.keys)
}
-
+
// Get all windows for a specific app
public func getWindowsForApp(_ app: String) -> [String] {
return globalElementValues[app.lowercased()]?.keys.map { $0 } ?? []
@@ -1437,29 +1563,79 @@ func getScreenPipeDbPath() -> String {
// Database connection helper
class ScreenPipeDB {
let db: OpaquePointer
-
+
init() throws {
var dbPointer: OpaquePointer?
let dbPath = getScreenPipeDbPath()
-
+
// Create directory if it doesn't exist
let dbDir = (dbPath as NSString).deletingLastPathComponent
try? FileManager.default.createDirectory(atPath: dbDir, withIntermediateDirectories: true)
-
+
if sqlite3_open(dbPath, &dbPointer) != SQLITE_OK {
- throw NSError(domain: "db error", code: 1,
- userInfo: [NSLocalizedDescriptionKey: "failed to open database"])
+ throw NSError(
+ domain: "db error", code: 1,
+ userInfo: [NSLocalizedDescriptionKey: "failed to open database"])
}
-
+
guard let db = dbPointer else {
- throw NSError(domain: "db error", code: 2,
- userInfo: [NSLocalizedDescriptionKey: "database pointer is nil"])
+ throw NSError(
+ domain: "db error", code: 2,
+ userInfo: [NSLocalizedDescriptionKey: "database pointer is nil"])
}
-
+
self.db = db
}
-
+
deinit {
sqlite3_close(db)
}
}
+
+func writeToPipe(uiFrame: UIFrame) throws {
+ let message = uiFrame.toBytes()
+ // let bytesWritten = message.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in
+ // write(handle, buffer.baseAddress, message.count)
+ // }
+ // if bytesWritten == -1 {
+ // perror("error writing to pipe")
+ // }
+
+ var totalWritten = 0
+ while totalWritten < message.count {
+ let bytesWritten = message.withUnsafeBytes { buffer in
+ write(
+ handle,
+ buffer.baseAddress?.advanced(by: totalWritten),
+ message.count - totalWritten)
+ }
+ guard bytesWritten != -1 else {
+ throw NSError(
+ domain: "pipe error", code: 3,
+ userInfo: [NSLocalizedDescriptionKey: String(cString: strerror(errno))])
+ }
+ totalWritten += bytesWritten
+ }
+}
+
+guard CommandLine.arguments.count > 1 else {
+ print("error: named pipe path not provided")
+ exit(1)
+}
+
+let namedPipePath = CommandLine.arguments[1]
+
+// Check if the path is valid and is a named pipe
+var statInfo = stat()
+if stat(namedPipePath, &statInfo) != 0 || (statInfo.st_mode & S_IFMT) != S_IFIFO {
+ print("error: invalid named pipe path or not a named pipe")
+ exit(1)
+}
+
+let handle = open(namedPipePath, O_WRONLY)
+if handle == -1 {
+ perror("error: failed to open named pipe")
+ exit(1)
+}
+
+startMonitoring()