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(owned-browser): tag eval-with-url navigations with their owner (#3934)
Louis Beaumontce756748834c
diff --git a/.github/pr-media/owned-browser-eval-owner.png b/.github/pr-media/owned-browser-eval-owner.pngnew file mode 100644index 000000000..bcc495e14Binary files /dev/null and b/.github/pr-media/owned-browser-eval-owner.png differdiff --git a/apps/screenpipe-app-tauri/e2e/specs/zz-owned-browser-background-nav.spec.ts b/apps/screenpipe-app-tauri/e2e/specs/zz-owned-browser-background-nav.spec.tsindex eb51bcc4f..bf19817ae 100644--- a/apps/screenpipe-app-tauri/e2e/specs/zz-owned-browser-background-nav.spec.ts+++ b/apps/screenpipe-app-tauri/e2e/specs/zz-owned-browser-background-nav.spec.ts@@ -74,10 +74,12 @@ const canDriveOwnedBrowser = process.platform !== "linux";//// The fix tags each navigation with its owner (the chat/session id, or// `pipe:<name>` for a pipe) and the sidebar ignores navigations owned by a chat-// other than the one on screen. This block drives the *real* path a background-// pipe uses (POST /connections/browsers/owned-default/navigate with the-// `x-screenpipe-session` header the agent's curl shim adds) while a chat is on-// screen, and asserts the foreign navigation does NOT reveal the browser.+// other than the one on screen. This block drives BOTH *real* paths a+// background pipe uses while a chat is on screen — POST+// /connections/browsers/owned-default/navigate AND the navigate-and-scrape POST+// /connections/browsers/owned-default/eval with a `url` (both carrying the+// `x-screenpipe-session` header the agent's curl shim adds) — and asserts the+// foreign navigation does NOT reveal the browser.//// We assert on native visibility (`e2e_owned_browser_visible`), not persisted// browserState: a regression reveals the panel, which attaches the native child@@ -216,6 +218,33 @@ async function postNavigateAs(return res.status;}+/** POST the owned-browser eval endpoint with a `url` (navigate-and-scrape) the+ * way a background pipe does — carrying the same `x-screenpipe-session` owner+ * header. This is the second way a pipe drives the owned browser: a single+ * call that navigates then runs JS. Pre-fix the eval path ignored the header+ * and emitted the navigate event with owner=None. Returns the HTTP status. */+async function postEvalWithUrlAs(+ port: number,+ key: string | null,+ url: string,+ owner: string,+): Promise<number> {+ const res = await fetch(+ `http://127.0.0.1:${port}/connections/browsers/owned-default/eval`,+ {+ method: "POST",+ headers: {+ "content-type": "application/json",+ "x-screenpipe-session": owner,+ ...authHeaders(key),+ },+ body: JSON.stringify({ url, code: "return 1" }),+ },+ );+ await res.text().catch(() => ""); // drain so the socket closes cleanly+ return res.status;+}+describe("Owned browser — per-chat navigation ownership", function () {this.timeout(180_000);@@ -274,6 +303,19 @@ describe("Owned browser — per-chat navigation ownership", function () {expect(await invokeOrThrow<boolean>("e2e_owned_browser_visible")).toBe(false,);++ // 6. Same guarantee for the OTHER way a pipe drives the browser: a+ // navigate-and-scrape via POST /eval with a `url`. Pre-fix the eval+ // path ignored the `x-screenpipe-session` header and emitted the+ // navigate event with owner=None, which the sidebar honors in every+ // chat. The event fires before eval waits for the (absent) child+ // webview, so the gate is exercised regardless of the eval's own+ // result — we assert visibility, not the HTTP status.+ await postEvalWithUrlAs(port, key, FOREIGN_URL, FOREIGN_OWNER);+ await browser.pause(t(2_500));+ expect(await invokeOrThrow<boolean>("e2e_owned_browser_visible")).toBe(+ false,+ );},);});diff --git a/apps/screenpipe-app-tauri/lib/__tests__/owned-browser-ownership.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/owned-browser-ownership.test.tsindex 5dac752c6..73210cd47 100644--- a/apps/screenpipe-app-tauri/lib/__tests__/owned-browser-ownership.test.ts+++ b/apps/screenpipe-app-tauri/lib/__tests__/owned-browser-ownership.test.ts@@ -38,11 +38,18 @@ describe("owned-browser ownership", () => {expect(isForeignNavigation(null, "conv-C")).toBe(false);expect(isForeignNavigation(undefined, "conv-C")).toBe(false);expect(isForeignNavigation("", "conv-C")).toBe(false);+ // Untagged is honored even when no chat is bound — that's a fresh+ // chat's own restore/reload, not a foreign pipe.+ expect(isForeignNavigation(null, null)).toBe(false);});- it("does not gate when no chat is bound", () => {- expect(isForeignNavigation("pipe:x", null)).toBe(false);- expect(isForeignNavigation("pipe:x", undefined)).toBe(false);+ it("gates a tagged navigation when no chat is bound (fresh/unsaved chat)", () => {+ // conversationId is null until the first message is saved. A background+ // pipe (or another chat's agent) navigating the shared browser then must+ // NOT pop its page into the empty chat the user is looking at.+ expect(isForeignNavigation("pipe:x", null)).toBe(true);+ expect(isForeignNavigation("pipe:x", undefined)).toBe(true);+ expect(isForeignNavigation("conv-A", "")).toBe(true);});});diff --git a/apps/screenpipe-app-tauri/lib/owned-browser-ownership.ts b/apps/screenpipe-app-tauri/lib/owned-browser-ownership.tsindex 1a180e492..294274611 100644--- a/apps/screenpipe-app-tauri/lib/owned-browser-ownership.ts+++ b/apps/screenpipe-app-tauri/lib/owned-browser-ownership.ts@@ -38,14 +38,24 @@ export function parseNavigatePayload(payload: OwnedBrowserNavigatePayload): {* True when a navigation belongs to a DIFFERENT chat than the one on screen, so* the sidebar must ignore it (no reveal, no persist).*- * - owner null/empty → the sidebar's own restore/reload, always honored.- * - conversationId null/empty → no chat is bound, nothing to scope to (honored).+ * - owner null/empty → the sidebar's own restore/reload, always honored+ * (regardless of whether a chat is bound).* - owner === conversationId → this chat's own agent, honored.- * - otherwise (a different owner) → foreign, ignored.+ * - otherwise (a different owner, INCLUDING when no chat is bound) → foreign,+ * ignored. A null/empty conversationId means a fresh, unsaved chat: a tagged+ * navigation there can only come from a background pipe (`pipe:<name>`) or+ * another chat's agent, never from this surface, so a background pipe must+ * not pop into it. (Previously a null conversationId let any tagged+ * navigation through — the hole this closes.)*/export function isForeignNavigation(owner: string | null | undefined,conversationId: string | null | undefined,): boolean {- return Boolean(owner) && Boolean(conversationId) && owner !== conversationId;+ // The sidebar's own restore/reload is untagged — always honor it.+ if (!owner) return false;+ // A tagged navigation is honored only by the chat that issued it. When no+ // chat is bound (conversationId null/empty), `owner !== conversationId` is+ // true, so the navigation is treated as foreign and dropped.+ return owner !== conversationId;}diff --git a/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rs b/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rsindex 91cdd0c66..6d1e361fc 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rs@@ -505,13 +505,18 @@ async fn show_native_for_background_eval(active: &Webview<Wry>, state: &OwnedBro}}-#[async_trait]-impl OwnedWebviewHandle for TauriOwnedHandle {- async fn eval(+impl TauriOwnedHandle {+ /// Shared body for the `eval` / `eval_with_owner` trait methods. `owner`+ /// tags the navigation when `url` is supplied (the navigate-and-scrape+ /// path) so a background pipe's eval-with-url doesn't reveal its page in an+ /// unrelated chat; it is `None` for the plain `eval` entry point (snapshot,+ /// code-only eval), which never navigates.+ async fn eval_inner(&self,code: &str,url: Option<&str>,timeout: Duration,+ owner: Option<&str>,) -> Result<EvalResult, String> {// Hold the mutex for the entire eval — see eval_lock comment.let _guard = self.eval_lock.lock().await;@@ -523,9 +528,13 @@ impl OwnedWebviewHandle for TauriOwnedHandle {};if let Some(parsed) = &target_url {- // eval-with-url (snapshot) navigations aren't owner-tagged — the- // owner travels with the dedicated navigate path below.- prepare_navigation(&self.app, &self.state, parsed, None).await;+ // eval-with-url is a navigate-and-scrape: tag it with the issuing+ // chat/pipe so the sidebar keeps a background pipe's page out of an+ // unrelated chat, exactly like the dedicated navigate path. `owner`+ // is `None` for the plain `eval` entry point (snapshot, code-only+ // eval), which is fine — those don't pass a url, so this branch and+ // its navigate event don't fire.+ prepare_navigation(&self.app, &self.state, parsed, owner).await;}let active = match self.state.active().await {@@ -680,6 +689,32 @@ impl OwnedWebviewHandle for TauriOwnedHandle {error: parsed.error,})}+}++#[async_trait]+impl OwnedWebviewHandle for TauriOwnedHandle {+ async fn eval(+ &self,+ code: &str,+ url: Option<&str>,+ timeout: Duration,+ ) -> Result<EvalResult, String> {+ // Plain eval / snapshot — never owner-tagged (no navigation event).+ self.eval_inner(code, url, timeout, None).await+ }++ /// Owner-aware eval — the navigate-and-scrape path a background pipe uses+ /// to open a page and read it in one call. `owner` tags the navigation so+ /// the sidebar keeps that page out of an unrelated chat.+ async fn eval_with_owner(+ &self,+ code: &str,+ url: Option<&str>,+ timeout: Duration,+ owner: Option<&str>,+ ) -> Result<EvalResult, String> {+ self.eval_inner(code, url, timeout, owner).await+ }/// Native fire-and-forget navigate. Bypasses the eval round-trip so/// the HTTP caller doesn't sit in a 30s polling loop waiting for adiff --git a/crates/screenpipe-connect/src/connections/browser/mod.rs b/crates/screenpipe-connect/src/connections/browser/mod.rsindex 6d098d6cf..4edee886c 100644--- a/crates/screenpipe-connect/src/connections/browser/mod.rs+++ b/crates/screenpipe-connect/src/connections/browser/mod.rs@@ -73,6 +73,24 @@ pub trait Browser: Send + Sync {timeout: Duration,) -> Result<EvalResult, EvalError>;+ /// Like [`eval`](Self::eval) but tags any navigation the eval triggers+ /// (the owned webview treats a non-`None` `url` as a navigate-and-eval)+ /// with the chat/session that issued it. Same purpose and `owner` formats+ /// as [`navigate_with_owner`](Self::navigate_with_owner): the tag flows to+ /// the embedded owned-browser sidebar so a background pipe's+ /// navigate-then-scrape call doesn't pop its page into an unrelated chat.+ /// Default impl ignores `owner` and behaves exactly like `eval`; only the+ /// owned browser, whose webview is user-visible, overrides it.+ async fn eval_with_owner(+ &self,+ code: &str,+ url: Option<&str>,+ timeout: Duration,+ _owner: Option<&str>,+ ) -> Result<EvalResult, EvalError> {+ self.eval(code, url, timeout).await+ }+/// Navigate the browser to `url`. Fire-and-forget: returns as soon as/// the navigation has been dispatched, NOT when the page has loaded./// Callers that need to wait for content to be ready should follow updiff --git a/crates/screenpipe-connect/src/connections/browser/owned.rs b/crates/screenpipe-connect/src/connections/browser/owned.rsindex 8a5c9f1a1..347d408ef 100644--- a/crates/screenpipe-connect/src/connections/browser/owned.rs+++ b/crates/screenpipe-connect/src/connections/browser/owned.rs@@ -40,6 +40,23 @@ pub trait OwnedWebviewHandle: Send + Sync {timeout: Duration,) -> Result<EvalResult, String>;+ /// Owner-aware eval. When `url` is supplied the owned webview navigates+ /// before running `code`; `owner` tags that navigation (see+ /// [`Browser::eval_with_owner`](super::Browser::eval_with_owner)) so the+ /// frontend sidebar keeps a background pipe's navigate-then-scrape out of+ /// an unrelated chat. Default ignores `owner` and delegates to `eval` for+ /// transports that can't emit the frontend navigate event; the Tauri impl+ /// forwards it.+ async fn eval_with_owner(+ &self,+ code: &str,+ url: Option<&str>,+ timeout: Duration,+ _owner: Option<&str>,+ ) -> Result<EvalResult, String> {+ self.eval(code, url, timeout).await+ }+/// Fire-and-forget navigation. Default impl falls back to `eval` so/// existing transports keep working unchanged; the Tauri impl/// overrides it with the native webview `navigate(...)` call so we@@ -135,13 +152,22 @@ impl Browser for OwnedBrowser {code: &str,url: Option<&str>,timeout: Duration,+ ) -> Result<EvalResult, EvalError> {+ self.eval_with_owner(code, url, timeout, None).await+ }+ async fn eval_with_owner(+ &self,+ code: &str,+ url: Option<&str>,+ timeout: Duration,+ owner: Option<&str>,) -> Result<EvalResult, EvalError> {let handle = {let guard = self.handle.read().await;guard.as_ref().cloned().ok_or(EvalError::NotConnected)?};handle- .eval(code, url, timeout)+ .eval_with_owner(code, url, timeout, owner).await.map_err(EvalError::SendFailed)}@@ -178,6 +204,13 @@ mod tests {last_owner: Mutex<Option<String>>,}+ /// Records the owner forwarded to `eval_with_owner` — the eval-with-url+ /// (navigate-and-scrape) counterpart of `NativeNavigateHandle`.+ struct EvalOwnerHandle {+ last_url: Mutex<Option<String>>,+ last_owner: Mutex<Option<String>>,+ }+#[async_trait]impl OwnedWebviewHandle for StubHandle {async fn eval(@@ -217,6 +250,39 @@ mod tests {}}+ #[async_trait]+ impl OwnedWebviewHandle for EvalOwnerHandle {+ async fn eval(+ &self,+ _code: &str,+ _url: Option<&str>,+ _timeout: Duration,+ ) -> Result<EvalResult, String> {+ // Plain eval carries no owner.+ Ok(EvalResult {+ ok: true,+ result: None,+ error: None,+ })+ }++ async fn eval_with_owner(+ &self,+ _code: &str,+ url: Option<&str>,+ _timeout: Duration,+ owner: Option<&str>,+ ) -> Result<EvalResult, String> {+ *self.last_url.lock().await = url.map(|s| s.to_string());+ *self.last_owner.lock().await = owner.map(|s| s.to_string());+ Ok(EvalResult {+ ok: true,+ result: None,+ error: None,+ })+ }+ }+#[tokio::test]async fn unattached_owned_returns_not_connected() {let owned = OwnedBrowser::default_instance();@@ -319,4 +385,58 @@ mod tests {Some("pipe:reddit".into()));}++ #[tokio::test]+ async fn eval_with_owner_forwards_owner_to_handle() {+ // Regression: the eval-with-url (navigate-and-scrape) path is the other+ // way a background pipe drives the owned browser. It must tag the+ // navigation with the issuing session id too, or the sidebar pops the+ // pipe's page into whatever chat is on screen (the eval path used to+ // hardcode owner=None).+ let owned = OwnedBrowser::default_instance();+ let handle = Arc::new(EvalOwnerHandle {+ last_url: Mutex::new(None),+ last_owner: Mutex::new(None),+ });+ owned.attach(handle.clone()).await;++ owned+ .eval_with_owner(+ "return 1",+ Some("https://example.com/scrape"),+ Duration::from_secs(1),+ Some("pipe:reddit"),+ )+ .await+ .unwrap();++ assert_eq!(+ handle.last_url.lock().await.clone(),+ Some("https://example.com/scrape".into())+ );+ assert_eq!(+ handle.last_owner.lock().await.clone(),+ Some("pipe:reddit".into())+ );+ }++ #[tokio::test]+ async fn plain_eval_carries_no_owner() {+ // The `eval` entry point (snapshot, code-only eval) must stay un-owned+ // so it never reaches the owner-tagging navigate path.+ let owned = OwnedBrowser::default_instance();+ let handle = Arc::new(EvalOwnerHandle {+ last_url: Mutex::new(None),+ last_owner: Mutex::new(None),+ });+ owned.attach(handle.clone()).await;++ owned+ .eval("return 1", None, Duration::from_secs(1))+ .await+ .unwrap();++ // `eval` delegates to `eval_with_owner(.., None)`.+ assert_eq!(handle.last_owner.lock().await.clone(), None);+ }}diff --git a/crates/screenpipe-engine/src/connections_api.rs b/crates/screenpipe-engine/src/connections_api.rsindex 87323de41..36ec036de 100644--- a/crates/screenpipe-engine/src/connections_api.rs+++ b/crates/screenpipe-engine/src/connections_api.rs@@ -2544,11 +2544,25 @@ async fn browser_run_snapshot(}/// POST /connections/browsers/:id/eval — run JS in the named browser.+///+/// When `url` is supplied this is a navigate-and-scrape: the owned browser+/// navigates first, then runs `code`. That navigation must carry the same+/// `x-screenpipe-session` owner tag as the dedicated `/navigate` endpoint, or+/// a background pipe's eval-with-url pops its page into whatever chat is on+/// screen (the singleton owned-browser is shared by every chat + pipe). See+/// `browser_run_navigate` and `screenpipe-core::agents::bash_env`.async fn browser_run_eval(State(state): State<ConnectionsState>,Path(id): Path<String>,+ headers: HeaderMap,Json(body): Json<BrowserEvalBody>,) -> (StatusCode, Json<Value>) {+ let owner = headers+ .get("x-screenpipe-session")+ .and_then(|v| v.to_str().ok())+ .map(str::trim)+ .filter(|s| !s.is_empty());+let browser = match state.browser_registry.get(&id).await {Some(b) => b,None => {@@ -2560,7 +2574,10 @@ async fn browser_run_eval(};let timeout = std::time::Duration::from_secs(body.timeout_secs.unwrap_or(30).min(120));- match browser.eval(&body.code, body.url.as_deref(), timeout).await {+ match browser+ .eval_with_owner(&body.code, body.url.as_deref(), timeout, owner)+ .await+ {Ok(r) => {let status = if r.ok {StatusCode::OK@@ -3363,4 +3380,117 @@ mod tests {);}}++ /// Records the owner each `eval_with_owner` call receives so the route test+ /// can prove the `x-screenpipe-session` header reaches the browser.+ struct OwnerRecordingBrowser {+ last_owner: Arc<Mutex<Option<String>>>,+ }++ #[async_trait::async_trait]+ impl screenpipe_connect::connections::browser::Browser for OwnerRecordingBrowser {+ fn id(&self) -> &str {+ "owned-default"+ }+ fn name(&self) -> &str {+ "recorder"+ }+ fn description(&self) -> &str {+ "records the owner passed to eval"+ }+ async fn is_ready(&self) -> bool {+ true+ }+ async fn eval(+ &self,+ _code: &str,+ _url: Option<&str>,+ _timeout: std::time::Duration,+ ) -> Result<+ screenpipe_connect::connections::browser::EvalResult,+ screenpipe_connect::connections::browser::EvalError,+ > {+ // Plain eval is un-owned; record None so a regression that routed+ // through here (instead of eval_with_owner) is visible.+ *self.last_owner.lock().await = None;+ Ok(screenpipe_connect::connections::browser::EvalResult {+ ok: true,+ result: Some(json!("plain")),+ error: None,+ })+ }+ async fn eval_with_owner(+ &self,+ _code: &str,+ _url: Option<&str>,+ _timeout: std::time::Duration,+ owner: Option<&str>,+ ) -> Result<+ screenpipe_connect::connections::browser::EvalResult,+ screenpipe_connect::connections::browser::EvalError,+ > {+ *self.last_owner.lock().await = owner.map(|s| s.to_string());+ Ok(screenpipe_connect::connections::browser::EvalResult {+ ok: true,+ result: Some(json!("ok")),+ error: None,+ })+ }+ }++ /// Regression: a background pipe drives the owned browser via the+ /// navigate-and-scrape `/eval` endpoint, which (like `/navigate`) carries+ /// the `x-screenpipe-session` owner header the agent's curl shim injects.+ /// The handler must forward it so the sidebar can keep the pipe's page out+ /// of an unrelated chat. Before the fix, `/eval` ignored the header and the+ /// owned-browser navigate event was emitted with owner=None — honored in+ /// every chat.+ #[tokio::test]+ async fn browser_eval_forwards_session_owner_header() {+ let dir = TempDir::new().unwrap();+ let screenpipe_dir = dir.path().to_path_buf();+ let last_owner = Arc::new(Mutex::new(None));+ let registry = BrowserRegistry::new();+ registry+ .register(Arc::new(OwnerRecordingBrowser {+ last_owner: last_owner.clone(),+ }))+ .await;++ let cm = Arc::new(Mutex::new(ConnectionManager::new(+ screenpipe_dir.clone(),+ None,+ )));+ let wa = Arc::new(Mutex::new(WhatsAppGateway::new(screenpipe_dir.clone())));+ let app = router(+ cm,+ wa,+ screenpipe_dir,+ None,+ crate::routes::browser::BrowserBridge::new(),+ registry,+ None,+ );++ let response = app+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/browsers/owned-default/eval")+ .header(header::CONTENT_TYPE, "application/json")+ .header("x-screenpipe-session", "pipe:reddit-poster")+ .body(Body::from(+ r#"{"code":"return 1","url":"https://example.com/scrape"}"#,+ ))+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(+ last_owner.lock().await.clone(),+ Some("pipe:reddit-poster".to_string())+ );+ }}