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

Capture browser url (#1381)

neo7738ac04bb6c084
diff --git a/screenpipe-server/benches/db_benchmarks.rs b/screenpipe-server/benches/db_benchmarks.rs
index 9c7d391d3..843337a6c 100644
--- a/screenpipe-server/benches/db_benchmarks.rs
+++ b/screenpipe-server/benches/db_benchmarks.rs
@@ -17,7 +17,7 @@ async fn setup_large_db(size: usize) -> DatabaseManager {
.insert_video_chunk("test_video.mp4", "test_device")
.await
.unwrap();
- let frame_id = db.insert_frame("test_device", None).await.unwrap();
+ let frame_id = db.insert_frame("test_device", None, None).await.unwrap();
let ocr_text = format!("OCR text {}", rng.gen::<u32>());
let text_json = format!(r#"{{"text": "{}"}}"#, ocr_text);
db.insert_ocr_text(
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index c0fd04176..38eb11588 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -228,7 +228,7 @@ async fn record_video(
while is_running.load(Ordering::SeqCst) {
if let Some(frame) = video_capture.ocr_frame_queue.pop() {
for window_result in &frame.window_ocr_results {
- match db.insert_frame(&device_name, None).await {
+ match db.insert_frame(&device_name, None, window_result.browser_url.as_deref()).await {
Ok(frame_id) => {
let text_json =
serde_json::to_string(&window_result.text_json).unwrap_or_default();
diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rs
index 123f10ea7..ef9e9e08c 100644
--- a/screenpipe-server/src/db.rs
+++ b/screenpipe-server/src/db.rs
@@ -292,6 +292,7 @@ impl DatabaseManager {
&self,
device_name: &str,
timestamp: Option<DateTime<Utc>>,
+ browser_url: Option<&str>,
) -> Result<i64, sqlx::Error> {
let mut tx = self.pool.begin().await?;
debug!("insert_frame Transaction started");
@@ -328,12 +329,13 @@ impl DatabaseManager {
// Insert the new frame with file_path as name
let id = sqlx::query(
- "INSERT INTO frames (video_chunk_id, offset_index, timestamp, name) VALUES (?1, ?2, ?3, ?4)",
+ "INSERT INTO frames (video_chunk_id, offset_index, timestamp, name, browser_url) VALUES (?1, ?2, ?3, ?4, ?5)",
)
.bind(video_chunk_id)
.bind(offset_index)
.bind(timestamp)
.bind(file_path)
+ .bind(browser_url.map(|s| s.to_string()))
.execute(&mut *tx)
.await?
.last_insert_rowid();
@@ -400,7 +402,7 @@ impl DatabaseManager {
"Failed to insert OCR text for frame_id: {} after {} attempts",
frame_id, MAX_RETRIES
);
- return Err(sqlx::Error::PoolTimedOut); // Return error after max retries
+ return Err(sqlx::Error::PoolTimedOut);
}
}
diff --git a/screenpipe-server/src/migrations/20250219212616_add-browser_url-column.sql b/screenpipe-server/src/migrations/20250219212616_add-browser_url-column.sql
new file mode 100644
index 000000000..9c26bfee5
--- /dev/null
+++ b/screenpipe-server/src/migrations/20250219212616_add-browser_url-column.sql
@@ -0,0 +1,2 @@
+-- Add migration script here
+ALTER TABLE frames ADD COLUMN browser_url TEXT DEFAULT NULL;
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 166f0a65f..36eba297f 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -1106,7 +1106,7 @@ async fn add_frame_to_db(
let db = &state.db;
let frame_id = db
- .insert_frame(device_name, Some(frame.timestamp.unwrap_or_else(Utc::now)))
+ .insert_frame(device_name, Some(frame.timestamp.unwrap_or_else(Utc::now)), None)
.await?;
if let Some(ocr_results) = &frame.ocr_results {
diff --git a/screenpipe-server/tests/db.rs b/screenpipe-server/tests/db.rs
index 9e96eae47..9ae3dd810 100644
--- a/screenpipe-server/tests/db.rs
+++ b/screenpipe-server/tests/db.rs
@@ -21,7 +21,7 @@ mod tests {
.insert_video_chunk("test_video.mp4", "test_device")
.await
.unwrap();
- let frame_id = db.insert_frame("test_device", None).await.unwrap();
+ let frame_id = db.insert_frame("test_device", None, None).await.unwrap();
db.insert_ocr_text(
frame_id,
"Hello, world!",
@@ -200,7 +200,7 @@ mod tests {
.insert_video_chunk("test_video.mp4", "test_device")
.await
.unwrap();
- let frame_id = db.insert_frame("test_device", None).await.unwrap();
+ let frame_id = db.insert_frame("test_device", None, None).await.unwrap();
db.insert_ocr_text(
frame_id,
"Hello from OCR",
@@ -290,7 +290,7 @@ mod tests {
.insert_video_chunk("test_video.mp4", "test_device")
.await
.unwrap();
- let frame_id1 = db.insert_frame("test_device", None).await.unwrap();
+ let frame_id1 = db.insert_frame("test_device", None, None).await.unwrap();
db.insert_ocr_text(
frame_id1,
"Hello from OCR 1",
@@ -327,7 +327,7 @@ mod tests {
tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
// Insert remaining data
- let frame_id2 = db.insert_frame("test_device", None).await.unwrap();
+ let frame_id2 = db.insert_frame("test_device", None, None).await.unwrap();
db.insert_ocr_text(
frame_id2,
"Hello from OCR 2",
@@ -477,7 +477,7 @@ mod tests {
.insert_video_chunk("test_video.mp4", "test_device")
.await
.unwrap();
- let frame_id1 = db.insert_frame("test_device", None).await.unwrap();
+ let frame_id1 = db.insert_frame("test_device", None, None).await.unwrap();
db.insert_ocr_text(
frame_id1,
"Hello from OCR 1",
@@ -512,7 +512,7 @@ mod tests {
tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
// Insert remaining data
- let frame_id2 = db.insert_frame("test_device", None).await.unwrap();
+ let frame_id2 = db.insert_frame("test_device", None, None).await.unwrap();
db.insert_ocr_text(
frame_id2,
"Hello from OCR 2",
@@ -920,7 +920,7 @@ mod tests {
.unwrap();
// Insert first frame with OCR
- let frame_id1 = db.insert_frame("test_device", None).await.unwrap();
+ let frame_id1 = db.insert_frame("test_device", None, None).await.unwrap();
db.insert_ocr_text(
frame_id1,
"Hello from frame 1",
@@ -934,7 +934,7 @@ mod tests {
.unwrap();
// Insert second frame with OCR
- let frame_id2 = db.insert_frame("test_device", None).await.unwrap();
+ let frame_id2 = db.insert_frame("test_device", None, None).await.unwrap();
db.insert_ocr_text(
frame_id2,
"Hello from frame 2",
diff --git a/screenpipe-server/tests/endpoint_test.rs b/screenpipe-server/tests/endpoint_test.rs
index 48cd8eb9c..2f43e78ec 100644
--- a/screenpipe-server/tests/endpoint_test.rs
+++ b/screenpipe-server/tests/endpoint_test.rs
@@ -172,8 +172,8 @@ mod tests {
.insert_video_chunk("test_video1.mp4", "test_device")
.await
.unwrap();
- let frame_id1 = db.insert_frame("test_device", None).await.unwrap();
- let frame_id2 = db.insert_frame("test_device", None).await.unwrap();
+ let frame_id1 = db.insert_frame("test_device", None, None).await.unwrap();
+ let frame_id2 = db.insert_frame("test_device", None, None).await.unwrap();
db.insert_ocr_text(
frame_id1,
"This is a test OCR text", // 21 chars
@@ -363,7 +363,7 @@ mod tests {
.insert_video_chunk("test_video1.mp4", "test_device")
.await
.unwrap();
- let frame_id1 = db.insert_frame("test_device", None).await.unwrap();
+ let frame_id1 = db.insert_frame("test_device", None, None).await.unwrap();
let audio_chunk_id1 = db.insert_audio_chunk("test_audio1.wav").await.unwrap();
let now = DateTime::parse_from_rfc3339("2024-09-21T10:49:23.240367Z")
@@ -551,14 +551,14 @@ mod tests {
.insert_video_chunk("old_video.mp4", "test_device")
.await
.unwrap();
- let old_frame_id = db.insert_frame("test_device", None).await.unwrap();
+ let old_frame_id = db.insert_frame("test_device", None, None).await.unwrap();
// Insert recent data
let _ = db
.insert_video_chunk("recent_video.mp4", "test_device")
.await
.unwrap();
- let recent_frame_id = db.insert_frame("test_device", None).await.unwrap();
+ let recent_frame_id = db.insert_frame("test_device", None, None).await.unwrap();
// Insert OCR data with different timestamps
sqlx::query("UPDATE frames SET timestamp = ? WHERE id = ?")
diff --git a/screenpipe-server/tests/tags_test.rs b/screenpipe-server/tests/tags_test.rs
index 5e2accbc2..2542d1596 100644
--- a/screenpipe-server/tests/tags_test.rs
+++ b/screenpipe-server/tests/tags_test.rs
@@ -365,7 +365,7 @@ async fn insert_test_data(db: &Arc<DatabaseManager>) {
.unwrap();
// Insert test frame
- let frame_id = db.insert_frame("test_device", None).await.unwrap();
+ let frame_id = db.insert_frame("test_device", None, None).await.unwrap();
// Insert test OCR data
db.insert_ocr_text(
diff --git a/screenpipe-vision/Cargo.toml b/screenpipe-vision/Cargo.toml
index b9c00d334..3b6af9f2b 100644
--- a/screenpipe-vision/Cargo.toml
+++ b/screenpipe-vision/Cargo.toml
@@ -104,6 +104,9 @@ xcap = "0.2.2"
[target.'cfg(target_os = "macos")'.dependencies]
libc = "=0.2.164"
cidre = { git = "https://github.com/yury/cidre.git", version = "0.5.0" }
+accessibility-sys = "0.1.3"
+core-foundation = "0.9.4"
+url = "2.5.0"
[target.'cfg(target_os = "linux")'.dependencies]
-libc = "=0.2.164"
+libc = "=0.2.164"
\ No newline at end of file
diff --git a/screenpipe-vision/src/browser_utils/macos.rs b/screenpipe-vision/src/browser_utils/macos.rs
new file mode 100644
index 000000000..e6a770424
--- /dev/null
+++ b/screenpipe-vision/src/browser_utils/macos.rs
@@ -0,0 +1,137 @@
+use accessibility_sys::{
+ kAXChildrenAttribute, kAXFocusedWindowAttribute, kAXRoleAttribute, kAXTextFieldRole,
+ kAXValueAttribute, AXUIElementCopyAttributeValue, AXUIElementCreateApplication,
+ AXUIElementRef,
+};
+use anyhow::Result;
+use core_foundation::{
+ base::{CFTypeRef, TCFType},
+ string::CFString,
+ array::CFArray,
+};
+use url::Url;
+
+use super::BrowserUrlDetector;
+
+pub struct MacOSUrlDetector;
+
+impl MacOSUrlDetector {
+ pub fn new() -> Self {
+ Self
+ }
+
+ unsafe fn find_url_field(&self, element: AXUIElementRef) -> Option<AXUIElementRef> {
+ let mut role: CFTypeRef = std::ptr::null_mut();
+ let status = AXUIElementCopyAttributeValue(
+ element,
+ CFString::from_static_string(kAXRoleAttribute).as_concrete_TypeRef(),
+ &mut role,
+ );
+
+ if status == accessibility_sys::kAXErrorSuccess {
+ let cf_role = CFString::wrap_under_get_rule(role as _);
+ let role_str = cf_role.to_string();
+
+ if role_str == kAXTextFieldRole {
+ let mut value: CFTypeRef = std::ptr::null_mut();
+ let status = AXUIElementCopyAttributeValue(
+ element,
+ CFString::from_static_string(kAXValueAttribute).as_concrete_TypeRef(),
+ &mut value,
+ );
+
+ if status == accessibility_sys::kAXErrorSuccess {
+ let url_str = CFString::wrap_under_get_rule(value as _).to_string();
+ let url_to_parse = if !url_str.starts_with("http://") && !url_str.starts_with("https://") {
+ format!("https://{}", url_str)
+ } else {
+ url_str
+ };
+
+ if Url::parse(&url_to_parse).is_ok() {
+ return Some(element);
+ }
+ }
+ }
+ }
+
+ let mut children: CFTypeRef = std::ptr::null_mut();
+ let status = AXUIElementCopyAttributeValue(
+ element,
+ CFString::from_static_string(kAXChildrenAttribute).as_concrete_TypeRef(),
+ &mut children,
+ );
+
+ if status == accessibility_sys::kAXErrorSuccess {
+ let children_array = CFArray::<*const std::ffi::c_void>::wrap_under_get_rule(children as _);
+ for child in children_array.iter() {
+ if let Some(found) = self.find_url_field(*child as AXUIElementRef) {
+ return Some(found);
+ }
+ }
+ }
+
+ None
+ }
+
+ fn get_url_via_applescript(&self, script: &str) -> Result<Option<String>> {
+ let output = std::process::Command::new("osascript")
+ .arg("-e")
+ .arg(script)
+ .output()?;
+
+ if output.status.success() {
+ let url = String::from_utf8(output.stdout)?.trim().to_string();
+ return Ok(Some(url));
+ }
+ Ok(None)
+ }
+
+ fn get_url_via_accessibility(&self, process_id: i32) -> Result<Option<String>> {
+ unsafe {
+ let app_element = AXUIElementCreateApplication(process_id);
+
+ let mut focused_window: CFTypeRef = std::ptr::null_mut();
+ let status = AXUIElementCopyAttributeValue(
+ app_element,
+ CFString::from_static_string(kAXFocusedWindowAttribute).as_concrete_TypeRef(),
+ &mut focused_window,
+ );
+
+ if status != accessibility_sys::kAXErrorSuccess {
+ return Ok(None);
+ }
+
+ let window_ref = focused_window as AXUIElementRef;
+ let address_bar = match self.find_url_field(window_ref) {
+ Some(bar) => bar,
+ None => return Ok(None),
+ };
+
+ let mut url_value: CFTypeRef = std::ptr::null_mut();
+ let status = AXUIElementCopyAttributeValue(
+ address_bar,
+ CFString::from_static_string(kAXValueAttribute).as_concrete_TypeRef(),
+ &mut url_value,
+ );
+
+ if status == accessibility_sys::kAXErrorSuccess {
+ let url = CFString::wrap_under_get_rule(url_value as _).to_string();
+ Ok(Some(url))
+ } else {
+ Ok(None)
+ }
+ }
+ }
+}
+
+impl BrowserUrlDetector for MacOSUrlDetector {
+ fn get_active_url(&self, app_name: &str, process_id: i32) -> Result<Option<String>> {
+ if app_name == "Arc" {
+ let script = r#"tell application "Arc" to return URL of active tab of front window"#;
+ self.get_url_via_applescript(script)
+ } else {
+ self.get_url_via_accessibility(process_id)
+ }
+ }
+}
\ No newline at end of file
diff --git a/screenpipe-vision/src/browser_utils/mod.rs b/screenpipe-vision/src/browser_utils/mod.rs
new file mode 100644
index 000000000..fb1cedf93
--- /dev/null
+++ b/screenpipe-vision/src/browser_utils/mod.rs
@@ -0,0 +1,36 @@
+use anyhow::Result;
+
+// Trait definition
+pub trait BrowserUrlDetector {
+ fn get_active_url(&self, app_name: &str, process_id: i32) -> Result<Option<String>>;
+}
+
+// Factory function
+pub fn create_url_detector() -> Box<dyn BrowserUrlDetector> {
+ #[cfg(target_os = "macos")]
+ return Box::new(MacOSUrlDetector::new());
+
+ #[cfg(not(target_os = "macos"))]
+ return Box::new(UnsupportedUrlDetector::new());
+}
+
+// Unsupported implementation
+pub struct UnsupportedUrlDetector;
+
+impl UnsupportedUrlDetector {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+impl BrowserUrlDetector for UnsupportedUrlDetector {
+ fn get_active_url(&self, _app_name: &str, _process_id: i32) -> Result<Option<String>> {
+ Ok(None)
+ }
+}
+
+// Re-export MacOS implementation
+#[cfg(target_os = "macos")]
+mod macos;
+#[cfg(target_os = "macos")]
+pub use macos::MacOSUrlDetector;
\ No newline at end of file
diff --git a/screenpipe-vision/src/capture_screenshot_by_window.rs b/screenpipe-vision/src/capture_screenshot_by_window.rs
index 2cb225cf3..8c72ee87b 100644
--- a/screenpipe-vision/src/capture_screenshot_by_window.rs
+++ b/screenpipe-vision/src/capture_screenshot_by_window.rs
@@ -139,6 +139,7 @@ pub struct CapturedWindow {
pub image: DynamicImage,
pub app_name: String,
pub window_name: String,
+ pub process_id: i32,
pub is_focused: bool,
}
@@ -203,10 +204,10 @@ pub async fn capture_all_visible_windows(
let app_name = window.app_name().to_string();
let title = window.title().to_string();
let is_focused = window.is_focused();
-
+ let process_id = window.pid();
// Capture image immediately while we have access to the window
match window.capture_image() {
- Ok(buffer) => Some((app_name, title, is_focused, buffer)),
+ Ok(buffer) => Some((app_name, title, is_focused, buffer, process_id)),
Err(_) => None,
}
})
@@ -217,7 +218,7 @@ pub async fn capture_all_visible_windows(
}
// Process the captured data
- for (app_name, window_name, is_focused, buffer) in windows_data {
+ for (app_name, window_name, is_focused, buffer, process_id) in windows_data {
// Convert to DynamicImage
let image = DynamicImage::ImageRgba8(
image::ImageBuffer::from_raw(buffer.width(), buffer.height(), buffer.into_raw())
@@ -235,6 +236,7 @@ pub async fn capture_all_visible_windows(
image,
app_name,
window_name,
+ process_id: process_id as i32,
is_focused,
});
}
diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rs
index cd6539591..cdb2b8c00 100644
--- a/screenpipe-vision/src/core.rs
+++ b/screenpipe-vision/src/core.rs
@@ -32,6 +32,7 @@ use tokio::sync::mpsc::Sender;
use tokio::time::sleep;
use xcap::Monitor;
+use crate::browser_utils::create_url_detector;
fn serialize_image<S>(image: &Option<DynamicImage>, serializer: S) -> Result<S::Ok, S::Error>
where
@@ -116,6 +117,7 @@ pub struct WindowOcrResult {
pub text_json: Vec<HashMap<String, String>>, // Change this line
pub focused: bool,
pub confidence: f64,
+ pub browser_url: Option<String>,
}
pub struct OcrTaskData {
@@ -126,6 +128,8 @@ pub struct OcrTaskData {
pub result_tx: Sender<CaptureResult>,
}
+const BROWSER_NAMES: [&str; 9] = ["chrome", "firefox", "safari", "edge", "brave", "arc", "chromium", "vivaldi", "opera"];
+
pub async fn continuous_capture(
result_tx: Sender<CaptureResult>,
interval: Duration,
@@ -278,6 +282,24 @@ pub async fn process_ocr_task(
let mut window_count = 0;
for captured_window in window_images {
+ let app_name = captured_window.app_name.clone();
+ let browser_url = if cfg!(target_os = "macos") && captured_window.is_focused &&
+ BROWSER_NAMES.iter().any(|&browser| app_name.to_lowercase().contains(browser)) {
+ match tokio::task::spawn_blocking(move || get_active_browser_url_sync(&app_name, captured_window.process_id)).await {
+ Ok(Ok(url)) => Some(url),
+ Ok(Err(e)) => {
+ error!("Failed to get browser URL: {}", e);
+ None
+ }
+ Err(e) => {
+ error!("Failed to spawn blocking task: {}", e);
+ None
+ }
+ }
+ } else {
+ None
+ };
+
let (window_text, window_json_output, confidence) = match ocr_engine {
OcrEngine::Unstructured => perform_ocr_cloud(&captured_window.image, languages.clone())
.await
@@ -317,6 +339,7 @@ pub async fn process_ocr_task(
text_json: parse_json_output(&window_json_output),
focused: captured_window.is_focused,
confidence: confidence.unwrap_or(0.0),
+ browser_url: browser_url.clone(),
});
}
@@ -438,3 +461,18 @@ impl UIFrame {
}
}
}
+
+fn get_active_browser_url_sync(app_name: &str, process_id: i32) -> Result<String, std::io::Error> {
+ let detector = create_url_detector();
+ match detector.get_active_url(app_name, process_id) {
+ Ok(Some(url)) => Ok(url),
+ Ok(None) => Err(std::io::Error::new(
+ std::io::ErrorKind::Other,
+ "Failed to get browser URL"
+ )),
+ Err(e) => Err(std::io::Error::new(
+ std::io::ErrorKind::Other,
+ format!("Error getting browser URL: {}", e)
+ )),
+ }
+}
\ No newline at end of file
diff --git a/screenpipe-vision/src/lib.rs b/screenpipe-vision/src/lib.rs
index 6461555f3..131687835 100644
--- a/screenpipe-vision/src/lib.rs
+++ b/screenpipe-vision/src/lib.rs
@@ -21,3 +21,4 @@ pub use microsoft::perform_ocr_windows;
#[cfg(target_os = "macos")]
pub use run_ui_monitoring_macos::run_ui;
pub use tesseract::perform_ocr_tesseract;
+pub mod browser_utils;