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

feat: instant VisionKit Live Text with LRU cache + prefetch, remove pipe semaphore, bump pi agent

Louis Beaumont7800b338d166
diff --git a/apps/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsx b/apps/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsx
index 6d19bd3b5..f8675d6d1 100644
--- a/apps/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsx
+++ b/apps/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsx
@@ -277,6 +277,7 @@ export const CurrentFrameTimeline: FC<CurrentFrameTimelineProps> = ({
windowLabel: liveTextWindowLabel,
navBarRef,
guardRefs,
+ adjacentFrames,
});
if (!frameId) {
diff --git a/apps/screenpipe-app-tauri/components/rewind/hooks/use-live-text.ts b/apps/screenpipe-app-tauri/components/rewind/hooks/use-live-text.ts
index 5e9ba2309..e8857c73e 100644
--- a/apps/screenpipe-app-tauri/components/rewind/hooks/use-live-text.ts
+++ b/apps/screenpipe-app-tauri/components/rewind/hooks/use-live-text.ts
@@ -23,6 +23,8 @@ export function useLiveText(opts: {
/** Named guard refs — each entry becomes a transparent click guard above the
* Live Text overlay, keyed by name (e.g. "filters", "scrubber"). */
guardRefs?: Record<string, React.RefObject<HTMLDivElement | null>>;
+ /** Adjacent frames for prefetching VisionKit analysis */
+ adjacentFrames?: Array<{ devices?: Array<{ frame_id?: string; metadata?: { file_path?: string } }> } | null>;
}) {
const {
debouncedFrame,
@@ -36,6 +38,7 @@ export function useLiveText(opts: {
containerRef,
navBarRef,
guardRefs,
+ adjacentFrames,
} = opts;
// Native macOS Live Text overlay (VisionKit ImageAnalysisOverlayView)
@@ -103,9 +106,9 @@ export function useLiveText(opts: {
// Position is managed exclusively by livetext_update_position.
// The analyze call only sets the analysis + shows the overlay.
- // Debounce: 150ms — short enough to feel responsive, long enough to skip
- // intermediate frames during fast scroll. Generation counter in Swift
- // handles cancellation of stale in-flight requests.
+ // Debounce: 50ms — short enough to feel near-instant, long enough to skip
+ // rapid arrow key presses. The 80ms frame-loading debounce already handles
+ // fast scrolling; generation counter in Swift cancels stale requests.
let cancelled = false;
const timer = setTimeout(() => {
if (cancelled) return;
@@ -137,10 +140,41 @@ export function useLiveText(opts: {
}
console.warn("live text analyze failed:", e);
});
- }, 150);
+ }, 50);
return () => { cancelled = true; clearTimeout(timer); };
}, [nativeLiveTextActive, debouncedFrame?.frameId, isSnapshotFrame]);
+ // Prefetch VisionKit analysis for adjacent frames so scrolling is instant.
+ // Fire-and-forget: Swift caches results in an LRU for future hits.
+ useEffect(() => {
+ if (!nativeLiveTextActive || !adjacentFrames?.length) return;
+
+ const paths: string[] = [];
+ const seen = new Set<string>();
+ if (debouncedFrame?.filePath) seen.add(debouncedFrame.filePath);
+
+ for (const frame of adjacentFrames) {
+ const dev = frame?.devices?.[0];
+ if (!dev?.frame_id) continue;
+ const filePath = dev.metadata?.file_path;
+ const lower = filePath?.toLowerCase() ?? "";
+ const isSnapshot = lower.endsWith(".jpg") || lower.endsWith(".jpeg") || lower.endsWith(".png");
+
+ // Use local file for snapshots, HTTP for video chunks
+ const imagePath = isSnapshot && filePath
+ ? filePath
+ : `http://localhost:3030/frames/${dev.frame_id}`;
+
+ if (seen.has(imagePath)) continue;
+ seen.add(imagePath);
+ paths.push(imagePath);
+ }
+
+ if (paths.length > 0) {
+ invoke("livetext_prefetch", { paths }).catch(() => {});
+ }
+ }, [nativeLiveTextActive, debouncedFrame?.frameId, adjacentFrames]);
+
// Update overlay position on resize or when renderedImageInfo first becomes available
useEffect(() => {
if (!nativeLiveTextActive || !renderedImageInfo) return;
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
index 92055be54..69b5c3520 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -9329,7 +9329,7 @@ dependencies = [
[[package]]
name = "screenpipe-app"
-version = "2.2.123"
+version = "2.2.125"
dependencies = [
"anyhow",
"arboard",
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/livetext.rs b/apps/screenpipe-app-tauri/src-tauri/src/livetext.rs
index 6ab8481c2..b22b9c099 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/livetext.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/livetext.rs
@@ -171,6 +171,28 @@ pub async fn livetext_analyze(
}
}
+/// Prefetch VisionKit analysis for adjacent frames in the background.
+/// Fire-and-forget — results are cached in Swift for instant hits later.
+#[tauri::command]
+pub async fn livetext_prefetch(paths: Vec<String>) -> Result<(), String> {
+ #[cfg(target_os = "macos")]
+ {
+ let json = serde_json::to_string(&paths).map_err(|e| format!("json error: {}", e))?;
+ let json_c = CString::new(json).map_err(|e| format!("invalid json: {}", e))?;
+ // Fire-and-forget: lt_prefetch dispatches work to a background queue
+ // and returns immediately. We don't need to spawn a thread here.
+ crate::window_api::with_autorelease_pool(|| unsafe {
+ livetext_ffi::lt_prefetch(json_c.as_ptr());
+ });
+ return Ok(());
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ let _ = paths;
+ Ok(())
+ }
+}
+
#[tauri::command]
pub async fn livetext_update_position(x: f64, y: f64, w: f64, h: f64) -> Result<(), String> {
#[cfg(target_os = "macos")]
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/livetext_ffi.rs b/apps/screenpipe-app-tauri/src-tauri/src/livetext_ffi.rs
index cbc707b41..33fd532e5 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/livetext_ffi.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/livetext_ffi.rs
@@ -20,6 +20,8 @@ extern "C" {
out_error: *mut *mut c_char,
) -> i32;
+ pub fn lt_prefetch(paths_json: *const c_char) -> i32;
+
pub fn lt_update_position(x: f64, y: f64, w: f64, h: f64) -> i32;
pub fn lt_highlight_ranges(search_terms_json: *const c_char) -> i32;
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index 68a89e2f4..0ad57d87c 100755
--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -1655,6 +1655,7 @@ async fn main() {
livetext::livetext_is_available,
livetext::livetext_init,
livetext::livetext_analyze,
+ livetext::livetext_prefetch,
livetext::livetext_update_position,
livetext::livetext_highlight,
livetext::livetext_clear_highlights,
diff --git a/apps/screenpipe-app-tauri/src-tauri/swift/livetext_bridge.swift b/apps/screenpipe-app-tauri/src-tauri/swift/livetext_bridge.swift
index 954dd6bf3..c84ea124e 100644
--- a/apps/screenpipe-app-tauri/src-tauri/swift/livetext_bridge.swift
+++ b/apps/screenpipe-app-tauri/src-tauri/swift/livetext_bridge.swift
@@ -67,6 +67,38 @@ private class LiveTextManager {
/// from intercepting clicks on UI controls (nav bar, filters, scrubber, etc.).
var guardViews: [String: ClickGuardView] = [:]
+ // MARK: - Analysis LRU Cache
+ /// Caches ImageAnalysis objects keyed by image path so revisiting frames
+ /// and prefetched adjacent frames are instant (no re-analysis needed).
+ private let cacheMaxSize = 30
+ private var cacheOrder: [String] = [] // oldest first
+ private var cacheMap: [String: ImageAnalysis] = [:]
+ private let cacheLock = NSLock()
+
+ func getCachedAnalysis(_ key: String) -> ImageAnalysis? {
+ cacheLock.lock()
+ defer { cacheLock.unlock() }
+ guard let analysis = cacheMap[key] else { return nil }
+ // Move to end (most recently used)
+ cacheOrder.removeAll { $0 == key }
+ cacheOrder.append(key)
+ return analysis
+ }
+
+ func setCachedAnalysis(_ key: String, _ analysis: ImageAnalysis) {
+ cacheLock.lock()
+ defer { cacheLock.unlock() }
+ if cacheMap[key] != nil {
+ cacheOrder.removeAll { $0 == key }
+ } else if cacheOrder.count >= cacheMaxSize {
+ // Evict oldest
+ let oldest = cacheOrder.removeFirst()
+ cacheMap.removeValue(forKey: oldest)
+ }
+ cacheMap[key] = analysis
+ cacheOrder.append(key)
+ }
+
/// Reusable URLSession for fetching frame images (avoid per-call session alloc).
lazy var urlSession: URLSession = {
let config = URLSessionConfiguration.ephemeral
@@ -85,6 +117,48 @@ private class LiveTextManager {
analyzer = a
return a
}
+
+ /// Load an image from a local path or HTTP URL. Returns nil on failure.
+ func loadImage(_ pathStr: String) -> NSImage? {
+ var result: NSImage?
+ autoreleasepool {
+ if pathStr.hasPrefix("http://") || pathStr.hasPrefix("https://") {
+ if let url = URL(string: pathStr) {
+ let sem = DispatchSemaphore(value: 0)
+ var fetchedData: Data?
+ urlSession.dataTask(with: url) { data, _, _ in
+ fetchedData = data
+ sem.signal()
+ }.resume()
+ sem.wait()
+ if let data = fetchedData, !data.isEmpty {
+ result = NSImage(data: data)
+ }
+ }
+ } else {
+ result = NSImage(contentsOfFile: pathStr)
+ }
+ }
+ return result
+ }
+
+ /// Run VisionKit analysis on an image. Returns the analysis or nil.
+ func analyzeImage(_ image: NSImage) -> ImageAnalysis? {
+ let analyzer = ensureAnalyzer()
+ let semaphore = DispatchSemaphore(value: 0)
+ var analysisResult: ImageAnalysis?
+ let config = ImageAnalyzer.Configuration([.text, .machineReadableCode])
+
+ Task.detached { [image] in
+ do {
+ let analysis = try await analyzer.analyze(image, orientation: .up, configuration: config)
+ analysisResult = analysis
+ } catch {}
+ semaphore.signal()
+ }
+ semaphore.wait()
+ return analysisResult
+ }
}
#endif
@@ -175,92 +249,41 @@ public func ltAnalyzeImage(
}
let pathStr = String(cString: path)
let mgr = LiveTextManager.shared
- guard let overlay = mgr.overlayView else {
+ guard mgr.overlayView != nil else {
outError.pointee = makeCString("overlay not initialized, call lt_init first")
return -2
}
- guard let contentView = mgr.hostContentView else {
+ guard mgr.hostContentView != nil else {
outError.pointee = makeCString("no host content view")
return -3
}
- // Load image from path or URL — use autorelease pool to ensure
- // transient NSImage/CGImage/Data objects are freed promptly.
- var nsImage: NSImage?
- var loadError: String?
- autoreleasepool {
- if pathStr.hasPrefix("http://") || pathStr.hasPrefix("https://") {
- if let url = URL(string: pathStr) {
- let sem = DispatchSemaphore(value: 0)
- var fetchedData: Data?
- var fetchError: Error?
- mgr.urlSession.dataTask(with: url) { data, response, error in
- fetchedData = data
- fetchError = error
- sem.signal()
- }.resume()
- sem.wait()
-
- if let err = fetchError {
- loadError = "fetch error: \(err.localizedDescription)"
- } else if let data = fetchedData, !data.isEmpty {
- nsImage = NSImage(data: data)
- if nsImage == nil { loadError = "NSImage init failed (\(data.count) bytes)" }
- } else {
- loadError = "empty response"
- }
- } else {
- loadError = "invalid URL"
- }
- } else {
- nsImage = NSImage(contentsOfFile: pathStr)
- if nsImage == nil { loadError = "file not found" }
- }
- }
- guard let image = nsImage, image.cgImage(forProposedRect: nil, context: nil, hints: nil) != nil else {
- outError.pointee = makeCString("failed to load image: \(pathStr) (\(loadError ?? "unknown"))")
- return -4
+ // Check analysis cache first — revisited or prefetched frames are instant
+ if let cached = mgr.getCachedAnalysis(pathStr) {
+ mgr.currentAnalysis = cached
+ mgr.pendingAnalysis = cached
+ outText.pointee = makeCString(cached.transcript)
+ return 0
}
- // Run analysis (async bridged with semaphore).
- // Must use Task.detached so the task runs on the cooperative thread pool
- // rather than inheriting the caller's (non-Swift) execution context.
- let analyzer = mgr.ensureAnalyzer()
- let semaphore = DispatchSemaphore(value: 0)
- var analysisResult: ImageAnalysis?
- var analysisError: Error?
-
- let analyzerConfig = ImageAnalyzer.Configuration([.text, .machineReadableCode])
-
- Task.detached { [image] in
- do {
- let analysis = try await analyzer.analyze(image, orientation: .up, configuration: analyzerConfig)
- analysisResult = analysis
- } catch {
- analysisError = error
- }
- semaphore.signal()
+ // Load and analyze
+ guard let image = mgr.loadImage(pathStr),
+ image.cgImage(forProposedRect: nil, context: nil, hints: nil) != nil else {
+ outError.pointee = makeCString("failed to load image: \(pathStr)")
+ return -4
}
- semaphore.wait()
- // Release image immediately — analysis holds its own data
- nsImage = nil
- if let err = analysisError {
- outError.pointee = makeCString("analysis failed: \(err.localizedDescription)")
- return -5
- }
- guard let analysis = analysisResult else {
+ guard let analysis = mgr.analyzeImage(image) else {
outError.pointee = makeCString("analysis returned nil")
return -5
}
+ mgr.setCachedAnalysis(pathStr, analysis)
mgr.currentAnalysis = analysis
// Don't apply to overlay yet — store as pending. The analysis will be
// applied in lt_update_position once the correct frame geometry is set.
- // This ensures VisionKit computes hit regions against the right rect.
mgr.pendingAnalysis = analysis
- // Return recognized text from the analysis transcript (macOS 13+)
outText.pointee = makeCString(analysis.transcript)
return 0
}
@@ -270,6 +293,46 @@ public func ltAnalyzeImage(
return -1
}
+// MARK: - Prefetch (background analysis for adjacent frames)
+
+/// Analyze images in the background and cache results. Fire-and-forget.
+/// Skips images that are already cached. Does NOT set pendingAnalysis
+/// or update the overlay — only populates the cache for future instant hits.
+@_cdecl("lt_prefetch")
+public func ltPrefetch(_ pathsJson: UnsafePointer<CChar>?) -> Int32 {
+ #if canImport(VisionKit)
+ if #available(macOS 13.0, *) {
+ guard let pathsJson = pathsJson else { return -1 }
+ let jsonStr = String(cString: pathsJson)
+ guard let data = jsonStr.data(using: .utf8),
+ let paths = try? JSONSerialization.jsonObject(with: data) as? [String],
+ !paths.isEmpty else { return -2 }
+
+ let mgr = LiveTextManager.shared
+
+ // Fire-and-forget on a background queue
+ DispatchQueue.global(qos: .utility).async {
+ for pathStr in paths {
+ // Skip already cached
+ if mgr.getCachedAnalysis(pathStr) != nil { continue }
+
+ autoreleasepool {
+ guard let image = mgr.loadImage(pathStr),
+ image.cgImage(forProposedRect: nil, context: nil, hints: nil) != nil else {
+ return // skip this image
+ }
+ if let analysis = mgr.analyzeImage(image) {
+ mgr.setCachedAnalysis(pathStr, analysis)
+ }
+ }
+ }
+ }
+ return 0
+ }
+ #endif
+ return -1
+}
+
// MARK: - Update Position
@_cdecl("lt_update_position")
diff --git a/crates/screenpipe-core/src/agents/pi.rs b/crates/screenpipe-core/src/agents/pi.rs
index dc5b5ec88..94bc4caa8 100644
--- a/crates/screenpipe-core/src/agents/pi.rs
+++ b/crates/screenpipe-core/src/agents/pi.rs
@@ -13,7 +13,7 @@ use serde_json::json;
use std::path::{Path, PathBuf};
use tracing::{debug, error, info, warn};
-const PI_PACKAGE: &str = "@mariozechner/[email protected]";
+const PI_PACKAGE: &str = "@mariozechner/[email protected]";
pub const SCREENPIPE_API_URL: &str = "https://api.screenpi.pe/v1";
/// Returns the screenpipe cloud models array as a serde_json::Value.
diff --git a/crates/screenpipe-core/src/pipes/mod.rs b/crates/screenpipe-core/src/pipes/mod.rs
index 94513473b..28be6f21d 100644
--- a/crates/screenpipe-core/src/pipes/mod.rs
+++ b/crates/screenpipe-core/src/pipes/mod.rs
@@ -26,7 +26,7 @@ use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::Arc;
use std::time::Instant;
-use tokio::sync::{Mutex, Semaphore};
+use tokio::sync::Mutex;
use tracing::{debug, error, info, warn};
// ---------------------------------------------------------------------------
@@ -517,8 +517,6 @@ pub struct PipeManager {
running: Arc<Mutex<HashMap<String, ExecutionHandle>>>,
/// Currently running execution IDs (for stop API).
running_execution_ids: Arc<Mutex<HashMap<String, i64>>>,
- /// Global concurrency limit — only one pipe runs at a time.
- semaphore: Arc<Semaphore>,
/// Shutdown signal for the scheduler.
shutdown_tx: Option<tokio::sync::watch::Sender<bool>>,
/// Optional callback fired after each scheduled pipe run.
@@ -551,7 +549,6 @@ impl PipeManager {
logs: Arc::new(Mutex::new(HashMap::new())),
running: Arc::new(Mutex::new(HashMap::new())),
running_execution_ids: Arc::new(Mutex::new(HashMap::new())),
- semaphore: Arc::new(Semaphore::new(1)),
shutdown_tx: None,
on_run_complete: None,
on_output_line: None,
@@ -1040,7 +1037,6 @@ impl PipeManager {
let running_ref = self.running.clone();
let running_exec_ids_ref = self.running_execution_ids.clone();
let logs_ref = self.logs.clone();
- let semaphore = self.semaphore.clone();
let store_ref = self.store.clone();
let on_complete = self.on_run_complete.clone();
let on_output = self.on_output_line.clone();
@@ -1050,7 +1046,6 @@ impl PipeManager {
// Spawn the actual execution in a background task
tokio::spawn(async move {
- let _permit = semaphore.acquire().await;
let started_at = Utc::now();
let timeout_duration = std::time::Duration::from_secs(DEFAULT_TIMEOUT_SECS);
@@ -1365,9 +1360,6 @@ impl PipeManager {
// Create a channel so the executor can report PID immediately
let (pid_tx, pid_rx) = tokio::sync::oneshot::channel::<u32>();
- // Acquire semaphore (one pipe at a time)
- let _permit = self.semaphore.acquire().await?;
-
// Mark as running in DB
if let (Some(ref store), Some(id)) = (&self.store, exec_id) {
let _ = store.set_execution_running(id, None).await;
@@ -1880,7 +1872,6 @@ impl PipeManager {
let logs = self.logs.clone();
let running = self.running.clone();
let running_execution_ids = self.running_execution_ids.clone();
- let semaphore = self.semaphore.clone();
let executors = self.executors.clone();
let pipes_dir = self.pipes_dir.clone();
let on_run_complete = self.on_run_complete.clone();
@@ -2045,7 +2036,6 @@ impl PipeManager {
let logs_ref = logs.clone();
let running_ref = running.clone();
let running_exec_ids_ref = running_execution_ids.clone();
- let sem = semaphore.clone();
let pipes_dir_for_log = pipes_dir.clone();
let on_complete = on_run_complete.clone();
let on_output = on_output_line.clone();
@@ -2078,8 +2068,6 @@ impl PipeManager {
None
};
- let _permit = sem.acquire().await;
-
// Mark running in DB
if let (Some(ref store), Some(id)) = (&store_ref, exec_id) {
let _ = store.set_execution_running(id, None).await;