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 lifecycle events leaking into the wrong chat (#3997)
Harsh Kumar0f9028bdd06c
diff --git a/apps/screenpipe-app-tauri/components/browser-sidebar.tsx b/apps/screenpipe-app-tauri/components/browser-sidebar.tsxindex 9ed6db3f6..9fb82bb98 100644--- a/apps/screenpipe-app-tauri/components/browser-sidebar.tsx+++ b/apps/screenpipe-app-tauri/components/browser-sidebar.tsx@@ -57,6 +57,7 @@ import { localFetch } from "@/lib/api";import { useSettings } from "@/lib/hooks/use-settings";import {isForeignNavigation,+ isMismatchedNavigation,parseNavigatePayload,type OwnedBrowserNavigatePayload,} from "@/lib/owned-browser-ownership";@@ -89,8 +90,9 @@ interface SessionAccessEvent {host: string;already_granted?: boolean;alreadyGranted?: boolean;+ navigationId?: string | null;/** Conversation that issued the navigation (see `owner` on the navigate- * event). Null for the sidebar's own restore/reload. */+ * event). Ownerless payloads are treated as stale/legacy and ignored. */owner?: string | null;}@@ -99,6 +101,8 @@ interface ActiveSessionAccessRequest {url: string;host: string;alreadyGranted: boolean;+ navigationId: string;+ owner: string | null;}interface V20CookieBlockEvent {@@ -109,6 +113,7 @@ interface V20CookieBlockEvent {v20_count?: number;sources?: string[];reason?: string;+ navigationId?: string | null;owner?: string | null;}@@ -119,12 +124,15 @@ interface ActiveV20CookieBlock {v20Count: number;sources: string[];reason: string;+ navigationId: string;+ owner: string | null;}interface OwnedBrowserStateEvent {url?: string | null;title?: string | null;loading?: boolean | null;+ navigationId?: string | null;owner?: string | null;}@@ -149,6 +157,8 @@ export function BrowserSidebar({const [visible, setVisible] = useState(false);const [collapsed, setCollapsed] = useState(false);const [currentUrl, setCurrentUrl] = useState<string | null>(null);+ const [currentOwner, setCurrentOwner] = useState<string | null>(null);+ const [currentNavigationId, setCurrentNavigationId] = useState<string | null>(null);const [currentTitle, setCurrentTitle] = useState<string | null>(null);const [loading, setLoading] = useState(false);const [sessionAccessRequest, setSessionAccessRequest] =@@ -335,27 +345,27 @@ export function BrowserSidebar({const unlistenPromise = listen<OwnedBrowserNavigatePayload>(NAVIGATE_EVENT,(e) => {- const { url, owner } = parseNavigatePayload(e.payload);+ const { url, owner, navigationId, reveal } = parseNavigatePayload(e.payload);if (!url) return;// The owned browser is a singleton shared across every chat and// background pipe. Ignore navigations owned by a *different*// conversation than the one on screen — otherwise a background pipe// (or another chat's agent) pops its page into whatever chat the user// is looking at, and `persistState` writes that URL into the wrong- // chat's file so it sticks on reopen. Untagged events (owner == null)- // are the sidebar's own restore/reload and are always honored.+ // chat's file so it sticks on reopen. Restore/reload paths now tag+ // themselves with the foreground conversation id; ownerless events are+ // treated as stale/legacy and ignored.if (isForeignNavigation(owner, conversationId)) return;+ if (!navigationId) return;setSessionAccessRequest(null);setSessionAccessAnswer(null);setV20CookieBlock(null);setCurrentUrl(url);+ setCurrentOwner(owner);+ setCurrentNavigationId(navigationId);setCurrentTitle(null);setLoading(true);- // Agent-driven navigations (owner is set) always open the panel.- // Ownerless events (restore/reload after chat switch) must not- // override the persisted collapsed state — otherwise switching- // away from a chat with a collapsed sidebar and back re-opens it.- if (owner) {+ if (reveal) {setVisible(true);setCollapsed(false);persistState({ url, collapsed: false });@@ -379,12 +389,15 @@ export function BrowserSidebar({// Same ownership gate as the navigate event — a background pipe's// cookie-consent prompt must not surface in another chat.if (isForeignNavigation(payload.owner, conversationId)) return;+ if (isMismatchedNavigation(payload.navigationId, currentNavigationId)) return;const request = {requestId,url: payload.url,host: payload.host,alreadyGranted:payload.alreadyGranted ?? payload.already_granted ?? false,+ navigationId: payload.navigationId!,+ owner: payload.owner ?? null,};setSessionAccessRequest(request);setSessionAccessAnswer(null);@@ -392,6 +405,8 @@ export function BrowserSidebar({setVisible(true);setCollapsed(false);setCurrentUrl(request.url);+ setCurrentOwner(request.owner);+ setCurrentNavigationId(request.navigationId);setCurrentTitle(null);setLoading(true);persistState({ url: request.url, collapsed: false });@@ -401,7 +416,7 @@ export function BrowserSidebar({return () => {unlistenPromise.then((fn) => fn()).catch(() => {});};- }, [persistState, conversationId]);+ }, [persistState, conversationId, currentNavigationId]);useEffect(() => {const unlistenPromise = listen<V20CookieBlockEvent>(@@ -410,6 +425,7 @@ export function BrowserSidebar({const payload = e.payload;if (!payload?.url || !payload?.host) return;if (isForeignNavigation(payload.owner, conversationId)) return;+ if (isMismatchedNavigation(payload.navigationId, currentNavigationId)) return;const block = {url: payload.url,host: payload.host,@@ -417,6 +433,8 @@ export function BrowserSidebar({v20Count: payload.v20Count ?? payload.v20_count ?? 0,sources: payload.sources ?? [],reason: payload.reason ?? "v20",+ navigationId: payload.navigationId!,+ owner: payload.owner ?? null,};setSessionAccessRequest(null);setSessionAccessAnswer(null);@@ -424,6 +442,8 @@ export function BrowserSidebar({setVisible(true);setCollapsed(false);setCurrentUrl(block.url);+ setCurrentOwner(block.owner);+ setCurrentNavigationId(block.navigationId);setCurrentTitle(null);setLoading(false);persistState({ url: block.url, collapsed: false });@@ -433,7 +453,7 @@ export function BrowserSidebar({return () => {unlistenPromise.then((fn) => fn()).catch(() => {});};- }, [persistState, conversationId]);+ }, [persistState, conversationId, currentNavigationId]);useEffect(() => {sessionAccessActiveRef.current =@@ -466,7 +486,13 @@ export function BrowserSidebar({// Extension is now connected — retry the navigation, which will// go through the extension cookie path.setV20CookieBlock(null);- commands.ownedBrowserNavigate(retryUrl).catch(() => {});+ commands+ .ownedBrowserNavigate(+ retryUrl,+ v20CookieBlock.owner ?? currentOwner ?? conversationId ?? null,+ true,+ )+ .catch(() => {});}} else {setExtensionConnected(false);@@ -494,12 +520,15 @@ export function BrowserSidebar({// sticky half of the leak: without this the URL is restored on reopen// even though the panel never visibly popped).if (isForeignNavigation(payload.owner, conversationId)) return;+ if (isMismatchedNavigation(payload.navigationId, currentNavigationId)) return;if (typeof payload.url === "string" && payload.url.length > 0) {if (payload.url !== currentUrl) {setCurrentTitle(null);}setCurrentUrl(payload.url);+ setCurrentOwner(payload.owner ?? conversationId ?? null);+ setCurrentNavigationId(payload.navigationId!);persistState({ url: payload.url });}if (typeof payload.title === "string") {@@ -513,7 +542,7 @@ export function BrowserSidebar({return () => {unlistenPromise.then((fn) => fn()).catch(() => {});};- }, [currentUrl, persistState, conversationId]);+ }, [currentNavigationId, currentUrl, persistState, conversationId]);// ---------------------------------------------------------------------------// Per-conversation restore@@ -525,6 +554,8 @@ export function BrowserSidebar({setVisible(false);setCollapsed(false);setCurrentUrl(null);+ setCurrentOwner(null);+ setCurrentNavigationId(null);setCurrentTitle(null);setLoading(false);setSessionAccessRequest(null);@@ -552,6 +583,8 @@ export function BrowserSidebar({setVisible(true);setCollapsed(wasCollapsed);setCurrentUrl(url);+ setCurrentOwner(conversationId);+ setCurrentNavigationId(null);setCurrentTitle(null);setLoading(!wasCollapsed);// The webview install runs on a background task that retries@@ -562,7 +595,7 @@ export function BrowserSidebar({// browser silently fails to restore. Retry once when Rust emits// `owned-browser:ready` so the saved state survives app quit.const tryNavigate = () =>- commands.ownedBrowserNavigate(url).catch((e) => {+ commands.ownedBrowserNavigate(url, conversationId, false).catch((e) => {const msg = typeof e === "string" ? e : String(e);return msg.includes("not initialized") ? "retry" : null;});@@ -579,6 +612,8 @@ export function BrowserSidebar({setVisible(false);setCollapsed(false);setCurrentUrl(null);+ setCurrentOwner(null);+ setCurrentNavigationId(null);setCurrentTitle(null);setLoading(false);setV20CookieBlock(null);@@ -684,11 +719,15 @@ export function BrowserSidebar({if (!currentUrl) return;try {setLoading(true);- await commands.ownedBrowserNavigate(currentUrl);+ await commands.ownedBrowserNavigate(+ currentUrl,+ currentOwner ?? conversationId ?? null,+ true,+ );} catch (e) {console.error("reload failed", e);}- }, [currentUrl]);+ }, [conversationId, currentOwner, currentUrl]);const setCookieAccessGranted = useCallback(async (granted: boolean) => {@@ -702,10 +741,16 @@ export function BrowserSidebar({if (!currentUrl) return;await commands.confirmBrowserCookieAccessForSession();setLoading(true);- await commands.ownedBrowserNavigate(currentUrl).catch((e) => {- console.error("retry cookie navigation failed", e);- });- }, [currentUrl]);+ await commands+ .ownedBrowserNavigate(+ currentUrl,+ currentOwner ?? conversationId ?? null,+ true,+ )+ .catch((e) => {+ console.error("retry cookie navigation failed", e);+ });+ }, [conversationId, currentOwner, currentUrl]);const clearBrowserData = useCallback(async () => {try {@@ -715,12 +760,16 @@ export function BrowserSidebar({await commands.ownedBrowserClearBrowsingData();if (currentUrl) {setLoading(true);- await commands.ownedBrowserNavigate(currentUrl);+ await commands.ownedBrowserNavigate(+ currentUrl,+ currentOwner ?? conversationId ?? null,+ true,+ );}} catch (e) {console.error("clear owned-browser browsing data failed", e);}- }, [currentUrl, setCookieAccessGranted]);+ }, [conversationId, currentOwner, currentUrl, setCookieAccessGranted]);const enableAndRetryWithCookies = useCallback(async () => {await setCookieAccessGranted(true);diff --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 bf19817ae..8e22eb8ee 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@@ -13,11 +13,14 @@* session (see harness note below) — and that handle never re-enumerates, so* `openHomeWindow()` can't recover it. If any spec ran after this one it would* fail its `before` hook with "Could not get home window handle" and cascade.- * The `zz-` prefix sorts it after every other spec (incl. `windows-*`) so- * nothing depends on `home` afterwards. Do NOT rename it back / un-prefix it.- * (An earlier revision filed this as macOS-only "Windows is also fine"; in CI- * it poisoned the session on BOTH macOS and Windows — Linux only escaped- * because it skips the spec entirely.)+ * The `zz-` prefix sorts it after the normal app-window specs so nothing that+ * still depends on `home` runs afterwards. The one intentional exception is+ * the later `zzz-browser-state-chat-switch` spec, which is search-driven and+ * does not need a recoverable `home` handle. Inside THIS file, keep the+ * destructive attach-to-`home` block last for the same reason. Do NOT rename+ * it back / un-prefix it. (An earlier revision filed this as macOS-only+ * "Windows is also fine"; in CI it poisoned the session on BOTH macOS and+ * Windows — Linux only escaped because it skips the spec entirely.)** Bug: the owned browser is a native child Webview parented to the `home`* window, behind the chat sidebar. The meeting-notes section lives in the SAME@@ -43,7 +46,13 @@* fallout to the end of the run.*/-import { existsSync, rmSync } from "node:fs";+import {+ existsSync,+ mkdirSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";import { homedir } from "node:os";import { join } from "node:path";import {@@ -92,6 +101,11 @@ const OWN_CHAT = "33333333-cccc-cccc-cccc-cccccccccccc";const FOREIGN_OWNER = "pipe:e2e-background-poster";const CHATS_DIR = join(homedir(), ".screenpipe", "chats");const FOREIGN_URL = "https://example.com/e2e-foreign-pipe";+const BROWSER_CHAT_A = "44444444-dddd-dddd-dddd-dddddddddddd";+const BROWSER_CHAT_B = "55555555-eeee-eeee-eeee-eeeeeeeeeeee";+const PLAIN_CHAT = "66666666-ffff-ffff-ffff-ffffffffffff";+const BROWSER_URL_A = "https://example.com/e2e-browser-chat-a";+const BROWSER_URL_B = "https://example.com/e2e-browser-chat-b";function removeChatFile(id: string): void {try {@@ -102,6 +116,73 @@ function removeChatFile(id: string): void {}}+function writeSeedChatFile(+ id: string,+ userText: string,+ browserState?: { url: string; collapsed?: boolean; width?: number },+): void {+ if (!existsSync(CHATS_DIR)) mkdirSync(CHATS_DIR, { recursive: true });+ const now = Date.now();+ writeFileSync(+ join(CHATS_DIR, `${id}.json`),+ JSON.stringify({+ id,+ title: "e2e",+ messages: [+ {+ id: `e2e-seed-${id.slice(0, 12)}`,+ role: "user",+ content: userText,+ timestamp: now,+ },+ ],+ createdAt: now,+ updatedAt: now,+ ...(browserState+ ? {+ browserState: {+ url: browserState.url,+ updatedAt: now,+ ...(typeof browserState.width === "number"+ ? { width: browserState.width }+ : {}),+ ...(browserState.collapsed === true ? { collapsed: true } : {}),+ },+ }+ : {}),+ }),+ );+}++function loadChatFile(+ id: string,+): { id: string; messages: any[]; browserState?: { url?: string } } | null {+ const p = join(CHATS_DIR, `${id}.json`);+ if (!existsSync(p)) return null;+ return JSON.parse(readFileSync(p, "utf-8"));+}++async function clearBrowserStateCache(chatId: string): Promise<void> {+ await browser.execute((key: string) => {+ window.localStorage.removeItem(key);+ }, `screenpipe:browser-state:${chatId}`);+}++async function readBrowserStateCacheUrl(+ chatId: string,+): Promise<string | null> {+ return (await browser.execute((key: string) => {+ try {+ const raw = window.localStorage.getItem(key);+ if (!raw) return null;+ const parsed = JSON.parse(raw);+ return parsed?.url ?? null;+ } catch {+ return null;+ }+ }, `screenpipe:browser-state:${chatId}`)) as string | null;+}+async function waitForChatSeedHook(): Promise<void> {await browser.waitUntil(async () =>@@ -320,6 +401,105 @@ describe("Owned browser — per-chat navigation ownership", function () {);});+describe("Owned browser — fast chat switching keeps pipe state out of other chats", function () {+ this.timeout(180_000);++ before(async () => {+ await waitForAppReady();+ await openHomeWindow();+ await showWindow({ Search: { query: null } });+ await waitForWindowHandle("search", t(10_000));+ await browser.switchToWindow("search");+ await browser.pause(t(800));++ for (const id of [BROWSER_CHAT_A, BROWSER_CHAT_B, PLAIN_CHAT]) {+ removeChatFile(id);+ await clearBrowserStateCache(id);+ }+ });++ after(async () => {+ await invoke("owned_browser_hide").catch(() => {});+ for (const id of [BROWSER_CHAT_A, BROWSER_CHAT_B, PLAIN_CHAT]) {+ removeChatFile(id);+ await clearBrowserStateCache(id);+ }+ });++ (canDriveOwnedBrowser ? it : it.skip)(+ "does not persist a pipe-driven browser URL into another browser chat or a plain chat during fast switching",+ async () => {+ await installSessionCapture();+ writeSeedChatFile(+ BROWSER_CHAT_A,+ "(e2e) browser chat A",+ { url: BROWSER_URL_A, collapsed: true, width: 420 },+ );+ writeSeedChatFile(+ BROWSER_CHAT_B,+ "(e2e) browser chat B",+ { url: BROWSER_URL_B, collapsed: true, width: 420 },+ );+ writeSeedChatFile(PLAIN_CHAT, "(e2e) plain chat");++ await loadChatIntoHome(BROWSER_CHAT_A);+ await waitForActiveConversation(BROWSER_CHAT_A);+ await browser.pause(t(800));+ await invokeOrThrow("owned_browser_hide");+ expect(await invokeOrThrow<boolean>("e2e_owned_browser_visible")).toBe(+ false,+ );++ const { port, key } = await getLocalApiConfig();++ await loadChatIntoHome(PLAIN_CHAT);+ await waitForActiveConversation(PLAIN_CHAT);+ const navigateStatus = await postNavigateAs(+ port,+ key,+ FOREIGN_URL,+ FOREIGN_OWNER,+ );+ expect(navigateStatus).toBe(200);+ await browser.pause(t(1_200));+ expect(await invokeOrThrow<boolean>("e2e_owned_browser_visible")).toBe(+ false,+ );++ await loadChatIntoHome(BROWSER_CHAT_B);+ await waitForActiveConversation(BROWSER_CHAT_B);+ await loadChatIntoHome(PLAIN_CHAT);+ await waitForActiveConversation(PLAIN_CHAT);+ await postEvalWithUrlAs(port, key, FOREIGN_URL, FOREIGN_OWNER);+ await browser.pause(t(1_200));+ expect(await invokeOrThrow<boolean>("e2e_owned_browser_visible")).toBe(+ false,+ );+ await loadChatIntoHome(BROWSER_CHAT_A);+ await waitForActiveConversation(BROWSER_CHAT_A);+ await loadChatIntoHome(BROWSER_CHAT_B);+ await waitForActiveConversation(BROWSER_CHAT_B);+ await browser.pause(t(1_000));++ const chatA = loadChatFile(BROWSER_CHAT_A);+ const chatB = loadChatFile(BROWSER_CHAT_B);+ const plain = loadChatFile(PLAIN_CHAT);++ if (!chatA || !chatB || !plain) {+ throw new Error("expected all seeded chat files to exist");+ }++ expect(chatA.browserState?.url).toBe(BROWSER_URL_A);+ expect(chatB.browserState?.url).toBe(BROWSER_URL_B);+ expect(plain.browserState).toBeUndefined();++ expect(await readBrowserStateCacheUrl(BROWSER_CHAT_A)).toBe(BROWSER_URL_A);+ expect(await readBrowserStateCacheUrl(BROWSER_CHAT_B)).toBe(BROWSER_URL_B);+ expect(await readBrowserStateCacheUrl(PLAIN_CHAT)).toBeNull();+ },+ );+});+describe("Owned browser — background navigation visibility", function () {this.timeout(180_000);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 73210cd47..8c247a690 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@@ -18,6 +18,7 @@import { describe, it, expect } from "vitest";import {isForeignNavigation,+ isMismatchedNavigation,parseNavigatePayload,} from "@/lib/owned-browser-ownership";@@ -34,13 +35,11 @@ describe("owned-browser ownership", () => {expect(isForeignNavigation("conv-C", "conv-C")).toBe(false);});- it("honors untagged navigations (the sidebar's own restore/reload)", () => {- 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("drops ownerless navigations (stale/legacy emits)", () => {+ expect(isForeignNavigation(null, "conv-C")).toBe(true);+ expect(isForeignNavigation(undefined, "conv-C")).toBe(true);+ expect(isForeignNavigation("", "conv-C")).toBe(true);+ expect(isForeignNavigation(null, null)).toBe(true);});it("gates a tagged navigation when no chat is bound (fresh/unsaved chat)", () => {@@ -56,14 +55,26 @@ describe("owned-browser ownership", () => {describe("parseNavigatePayload", () => {it("parses the object payload with an owner", () => {expect(- parseNavigatePayload({ url: "https://example.com", owner: "pipe:x" }),- ).toEqual({ url: "https://example.com", owner: "pipe:x" });+ parseNavigatePayload({+ url: "https://example.com",+ owner: "pipe:x",+ navigationId: "nav-1",+ reveal: false,+ }),+ ).toEqual({+ url: "https://example.com",+ owner: "pipe:x",+ navigationId: "nav-1",+ reveal: false,+ });});it("treats a bare string (legacy/stale emit) as un-owned", () => {expect(parseNavigatePayload("https://example.com")).toEqual({url: "https://example.com",owner: null,+ navigationId: null,+ reveal: true,});});@@ -71,9 +82,37 @@ describe("owned-browser ownership", () => {expect(parseNavigatePayload({ url: "https://example.com" })).toEqual({url: "https://example.com",owner: null,+ navigationId: null,+ reveal: true,+ });+ expect(parseNavigatePayload({})).toEqual({+ url: null,+ owner: null,+ navigationId: null,+ reveal: true,});- expect(parseNavigatePayload({})).toEqual({ url: null, owner: null });- expect(parseNavigatePayload("")).toEqual({ url: null, owner: null });+ expect(parseNavigatePayload("")).toEqual({+ url: null,+ owner: null,+ navigationId: null,+ reveal: true,+ });+ });+ });++ describe("isMismatchedNavigation", () => {+ it("rejects missing navigation ids", () => {+ expect(isMismatchedNavigation(null, "nav-1")).toBe(true);+ expect(isMismatchedNavigation(undefined, null)).toBe(true);+ });++ it("accepts the first adopted navigation when none is active yet", () => {+ expect(isMismatchedNavigation("nav-1", null)).toBe(false);+ });++ it("rejects a different navigation once one is active", () => {+ expect(isMismatchedNavigation("nav-2", "nav-1")).toBe(true);+ expect(isMismatchedNavigation("nav-1", "nav-1")).toBe(false);});});});diff --git a/apps/screenpipe-app-tauri/lib/owned-browser-ownership.ts b/apps/screenpipe-app-tauri/lib/owned-browser-ownership.tsindex 294274611..11c345696 100644--- a/apps/screenpipe-app-tauri/lib/owned-browser-ownership.ts+++ b/apps/screenpipe-app-tauri/lib/owned-browser-ownership.ts@@ -21,41 +21,65 @@* upgrade still navigates. */export type OwnedBrowserNavigatePayload =| string- | { url?: string | null; owner?: string | null };+ | {+ url?: string | null;+ owner?: string | null;+ navigationId?: string | null;+ reveal?: boolean | null;+ };export function parseNavigatePayload(payload: OwnedBrowserNavigatePayload): {url: string | null;owner: string | null;+ navigationId: string | null;+ reveal: boolean;} {- if (typeof payload === "string") return { url: payload || null, owner: null };+ if (typeof payload === "string") {+ return { url: payload || null, owner: null, navigationId: null, reveal: true };+ }if (payload && typeof payload === "object") {- return { url: payload.url ?? null, owner: payload.owner ?? null };+ return {+ url: payload.url ?? null,+ owner: payload.owner ?? null,+ navigationId: payload.navigationId ?? null,+ reveal: payload.reveal !== false,+ };}- return { url: null, owner: null };+ return { url: null, owner: null, navigationId: null, reveal: true };}/*** 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- * (regardless of whether a chat is bound).- * - owner === conversationId → this chat's own agent, honored.+ * - owner === conversationId → this chat's own browser lifecycle event,+ * honored.+ * - owner null/empty → foreign/stale, ignored. All supported restore/reload+ * paths now send the real `conversationId`; leaving ownerless events+ * writable lets the singleton browser leak into whichever chat is open.* - 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.)+ * ignored. A null/empty conversationId means a fresh chat: any tagged event+ * necessarily belongs to another chat or a background pipe.*/export function isForeignNavigation(owner: string | null | undefined,conversationId: string | null | undefined,): boolean {- // The sidebar's own restore/reload is untagged — always honor it.- if (!owner) return false;+ // Ownerless events are stale/legacy and must not mutate whichever chat is+ // currently open. Every supported restore/reload path now tags itself with+ // the foreground conversation id.+ if (!owner) return true;// 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;}++export function isMismatchedNavigation(+ navigationId: string | null | undefined,+ currentNavigationId: string | null | undefined,+): boolean {+ if (!navigationId) return true;+ if (!currentNavigationId) return false;+ return navigationId !== currentNavigationId;+}diff --git a/apps/screenpipe-app-tauri/lib/utils/tauri.ts b/apps/screenpipe-app-tauri/lib/utils/tauri.tsindex d650435e6..97d8c0eca 100644--- a/apps/screenpipe-app-tauri/lib/utils/tauri.ts+++ b/apps/screenpipe-app-tauri/lib/utils/tauri.ts@@ -1058,14 +1058,17 @@ async ownedBrowserHide() : Promise<Result<null, string>> {}},/**- * Navigate the embedded webview to `url`. Used by the sidebar when restoring- * per-chat state or on user reload — i.e. always an action of the chat that's- * on screen, so it carries no owner (`None`) and the frontend always honors- * it. The agent/pipe path is the connect-trait `navigate` (owner-tagged).+ * Navigate the embedded webview to `url`.+ *+ * Frontend restore/reload calls pass the foreground conversation id as+ * `owner`, so the entire browser lifecycle stays scoped to that chat. Retry+ * paths that are continuing a pipe/chat-owned navigation (for example after an+ * extension or cookie-consent flow) can pass the original `owner` through so+ * the follow-up navigate does not look like a fresh restore in every chat.*/-async ownedBrowserNavigate(url: string) : Promise<Result<null, string>> {+async ownedBrowserNavigate(url: string, owner: string | null, reveal: boolean | null) : Promise<Result<null, string>> {try {- return { status: "ok", data: await TAURI_INVOKE("owned_browser_navigate", { url }) };+ return { status: "ok", data: await TAURI_INVOKE("owned_browser_navigate", { url, owner, reveal }) };} catch (e) {if(e instanceof Error) throw e;else return { status: "error", error: e as any };diff --git a/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rs b/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rsindex 6d1e361fc..2778995a4 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rs@@ -47,6 +47,8 @@ use tokio::sync::{oneshot, Mutex};use tracing::{debug, info, warn};use uuid::Uuid;+const RECENT_NAVIGATION_CONTEXT_LIMIT: usize = 16;+/// Embedded webview label — also used by the frontend Tauri commands.pub const WEBVIEW_LABEL: &str = "owned-browser";@@ -128,22 +130,26 @@ struct OwnedBrowserStateEvent {url: Option<String>,title: Option<String>,loading: Option<bool>,+ navigation_id: Option<String>,/// Conversation/session that issued the navigation currently in flight.- /// See [`OwnedBrowserNavigateEvent::owner`]. `None` for the sidebar's own- /// restore/reload; the frontend always honors those.+ /// See [`OwnedBrowserNavigateEvent::owner`]. `None` means stale/legacy;+ /// supported restore/reload paths now send the foreground conversation id.owner: Option<String>,}/// Payload of [`NAVIGATE_EVENT`]. `owner` is the chat/session id that drove the/// navigation — `sid` for a chat agent (equals the frontend `conversationId`),-/// `pipe:<name>` for a background pipe, `None` for the sidebar's own-/// restore/reload. The owned browser is a singleton broadcast to every window,-/// so the frontend uses `owner` to ignore navigations that belong to a chat-/// other than the one on screen.+/// `pipe:<name>` for a background pipe. `None` means stale/legacy; supported+/// restore/reload paths now send the foreground conversation id. The owned+/// browser is a singleton broadcast to every window, so the frontend uses+/// `owner` to ignore navigations that belong to a chat other than the one on+/// screen.#[derive(Clone, Serialize)]#[serde(rename_all = "camelCase")]struct OwnedBrowserNavigateEvent {url: String,+ navigation_id: String,+ reveal: bool,owner: Option<String>,}@@ -160,6 +166,7 @@ struct BrowserSessionAccessRequestPayload {url: String,host: String,already_granted: bool,+ navigation_id: Option<String>,/// Owner of the navigation that triggered this prompt — see/// [`OwnedBrowserNavigateEvent::owner`].owner: Option<String>,@@ -177,6 +184,7 @@ struct V20CookieBlockPayload {/// "v20" = app-bound encryption blocked decrypt; "locked" = browser running, DB inaccessible#[serde(default)]reason: String,+ navigation_id: Option<String>,/// Owner of the navigation that triggered this block — see/// [`OwnedBrowserNavigateEvent::owner`].owner: Option<String>,@@ -304,9 +312,18 @@ struct OwnedBrowserInner {visible: bool,}+#[derive(Clone)]+struct NavigationContext {+ navigation_id: String,+ owner: Option<String>,+ requested_url: String,+}+struct OwnedBrowserState {inner: Mutex<OwnedBrowserInner>,last_title: StdMutex<String>,+ recent_navigations: StdMutex<Vec<NavigationContext>>,+ pending_navigation_id: StdMutex<Option<String>>,/// Owner (chat/session id) of the most recent navigation. Set by/// `prepare_navigation` and read by the native page-state / cookie event/// emitters, which fire from sync callbacks that don't carry the owner.@@ -323,10 +340,89 @@ impl OwnedBrowserState {Self {inner: Mutex::new(OwnedBrowserInner::default()),last_title: StdMutex::new(String::new()),+ recent_navigations: StdMutex::new(Vec::new()),+ pending_navigation_id: StdMutex::new(None),pending_owner: StdMutex::new(None),}}+ fn remember_navigation(+ &self,+ requested_url: String,+ owner: Option<String>,+ ) -> NavigationContext {+ let context = NavigationContext {+ navigation_id: Uuid::new_v4().to_string(),+ owner,+ requested_url,+ };+ if let Ok(mut guard) = self.recent_navigations.lock() {+ guard.push(context.clone());+ if guard.len() > RECENT_NAVIGATION_CONTEXT_LIMIT {+ let drop_count = guard.len() - RECENT_NAVIGATION_CONTEXT_LIMIT;+ guard.drain(0..drop_count);+ }+ }+ context+ }++ fn context_for_url(&self, url: &str) -> Option<NavigationContext> {+ self.recent_navigations+ .lock()+ .ok()+ .and_then(|guard| {+ guard+ .iter()+ .rev()+ .find(|ctx| ctx.requested_url == url)+ .cloned()+ })+ }++ fn remember_committed_url_for_context(&self, url: &str, context: &NavigationContext) {+ if let Ok(mut guard) = self.recent_navigations.lock() {+ if guard+ .iter()+ .rev()+ .any(|ctx| ctx.navigation_id == context.navigation_id && ctx.requested_url == url)+ {+ return;+ }+ guard.push(NavigationContext {+ navigation_id: context.navigation_id.clone(),+ owner: context.owner.clone(),+ requested_url: url.to_string(),+ });+ if guard.len() > RECENT_NAVIGATION_CONTEXT_LIMIT {+ let drop_count = guard.len() - RECENT_NAVIGATION_CONTEXT_LIMIT;+ guard.drain(0..drop_count);+ }+ }+ }++ fn current_context(&self) -> Option<NavigationContext> {+ let navigation_id = self.pending_navigation_id();+ let owner = self.pending_owner();+ navigation_id.map(|navigation_id| NavigationContext {+ navigation_id,+ owner,+ requested_url: String::new(),+ })+ }++ fn set_pending_navigation_id(&self, navigation_id: Option<String>) {+ if let Ok(mut guard) = self.pending_navigation_id.lock() {+ *guard = navigation_id;+ }+ }++ fn pending_navigation_id(&self) -> Option<String> {+ self.pending_navigation_id+ .lock()+ .ok()+ .and_then(|guard| guard.clone())+ }+fn set_pending_owner(&self, owner: Option<String>) {if let Ok(mut guard) = self.pending_owner.lock() {*guard = owner;@@ -388,14 +484,31 @@ fn emit_state_event(title: Option<String>,loading: Option<bool>,) {+ let state = browser_state();+ let context = if let Some(ref current_url) = url {+ if let Some(context) = state.context_for_url(current_url) {+ Some(context)+ } else {+ let fallback = state.current_context();+ if let Some(ref context) = fallback {+ // Redirects commit a different main-document URL than the one+ // we originally requested. Bind that committed URL onto the+ // same navigation context so later title/state events resolve+ // by exact URL instead of depending on the mutable pending+ // fallback.+ state.remember_committed_url_for_context(current_url, context);+ }+ fallback+ }+ } else {+ state.current_context()+ };let payload = OwnedBrowserStateEvent {url,title,loading,- // Native page-load/title callbacks don't know which navigation they- // belong to; tag with the owner of the most recent navigate so the- // frontend can drop state for a chat other than the one on screen.- owner: browser_state().pending_owner(),+ navigation_id: context.as_ref().map(|ctx| ctx.navigation_id.clone()),+ owner: context.and_then(|ctx| ctx.owner),};if let Err(e) = app.emit(STATE_EVENT, payload) {debug!("owned-browser: failed to emit state event: {e}");@@ -534,7 +647,7 @@ impl TauriOwnedHandle {// 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;+ prepare_navigation(&self.app, &self.state, parsed, owner, true).await;}let active = match self.state.active().await {@@ -732,7 +845,7 @@ impl OwnedWebviewHandle for TauriOwnedHandle {// hook the agent always lands on the logged-out version of the// site even though the Tauri-command-driven sidebar restore// path was injecting correctly.- prepare_navigation(&self.app, &self.state, &parsed, owner).await;+ prepare_navigation(&self.app, &self.state, &parsed, owner, true).await;inject_cookies_for_url(&self.app, &parsed).await;if let Some(active) = self.state.active().await {@@ -905,24 +1018,32 @@ async fn prepare_navigation(state: &OwnedBrowserState,parsed: &url::Url,owner: Option<&str>,+ reveal: bool,) {+ let context = state.remember_navigation(+ parsed.as_str().to_string(),+ owner.map(|s| s.to_string()),+ );// Record the owner before emitting anything so the provisional state event// below — and the native page-load/title callbacks that follow — carry the// same tag. `owner` is the chat/session that issued this navigation; the// frontend uses it to keep a background pipe's page out of whatever chat is// on screen.- state.set_pending_owner(owner.map(|s| s.to_string()));- // Provisional omnibox URL while a top-level navigation is in flight- // (agent or sidebar initiated). Committed URL comes from `webview.url()`- // on main-document load finish / title change.- emit_state_event(app, Some(parsed.as_str().to_string()), None, Some(true));+ state.set_pending_navigation_id(Some(context.navigation_id.clone()));+ state.set_pending_owner(context.owner.clone());let _ = app.emit(NAVIGATE_EVENT,OwnedBrowserNavigateEvent {url: parsed.as_str().to_string(),- owner: owner.map(|s| s.to_string()),+ navigation_id: context.navigation_id,+ reveal,+ owner: context.owner,},);+ // Provisional omnibox URL while a top-level navigation is in flight+ // (agent or sidebar initiated). Committed URL comes from `webview.url()`+ // on main-document load finish / title change.+ emit_state_event(app, Some(parsed.as_str().to_string()), None, Some(true));state.store_pending_url(parsed.clone()).await;}@@ -1018,7 +1139,7 @@ fn normalize_url(raw: &str) -> Result<url::Url, String> {#[cfg(test)]mod normalize_url_tests {- use super::{normalize_url, title_after_eval_marker};+ use super::{normalize_url, title_after_eval_marker, OwnedBrowserState};#[test]fn keeps_fully_qualified() {@@ -1087,19 +1208,65 @@ mod normalize_url_tests {"Example Domain");}++ #[test]+ fn redirect_committed_url_keeps_same_navigation_context() {+ let state = OwnedBrowserState::new();+ let context =+ state.remember_navigation("http://example.com".to_string(), Some("conv-1".to_string()));++ assert_eq!(+ state+ .context_for_url("http://example.com")+ .as_ref()+ .map(|ctx| ctx.navigation_id.as_str()),+ Some(context.navigation_id.as_str())+ );+ assert!(state.context_for_url("https://www.example.com").is_none());++ state.remember_committed_url_for_context("https://www.example.com", &context);++ let redirected = state+ .context_for_url("https://www.example.com")+ .expect("redirect target should resolve to the original navigation context");+ assert_eq!(redirected.navigation_id, context.navigation_id);+ assert_eq!(redirected.owner, context.owner);+ assert_eq!(+ state+ .context_for_url("http://example.com")+ .as_ref()+ .map(|ctx| ctx.navigation_id.as_str()),+ Some(context.navigation_id.as_str())+ );+ }}-/// Navigate the embedded webview to `url`. Used by the sidebar when restoring-/// per-chat state or on user reload — i.e. always an action of the chat that's-/// on screen, so it carries no owner (`None`) and the frontend always honors-/// it. The agent/pipe path is the connect-trait `navigate` (owner-tagged).+/// Navigate the embedded webview to `url`.+///+/// Frontend restore/reload calls pass the foreground conversation id as+/// `owner`, so the entire browser lifecycle stays scoped to that chat. Retry+/// paths that are continuing a pipe/chat-owned navigation (for example after an+/// extension or cookie-consent flow) can pass the original `owner` through so+/// the follow-up navigate does not look like a fresh restore in every chat.#[specta::specta]#[tauri::command]-pub async fn owned_browser_navigate(app: AppHandle, url: String) -> Result<(), String> {+pub async fn owned_browser_navigate(+ app: AppHandle,+ url: String,+ owner: Option<String>,+ reveal: Option<bool>,+) -> Result<(), String> {let state = browser_state();let parsed: url::Url = normalize_url(&url)?;- prepare_navigation(&app, &state, &parsed, None).await;+ prepare_navigation(+ &app,+ &state,+ &parsed,+ owner.as_deref(),+ reveal.unwrap_or(true),+ )+ .await;inject_cookies_for_url(&app, &parsed).await;if let Some(active) = state.active().await {// Visibility is owned by the frontend sidebar — never force-show here@@ -1219,6 +1386,7 @@ async fn inject_cookies_for_url(app: &AppHandle, url: &url::Url) {}}if cookies.is_empty() {+ let context = browser_state().context_for_url(url.as_str());// Extension couldn't supply cookies — show the v20 card.let payload = V20CookieBlockPayload {url: url.as_str().to_string(),@@ -1227,7 +1395,8 @@ async fn inject_cookies_for_url(app: &AppHandle, url: &url::Url) {v20_count: block.v20_count,sources: block.sources,reason: "v20".to_string(),- owner: browser_state().pending_owner(),+ navigation_id: context.as_ref().map(|ctx| ctx.navigation_id.clone()),+ owner: context.and_then(|ctx| ctx.owner),};if let Err(e) = app.emit(V20_COOKIE_BLOCK_EVENT, payload) {warn!("owned-browser cookies: failed to emit v20 block event: {e}");@@ -1439,6 +1608,7 @@ async fn browser_session_decision_for_url();return BrowserSessionDecision::UseBrowserSession;}+ let context = browser_state().context_for_url(url.as_str());let payload = V20CookieBlockPayload {url: url.as_str().to_string(),host: block.host,@@ -1446,7 +1616,8 @@ async fn browser_session_decision_for_url(v20_count: 0,sources: block.sources,reason: "locked".to_string(),- owner: browser_state().pending_owner(),+ navigation_id: context.as_ref().map(|ctx| ctx.navigation_id.clone()),+ owner: context.and_then(|ctx| ctx.owner),};if let Err(e) = app.emit(V20_COOKIE_BLOCK_EVENT, payload) {warn!("owned-browser: failed to emit locked-browser event: {e}");@@ -1546,12 +1717,14 @@ async fn browser_session_decision_for_url(.await.insert(request_id.clone(), tx);+ let context = browser_state().context_for_url(url.as_str());let payload = BrowserSessionAccessRequestPayload {request_id: request_id.clone(),url: url.as_str().to_string(),host: host_key.clone(),already_granted,- owner: browser_state().pending_owner(),+ navigation_id: context.as_ref().map(|ctx| ctx.navigation_id.clone()),+ owner: context.and_then(|ctx| ctx.owner),};if let Err(e) = app.emit(SESSION_ACCESS_REQUEST_EVENT, payload) {