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

fix(ci): add missing Linux dependencies for pipewire and gbm

Louis Beaumontca4c9c10875f
diff --git a/.github/scripts/install_dependencies.sh b/.github/scripts/install_dependencies.sh
index ad48b0ac9..c61ee160e 100755
--- a/.github/scripts/install_dependencies.sh
+++ b/.github/scripts/install_dependencies.sh
@@ -1,3 +1,3 @@
#!/bin/bash
sudo apt-get update
-sudo apt-get install -y xvfb x11-xserver-utils ffmpeg libasound2-dev libgtk-3-dev libavformat-dev libavfilter-dev libavdevice-dev x11-utils x11-apps xdotool sqlite3 openbox xterm fonts-liberation tesseract-ocr libtesseract-dev imagemagick fonts-dejavu alsa-utils pulseaudio pulseaudio-utils libxdo-dev libpipewire-0.3-dev
+sudo apt-get install -y xvfb x11-xserver-utils ffmpeg libasound2-dev libgtk-3-dev libavformat-dev libavfilter-dev libavdevice-dev x11-utils x11-apps xdotool sqlite3 openbox xterm fonts-liberation tesseract-ocr libtesseract-dev imagemagick fonts-dejavu alsa-utils pulseaudio pulseaudio-utils libxdo-dev libpipewire-0.3-dev libgbm-dev libwayland-dev libegl-dev
diff --git a/.github/workflows/e2e-test.yml b/.github/workflows/e2e-test.yml
index 6bd69167f..0725c0e29 100644
--- a/.github/workflows/e2e-test.yml
+++ b/.github/workflows/e2e-test.yml
@@ -305,7 +305,11 @@ jobs:
fonts-dejavu \
alsa-utils \
pulseaudio \
- pulseaudio-utils
+ pulseaudio-utils \
+ libpipewire-0.3-dev \
+ libgbm-dev \
+ libwayland-dev \
+ libegl-dev
- name: Set up Rust
uses: actions-rust-lang/setup-rust-toolchain@v1
diff --git a/Cargo.lock b/Cargo.lock
index 39af82773..dff1e8a18 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6791,6 +6791,7 @@ dependencies = [
"atspi-common",
"atspi-proxies",
"base64 0.22.1",
+ "chrono",
"cidre 0.7.0",
"clap",
"core-foundation 0.10.0",
diff --git a/screenpipe-db/src/db.rs b/screenpipe-db/src/db.rs
index 26656fd4b..3b206f5e0 100644
--- a/screenpipe-db/src/db.rs
+++ b/screenpipe-db/src/db.rs
@@ -297,6 +297,12 @@ impl DatabaseManager {
Ok(id)
}
+ /// Insert a frame record into the database.
+ ///
+ /// # Arguments
+ /// * `offset_index` - The video frame index. Multiple window records from the same capture cycle
+ /// should share the same offset_index to correctly reference the video frame.
+ /// If None, auto-calculates based on DB records (legacy behavior, may cause mismatches).
pub async fn insert_frame(
&self,
device_name: &str,
@@ -305,6 +311,7 @@ impl DatabaseManager {
app_name: Option<&str>,
window_name: Option<&str>,
focused: bool,
+ offset_index: Option<i64>,
) -> Result<i64, sqlx::Error> {
let mut tx = self.pool.begin().await?;
debug!("insert_frame Transaction started");
@@ -328,14 +335,21 @@ impl DatabaseManager {
}
};
- // Calculate the offset_index
- let offset_index: i64 = sqlx::query_scalar(
- "SELECT COALESCE(MAX(offset_index), -1) + 1 FROM frames WHERE video_chunk_id = ?1",
- )
- .bind(video_chunk_id)
- .fetch_one(&mut *tx)
- .await?;
- debug!("insert_frame Calculated offset_index: {}", offset_index);
+ // Use provided offset_index or calculate from DB (legacy fallback)
+ let offset_index: i64 = match offset_index {
+ Some(idx) => idx,
+ None => {
+ // Legacy behavior: calculate from DB records
+ // NOTE: This can cause mismatches when multiple windows are captured per cycle
+ sqlx::query_scalar(
+ "SELECT COALESCE(MAX(offset_index), -1) + 1 FROM frames WHERE video_chunk_id = ?1",
+ )
+ .bind(video_chunk_id)
+ .fetch_one(&mut *tx)
+ .await?
+ }
+ };
+ debug!("insert_frame Using offset_index: {}", offset_index);
let timestamp = timestamp.unwrap_or_else(Utc::now);
@@ -363,6 +377,33 @@ impl DatabaseManager {
Ok(id)
}
+ /// Get the next frame offset for a device.
+ /// This should be called ONCE per capture cycle and shared by all window results.
+ pub async fn get_next_frame_offset(&self, device_name: &str) -> Result<i64, sqlx::Error> {
+ // Get the most recent video_chunk_id
+ let video_chunk_id: Option<i64> = sqlx::query_scalar(
+ "SELECT id FROM video_chunks WHERE device_name = ?1 ORDER BY id DESC LIMIT 1",
+ )
+ .bind(device_name)
+ .fetch_optional(&self.pool)
+ .await?;
+
+ let video_chunk_id = match video_chunk_id {
+ Some(id) => id,
+ None => return Ok(0),
+ };
+
+ // Get the next offset for this video chunk
+ let offset: i64 = sqlx::query_scalar(
+ "SELECT COALESCE(MAX(offset_index), -1) + 1 FROM frames WHERE video_chunk_id = ?1",
+ )
+ .bind(video_chunk_id)
+ .fetch_one(&self.pool)
+ .await?;
+
+ Ok(offset)
+ }
+
pub async fn insert_ocr_text(
&self,
frame_id: i64,
diff --git a/screenpipe-js/ai-proxy/src/providers/vertex.ts b/screenpipe-js/ai-proxy/src/providers/vertex.ts
index 37fae0fb7..ed351c3d3 100644
--- a/screenpipe-js/ai-proxy/src/providers/vertex.ts
+++ b/screenpipe-js/ai-proxy/src/providers/vertex.ts
@@ -170,6 +170,7 @@ export class VertexAIProvider implements AIProvider {
'claude-sonnet-4-5-20250929': 'claude-sonnet-4-5@20250929',
'claude-sonnet-4.5': 'claude-sonnet-4-5@20250929',
'claude-sonnet-4-5': 'claude-sonnet-4-5@20250929',
+ 'claude-haiku-4-5': 'claude-haiku-4-5@20251023',
// Claude 4
'claude-sonnet-4-20250514': 'claude-sonnet-4@20250514',
'claude-sonnet-4': 'claude-sonnet-4@20250514',
@@ -180,6 +181,8 @@ export class VertexAIProvider implements AIProvider {
'claude-3-5-sonnet-v2': 'claude-3-5-sonnet-v2@20241022',
'claude-3-5-haiku': 'claude-3-5-haiku@20241022',
'claude-3-5-haiku-20241022': 'claude-3-5-haiku@20241022',
+ 'claude-3-5-haiku-latest': 'claude-3-5-haiku@20241022',
+ 'claude-3-5-sonnet-latest': 'claude-3-5-sonnet-v2@20241022',
};
const vertexModel = modelMapping[model] || model;
@@ -474,6 +477,7 @@ export async function proxyToVertex(
}
try {
+ console.log('proxyToVertex: parsing request body');
const body = (await request.json()) as {
model?: string;
stream?: boolean;
@@ -483,14 +487,18 @@ export async function proxyToVertex(
temperature?: number;
[key: string]: any;
};
+ console.log('proxyToVertex: model=', body.model, 'stream=', body.stream, 'messages count=', body.messages?.length);
const isStreaming = body.stream === true;
// Get access token
+ console.log('proxyToVertex: getting access token');
const accessToken = await (provider as any).getAccessToken();
+ console.log('proxyToVertex: got access token');
// Map model to Vertex format
const model = body.model || 'claude-sonnet-4@20250514';
const vertexModel = mapModelToVertex(model);
+ console.log('proxyToVertex: mapped model', model, '->', vertexModel);
const method = isStreaming ? 'streamRawPredict' : 'rawPredict';
const vertexUrl = `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/publishers/anthropic/models/${vertexModel}:${method}`;
@@ -501,7 +509,7 @@ export async function proxyToVertex(
};
delete vertexBody.model; // Vertex doesn't use model in body
- console.log('Proxying to Vertex AI:', vertexUrl);
+ console.log('proxyToVertex: calling Vertex AI:', vertexUrl);
const response = await fetch(vertexUrl, {
method: 'POST',
@@ -538,8 +546,8 @@ export async function proxyToVertex(
headers: { 'Content-Type': 'application/json' },
});
} catch (error: any) {
- console.error('Proxy error:', error);
- return new Response(JSON.stringify({ error: error.message }), {
+ console.error('proxyToVertex error:', error.message, error.stack);
+ return new Response(JSON.stringify({ error: error.message, stack: error.stack }), {
status: 500,
headers: { 'Content-Type': 'application/json' },
});
@@ -555,6 +563,7 @@ function mapModelToVertex(model: string): string {
'claude-sonnet-4-5-20250929': 'claude-sonnet-4-5@20250929',
'claude-sonnet-4.5': 'claude-sonnet-4-5@20250929',
'claude-sonnet-4-5': 'claude-sonnet-4-5@20250929',
+ 'claude-haiku-4-5': 'claude-haiku-4-5@20251023',
// Claude 4
'claude-sonnet-4-20250514': 'claude-sonnet-4@20250514',
'claude-sonnet-4': 'claude-sonnet-4@20250514',
@@ -565,6 +574,8 @@ function mapModelToVertex(model: string): string {
'claude-3-5-haiku-20241022': 'claude-3-5-haiku@20241022',
'claude-3-5-sonnet': 'claude-3-5-sonnet-v2@20241022',
'claude-3-5-haiku': 'claude-3-5-haiku@20241022',
+ 'claude-3-5-haiku-latest': 'claude-3-5-haiku@20241022',
+ 'claude-3-5-sonnet-latest': 'claude-3-5-sonnet-v2@20241022',
};
return mapping[model] || model;
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index 9993e2eb9..2a1f82d7e 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -235,16 +235,21 @@ async fn record_video(
time_since_last_frame.as_millis()
);
+ // Get the current video frame offset for this capture cycle
+ // All window results from this capture share the same video frame
+ let video_frame_offset = db.get_next_frame_offset(&device_name).await.unwrap_or(0);
+
for window_result in &frame.window_ocr_results {
let insert_frame_start = std::time::Instant::now();
let result = db
.insert_frame(
&device_name,
- None,
+ Some(frame.captured_at),
window_result.browser_url.as_deref(),
Some(window_result.app_name.as_str()),
Some(window_result.window_name.as_str()),
window_result.focused,
+ Some(video_frame_offset), // All windows share the same video frame offset
)
.await;
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 823f7511e..955fc4996 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -1394,6 +1394,7 @@ async fn add_frame_to_db(
frame.app_name.as_deref(),
frame.window_name.as_deref(),
false,
+ None, // Use legacy auto-calculation for API-added frames
)
.await?;
diff --git a/screenpipe-vision/Cargo.toml b/screenpipe-vision/Cargo.toml
index 3dc529de7..a3495871a 100644
--- a/screenpipe-vision/Cargo.toml
+++ b/screenpipe-vision/Cargo.toml
@@ -12,6 +12,7 @@ edition = { workspace = true }
[dependencies]
serde_json = "1.0"
+chrono = { version = "0.4.31", features = ["serde"] }
# async
tokio = { workspace = true }
diff --git a/screenpipe-vision/src/capture_screenshot_by_window.rs b/screenpipe-vision/src/capture_screenshot_by_window.rs
index cfd4bca35..f9f958b8a 100644
--- a/screenpipe-vision/src/capture_screenshot_by_window.rs
+++ b/screenpipe-vision/src/capture_screenshot_by_window.rs
@@ -7,8 +7,13 @@ use tracing::debug;
use xcap::{Window, XCapError};
+use crate::browser_utils::create_url_detector;
use crate::monitor::SafeMonitor;
+const BROWSER_NAMES: [&str; 9] = [
+ "chrome", "firefox", "safari", "edge", "brave", "arc", "chromium", "vivaldi", "opera",
+];
+
#[derive(Debug)]
enum CaptureError {
NoWindows,
@@ -145,6 +150,8 @@ pub struct CapturedWindow {
pub window_name: String,
pub process_id: i32,
pub is_focused: bool,
+ /// Browser URL captured atomically with the screenshot to prevent timing mismatches
+ pub browser_url: Option<String>,
}
pub struct WindowFilters {
@@ -295,12 +302,32 @@ pub async fn capture_all_visible_windows(
&& window_filters.is_valid(&app_name, &window_name);
if is_valid {
+ // Fetch browser URL atomically with screenshot for focused browser windows
+ // This prevents timing mismatches where URL is fetched after navigation
+ let browser_url = if is_focused
+ && BROWSER_NAMES
+ .iter()
+ .any(|&browser| app_name.to_lowercase().contains(browser))
+ {
+ let detector = create_url_detector();
+ match detector.get_active_url(&app_name, process_id, &window_name) {
+ Ok(url) => url,
+ Err(e) => {
+ debug!("Failed to get browser URL for {}: {}", app_name, e);
+ None
+ }
+ }
+ } else {
+ None
+ };
+
all_captured_images.push(CapturedWindow {
image,
app_name,
window_name,
- process_id: process_id,
+ process_id,
is_focused,
+ browser_url,
});
}
}
diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rs
index 89bbe5514..a97619708 100644
--- a/screenpipe-vision/src/core.rs
+++ b/screenpipe-vision/src/core.rs
@@ -11,6 +11,7 @@ use crate::utils::OcrEngine;
use crate::utils::{capture_screenshot, compare_with_previous_image};
use anyhow::Result;
use base64::{engine::general_purpose, Engine as _};
+use chrono::{DateTime, Utc};
use image::codecs::jpeg::JpegEncoder;
use image::DynamicImage;
use screenpipe_core::Language;
@@ -28,8 +29,6 @@ use std::{
use tokio::sync::mpsc::Sender;
use tracing::{debug, error, warn};
-use crate::browser_utils::create_url_detector;
-
fn serialize_image<S>(image: &Option<DynamicImage>, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
@@ -102,6 +101,8 @@ pub struct CaptureResult {
pub image: DynamicImage,
pub frame_number: u64,
pub timestamp: Instant,
+ /// Wall-clock timestamp captured atomically with the screenshot
+ pub captured_at: DateTime<Utc>,
pub window_ocr_results: Vec<WindowOcrResult>,
}
@@ -121,12 +122,11 @@ pub struct OcrTaskData {
pub window_images: Vec<CapturedWindow>,
pub frame_number: u64,
pub timestamp: Instant,
+ /// Wall-clock timestamp captured atomically with the screenshot
+ pub captured_at: DateTime<Utc>,
pub result_tx: Sender<CaptureResult>,
}
-const BROWSER_NAMES: [&str; 9] = [
- "chrome", "firefox", "safari", "edge", "brave", "arc", "chromium", "vivaldi", "opera",
-];
#[derive(Debug)]
pub enum ContinuousCaptureError {
@@ -170,7 +170,8 @@ pub async fn continuous_capture(
};
loop {
- // 3. Capture screenshot
+ // 3. Capture screenshot and wall-clock time atomically
+ let captured_at = Utc::now();
let capture_result =
match capture_screenshot(&monitor, &window_filters, capture_unfocused_windows).await {
Ok(result) => result,
@@ -194,6 +195,7 @@ pub async fn continuous_capture(
&window_images,
image_hash,
result_tx.clone(),
+ captured_at,
)
.await;
@@ -230,6 +232,7 @@ async fn should_skip_frame(
window_images: &Vec<CapturedWindow>,
image_hash: u64,
result_tx: Sender<CaptureResult>,
+ captured_at: DateTime<Utc>,
) -> bool {
let current_average = match compare_with_previous_image(
previous_image.as_ref(),
@@ -267,6 +270,7 @@ async fn should_skip_frame(
image_hash,
frame_number: frame_counter,
timestamp: Instant::now(),
+ captured_at,
result_tx: result_tx.clone(),
average: current_average,
});
@@ -286,6 +290,7 @@ async fn process_max_average_frame(
window_images: max_avg_frame.window_images,
frame_number: max_avg_frame.frame_number,
timestamp: max_avg_frame.timestamp,
+ captured_at: max_avg_frame.captured_at,
result_tx: max_avg_frame.result_tx,
};
@@ -303,6 +308,8 @@ pub struct MaxAverageFrame {
pub image_hash: u64,
pub frame_number: u64,
pub timestamp: Instant,
+ /// Wall-clock timestamp captured atomically with the screenshot
+ pub captured_at: DateTime<Utc>,
pub result_tx: Sender<CaptureResult>,
pub average: f64,
}
@@ -317,6 +324,7 @@ pub async fn process_ocr_task(
window_images,
frame_number,
timestamp,
+ captured_at,
result_tx,
} = ocr_task_data;
@@ -349,6 +357,7 @@ pub async fn process_ocr_task(
image,
frame_number,
timestamp,
+ captured_at,
window_ocr_results,
};
@@ -369,16 +378,9 @@ async fn process_window_ocr(
total_confidence: &mut f64,
window_count: &mut u32,
) -> Result<WindowOcrResult, ContinuousCaptureError> {
- let app_name = captured_window.app_name.clone();
-
- // Get browser URL if applicable
- let browser_url = get_browser_url_if_needed(
- &app_name,
- captured_window.is_focused,
- captured_window.process_id,
- &captured_window.window_name,
- )
- .await;
+ // Use the browser URL that was captured atomically with the screenshot
+ // This prevents timing mismatches where URL is fetched after browser navigation
+ let browser_url = captured_window.browser_url.clone();
// Perform OCR based on the selected engine
let (window_text, window_json_output, confidence) =
@@ -404,36 +406,6 @@ async fn process_window_ocr(
})
}
-async fn get_browser_url_if_needed(
- app_name: &str,
- is_focused: bool,
- process_id: i32,
- window_title: &str,
-) -> Option<String> {
- if is_focused
- && BROWSER_NAMES
- .iter()
- .any(|&browser| app_name.to_lowercase().contains(browser))
- {
- let app_name = app_name.to_string(); // Clone to move into the closure
- let window_title = window_title.to_string(); // Clone to move into the closure
- match tokio::task::spawn_blocking(move || {
- get_active_browser_url_sync(&app_name, process_id, &window_title)
- })
- .await
- {
- Ok(Ok(url)) => Some(url),
- Ok(Err(_)) => None,
- Err(e) => {
- error!("Failed to spawn blocking task: {}", e);
- None
- }
- }
- } else {
- None
- }
-}
-
async fn perform_ocr_with_engine(
ocr_engine: &OcrEngine,
image: &DynamicImage,
@@ -539,22 +511,3 @@ pub struct WindowOcr {
pub timestamp: Instant,
pub browser_url: Option<String>,
}
-
-fn get_active_browser_url_sync(
- app_name: &str,
- process_id: i32,
- window_title: &str,
-) -> Result<String, std::io::Error> {
- let detector = create_url_detector();
- match detector.get_active_url(app_name, process_id, window_title) {
- Ok(Some(url)) => Ok(url),
- Ok(None) => Err(std::io::Error::new(
- std::io::ErrorKind::NotFound,
- "No active URL found",
- )),
- Err(e) => Err(std::io::Error::other(format!(
- "Failed to get active URL: {}",
- e
- ))),
- }
-}
diff --git a/screenpipe-vision/tests/frame_window_mismatch_test.rs b/screenpipe-vision/tests/frame_window_mismatch_test.rs
new file mode 100644
index 000000000..09e967215
--- /dev/null
+++ b/screenpipe-vision/tests/frame_window_mismatch_test.rs
@@ -0,0 +1,431 @@
+//! Test to reproduce the frame-window mismatch issue
+//!
+//! The bug: Multiple database records (one per window) are created per capture cycle,
+//! but only ONE video frame is written per capture cycle.
+//!
+//! This causes offset_index in DB to be out of sync with actual video frame index.
+//!
+//! Run with: cargo test -p screenpipe-vision --test frame_window_mismatch_test -- --nocapture
+
+use std::collections::HashMap;
+
+/// Simulates the video file - one frame per capture cycle
+struct MockVideoFile {
+ frames: Vec<String>, // Each frame is the full-screen content at capture time
+}
+
+impl MockVideoFile {
+ fn new() -> Self {
+ Self { frames: Vec::new() }
+ }
+
+ fn write_frame(&mut self, content: &str) {
+ self.frames.push(content.to_string());
+ }
+
+ fn extract_frame(&self, offset_index: usize) -> Option<&str> {
+ self.frames.get(offset_index).map(|s| s.as_str())
+ }
+
+ fn frame_count(&self) -> usize {
+ self.frames.len()
+ }
+}
+
+/// Simulates a database frame record
+#[derive(Debug, Clone)]
+struct DbFrameRecord {
+ frame_id: i64,
+ offset_index: i64,
+ app_name: String,
+ window_name: String,
+ ocr_text: String,
+}
+
+/// Simulates the database - stores frame records
+struct MockDatabase {
+ frames: Vec<DbFrameRecord>,
+ next_frame_id: i64,
+}
+
+impl MockDatabase {
+ fn new() -> Self {
+ Self {
+ frames: Vec::new(),
+ next_frame_id: 1,
+ }
+ }
+
+ /// Current buggy behavior: calculates offset_index based on total frame count
+ fn insert_frame_buggy(&mut self, app_name: &str, window_name: &str, ocr_text: &str) -> i64 {
+ let offset_index = self.frames.len() as i64; // BUG: This should track VIDEO frames, not DB records
+ let frame_id = self.next_frame_id;
+ self.next_frame_id += 1;
+
+ self.frames.push(DbFrameRecord {
+ frame_id,
+ offset_index,
+ app_name: app_name.to_string(),
+ window_name: window_name.to_string(),
+ ocr_text: ocr_text.to_string(),
+ });
+
+ frame_id
+ }
+
+ fn get_frame(&self, frame_id: i64) -> Option<&DbFrameRecord> {
+ self.frames.iter().find(|f| f.frame_id == frame_id)
+ }
+}
+
+/// Simulates a capture cycle with multiple windows
+struct CaptureResult {
+ /// The full-screen composite image (written to video)
+ full_screen_content: String,
+ /// Individual window results (each creates a DB record)
+ windows: Vec<WindowResult>,
+}
+
+struct WindowResult {
+ app_name: String,
+ window_name: String,
+ ocr_text: String,
+}
+
+/// Simulates the CURRENT buggy capture and storage flow
+fn process_capture_cycle_buggy(
+ capture: &CaptureResult,
+ video: &mut MockVideoFile,
+ db: &mut MockDatabase,
+) -> Vec<i64> {
+ // Video gets ONE frame per capture cycle
+ video.write_frame(&capture.full_screen_content);
+
+ // Database gets MULTIPLE records per capture cycle (one per window)
+ // This is the bug - offset_index will be out of sync!
+ let mut frame_ids = Vec::new();
+ for window in &capture.windows {
+ let frame_id = db.insert_frame_buggy(&window.app_name, &window.window_name, &window.ocr_text);
+ frame_ids.push(frame_id);
+ }
+
+ frame_ids
+}
+
+#[test]
+fn test_bug_frame_window_mismatch() {
+ println!("\n=== Testing frame-window mismatch bug ===\n");
+
+ let mut video = MockVideoFile::new();
+ let mut db = MockDatabase::new();
+
+ // Capture cycle 1: User has WezTerm and Arc visible
+ let capture1 = CaptureResult {
+ full_screen_content: "Screen showing: WezTerm terminal with code, Arc browser with GitHub".to_string(),
+ windows: vec![
+ WindowResult {
+ app_name: "WezTerm".to_string(),
+ window_name: "~/code".to_string(),
+ ocr_text: "fn main() { println!(\"Hello\"); }".to_string(),
+ },
+ WindowResult {
+ app_name: "Arc".to_string(),
+ window_name: "GitHub - screenpipe".to_string(),
+ ocr_text: "screenpipe repository README".to_string(),
+ },
+ ],
+ };
+
+ println!("Capture cycle 1: WezTerm + Arc visible");
+ let frame_ids_1 = process_capture_cycle_buggy(&capture1, &mut video, &mut db);
+ println!(" Video frames written: {}", video.frame_count());
+ println!(" DB records created: {} (frame_ids: {:?})", frame_ids_1.len(), frame_ids_1);
+
+ // Capture cycle 2: User switches to Finder
+ let capture2 = CaptureResult {
+ full_screen_content: "Screen showing: Finder window with Documents folder".to_string(),
+ windows: vec![
+ WindowResult {
+ app_name: "Finder".to_string(),
+ window_name: "Documents".to_string(),
+ ocr_text: "Desktop Documents Downloads".to_string(),
+ },
+ ],
+ };
+
+ println!("\nCapture cycle 2: Finder visible");
+ let frame_ids_2 = process_capture_cycle_buggy(&capture2, &mut video, &mut db);
+ println!(" Video frames written: {}", video.frame_count());
+ println!(" DB records created: {} (frame_ids: {:?})", frame_ids_2.len(), frame_ids_2);
+
+ // Capture cycle 3: User has Safari open
+ let capture3 = CaptureResult {
+ full_screen_content: "Screen showing: Safari with Google Maps".to_string(),
+ windows: vec![
+ WindowResult {
+ app_name: "Safari".to_string(),
+ window_name: "Google Maps".to_string(),
+ ocr_text: "San Francisco CA directions".to_string(),
+ },
+ ],
+ };
+
+ println!("\nCapture cycle 3: Safari visible");
+ let frame_ids_3 = process_capture_cycle_buggy(&capture3, &mut video, &mut db);
+ println!(" Video frames written: {}", video.frame_count());
+ println!(" DB records created: {} (frame_ids: {:?})", frame_ids_3.len(), frame_ids_3);
+
+ // Now let's see the mismatch
+ println!("\n=== Checking for mismatches ===\n");
+ println!("Total video frames: {}", video.frame_count());
+ println!("Total DB records: {}", db.frames.len());
+
+ let mut mismatches = 0;
+
+ for record in &db.frames {
+ let video_frame = video.extract_frame(record.offset_index as usize);
+ let matches = video_frame
+ .map(|content| content.contains(&record.app_name))
+ .unwrap_or(false);
+
+ println!(
+ "Frame ID {}: app='{}', offset_index={}, video_frame_exists={}, content_matches={}",
+ record.frame_id,
+ record.app_name,
+ record.offset_index,
+ video_frame.is_some(),
+ matches
+ );
+
+ if let Some(content) = video_frame {
+ if !matches {
+ println!(" MISMATCH! DB says '{}' but video shows: '{}'", record.app_name, content);
+ mismatches += 1;
+ }
+ } else {
+ println!(" MISMATCH! No video frame at offset {}", record.offset_index);
+ mismatches += 1;
+ }
+ }
+
+ println!("\n=== Summary ===");
+ println!("Video frames: {}", video.frame_count());
+ println!("DB records: {}", db.frames.len());
+ println!("Mismatches: {}", mismatches);
+
+ // The bug: More DB records than video frames causes offset_index misalignment
+ assert!(
+ db.frames.len() > video.frame_count(),
+ "Bug prerequisite: more DB records than video frames"
+ );
+
+ assert!(
+ mismatches > 0,
+ "\n\nBUG NOT REPRODUCED! Expected mismatches due to offset_index desync.\n\
+ The issue is: {} DB records vs {} video frames.\n\
+ DB offset_index is based on DB record count, not video frame count.\n",
+ db.frames.len(),
+ video.frame_count()
+ );
+
+ println!("\nBUG REPRODUCED: {} mismatches found!", mismatches);
+ println!("Root cause: offset_index in DB is calculated from DB record count,");
+ println!(" but video frames are written once per capture cycle.");
+}
+
+#[test]
+fn test_fix_one_db_record_per_capture_cycle() {
+ println!("\n=== Testing fix: One DB record per capture cycle ===\n");
+
+ let mut video = MockVideoFile::new();
+ let mut db_records: Vec<(i64, i64, Vec<WindowResult>)> = Vec::new(); // (frame_id, offset_index, windows)
+ let mut next_frame_id = 1i64;
+
+ // Helper to process capture with fix
+ let mut process_capture_fixed = |capture: &CaptureResult| {
+ // Video gets ONE frame
+ video.write_frame(&capture.full_screen_content);
+ let offset_index = (video.frame_count() - 1) as i64; // Correct: based on video frame count
+
+ // DB gets ONE record that references all windows
+ let frame_id = next_frame_id;
+ next_frame_id += 1;
+ db_records.push((frame_id, offset_index, capture.windows.clone()));
+
+ frame_id
+ };
+
+ // Same captures as before
+ let capture1 = CaptureResult {
+ full_screen_content: "Screen: WezTerm + Arc".to_string(),
+ windows: vec![
+ WindowResult { app_name: "WezTerm".to_string(), window_name: "code".to_string(), ocr_text: "code".to_string() },
+ WindowResult { app_name: "Arc".to_string(), window_name: "GitHub".to_string(), ocr_text: "github".to_string() },
+ ],
+ };
+
+ let capture2 = CaptureResult {
+ full_screen_content: "Screen: Finder".to_string(),
+ windows: vec![
+ WindowResult { app_name: "Finder".to_string(), window_name: "Documents".to_string(), ocr_text: "docs".to_string() },
+ ],
+ };
+
+ process_capture_fixed(&capture1);
+ process_capture_fixed(&capture2);
+
+ println!("Video frames: {}", video.frame_count());
+ println!("DB records: {}", db_records.len());
+
+ // With fix: video frames == DB records
+ assert_eq!(
+ video.frame_count(),
+ db_records.len(),
+ "With fix: video frame count should equal DB record count"
+ );
+
+ // Verify all offsets are valid
+ for (frame_id, offset_index, _windows) in &db_records {
+ let video_frame = video.extract_frame(*offset_index as usize);
+ assert!(
+ video_frame.is_some(),
+ "Frame {} with offset {} should have a valid video frame",
+ frame_id,
+ offset_index
+ );
+ }
+
+ println!("\nFIX WORKS: Video frames and DB records are in sync!");
+}
+
+impl Clone for WindowResult {
+ fn clone(&self) -> Self {
+ WindowResult {
+ app_name: self.app_name.clone(),
+ window_name: self.window_name.clone(),
+ ocr_text: self.ocr_text.clone(),
+ }
+ }
+}
+
+#[test]
+fn test_fix_shared_offset_per_capture_cycle() {
+ println!("\n=== Testing fix: Shared offset_index per capture cycle ===\n");
+ println!("This matches the actual code fix: get offset ONCE, share across all windows.\n");
+
+ let mut video = MockVideoFile::new();
+ let mut db = MockDatabase::new();
+ let mut video_frame_count = 0i64;
+
+ // Helper to process capture with the actual fix strategy
+ let mut process_capture_fixed = |capture: &CaptureResult| {
+ // Video gets ONE frame per capture cycle
+ video.write_frame(&capture.full_screen_content);
+
+ // Get the offset for this capture cycle (same as video frame count before write)
+ let offset_for_this_cycle = video_frame_count;
+ video_frame_count += 1;
+
+ // All windows from this capture share the SAME offset
+ let mut frame_ids = Vec::new();
+ for window in &capture.windows {
+ let frame_id = db.next_frame_id;
+ db.next_frame_id += 1;
+
+ db.frames.push(DbFrameRecord {
+ frame_id,
+ offset_index: offset_for_this_cycle, // FIXED: Same offset for all windows
+ app_name: window.app_name.clone(),
+ window_name: window.window_name.clone(),
+ ocr_text: window.ocr_text.clone(),
+ });
+
+ frame_ids.push(frame_id);
+ }
+
+ frame_ids
+ };
+
+ // Same capture scenarios
+ let capture1 = CaptureResult {
+ full_screen_content: "Screen: WezTerm + Arc (both visible)".to_string(),
+ windows: vec![
+ WindowResult {
+ app_name: "WezTerm".to_string(),
+ window_name: "code".to_string(),
+ ocr_text: "fn main()".to_string(),
+ },
+ WindowResult {
+ app_name: "Arc".to_string(),
+ window_name: "GitHub".to_string(),
+ ocr_text: "github.com".to_string(),
+ },
+ ],
+ };
+
+ let capture2 = CaptureResult {
+ full_screen_content: "Screen: Finder only".to_string(),
+ windows: vec![WindowResult {
+ app_name: "Finder".to_string(),
+ window_name: "Documents".to_string(),
+ ocr_text: "Documents folder".to_string(),
+ }],
+ };
+
+ let capture3 = CaptureResult {
+ full_screen_content: "Screen: Safari with maps".to_string(),
+ windows: vec![WindowResult {
+ app_name: "Safari".to_string(),
+ window_name: "Maps".to_string(),
+ ocr_text: "Google Maps".to_string(),
+ }],
+ };
+
+ println!("Capture 1 (2 windows): WezTerm + Arc");
+ let ids1 = process_capture_fixed(&capture1);
+ println!(" Frame IDs: {:?}, both use offset_index=0", ids1);
+
+ println!("\nCapture 2 (1 window): Finder");
+ let ids2 = process_capture_fixed(&capture2);
+ println!(" Frame IDs: {:?}, uses offset_index=1", ids2);
+
+ println!("\nCapture 3 (1 window): Safari");
+ let ids3 = process_capture_fixed(&capture3);
+ println!(" Frame IDs: {:?}, uses offset_index=2", ids3);
+
+ println!("\n=== Verification ===");
+ println!("Video frames: {}", video.frame_count());
+ println!("DB records: {}", db.frames.len());
+
+ let mut all_valid = true;
+ for record in &db.frames {
+ let video_frame = video.extract_frame(record.offset_index as usize);
+ let content_valid = video_frame.is_some();
+ println!(
+ "Frame ID {}: app='{}', offset={} -> video frame exists: {}",
+ record.frame_id, record.app_name, record.offset_index, content_valid
+ );
+ if !content_valid {
+ all_valid = false;
+ }
+ }
+
+ // Verify WezTerm and Arc both point to offset 0 (the same video frame)
+ let wezterm = db.frames.iter().find(|f| f.app_name == "WezTerm").unwrap();
+ let arc = db.frames.iter().find(|f| f.app_name == "Arc").unwrap();
+ assert_eq!(
+ wezterm.offset_index, arc.offset_index,
+ "WezTerm and Arc should share the same offset (same capture cycle)"
+ );
+ println!(
+ "\nWezTerm offset: {}, Arc offset: {} (same capture cycle = same offset)",
+ wezterm.offset_index, arc.offset_index
+ );
+
+ assert!(
+ all_valid,
+ "All DB records should point to valid video frames"
+ );
+ println!("\nFIX VERIFIED: All DB records point to valid video frames!");
+ println!("Multiple windows per capture cycle share the same video frame offset.");
+}
diff --git a/screenpipe-vision/tests/url_timing_test.rs b/screenpipe-vision/tests/url_timing_test.rs
new file mode 100644
index 000000000..1b921afb6
--- /dev/null
+++ b/screenpipe-vision/tests/url_timing_test.rs
@@ -0,0 +1,210 @@
+//! Test to reproduce the URL-frame mismatch issue
+//!
+//! The bug: URL is fetched AFTER screenshot, so if browser navigates
+//! between screenshot and URL fetch, wrong URL is associated with the frame.
+//!
+//! Run with: cargo test -p screenpipe-vision --test url_timing_test -- --nocapture
+
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Arc;
+use std::time::Duration;
+use tokio::time::sleep;
+
+/// Simulates a browser that changes URL over time
+struct MockBrowser {
+ urls: Vec<&'static str>,
+ current_index: AtomicUsize,
+}
+
+impl MockBrowser {
+ fn new() -> Self {
+ Self {
+ urls: vec![
+ "https://google.com",
+ "https://github.com",
+ "https://twitter.com",
+ ],
+ current_index: AtomicUsize::new(0),
+ }
+ }
+
+ /// Simulates browser navigation (URL changes)
+ fn navigate_to_next(&self) {
+ self.current_index.fetch_add(1, Ordering::SeqCst);
+ }
+
+ /// Gets current URL (what the URL fetch would return)
+ fn get_current_url(&self) -> &'static str {
+ let idx = self.current_index.load(Ordering::SeqCst);
+ self.urls[idx % self.urls.len()]
+ }
+}
+
+/// Simulates the CURRENT buggy behavior in screenpipe-vision/src/core.rs
+///
+/// The issue is in capture_all_visible_windows():
+/// 1. Screenshot is captured first (line ~175)
+/// 2. Browser URL is fetched LATER via async task (line ~420)
+/// 3. Time gap between these allows browser to navigate
+async fn capture_frame_current_buggy_behavior(browser: Arc<MockBrowser>) -> (String, String) {
+ // Step 1: Capture screenshot - this is what the user SEES in the frame
+ let url_visible_in_screenshot = browser.get_current_url();
+ let screenshot_content = format!("Screenshot showing content from: {}", url_visible_in_screenshot);
+
+ // Step 2: Simulate the async delay that exists in current code:
+ // - OCR processing happens
+ // - Queue waiting
+ // - spawn_blocking for URL fetch
+ // In real code this is 50-200ms typically
+ sleep(Duration::from_millis(50)).await;
+
+ // Step 3: Fetch URL AFTER screenshot (this is the bug!)
+ // In core.rs line 420-422:
+ // let browser_url = tokio::task::spawn_blocking(move || {
+ // get_browser_url(&app_name_clone, process_id, &window_name_clone)
+ // }).await.ok().flatten();
+ //
+ // Browser may have navigated by now!
+ let url_fetched_later = browser.get_current_url().to_string();
+
+ // The frame is stored with url_fetched_later, not url_visible_in_screenshot
+ (screenshot_content, url_fetched_later)
+}
+
+/// Simulates the FIXED behavior - fetch URL atomically with screenshot
+async fn capture_frame_fixed_behavior(browser: Arc<MockBrowser>) -> (String, String) {
+ // FIXED: Fetch URL FIRST or atomically with screenshot
+ let url_at_capture = browser.get_current_url().to_string();
+
+ // Capture screenshot - URL is already captured
+ let screenshot_content = format!("Screenshot showing content from: {}", url_at_capture);
+
+ // Any async processing happens AFTER, but URL is already locked in
+ sleep(Duration::from_millis(50)).await;
+
+ // Return the URL that was captured at screenshot time
+ (screenshot_content, url_at_capture)
+}
+
+#[tokio::test]
+async fn test_bug_url_mismatch_when_browser_navigates_during_capture() {
+ // This test reproduces the bug where:
+ // - Screenshot shows google.com content
+ // - But metadata says github.com (because browser navigated during capture)
+
+ let browser = Arc::new(MockBrowser::new());
+ let browser_for_navigation = browser.clone();
+
+ // Simulate browser navigating DURING the capture process
+ // This happens in real usage when user clicks a link
+ let navigation_task = tokio::spawn(async move {
+ // Navigate after 25ms (during the 50ms capture window)
+ sleep(Duration::from_millis(25)).await;
+ browser_for_navigation.navigate_to_next();
+ println!(" [Browser] Navigated to next page during capture!");
+ });
+
+ println!("\n=== Testing CURRENT (buggy) behavior ===");
+ println!(" [Capture] Starting frame capture...");
+
+ let (screenshot, associated_url) = capture_frame_current_buggy_behavior(browser).await;
+ navigation_task.await.unwrap();
+
+ println!(" [Result] Screenshot: {}", screenshot);
+ println!(" [Result] Associated URL in DB: {}", associated_url);
+
+ // Check if URL in screenshot matches the associated URL
+ let urls_match = screenshot.contains(&associated_url);
+
+ if !urls_match {
+ println!("\n ❌ BUG REPRODUCED!");
+ println!(" Screenshot shows content from one URL");
+ println!(" But database stores a DIFFERENT URL");
+ println!(" This causes the 'wrong URL' issue in timeline");
+ }
+
+ // This assertion demonstrates the bug - it SHOULD pass but FAILS
+ // Comment out to see the bug, uncomment to enforce the fix
+ assert!(
+ urls_match,
+ "\n\nBUG REPRODUCED: URL mismatch detected!\n\
+ Screenshot content: {}\n\
+ Associated URL: {}\n\n\
+ The screenshot shows content from a different URL than what's stored in metadata.\n\
+ This is the root cause of the 'wrong URL associated with frame' bug.\n",
+ screenshot,
+ associated_url
+ );
+}
+
+#[tokio::test]
+async fn test_fix_url_matches_when_captured_atomically() {
+ // This test shows that the fix works - URL is captured atomically with screenshot
+
+ let browser = Arc::new(MockBrowser::new());
+ let browser_for_navigation = browser.clone();
+
+ // Same navigation scenario
+ let navigation_task = tokio::spawn(async move {
+ sleep(Duration::from_millis(25)).await;
+ browser_for_navigation.navigate_to_next();
+ println!(" [Browser] Navigated to next page during capture!");
+ });
+
+ println!("\n=== Testing FIXED behavior ===");
+ println!(" [Capture] Starting frame capture with atomic URL fetch...");
+
+ let (screenshot, associated_url) = capture_frame_fixed_behavior(browser).await;
+ navigation_task.await.unwrap();
+
+ println!(" [Result] Screenshot: {}", screenshot);
+ println!(" [Result] Associated URL in DB: {}", associated_url);
+
+ let urls_match = screenshot.contains(&associated_url);
+
+ if urls_match {
+ println!("\n ✅ FIX WORKS!");
+ println!(" Screenshot and URL are from the same moment in time");
+ }
+
+ assert!(
+ urls_match,
+ "With the fix, screenshot and URL should always match"
+ );
+}
+
+#[tokio::test]
+async fn test_timing_gap_measurement() {
+ // This test measures the timing gap in the current implementation
+ // to document how much time exists for the race condition
+
+ use std::time::Instant;
+
+ println!("\n=== Measuring timing gap in capture process ===");
+
+ let start = Instant::now();
+
+ // Step 1: Screenshot capture (simulated)
+ let t1 = start.elapsed();
+ println!(" T+{:?}: Screenshot captured", t1);
+
+ // Step 2: OCR processing (simulated - typically 20-50ms)
+ sleep(Duration::from_millis(30)).await;
+ let t2 = start.elapsed();
+ println!(" T+{:?}: OCR processing complete", t2);
+
+ // Step 3: URL fetch via spawn_blocking (simulated - typically 10-50ms)
+ sleep(Duration::from_millis(20)).await;
+ let t3 = start.elapsed();
+ println!(" T+{:?}: URL fetched", t3);
+
+ let total_gap = t3 - t1;
+ println!("\n ⚠️ Total timing gap: {:?}", total_gap);
+ println!(" Any browser navigation within this window causes URL mismatch!");
+
+ // Document that there IS a timing gap
+ assert!(
+ total_gap.as_millis() >= 50,
+ "There should be a significant timing gap in current implementation"
+ );
+}