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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix: combine OCR + snapshot frame into single transaction, remove unused UI elements
Louis Beaumont73006a1f48a2
diff --git a/apps/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsx b/apps/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsxindex 2499f7ae7..aaaaf04d1 100644--- a/apps/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsx+++ b/apps/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsx@@ -32,21 +32,6 @@ interface CurrentFrameTimelineProps {allDeviceIds?: string[];}-/**- * Parse a device_id like "monitor_4" → "4" or "louis-macbook/monitor_1" → "macbook · 1"- */-function formatDeviceLabel(deviceId: string): string {- // cloud sync format: "hostname/monitor_N"- if (deviceId.includes("/")) {- const [host, monitor] = deviceId.split("/");- const shortHost = host.replace(/^[^-]*-/, ""); // "louis-macbook" → "macbook"- const num = monitor.replace(/\D/g, "");- return `${shortHost} · ${num}`;- }- // local format: "monitor_N"- const num = deviceId.replace(/\D/g, "");- return num || deviceId;-}export const SkeletonLoader: FC = () => {return (@@ -145,12 +130,6 @@ export const CurrentFrameTimeline: FC<CurrentFrameTimelineProps> = ({const offsetIndex = device?.offset_index ?? 0;const fpsFromServer = device?.fps ?? 0.5;- // monitor pill — only show when session has multiple monitors- const deviceId = device?.device_id;- const showMonitorPill = Boolean(- deviceId && allDeviceIds && allDeviceIds.length > 1- );- const monitorLabel = deviceId ? formatDeviceLabel(deviceId) : "";// Track skipped frames for analyticsuseEffect(() => {@@ -777,12 +756,6 @@ export const CurrentFrameTimeline: FC<CurrentFrameTimelineProps> = ({/>)}- {/* monitor indicator pill */}- {showMonitorPill && !isLoading && !hasError && (- <div className="absolute top-2 right-2 z-20 px-1.5 py-0.5 text-[10px] font-mono bg-black/60 text-white/70 rounded-sm select-none pointer-events-none">- {monitorLabel}- </div>- )}{/* OCR text overlay — clickable text + URLs for frames with OCR data */}{!isLoading && !hasError && !ocrLoading && naturalDimensions && renderedImageInfo && textPositions.length > 0 && (@@ -806,18 +779,6 @@ export const CurrentFrameTimeline: FC<CurrentFrameTimelineProps> = ({</div>)}- {/* Copy text button — top-right, when no OCR TextOverlay is showing */}- {!isLoading && !hasError && frameContext?.text && textPositions.length === 0 && (- <button- type="button"- onClick={copyFrameText}- className="absolute top-2 right-2 z-20 p-1.5 bg-black/60 hover:bg-black/80 text-white/80 hover:text-white rounded-sm transition-colors"- style={{ ...(showMonitorPill ? { right: "4.5rem" } : {}) }}- title="Copy all text"- >- <Copy className="w-3.5 h-3.5" />- </button>- )}{/* URL chips — bottom of frame, when no OCR TextOverlay is showing */}{!isLoading && !hasError && textPositions.length === 0 && detectedUrls.length > 0 && (diff --git a/apps/screenpipe-app-tauri/components/rewind/timeline/timeline.tsx b/apps/screenpipe-app-tauri/components/rewind/timeline/timeline.tsxindex f176dd2d6..9b99bf7ca 100644--- a/apps/screenpipe-app-tauri/components/rewind/timeline/timeline.tsx+++ b/apps/screenpipe-app-tauri/components/rewind/timeline/timeline.tsx@@ -338,20 +338,6 @@ export const TimelineSlider = ({return Math.max(1, Math.round(baseMargin * zoomLevel));}, [zoomLevel]);- // Animation state for new frames pulse- const [showNewFramesPulse, setShowNewFramesPulse] = useState(false);- const prevFlushTimestampRef = useRef(lastFlushTimestamp);-- // Trigger pulse animation when new frames arrive- useEffect(() => {- if (lastFlushTimestamp > prevFlushTimestampRef.current && newFramesCount > 0) {- setShowNewFramesPulse(true);- const timer = setTimeout(() => setShowNewFramesPulse(false), 1500);- prevFlushTimestampRef.current = lastFlushTimestamp;- return () => clearTimeout(timer);- }- prevFlushTimestampRef.current = lastFlushTimestamp;- }, [lastFlushTimestamp, newFramesCount]);// Pre-compute frame index map for O(1) lookups instead of O(n) indexOf// This reduces 2.68M comparisons per render to just 400 Map lookups@@ -658,26 +644,6 @@ export const TimelineSlider = ({</button></div>- {/* New frames pulse indicator - appears on right side (newest) */}- {showNewFramesPulse && (- <motion.div- className="absolute right-0 top-0 bottom-0 w-24 pointer-events-none z-20"- initial={{ opacity: 0 }}- animate={{ opacity: [0, 1, 0] }}- transition={{ duration: 1.5, ease: "easeOut" }}- >- <div className="h-full w-full bg-gradient-to-l from-foreground/30 via-foreground/15 to-transparent" />- <motion.div- className="absolute right-2 top-1/2 -translate-y-1/2 bg-foreground text-background text-xs font-medium px-2 py-1 rounded-full shadow-lg"- initial={{ scale: 0, x: 20 }}- animate={{ scale: 1, x: 0 }}- exit={{ scale: 0, x: 20 }}- transition={{ type: "spring", damping: 15 }}- >- +{newFramesCount} new- </motion.div>- </motion.div>- )}<divref={containerRef}tabIndex={0}diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rsindex fa3a9f529..046b5524f 100644--- a/crates/screenpipe-db/src/db.rs+++ b/crates/screenpipe-db/src/db.rs@@ -65,7 +65,7 @@ pub struct DeleteTimeRangeResult {pub struct ImmediateTx {conn: Option<PoolConnection<Sqlite>>,committed: bool,- _write_permit: OwnedSemaphorePermit,+ _write_permit: Option<OwnedSemaphorePermit>,}impl ImmediateTx {@@ -98,27 +98,23 @@ impl Drop for ImmediateTx {fn drop(&mut self) {if !self.committed {if let Some(mut conn) = self.conn.take() {- // Roll back the open transaction and return the connection to the pool.- //- // Previous approach detached (leaked) the connection to avoid async- // issues, but that slowly exhausted the pool over time.- //- // We spawn a task to rollback asynchronously. The connection is moved- // into the task, so if rollback succeeds, the clean connection is- // returned to the pool when dropped. If rollback fails, we detach.+ // Move the write permit into the rollback task so the semaphore+ // is NOT released until the ROLLBACK actually completes and frees+ // the SQLite write lock. Without this, the next writer acquires+ // the semaphore while the old connection still holds the SQLite+ // write lock, causing BEGIN IMMEDIATE to block for 30-62s.+ let permit = self._write_permit.take();warn!("ImmediateTx dropped without commit — scheduling rollback");- // Rollback and return the connection to the pool. We spawn an async- // task because Drop is synchronous. The connection is moved into the- // task; if rollback succeeds, it returns to the pool when dropped.tokio::spawn(async move {if let Err(e) = sqlx::query("ROLLBACK").execute(&mut *conn).await {error!("failed to rollback on drop: {}", e);let _raw = conn.detach();}+ // permit is dropped here AFTER rollback, releasing the semaphore+ drop(permit);});}}- // _write_permit is dropped here, releasing the semaphore for the next writer}}@@ -424,7 +420,7 @@ impl DatabaseManager {return Ok(ImmediateTx {conn: Some(conn),committed: false,- _write_permit: permit,+ _write_permit: Some(permit),})}Err(e) if attempt < max_retries && Self::is_busy_error(&e) => {@@ -477,7 +473,7 @@ impl DatabaseManager {Ok(_) => Ok(Some(ImmediateTx {conn: Some(conn),committed: false,- _write_permit: permit,+ _write_permit: Some(permit),})),Err(e) if Self::is_busy_error(&e) => {drop(conn);@@ -1078,6 +1074,7 @@ impl DatabaseManager {/// The snapshot JPEG path is stored directly on the frame row./// Returns the new frame id.#[allow(clippy::too_many_arguments)]+ #[allow(clippy::too_many_arguments)]pub async fn insert_snapshot_frame(&self,device_name: &str,@@ -1093,6 +1090,33 @@ impl DatabaseManager {accessibility_tree_json: Option<&str>,content_hash: Option<i64>,simhash: Option<i64>,+ ) -> Result<i64, sqlx::Error> {+ self.insert_snapshot_frame_with_ocr(+ device_name, timestamp, snapshot_path, app_name, window_name,+ browser_url, focused, capture_trigger, accessibility_text, text_source,+ accessibility_tree_json, content_hash, simhash, None,+ ).await+ }++ /// Insert a snapshot frame AND optional OCR text positions in a single transaction.+ /// This avoids opening two separate transactions per capture which doubles pool pressure.+ #[allow(clippy::too_many_arguments)]+ pub async fn insert_snapshot_frame_with_ocr(+ &self,+ device_name: &str,+ timestamp: DateTime<Utc>,+ snapshot_path: &str,+ app_name: Option<&str>,+ window_name: Option<&str>,+ browser_url: Option<&str>,+ focused: bool,+ capture_trigger: Option<&str>,+ accessibility_text: Option<&str>,+ text_source: Option<&str>,+ accessibility_tree_json: Option<&str>,+ content_hash: Option<i64>,+ simhash: Option<i64>,+ ocr_data: Option<(&str, &str, &str)>, // (text, text_json, ocr_engine)) -> Result<i64, sqlx::Error> {let mut tx = self.begin_immediate_with_retry().await?;@@ -1127,8 +1151,23 @@ impl DatabaseManager {.await?.last_insert_rowid();+ // Insert OCR text positions in the same transaction (no extra connection needed)+ if let Some((text, text_json, ocr_engine)) = ocr_data {+ let text_length = text.len() as i64;+ sqlx::query(+ "INSERT INTO ocr_text (frame_id, text, text_json, ocr_engine, text_length) VALUES (?1, ?2, ?3, ?4, ?5)",+ )+ .bind(id)+ .bind(text)+ .bind(text_json)+ .bind(ocr_engine)+ .bind(text_length)+ .execute(&mut **tx.conn())+ .await?;+ }+tx.commit().await?;- debug!("insert_snapshot_frame: id={}, trigger={:?}", id, capture_trigger);+ debug!("insert_snapshot_frame: id={}, trigger={:?}, has_ocr={}", id, capture_trigger, ocr_data.is_some());Ok(id)}diff --git a/crates/screenpipe-server/src/paired_capture.rs b/crates/screenpipe-server/src/paired_capture.rsindex 476b3eed1..a13385f8f 100644--- a/crates/screenpipe-server/src/paired_capture.rs+++ b/crates/screenpipe-server/src/paired_capture.rs@@ -82,7 +82,29 @@ pub async fn paired_capture(ctx.capture_trigger);- // Extract data from tree snapshot, with OCR fallback when accessibility text is empty+ // --- Run OCR to get text positions with bounding boxes (for TextOverlay) ---+ // Always run OCR regardless of accessibility data so the timeline has+ // clickable text blocks that users can hover/click to copy.+ let image_for_ocr = ctx.image.clone();+ let ocr_result = tokio::task::spawn_blocking(move || {+ #[cfg(target_os = "macos")]+ {+ let (text, json, confidence) =+ screenpipe_vision::perform_ocr_apple(&image_for_ocr, &[]);+ (text, json, confidence)+ }+ #[cfg(not(target_os = "macos"))]+ {+ let _ = image_for_ocr;+ (String::new(), "[]".to_string(), None::<f64>)+ }+ })+ .await+ .unwrap_or_else(|_| (String::new(), "[]".to_string(), None));++ let (ocr_text, ocr_text_json, _ocr_confidence) = ocr_result;++ // --- Extract data from tree snapshot, fall back to OCR text ---#[cfg(feature = "ui-events")]let (accessibility_text, tree_json, content_hash, simhash) = match tree_snapshot {Some(snap) if !snap.text_content.is_empty() => {@@ -96,28 +118,10 @@ pub async fn paired_capture(}_ => {// OCR fallback: accessibility returned no text (games, terminals, bad a11y apps).- // Use platform-native OCR on the screenshot (fast: ~50-200ms on macOS).- let image = ctx.image.clone();- let ocr_text = tokio::task::spawn_blocking(move || {- #[cfg(target_os = "macos")]- {- let (text, _json, _confidence) =- screenpipe_vision::perform_ocr_apple(&image, &[]);- text- }- #[cfg(not(target_os = "macos"))]- {- let _ = image;- String::new()- }- })- .await- .unwrap_or_default();-if ocr_text.is_empty() {(None, None, None, None)} else {- (Some(ocr_text), None, None, None)+ (Some(ocr_text.clone()), None, None, None)}}};@@ -128,7 +132,11 @@ pub async fn paired_capture(Option<String>,Option<i64>,Option<i64>,- ) = (None, None, None, None);+ ) = if ocr_text.is_empty() {+ (None, None, None, None)+ } else {+ (Some(ocr_text.clone()), None, None, None)+ };// Determine text source: "accessibility" when tree nodes were available, "ocr" for fallbacklet (final_text, text_source) = if let Some(ref text) = accessibility_text {@@ -144,10 +152,18 @@ pub async fn paired_capture((None, None)};- // Insert snapshot frame into DB+ // Insert snapshot frame + OCR text positions in a single transaction.+ // Combining both writes avoids opening two separate transactions per capture,+ // which halves pool pressure during high-frequency event-driven captures.+ let ocr_data = if !ocr_text.is_empty() {+ Some((ocr_text.as_str(), ocr_text_json.as_str(), "AppleNative"))+ } else {+ None+ };+let frame_id = ctx.db- .insert_snapshot_frame(+ .insert_snapshot_frame_with_ocr(ctx.device_name,ctx.captured_at,&snapshot_path_str,@@ -161,6 +177,7 @@ pub async fn paired_capture(tree_json.as_deref(),content_hash,simhash,+ ocr_data,).await?;