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
feat(sdk): honor ignored/included windows + ignored URLs filter
Louis Beaumont9961d1907ca9
diff --git a/ee/sdk/README.md b/ee/sdk/README.mdindex b43e74a47..170c74418 100644--- a/ee/sdk/README.md+++ b/ee/sdk/README.md@@ -48,7 +48,13 @@ if (!permissions.screen) {throw new Error("Screen Recording permission is required");}-const recorder = new Recorder({ output: "/tmp/session.mp4" });+const recorder = new Recorder({+ output: "/tmp/session.mp4",+ // Optional privacy filters — recording pauses (hard cut in the MP4)+ // while a matching window/URL is focused.+ ignoredWindows: ["1password", "private"],+ ignoredUrls: ["wellsfargo.com", "chase"],+});await recorder.start();// ... user does stuff ...@@ -64,6 +70,22 @@ await recorder.stop();- `options.monitorId` (number, optional): display id; defaults to the primary display.- `options.microphone` (boolean, optional): accepted for forward compatibility.- `options.systemAudio` (boolean, optional): accepted for forward compatibility.+- `options.ignoredWindows` (string[], optional): substring patterns matched+ case-insensitively against the focused app name and window title. While a+ matching window is in focus, the recorder skips writing frames — the MP4+ contains a hard cut over the filtered period. Mirrors the engine's+ `--ignored-windows` CLI flag.+- `options.includedWindows` (string[], optional): substring whitelist. If+ non-empty, frames are written ONLY while the focused app name or window+ title matches at least one pattern. Mirrors `--included-windows`.+- `options.ignoredUrls` (string[], optional): URL patterns to skip+ (case-insensitive, domain-aware match — `chase` matches `chase.com` and+ `online.chase.com` but not `purchase.com`). When the focused browser is on+ a matching URL, the recorder skips writing frames. Mirrors `--ignored-urls`.++Filtering uses the macOS Accessibility API; without that permission the+filter fails open (records everything). Without any filter list set, the+recorder stays on the zero-overhead fast path — no a11y polling is done.### Methodsdiff --git a/ee/sdk/Sources/Screenpipe/ScreenpipeModels.swift b/ee/sdk/Sources/Screenpipe/ScreenpipeModels.swiftindex 00756c51e..a01e0fa1c 100644--- a/ee/sdk/Sources/Screenpipe/ScreenpipeModels.swift+++ b/ee/sdk/Sources/Screenpipe/ScreenpipeModels.swift@@ -178,6 +178,9 @@ public struct ScreenpipeStartOptions: Codable, Equatable, Sendable {public var monitorId: Int?public var microphone: Bool?public var systemAudio: Bool?+ public var ignoredWindows: [String]?+ public var includedWindows: [String]?+ public var ignoredUrls: [String]?public init(output: String? = nil,@@ -186,7 +189,10 @@ public struct ScreenpipeStartOptions: Codable, Equatable, Sendable {filenamePrefix: String? = nil,monitorId: Int? = nil,microphone: Bool? = nil,- systemAudio: Bool? = nil+ systemAudio: Bool? = nil,+ ignoredWindows: [String]? = nil,+ includedWindows: [String]? = nil,+ ignoredUrls: [String]? = nil) {self.output = outputself.outputDir = outputDir@@ -195,6 +201,9 @@ public struct ScreenpipeStartOptions: Codable, Equatable, Sendable {self.monitorId = monitorIdself.microphone = microphoneself.systemAudio = systemAudio+ self.ignoredWindows = ignoredWindows+ self.includedWindows = includedWindows+ self.ignoredUrls = ignoredUrls}public init(@@ -203,7 +212,10 @@ public struct ScreenpipeStartOptions: Codable, Equatable, Sendable {filenamePrefix: String? = nil,monitorId: Int? = nil,microphone: Bool? = nil,- systemAudio: Bool? = nil+ systemAudio: Bool? = nil,+ ignoredWindows: [String]? = nil,+ includedWindows: [String]? = nil,+ ignoredUrls: [String]? = nil) {self.init(output: outputURL.path,@@ -211,7 +223,10 @@ public struct ScreenpipeStartOptions: Codable, Equatable, Sendable {filenamePrefix: filenamePrefix,monitorId: monitorId,microphone: microphone,- systemAudio: systemAudio+ systemAudio: systemAudio,+ ignoredWindows: ignoredWindows,+ includedWindows: includedWindows,+ ignoredUrls: ignoredUrls)}@@ -221,7 +236,10 @@ public struct ScreenpipeStartOptions: Codable, Equatable, Sendable {filenamePrefix: String? = nil,monitorId: Int? = nil,microphone: Bool? = nil,- systemAudio: Bool? = nil+ systemAudio: Bool? = nil,+ ignoredWindows: [String]? = nil,+ includedWindows: [String]? = nil,+ ignoredUrls: [String]? = nil) {self.init(outputDir: outputDirectoryURL.path,@@ -229,7 +247,10 @@ public struct ScreenpipeStartOptions: Codable, Equatable, Sendable {filenamePrefix: filenamePrefix,monitorId: monitorId,microphone: microphone,- systemAudio: systemAudio+ systemAudio: systemAudio,+ ignoredWindows: ignoredWindows,+ includedWindows: includedWindows,+ ignoredUrls: ignoredUrls)}diff --git a/ee/sdk/__test__/options.test.mjs b/ee/sdk/__test__/options.test.mjsindex d0c015ef4..f1303c3d2 100644--- a/ee/sdk/__test__/options.test.mjs+++ b/ee/sdk/__test__/options.test.mjs@@ -36,6 +36,29 @@ test("accepts undefined microphone + systemAudio (all optional)", () => {assert.ok(r);});+test("accepts ignoredWindows / includedWindows / ignoredUrls filter lists", () => {+ // Construction only — verifies the filter fields are accepted by the+ // native binding. The actual pause behavior is exercised in+ // recording.test.mjs against a focused app the host controls.+ const r = new Recorder({+ output: tempMp4("filters"),+ ignoredWindows: ["1password", "private"],+ includedWindows: [],+ ignoredUrls: ["wellsfargo.com", "chase"],+ });+ assert.ok(r);+});++test("accepts empty filter arrays (zero-overhead fast path)", () => {+ const r = new Recorder({+ output: tempMp4("filters-empty"),+ ignoredWindows: [],+ includedWindows: [],+ ignoredUrls: [],+ });+ assert.ok(r);+});+test("start() with a non-existent monitor id reports a useful error", async (t) => {if (!hasFfmpeg()) { t.skip("ffmpeg not on PATH"); return; }const r = new Recorder({ output: tempMp4("bad-mon"), monitorId: 999_999 });diff --git a/ee/sdk/index.d.ts b/ee/sdk/index.d.tsindex 23b26eee2..f834c1322 100644--- a/ee/sdk/index.d.ts+++ b/ee/sdk/index.d.ts@@ -13,6 +13,25 @@ export interface RecorderOptions {microphone?: boolean/** Reserved for future system-audio muxing. Accepted today but not recorded. */systemAudio?: boolean+ /**+ * Substring patterns matched against the focused app name and window title+ * (case-insensitive). While a matching window is in focus, the recorder+ * skips writing frames — the MP4 contains a hard cut over the filtered+ * period. Mirrors the engine's `--ignored-windows` CLI flag.+ */+ ignoredWindows?: Array<string>+ /**+ * Substring whitelist. If non-empty, frames are written ONLY while the+ * focused app name or window title matches at least one pattern.+ * Mirrors the engine's `--included-windows` CLI flag.+ */+ includedWindows?: Array<string>+ /**+ * URL patterns to skip (case-insensitive, domain-aware matching).+ * When the focused window is a browser navigated to a matching URL,+ * the recorder skips writing frames. Mirrors `--ignored-urls`.+ */+ ignoredUrls?: Array<string>}/** Permission status returned by `requestPermissions`. */export interface PermissionStatus {diff --git a/ee/sdk/src/lib.rs b/ee/sdk/src/lib.rsindex 92c616e88..4e28c72f2 100644--- a/ee/sdk/src/lib.rs+++ b/ee/sdk/src/lib.rs@@ -30,6 +30,19 @@ pub struct RecorderOptions {pub microphone: Option<bool>,/// Reserved for future system-audio muxing. Accepted today but not recorded.pub system_audio: Option<bool>,+ /// Substring patterns matched against the focused app name and window title+ /// (case-insensitive). While a matching window is in focus, the recorder+ /// skips writing frames — the MP4 contains a hard cut over the filtered+ /// period. Mirrors the engine's `--ignored-windows` CLI flag.+ pub ignored_windows: Option<Vec<String>>,+ /// Substring whitelist. If non-empty, frames are written ONLY while the+ /// focused app name or window title matches at least one pattern.+ /// Mirrors the engine's `--included-windows` CLI flag.+ pub included_windows: Option<Vec<String>>,+ /// URL patterns to skip (case-insensitive, domain-aware matching).+ /// When the focused window is a browser navigated to a matching URL,+ /// the recorder skips writing frames. Mirrors `--ignored-urls`.+ pub ignored_urls: Option<Vec<String>>,}/// Permission status returned by `requestPermissions`.diff --git a/ee/sdk/src/platform/recorder.rs b/ee/sdk/src/platform/recorder.rsindex c59d27ef7..ebbc90b08 100644--- a/ee/sdk/src/platform/recorder.rs+++ b/ee/sdk/src/platform/recorder.rs@@ -16,7 +16,9 @@use crate::{PermissionStatus, RecorderOptions};use anyhow::{anyhow, Context, Result};+use screenpipe_a11y::tree::{create_tree_walker, TreeWalkResult, TreeWalkerConfig};use screenpipe_core::video::{finish_ffmpeg_process, start_ffmpeg_process, write_frame_to_ffmpeg};+use screenpipe_screen::capture_screenshot_by_window::WindowFilters;use screenpipe_screen::monitor::{list_monitors_detailed, SafeMonitor};use std::io::Cursor;use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};@@ -29,21 +31,41 @@ use tracing::{debug, info, warn};const TARGET_FPS: f64 = 15.0;const VIDEO_QUALITY: &str = "balanced";+/// How often the focus-watcher task re-evaluates the filter against the+/// currently focused window. 1 Hz is the slowest cadence that still feels+/// "responsive" when a user alt-tabs into a banking site — and walking the+/// AX tree more often than that would compete with the capture thread.+const FILTER_POLL_INTERVAL: Duration = Duration::from_millis(1000);pub struct RecorderImpl {options: RecorderOptions,+ filter: Option<Arc<FilterState>>,stop_flag: Arc<AtomicBool>,frames_written: Arc<AtomicU64>,handle: Option<JoinHandle<Result<()>>>,+ filter_handle: Option<JoinHandle<()>>,+}++/// Cached state shared between the focus-watcher task and the capture loop.+/// `paused` is the only thing the capture loop reads per frame — keep it on+/// a hot, lock-free path.+struct FilterState {+ filters: WindowFilters,+ ignored_windows: Vec<String>,+ included_windows: Vec<String>,+ paused: AtomicBool,}impl RecorderImpl {pub fn new(options: RecorderOptions) -> Result<Self> {+ let filter = build_filter_state(&options);Ok(Self {options,+ filter,stop_flag: Arc::new(AtomicBool::new(false)),frames_written: Arc::new(AtomicU64::new(0)),handle: None,+ filter_handle: None,})}@@ -83,9 +105,10 @@ impl RecorderImpl {let stop_flag = Arc::clone(&self.stop_flag);let frames_written = Arc::clone(&self.frames_written);let stdin_loop = Arc::clone(&stdin_arc);+ let filter_loop = self.filter.clone();let handle = tokio::spawn(async move {- capture_loop(monitor, stdin_loop, stop_flag, frames_written).await;+ capture_loop(monitor, stdin_loop, stop_flag, frames_written, filter_loop).await;// Hand ownership of the stdin back to finish_ffmpeg_process so// it can drop+close it before waiting for the child.let stdin_opt = Arc::try_unwrap(stdin_arc).ok().and_then(|m| m.into_inner());@@ -94,6 +117,15 @@ impl RecorderImpl {});self.handle = Some(handle);++ // Spawn the focus-watcher task only when at least one filter is set.+ // Otherwise the recorder stays on the original fast path with zero+ // a11y overhead.+ if let Some(filter) = self.filter.clone() {+ let stop_flag = Arc::clone(&self.stop_flag);+ self.filter_handle = Some(tokio::spawn(focus_watch_loop(filter, stop_flag)));+ }+Ok(())}@@ -109,6 +141,16 @@ impl RecorderImpl {Err(e) => return Err(anyhow!("capture task panicked: {e}")),}}+ if let Some(h) = self.filter_handle.take() {+ // The focus watcher exits on stop_flag — joining is cheap.+ let _ = h.await;+ }+ // Reset the paused flag so a subsequent `start()` on the same+ // recorder begins from a clean "record" state until the watcher+ // catches up.+ if let Some(ref f) = self.filter {+ f.paused.store(false, Ordering::SeqCst);+ }info!("screenpipe-sdk: stopped. {} frames written to {}",self.frames_written.load(Ordering::SeqCst),@@ -181,6 +223,7 @@ async fn capture_loop(stdin: Arc<Mutex<Option<ChildStdin>>>,stop_flag: Arc<AtomicBool>,frames_written: Arc<AtomicU64>,+ filter: Option<Arc<FilterState>>,) {let frame_interval = Duration::from_millis((1000.0 / TARGET_FPS) as u64);let mut ticker = interval(frame_interval);@@ -191,6 +234,17 @@ async fn capture_loop(while !stop_flag.load(Ordering::Relaxed) {ticker.tick().await;+ // Window/URL filter: when the focus-watcher has flagged the current+ // window as a "skip", drop this tick entirely. Because ffmpeg's+ // image2pipe input is paced by `-r` (TARGET_FPS), a dropped frame+ // is a hard cut in the output — the MP4 never contains the filtered+ // moment, matching the engine's filter semantics.+ if let Some(ref f) = filter {+ if f.paused.load(Ordering::Relaxed) {+ continue;+ }+ }+let t_cap = std::time::Instant::now();// capture_image uses screenpipe-screen's persistent SCK stream// internally (stream_manager), already ar_pool-wrapped.@@ -253,6 +307,82 @@ async fn capture_loop(debug!("screenpipe-sdk: capture loop exiting");}+/// Build the focus-filter state from `RecorderOptions`. Returns `None`+/// when all three filter lists are empty/absent so the recorder stays+/// on the zero-overhead fast path.+fn build_filter_state(options: &RecorderOptions) -> Option<Arc<FilterState>> {+ let ignored = options.ignored_windows.clone().unwrap_or_default();+ let included = options.included_windows.clone().unwrap_or_default();+ let urls = options.ignored_urls.clone().unwrap_or_default();++ if ignored.is_empty() && included.is_empty() && urls.is_empty() {+ return None;+ }++ Some(Arc::new(FilterState {+ filters: WindowFilters::new(&ignored, &included, &urls),+ ignored_windows: ignored,+ included_windows: included,+ paused: AtomicBool::new(false),+ }))+}++/// Background task that re-evaluates the filter against the focused window+/// at `FILTER_POLL_INTERVAL` and flips `paused` accordingly. The tree walker+/// applies `ignored_windows` / `included_windows` itself (short-circuiting+/// the expensive AX walk on a match); URL matching runs on the snapshot we+/// get back for non-ignored windows.+async fn focus_watch_loop(filter: Arc<FilterState>, stop_flag: Arc<AtomicBool>) {+ let mut ticker = interval(FILTER_POLL_INTERVAL);++ while !stop_flag.load(Ordering::Relaxed) {+ ticker.tick().await;++ let filter_clone = Arc::clone(&filter);+ let verdict = tokio::task::spawn_blocking(move || evaluate_focus(&filter_clone)).await;++ match verdict {+ Ok(Some(should_pause)) => {+ filter.paused.store(should_pause, Ordering::Relaxed);+ }+ // None = couldn't determine focused window this tick; keep the+ // previous verdict. A11y permission not granted yet falls here.+ Ok(None) => {}+ Err(e) => {+ debug!("screenpipe-sdk: focus watcher task: {e}");+ }+ }+ }+}++/// Returns `Some(true)` if the current focus matches a configured filter+/// (recording should pause), `Some(false)` if it cleanly does not, and+/// `None` if we couldn't determine — caller keeps the previous verdict.+fn evaluate_focus(filter: &FilterState) -> Option<bool> {+ let mut config = TreeWalkerConfig::default();+ config.ignored_windows = filter.ignored_windows.clone();+ config.included_windows = filter.included_windows.clone();++ let walker = create_tree_walker(config);+ let result = walker.walk_focused_window().ok()?;++ match result {+ TreeWalkResult::Skipped(_) => Some(true),+ TreeWalkResult::Found(snap) => {+ let url = snap.browser_url.as_deref().unwrap_or("");+ // `is_valid` covers ignored/included title+app matching; URL+ // matching is a separate call so we can apply it on the snap+ // even after the walker has cleared the include/ignore lists.+ let url_blocked = !url.is_empty() && filter.filters.is_url_blocked(url);+ let title_blocked = filter+ .filters+ .is_title_suggesting_blocked_url(&snap.window_name);+ Some(url_blocked || title_blocked)+ }+ TreeWalkResult::NotFound => None,+ }+}+pub async fn request_permissions() -> Result<PermissionStatus> {// Calling list_monitors_detailed triggers the macOS Screen Recording// permission prompt on first call and reports current state afterward.diff --git a/ee/sdk/tauri/rust/src/lib.rs b/ee/sdk/tauri/rust/src/lib.rsindex 8dc968fb4..4f8ef639a 100644--- a/ee/sdk/tauri/rust/src/lib.rs+++ b/ee/sdk/tauri/rust/src/lib.rs@@ -272,6 +272,12 @@ pub struct StartOptions {pub monitor_id: Option<u32>,pub microphone: Option<bool>,pub system_audio: Option<bool>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub ignored_windows: Option<Vec<String>>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub included_windows: Option<Vec<String>>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub ignored_urls: Option<Vec<String>>,}#[derive(Debug, Deserialize, Serialize)]