Skip to content

refactor(desktop): Make browser tabs persistent - #1535

Merged
saddlepaddle merged 4 commits into
mainfrom
browser-use
Feb 17, 2026
Merged

saddlepaddle merged 4 commits into
mainfrom
browser-use

Conversation

@saddlepaddle

@saddlepaddle saddlepaddle commented Feb 17, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Reverts browser panes from Electron WebContentsView (native OS overlay that always renders above DOM) back to <webview> tags with persistent DOM reparenting
  • Webviews are parked in a hidden off-screen container on tab switch instead of destroyed, preserving page state without reloads
  • Fixes z-ordering: tooltips, popovers, and dropdowns now render correctly above browser content
  • Simplifies browser-manager from full lifecycle owner to a lightweight paneId→webContentsId registry
  • Simplifies tRPC browser router by removing create/destroy/setBounds/setVisibility procedures
  • New usePersistentWebview hook replaces useBrowserNavigation with direct webview DOM management

Bugs fixed

  1. Hidden container too small — parked webviews shrank to 1x1px, breaking capturePage() screenshots
  2. Missing allowpopups — target="_blank" links silently failed without this webview attribute
  3. partition as property — must be set via setAttribute, not property assignment
  4. Missing sanitizeUrl in navigate() — agent-triggered raw URLs (e.g. "google.com") weren't sanitized
  5. Stale webContentsId — changed from Set to Map<paneId, webContentsId> to detect ID changes after DOM reparenting
  6. DevTools CDP type mismatch — <webview> targets have type: "webview", not "page"
  7. DevTools fragile URL matching — added fallback matching strategies + retry polling in DevToolsPane
  8. Tab title never updating — updateBrowserUrl/navigateBrowserHistory now propagate name to tab via deriveTabName
  9. No isDestroyed() safety — getWebContents now checks wc.isDestroyed() before returning

Test plan

  • Open browser tab, navigate to a URL — page loads correctly
  • Switch to another tab and back — browser state preserved (no reload)
  • Hover sidebar near browser content — tooltips/popovers render above browser
  • Click back/forward buttons — history navigation works, tab title updates
  • Open DevTools pane — inspector loads and inspects the browser webview
  • Close browser tab — webview destroyed, no leaks
  • Agent tRPC navigate/screenshot/evaluateJS on hidden browser tab

Summary by CodeRabbit

  • New Features

    • Persistent webview system for improved browser stability and state retention
    • Automatic URL sanitization supporting multiple URL formats
    • Lifecycle hook to auto-tear down removed webview panes
  • Bug Fixes

    • More reliable DevTools detection via polling
    • Improved browser pane cleanup on pane removal and window close
    • Clipboard "Copy URL" now reads current tab URL from state
  • Refactor

    • Centralized navigation handling for consistent behavior
    • Tab names now derived from synchronized browser state

@coderabbitai

coderabbitai Bot commented Feb 17, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Centralizes navigation in BrowserManager.navigate; replaces the old per-pane useBrowserNavigation with a persistent webview hook and registry; adds renderer lifecycle to destroy/unregister removed panes; updates tabs store to derive tab names from pane state; improves DevTools polling; loads MCP env via dotenv and refines CDP page selection.

Changes

Cohort / File(s) Summary
Router → BrowserManager
apps/desktop/src/lib/trpc/routers/browser/browser.ts
Replaced inline webContents load with browserManager.navigate(paneId, url) delegation.
Browser manager (main process)
apps/desktop/src/main/lib/browser/browser-manager.ts
Renamed pane map, added sanitizeUrl, navigate, unregisterAll, getWebContents; consolidated console/window-open handlers; improved DevTools target matching and defensive WebContents handling.
Main window shutdown
apps/desktop/src/main/windows/main.ts
Calls browserManager.unregisterAll() when main window closes.
Renderer: BrowserPane UI
apps/desktop/src/renderer/.../BrowserPane/BrowserPane.tsx
Swapped inline <webview> and ref logic for usePersistentWebview and a container div; passes currentUrl as initialUrl.
Removed legacy hook
apps/desktop/src/renderer/.../hooks/useBrowserNavigation/*
Deleted useBrowserNavigation implementation and its re-export.
Persistent webview hook
apps/desktop/src/renderer/.../hooks/usePersistentWebview/*
Added usePersistentWebview and destroyPersistentWebview: global registry, hidden container, event wiring, history syncing, navigation controls, and main-process registration.
Renderer lifecycle
apps/desktop/src/renderer/.../hooks/useBrowserLifecycle/*, apps/desktop/src/renderer/.../WorkspaceLayout/WorkspaceLayout.tsx
Added useBrowserLifecycle to detect removed webview panes, call destroyPersistentWebview and unregister and invoked it from WorkspaceLayout.
Toolbar: URL copy
apps/desktop/src/renderer/.../BrowserOverflowMenu/BrowserOverflowMenu.tsx
Now reads currentUrl from tabs store instead of querying the DOM/webview.
Tabs store updates
apps/desktop/src/renderer/stores/tabs/store.ts
After browser/history updates, derives tab names from updated panes and updates the corresponding tab name consistently across branches.
DevTools polling
apps/desktop/src/renderer/.../DevToolsPane/DevToolsPane.tsx
Added 1s polling until DevTools URL becomes available.
MCP env & connection
packages/desktop-mcp/package.json, packages/desktop-mcp/src/bin.ts, packages/desktop-mcp/src/mcp/connection/connection-manager.ts
Added dotenv and root .env loading in bin; refined CDP page selection to prefer http://localhost: or file:// targets and improved error diagnostics.
Dotenv bumps
various package.json files (apps/, packages/)
Bumped dotenv versions and added dependency in desktop-mcp package.json.

Sequence Diagram(s)

sequenceDiagram
    participant Renderer as Renderer Process
    participant Hook as usePersistentWebview
    participant Registry as Webview Registry
    participant BM as BrowserManager (Main)
    participant WC as WebContents

    Renderer->>Hook: mount(paneId, initialUrl)
    Hook->>Registry: reclaim or create webview for paneId
    Hook->>BM: register(paneId, webContentsId)
    BM->>WC: webContents.fromId(webContentsId)
    BM->>WC: disableBackgroundThrottling & setup handlers
    WC-->>Hook: dom-ready / did-navigate events
    Hook->>TabsStore: update currentUrl, history, title, favicon

    User->>Hook: navigateTo(url)
    Hook->>BM: navigate(paneId, url)
    BM->>BM: sanitizeUrl(url)
    BM->>WC: loadURL(sanitizedUrl)
    WC-->>Hook: navigation events
    Hook->>TabsStore: persist history and update UI

    Renderer->>Hook: pane removed
    Hook->>Registry: destroyPersistentWebview(paneId)
    Hook->>BM: unregister(paneId)
    BM->>WC: remove listeners & cleanup mapping
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • Kitenite

Poem

🐇 I stitched webviews that sleep and roam,
A manager guides each browser home,
Hooks tuck history into neat rows,
Tabs wake gently as navigation flows,
Hops of code — a cozy chrome.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'refactor(desktop): Make browser tabs persistent' accurately describes the main change: converting browser panes from WebContentsView back to persistent tags.
Description check ✅ Passed The PR description comprehensively covers the changes, fixes, and test plan. All template sections are present and properly filled: Summary, Bugs fixed, and Test plan. The description exceeds template expectations with detailed technical context.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch browser-use

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

github-actions Bot commented Feb 17, 2026 •

Copy link
Copy Markdown
Contributor

🧹 Preview Cleanup Complete

The following preview resources have been cleaned up:

  • ✅ Neon database branch
  • ✅ Electric Fly.io app
  • ✅ Streams Fly.io app

Thank you for your contribution! 🎉

@saddlepaddle saddlepaddle changed the title refactor(desktop): revert browser panes to persistent webview refactor(desktop): Make browser tabs persistent Feb 17, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/components/BrowserToolbar/BrowserToolbar.tsx (1)

57-60: Unstable onEditingChange reference will cause redundant notifications.

If the parent doesn't wrap onEditingChange in useCallback, every parent render creates a new function reference, re-triggering this effect and calling onEditingChange(isEditing) even when isEditing hasn't changed.

Since the project is on React 19.2, you can use useEffectEvent to stabilise the callback reference without including it in the dependency array:

♻️ Suggested refactor using useEffectEvent
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useEffectEvent, useRef, useState } from "react";
+	const stableOnEditingChange = useEffectEvent((editing: boolean) => {
+		onEditingChange?.(editing);
+	});
+
 	// Notify parent when editing state changes
 	useEffect(() => {
-		onEditingChange?.(isEditing);
-	}, [isEditing, onEditingChange]);
+		stableOnEditingChange(isEditing);
+	}, [isEditing]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/components/BrowserToolbar/BrowserToolbar.tsx`
around lines 57 - 60, The effect calling onEditingChange should not depend on an
unstable parent callback; replace the current useEffect that depends on
[isEditing, onEditingChange] by creating a stable event handler using React's
useEffectEvent (e.g., const handleEditingChange = useEffectEvent((v) =>
onEditingChange?.(v))) and then use a simple useEffect that only depends on
isEditing to call handleEditingChange(isEditing). Update BrowserToolbar to
import useEffectEvent, reference handleEditingChange instead of onEditingChange
inside the effect, and remove onEditingChange from the effect dependency array
to avoid redundant notifications.
packages/desktop-mcp/src/bin.ts (1)

7-9: Relative path assumes execution from source location — fragile if bundled.

import.meta.dirname resolves to the directory of the executing file. If this file is ever compiled/bundled to a different output directory (e.g., dist/), the "../../../.env" traversal will no longer land at the monorepo root. Currently the package.json bin entry points directly at ./src/bin.ts (implying a ts-node/tsx runner), so this works today, but it's worth noting as a maintenance risk.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/desktop-mcp/src/bin.ts` around lines 7 - 9, The current use of
config({ path: resolve(import.meta.dirname, "../../../.env") }) is brittle
because import.meta.dirname + a fixed "../../../.env" assumes source layout and
will break when the file is bundled/moved; change to reliably locate the
monorepo root (and .env) by resolving from a stable anchor instead of a fixed
relative traversal—for example, locate the nearest package.json or monorepo
marker by walking up from import.meta.url (or use a utility like find-up or
pkg-dir) and then call config({ path: resolve(monorepoRootPath, ".env") });
update the code that uses config, resolve, and import.meta.dirname so it
computes monorepoRootPath robustly before passing it to config.
apps/desktop/src/shared/browser-types.ts (1)

1-16: Consider a discriminated union for stronger type narrowing.

Currently all fields are optional regardless of type, so consumers can't rely on e.g. errorCode being present when type === "did-fail-load". A discriminated union would let TypeScript narrow the payload per event type. That said, the flat shape is pragmatic if these events are forwarded as-is from Electron IPC.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop/src/shared/browser-types.ts` around lines 1 - 16,
NavigationEvent currently has a flat shape with all optional fields; change it
to a discriminated union so TypeScript can narrow payloads by the `type` field.
Define per-event interfaces (e.g., DidFailLoadEvent { type: "did-fail-load";
url?: string; errorCode: number; errorDescription?: string; validatedURL?:
string }, PageTitleUpdatedEvent { type: "page-title-updated"; title: string;
url?: string }, etc.) and then export type NavigationEvent = DidFailLoadEvent |
DidStartLoadingEvent | DidStopLoadingEvent | DidNavigateEvent |
DidNavigateInPageEvent | PageTitleUpdatedEvent | PageFaviconUpdatedEvent; update
any consumers of NavigationEvent to leverage the narrowed fields via switch/type
guards on the `type` property.
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/hooks/usePersistentWebview/usePersistentWebview.ts (1)

43-54: Consider explicitly blocking dangerous URI schemes for defense-in-depth.

The current logic happens to neutralize javascript: and data: URIs by falling through to the Google search or https:// prefix paths, but this relies on indirect behavior. An explicit early rejection would be clearer, especially since this handles agent-triggered URLs.

🛡️ Suggested defensive check
 function sanitizeUrl(url: string): string {
+	const trimmed = url.trim();
+	if (/^(javascript|data|vbscript):/i.test(trimmed)) {
+		return "about:blank";
+	}
 	if (/^https?:\/\//i.test(url) || url.startsWith("about:")) {
 		return url;
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/hooks/usePersistentWebview/usePersistentWebview.ts`
around lines 43 - 54, The sanitizeUrl function currently relies on indirect
fallthrough to neutralize dangerous schemes; add an explicit early check in
sanitizeUrl that detects and blocks unsafe schemes (at least "javascript:",
"data:", "vbscript:", and "file:") using a case-insensitive prefix test and
return a safe fallback (e.g., a Google search URL or "about:blank") or throw a
controlled error; update sanitizeUrl to perform this check before the existing
https?/about/localhost/127.0.0.1/ dot logic so malicious agent-triggered URLs
are explicitly rejected.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/desktop/src/main/lib/browser/browser-manager.ts`:
- Around line 12-23: sanitizeUrl currently prepends https:// to inputs that may
already be valid non-http schemes and uses a too-broad dot heuristic; update
sanitizeUrl to first detect any explicit scheme using a regex like /^\w+:\/\//
and return the url unchanged if matched, then refine the localhost branch to
only match exact "localhost" or "localhost:port" (and not "localhost." prefixes)
and prefer http for those, and finally tighten the dot heuristic to only treat
inputs as hostnames if they match a domain-like pattern (e.g., no spaces and a
domain label + TLD or port) before prepending https://; otherwise fall back to
the search URL. Ensure you reference the sanitizeUrl function and the existing
scheme/localhost/dot logic when making the changes.

In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/hooks/usePersistentWebview/usePersistentWebview.ts`:
- Around line 179-215: The issue is that isHistoryNavigation.current is being
consumed (set to false) in multiple handlers causing duplicate history updates;
modify handleDidNavigate so it only reads/checks isHistoryNavigation.current and
returns early if true but does NOT set it to false, and ensure only the terminal
handlers (handleDidStopLoading and handleDidNavigateInPage) perform the reset of
isHistoryNavigation.current = false after handling navigation; reference the
isHistoryNavigation.current flag and the functions handleDidNavigate,
handleDidStopLoading, and handleDidNavigateInPage when making the change.

In `@packages/desktop-mcp/src/mcp/connection/connection-manager.ts`:
- Around line 42-45: The current pages.find predicate (used to set appPage) is
too broad and may match webview tabs that navigate to http://localhost; update
the predicate to first filter out non-app targets (e.g., check p.type() or
p.target()?.type to exclude webview/webcontents and ignore about:blank), then
match only the known app origins: either the exact Vite dev-server port(s)
(check for the configured dev port) or the specific production file:// path used
by the renderer (instead of any file://), and fall back to carefully ordered
heuristics so appPage reliably selects the Electron renderer. Use the
appPage/pages/p.url() symbols when implementing the tighter checks.

---

Nitpick comments:
In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/components/BrowserToolbar/BrowserToolbar.tsx`:
- Around line 57-60: The effect calling onEditingChange should not depend on an
unstable parent callback; replace the current useEffect that depends on
[isEditing, onEditingChange] by creating a stable event handler using React's
useEffectEvent (e.g., const handleEditingChange = useEffectEvent((v) =>
onEditingChange?.(v))) and then use a simple useEffect that only depends on
isEditing to call handleEditingChange(isEditing). Update BrowserToolbar to
import useEffectEvent, reference handleEditingChange instead of onEditingChange
inside the effect, and remove onEditingChange from the effect dependency array
to avoid redundant notifications.

In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/hooks/usePersistentWebview/usePersistentWebview.ts`:
- Around line 43-54: The sanitizeUrl function currently relies on indirect
fallthrough to neutralize dangerous schemes; add an explicit early check in
sanitizeUrl that detects and blocks unsafe schemes (at least "javascript:",
"data:", "vbscript:", and "file:") using a case-insensitive prefix test and
return a safe fallback (e.g., a Google search URL or "about:blank") or throw a
controlled error; update sanitizeUrl to perform this check before the existing
https?/about/localhost/127.0.0.1/ dot logic so malicious agent-triggered URLs
are explicitly rejected.

In `@apps/desktop/src/shared/browser-types.ts`:
- Around line 1-16: NavigationEvent currently has a flat shape with all optional
fields; change it to a discriminated union so TypeScript can narrow payloads by
the `type` field. Define per-event interfaces (e.g., DidFailLoadEvent { type:
"did-fail-load"; url?: string; errorCode: number; errorDescription?: string;
validatedURL?: string }, PageTitleUpdatedEvent { type: "page-title-updated";
title: string; url?: string }, etc.) and then export type NavigationEvent =
DidFailLoadEvent | DidStartLoadingEvent | DidStopLoadingEvent | DidNavigateEvent
| DidNavigateInPageEvent | PageTitleUpdatedEvent | PageFaviconUpdatedEvent;
update any consumers of NavigationEvent to leverage the narrowed fields via
switch/type guards on the `type` property.

In `@packages/desktop-mcp/src/bin.ts`:
- Around line 7-9: The current use of config({ path:
resolve(import.meta.dirname, "../../../.env") }) is brittle because
import.meta.dirname + a fixed "../../../.env" assumes source layout and will
break when the file is bundled/moved; change to reliably locate the monorepo
root (and .env) by resolving from a stable anchor instead of a fixed relative
traversal—for example, locate the nearest package.json or monorepo marker by
walking up from import.meta.url (or use a utility like find-up or pkg-dir) and
then call config({ path: resolve(monorepoRootPath, ".env") }); update the code
that uses config, resolve, and import.meta.dirname so it computes
monorepoRootPath robustly before passing it to config.

Comment on lines +12 to +23
function sanitizeUrl(url: string): string {
if (/^https?:\/\//i.test(url) || url.startsWith("about:")) {
return url;
}
if (url.startsWith("localhost") || url.startsWith("127.0.0.1")) {
return `http://${url}`;
}
if (url.includes(".")) {
return `https://${url}`;
}
return `https://www.google.com/search?q=${encodeURIComponent(url)}`;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

sanitizeUrl doesn't handle non-http(s) schemes and has edge cases with the dot heuristic.

  1. URLs with valid schemes like file://, data:, or custom app protocols will get https:// prepended.
  2. url.includes(".") on line 19 will match search-like inputs containing dots (e.g., "node v22.1" → https://node v22.1).
  3. localhost.example.com would match the startsWith("localhost") check and get http:// instead of https://.

Consider adding a scheme-detection pass (e.g., /^\w+:\/\//) before the localhost/dot heuristics.

Suggested improvement
 function sanitizeUrl(url: string): string {
-	if (/^https?:\/\//i.test(url) || url.startsWith("about:")) {
+	// Allow any explicit scheme through (http, https, file, data, etc.)
+	if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//i.test(url) || url.startsWith("about:") || url.startsWith("data:")) {
 		return url;
 	}
 	if (url.startsWith("localhost") || url.startsWith("127.0.0.1")) {
 		return `http://${url}`;
 	}
-	if (url.includes(".")) {
+	// Only treat as a URL if it looks like a hostname (no spaces, has a dot)
+	if (!url.includes(" ") && url.includes(".")) {
 		return `https://${url}`;
 	}
 	return `https://www.google.com/search?q=${encodeURIComponent(url)}`;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function sanitizeUrl(url: string): string {
if (/^https?:\/\//i.test(url) || url.startsWith("about:")) {
return url;
}
if (url.startsWith("localhost") || url.startsWith("127.0.0.1")) {
return `http://${url}`;
}
if (url.includes(".")) {
return `https://${url}`;
}
return `https://www.google.com/search?q=${encodeURIComponent(url)}`;
}
function sanitizeUrl(url: string): string {
// Allow any explicit scheme through (http, https, file, data, etc.)
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//i.test(url) || url.startsWith("about:") || url.startsWith("data:")) {
return url;
}
if (url.startsWith("localhost") || url.startsWith("127.0.0.1")) {
return `http://${url}`;
}
// Only treat as a URL if it looks like a hostname (no spaces, has a dot)
if (!url.includes(" ") && url.includes(".")) {
return `https://${url}`;
}
return `https://www.google.com/search?q=${encodeURIComponent(url)}`;
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop/src/main/lib/browser/browser-manager.ts` around lines 12 - 23,
sanitizeUrl currently prepends https:// to inputs that may already be valid
non-http schemes and uses a too-broad dot heuristic; update sanitizeUrl to first
detect any explicit scheme using a regex like /^\w+:\/\// and return the url
unchanged if matched, then refine the localhost branch to only match exact
"localhost" or "localhost:port" (and not "localhost." prefixes) and prefer http
for those, and finally tighten the dot heuristic to only treat inputs as
hostnames if they match a domain-like pattern (e.g., no spaces and a domain
label + TLD or port) before prepending https://; otherwise fall back to the
search URL. Ensure you reference the sanitizeUrl function and the existing
scheme/localhost/dot logic when making the changes.

Comment on lines +179 to +215
if (isHistoryNavigation.current) {
isHistoryNavigation.current = false;
return;
}

const url = wv.getURL();
const title = wv.getTitle();
store.updateBrowserUrl(
paneId,
url ?? "",
title ?? "",
faviconUrlRef.current,
);

if (url && url !== "about:blank") {
upsertHistory({
url,
title: title ?? "",
faviconUrl: faviconUrlRef.current ?? null,
});
}
};

const handleDidNavigate = (e: Electron.DidNavigateEvent) => {
if (isHistoryNavigation.current) {
isHistoryNavigation.current = false;
return;
}
const store = useTabsStore.getState();
store.updateBrowserUrl(
paneId,
e.url ?? "",
wv.getTitle() ?? "",
faviconUrlRef.current,
);
store.updateBrowserLoading(paneId, false);
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

isHistoryNavigation flag is consumed by the first handler, leaving subsequent handlers unprotected.

During back/forward navigation, the typical Electron event sequence is: did-start-loading → did-navigate → did-stop-loading. Both handleDidNavigate (Line 204) and handleDidStopLoading (Line 180) check and reset isHistoryNavigation.current to false. Whichever fires first consumes the flag, so the later handler sees false and proceeds to call updateBrowserUrl and upsertHistory, creating duplicate history entries.

handleDidNavigate should check the flag but not reset it. Only the terminal handlers (handleDidStopLoading for full navigations, handleDidNavigateInPage for in-page navigations) should reset it.

🐛 Proposed fix
 		const handleDidNavigate = (e: Electron.DidNavigateEvent) => {
-			if (isHistoryNavigation.current) {
-				isHistoryNavigation.current = false;
+			if (isHistoryNavigation.current) {
 				return;
 			}
 			const store = useTabsStore.getState();
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (isHistoryNavigation.current) {
isHistoryNavigation.current = false;
return;
}
const url = wv.getURL();
const title = wv.getTitle();
store.updateBrowserUrl(
paneId,
url ?? "",
title ?? "",
faviconUrlRef.current,
);
if (url && url !== "about:blank") {
upsertHistory({
url,
title: title ?? "",
faviconUrl: faviconUrlRef.current ?? null,
});
}
};
const handleDidNavigate = (e: Electron.DidNavigateEvent) => {
if (isHistoryNavigation.current) {
isHistoryNavigation.current = false;
return;
}
const store = useTabsStore.getState();
store.updateBrowserUrl(
paneId,
e.url ?? "",
wv.getTitle() ?? "",
faviconUrlRef.current,
);
store.updateBrowserLoading(paneId, false);
};
const handleDidNavigate = (e: Electron.DidNavigateEvent) => {
if (isHistoryNavigation.current) {
return;
}
const store = useTabsStore.getState();
store.updateBrowserUrl(
paneId,
e.url ?? "",
wv.getTitle() ?? "",
faviconUrlRef.current,
);
store.updateBrowserLoading(paneId, false);
};
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/hooks/usePersistentWebview/usePersistentWebview.ts`
around lines 179 - 215, The issue is that isHistoryNavigation.current is being
consumed (set to false) in multiple handlers causing duplicate history updates;
modify handleDidNavigate so it only reads/checks isHistoryNavigation.current and
returns early if true but does NOT set it to false, and ensure only the terminal
handlers (handleDidStopLoading and handleDidNavigateInPage) perform the reset of
isHistoryNavigation.current = false after handling navigation; reference the
isHistoryNavigation.current flag and the functions handleDidNavigate,
handleDidStopLoading, and handleDidNavigateInPage when making the change.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (4)
apps/desktop/src/main/lib/browser/browser-manager.ts (1)

64-68: unregisterAll should also remove emitter listeners to prevent leaks.

unregister cleans up console listeners and map entries, but event listeners registered on the BrowserManager emitter itself (e.g., new-window:${paneId}, console:${paneId}) are never removed. Over the app's lifetime, if panes are repeatedly created and destroyed, these listeners accumulate.

Suggested fix
 unregister(paneId: string): void {
 	const cleanup = this.consoleListeners.get(paneId);
 	if (cleanup) {
 		cleanup();
 		this.consoleListeners.delete(paneId);
 	}
 	this.paneWebContentsIds.delete(paneId);
 	this.consoleLogs.delete(paneId);
+	this.removeAllListeners(`new-window:${paneId}`);
+	this.removeAllListeners(`console:${paneId}`);
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop/src/main/lib/browser/browser-manager.ts` around lines 64 - 68,
unregisterAll currently iterates paneWebContentsIds and calls unregister but
does not remove event listeners on the BrowserManager emitter, causing leaks;
update unregisterAll (or inside unregister) to remove the emitter listeners tied
to each paneId (e.g., remove listener for `new-window:${paneId}`,
`console:${paneId}` and any other `:${paneId}` events) by calling
emitter.removeListener or emitter.removeAllListeners for those specific event
names before deleting map entries (reference methods unregisterAll, unregister,
paneWebContentsIds, and the emitter instance used in this class).
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/hooks/usePersistentWebview/usePersistentWebview.ts (3)

128-152: On reclaim, stale initialUrlRef could cause issues if initialUrl prop changed.

initialUrlRef is captured once (line 72) and never updated. If the component is remounted with a different initialUrl for the same paneId (e.g., an existing webview being reclaimed), the new initialUrl is ignored since the webview already exists. This is likely intentional (the webview preserves its own state), but worth confirming that the currentUrl passed from BrowserPane is always in sync with the webview's actual URL.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/hooks/usePersistentWebview/usePersistentWebview.ts`
around lines 128 - 152, The reclaim branch can ignore a new initialUrl because
initialUrlRef is only set once; update initialUrlRef when the initialUrl prop
changes or, safer, use the currentUrl/currentUrl prop passed from BrowserPane
when re-attaching an existing webview so the reclaimed webview gets the intended
URL. Concretely, in the effect that references paneId, webviewRegistry,
syncStoreFromWebview and sanitizeUrl, refresh initialUrlRef.current (or read the
incoming currentUrl prop) before deciding to append the existing webview and, if
the URL differs from webview.src, set webview.src = sanitizeUrl(newUrl) so the
reclaimed webview reflects the latest requested URL.

43-54: Duplicate sanitizeUrl implementation across main and renderer processes.

This is an exact copy of the sanitizeUrl in browser-manager.ts. Consider extracting it into a shared module (e.g., under shared/) to keep the logic in one place.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/hooks/usePersistentWebview/usePersistentWebview.ts`
around lines 43 - 54, The sanitizeUrl function is duplicated; extract the logic
into a single shared module (e.g., create a new exported sanitizeUrl in a shared
utilities file) and replace the local sanitizeUrl definitions in both
usePersistentWebview.ts and browser-manager.ts with imports from that shared
module, preserving the exact behavior and string return type; ensure you export
the function (named export) from the shared file and update both files' imports
to use that symbol, then remove the duplicated implementations.

242-261: handlePageFaviconUpdated triggers upsertHistory on every favicon change.

Each time a favicon is updated (which can happen multiple times per page load as different favicon sizes are discovered), this calls upsertHistory. If upsertHistory is not idempotent or debounced, this could generate unnecessary IPC calls. Consider debouncing or only calling upsertHistory when the favicon URL actually changes from the previously stored value.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/hooks/usePersistentWebview/usePersistentWebview.ts`
around lines 242 - 261, handlePageFaviconUpdated currently calls upsertHistory
for every favicon event; change it to only call upsertHistory when the chosen
favicon actually changes (compare favicons[0] to faviconUrlRef.current or the
stored pane favicon) or implement a short debounce using a ref timer to coalesce
rapid updates. Update the logic inside handlePageFaviconUpdated (and keep
faviconUrlRef.current and store.updateBrowserUrl behavior) so you first check if
the new favicon differs before calling upsertHistory (or queue the call with a
debounced timeout), thereby preventing redundant IPC calls.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@apps/desktop/src/main/lib/browser/browser-manager.ts`:
- Around line 12-23: sanitizeUrl currently mis-classifies inputs with non-http
schemes (file:, data:, etc.) and treats any string with a dot as a hostname
(e.g., "node v22.1"). Update sanitizeUrl to first detect and return any existing
scheme using a generic scheme regex like /^[a-z][a-z0-9+.-]*:/i (so file:,
data:, about:, http:, https: pass through), then keep the existing explicit
checks for "http(s)://" and "about:", and treat hostnames only when the input
matches a hostname pattern (no spaces and a domain-like regex such as
/^[a-z0-9.-]+\.[a-z]{2,}$/i or allow exact matches "localhost" / "127.0.0.1");
otherwise fall back to returning a Google search URL. Apply these changes inside
the sanitizeUrl function.

In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/hooks/usePersistentWebview/usePersistentWebview.ts`:
- Around line 179-215: The two handlers handleDidStopLoading and
handleDidNavigate race on the shared isHistoryNavigation.current flag; replace
the direct reads/resets with a single atomic consumer helper (e.g., function
consumeIsHistoryNavigation() that returns true if the flag was set and clears
it) and call that helper at the start of both handlers so only the first
consumer proceeds; update both handlers to use consumeIsHistoryNavigation()
instead of directly checking/setting isHistoryNavigation.current, leaving the
rest of the logic (store.updateBrowserUrl, upsertHistory,
store.updateBrowserLoading) unchanged.

---

Nitpick comments:
In `@apps/desktop/src/main/lib/browser/browser-manager.ts`:
- Around line 64-68: unregisterAll currently iterates paneWebContentsIds and
calls unregister but does not remove event listeners on the BrowserManager
emitter, causing leaks; update unregisterAll (or inside unregister) to remove
the emitter listeners tied to each paneId (e.g., remove listener for
`new-window:${paneId}`, `console:${paneId}` and any other `:${paneId}` events)
by calling emitter.removeListener or emitter.removeAllListeners for those
specific event names before deleting map entries (reference methods
unregisterAll, unregister, paneWebContentsIds, and the emitter instance used in
this class).

In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/hooks/usePersistentWebview/usePersistentWebview.ts`:
- Around line 128-152: The reclaim branch can ignore a new initialUrl because
initialUrlRef is only set once; update initialUrlRef when the initialUrl prop
changes or, safer, use the currentUrl/currentUrl prop passed from BrowserPane
when re-attaching an existing webview so the reclaimed webview gets the intended
URL. Concretely, in the effect that references paneId, webviewRegistry,
syncStoreFromWebview and sanitizeUrl, refresh initialUrlRef.current (or read the
incoming currentUrl prop) before deciding to append the existing webview and, if
the URL differs from webview.src, set webview.src = sanitizeUrl(newUrl) so the
reclaimed webview reflects the latest requested URL.
- Around line 43-54: The sanitizeUrl function is duplicated; extract the logic
into a single shared module (e.g., create a new exported sanitizeUrl in a shared
utilities file) and replace the local sanitizeUrl definitions in both
usePersistentWebview.ts and browser-manager.ts with imports from that shared
module, preserving the exact behavior and string return type; ensure you export
the function (named export) from the shared file and update both files' imports
to use that symbol, then remove the duplicated implementations.
- Around line 242-261: handlePageFaviconUpdated currently calls upsertHistory
for every favicon event; change it to only call upsertHistory when the chosen
favicon actually changes (compare favicons[0] to faviconUrlRef.current or the
stored pane favicon) or implement a short debounce using a ref timer to coalesce
rapid updates. Update the logic inside handlePageFaviconUpdated (and keep
faviconUrlRef.current and store.updateBrowserUrl behavior) so you first check if
the new favicon differs before calling upsertHistory (or queue the call with a
debounced timeout), thereby preventing redundant IPC calls.

…WebContentsView

WebContentsView renders as a native OS overlay that always sits above DOM content,
breaking tooltips, popovers, and dropdowns. This reverts to <webview> tags with a
persistent reparenting strategy: webviews are parked in a hidden off-screen container
on tab switch instead of being destroyed, preserving page state across tab switches
while allowing normal DOM z-ordering.

Key changes:
- New usePersistentWebview hook replaces useBrowserNavigation
- browser-manager simplified from lifecycle owner to lightweight registry
- tRPC browser router simplified (remove create/destroy/setBounds/setVisibility)
- DevTools CDP target matching made robust with fallback strategies + retry polling
- Tab title now updates on navigation via deriveTabName propagation
- Fixes: hidden container sizing, partition attribute, allowpopups, sanitizeUrl,
  stale webContentsId detection, CDP target type matching for webview
- Remove unused browser-types.ts (NavigationEvent type never imported)
- Remove unused onEditingChange prop from BrowserToolbar (was for WebContentsView visibility toggle)
- Use Zustand store for Copy URL instead of tRPC getPageInfo query (avoids unnecessary IPC round-trip)

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (3)
packages/desktop-mcp/src/bin.ts (1)

7-9: Hardcoded relative path to .env is fragile.

The "../../../.env" path is coupled to the exact depth of this file within the monorepo. If desktop-mcp is ever relocated or nested differently, this silently fails to load any env vars. Consider deriving the monorepo root dynamically (e.g., walking up to find the root package.json or using a workspace-root utility), or at minimum logging a warning when the file is absent.

💡 Optional: add a diagnostic when .env is missing
-config({ path: resolve(import.meta.dirname, "../../../.env") });
+const envPath = resolve(import.meta.dirname, "../../../.env");
+const result = config({ path: envPath });
+if (result.error) {
+  console.error(`[desktop-mcp] Failed to load .env from ${envPath}: ${result.error.message}`);
+}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/desktop-mcp/src/bin.ts` around lines 7 - 9, The hardcoded path
"resolve(import.meta.dirname, '../../../.env')" is fragile; update the startup
to locate the monorepo root dynamically (e.g., walk up from import.meta.dirname
looking for a root marker like package.json or use a find-up/workspace-root
utility) and call config({ path }) with the discovered .env path; if no .env is
found, do not silently fail—emit a warning via the same logger (or console.warn)
so missing environment files are visible. Use the existing
resolve/import.meta.dirname context and change only the path resolution and add
the absent-file diagnostic around the config call.
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/BrowserPane.tsx (1)

118-119: Minor: redundant sizing on the container div.

The container div has className="w-full h-full" (width/height 100%) and also style={{ flex: 1 }}. Since the parent is flex flex-1, flex: 1 alone would suffice, or w-full h-full alone. Not a functional issue.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/BrowserPane.tsx`
around lines 118 - 119, The container div inside BrowserPane uses redundant
sizing: it sets className="w-full h-full" and style={{ flex: 1 }} while its
parent is already a flex child; update the element referenced by containerRef in
BrowserPane.tsx to use a single sizing approach—either remove the inline style
and rely on the Tailwind classes (w-full h-full) or remove the Tailwind classes
and keep style={{ flex: 1 }}—so only one sizing mechanism remains.
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/hooks/usePersistentWebview/usePersistentWebview.ts (1)

9-12: Module-level mutable singletons won't survive HMR and aren't cleaned up on app teardown.

webviewRegistry and registeredWebContentsIds are module-scoped Maps. During development with hot module replacement, a new module instance is created but the old webview DOM elements remain orphaned in the hidden container. This is a dev-only annoyance (not a production issue), but worth a // NOTE: comment or an import.meta.hot?.dispose handler if the framework supports it.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/hooks/usePersistentWebview/usePersistentWebview.ts`
around lines 9 - 12, The module-level Maps webviewRegistry and
registeredWebContentsIds and the hiddenContainer DOM reference are mutable
singletons that persist across HMR and can orphan webview elements; add cleanup
to avoid leaking: either add a clear NOTE comment and/or register an
import.meta.hot?.dispose handler that iterates webviewRegistry and
removes/destroys any orphaned Electron.WebviewTag DOM nodes, clears
webviewRegistry and registeredWebContentsIds, and nulls hiddenContainer;
reference the symbols webviewRegistry, registeredWebContentsIds, hiddenContainer
and put the dispose/cleanup next to their declarations or in the module init
path.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/desktop/src/main/lib/browser/browser-manager.ts`:
- Around line 125-148: The Strategy 3 fallback (the block that sets target when
webviewOnly.length === 1 using webviewTargets/webviewOnly and targetUrl) can
pick a webview from a different pane; update this fallback to prefer a webview
whose target.id or target.webContentsId matches a known pane webContents id
(compare target.id or target.webContentsId against paneWebContentsIds) before
returning the single webview, and only fall back to the lone webview if no
matching webContentsId is found; use the existing symbols webviewTargets,
targetUrl, webviewOnly, target.id/target.webContentsId and paneWebContentsIds to
implement the comparison.
- Around line 30-51: The register() method can leak console listeners when
called with the same webContentsId because setupConsoleCapture(paneId, wc) is
called unconditionally; modify register so it always removes any existing
listener for paneId before attaching a new one: lookup
this.consoleListeners.get(paneId), call the cleanup() and
this.consoleListeners.delete(paneId) if present (regardless of prevId ===
webContentsId), then set this.paneWebContentsIds.set(paneId, webContentsId),
obtain wc via webContents.fromId and call setupConsoleCapture(paneId, wc) as
before; this ensures old handlers are removed and prevents leaks tied to
paneId/webContentsId re-registration.

In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/hooks/usePersistentWebview/usePersistentWebview.ts`:
- Around line 43-54: The sanitizeUrl implementation is duplicated (sanitizeUrl
in usePersistentWebview.ts and the same function in browser-manager.ts); extract
this logic into a single shared utility module (e.g., src/shared/sanitizeUrl or
src/lib/urlUtils) that exports sanitizeUrl, then remove the local copies and
update usePersistentWebview.ts and browser-manager.ts to import and use the
shared sanitizeUrl; ensure exports are typed the same and adjust imports, run
build/tests to verify no breakage.

---

Duplicate comments:
In `@apps/desktop/src/main/lib/browser/browser-manager.ts`:
- Around line 12-23: sanitizeUrl currently treats any input containing a dot as
a URL and ignores non-http(s) schemes; update sanitizeUrl to first detect any
explicit scheme (e.g., match /^[a-z][a-z0-9+.-]*:/i or use URL parsing) and
return the input unchanged for valid schemes like file:, data:, about:,
javascript:, etc.; if no scheme, handle localhost/127.0.0.1 by prepending
"http://"; otherwise attempt to create a new URL by prepending "https://" and
validate that the resulting URL's hostname is a valid domain (no spaces,
hostname contains a dot or is a valid IP) before returning it; if validation
fails, return a Google search URL with encodeURIComponent; refer to the
sanitizeUrl function to implement these checks and fallbacks.

In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/hooks/usePersistentWebview/usePersistentWebview.ts`:
- Around line 202-215: handleDidNavigate currently consumes the
isHistoryNavigation flag (isHistoryNavigation.current = false) leaving
handleDidStopLoading unprotected and causing unnecessary upsertHistory IPC calls
on back/forward navigation; modify handleDidStopLoading to first check
isHistoryNavigation.current and if true clear it (isHistoryNavigation.current =
false) and return early before calling updateBrowserUrl/upsertHistory, so only
one handler consumes the flag and navigation history upserts are suppressed for
history navigations; reference isHistoryNavigation, handleDidNavigate,
handleDidStopLoading, updateBrowserUrl and the upsertHistory IPC call to locate
the changes.

---

Nitpick comments:
In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/BrowserPane.tsx`:
- Around line 118-119: The container div inside BrowserPane uses redundant
sizing: it sets className="w-full h-full" and style={{ flex: 1 }} while its
parent is already a flex child; update the element referenced by containerRef in
BrowserPane.tsx to use a single sizing approach—either remove the inline style
and rely on the Tailwind classes (w-full h-full) or remove the Tailwind classes
and keep style={{ flex: 1 }}—so only one sizing mechanism remains.

In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/hooks/usePersistentWebview/usePersistentWebview.ts`:
- Around line 9-12: The module-level Maps webviewRegistry and
registeredWebContentsIds and the hiddenContainer DOM reference are mutable
singletons that persist across HMR and can orphan webview elements; add cleanup
to avoid leaking: either add a clear NOTE comment and/or register an
import.meta.hot?.dispose handler that iterates webviewRegistry and
removes/destroys any orphaned Electron.WebviewTag DOM nodes, clears
webviewRegistry and registeredWebContentsIds, and nulls hiddenContainer;
reference the symbols webviewRegistry, registeredWebContentsIds, hiddenContainer
and put the dispose/cleanup next to their declarations or in the module init
path.

In `@packages/desktop-mcp/src/bin.ts`:
- Around line 7-9: The hardcoded path "resolve(import.meta.dirname,
'../../../.env')" is fragile; update the startup to locate the monorepo root
dynamically (e.g., walk up from import.meta.dirname looking for a root marker
like package.json or use a find-up/workspace-root utility) and call config({
path }) with the discovered .env path; if no .env is found, do not silently
fail—emit a warning via the same logger (or console.warn) so missing environment
files are visible. Use the existing resolve/import.meta.dirname context and
change only the path resolution and add the absent-file diagnostic around the
config call.

Comment on lines 30 to +51
register(paneId: string, webContentsId: number): void {
this.paneToWebContentsId.set(paneId, webContentsId);
this.setupConsoleCapture(paneId, webContentsId);
this.setupWindowOpenHandler(paneId, webContentsId);
// Clean up previous console listener if re-registering with a new webContentsId
const prevId = this.paneWebContentsIds.get(paneId);
if (prevId != null && prevId !== webContentsId) {
const cleanup = this.consoleListeners.get(paneId);
if (cleanup) {
cleanup();
this.consoleListeners.delete(paneId);
}
}
this.paneWebContentsIds.set(paneId, webContentsId);
const wc = webContents.fromId(webContentsId);
if (wc) {
wc.setBackgroundThrottling(false);
wc.setWindowOpenHandler(({ url }) => {
if (url && url !== "about:blank") {
this.emit(`new-window:${paneId}`, url);
}
return { action: "deny" as const };
});
this.setupConsoleCapture(paneId, wc);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Console listener leak when re-registering with the same webContentsId.

When register() is called with the same paneId and the same webContentsId (e.g., repeated mount/unmount without the webContents changing), the guard on line 33 skips cleanup because prevId === webContentsId. However, setupConsoleCapture on line 50 is still called unconditionally, attaching a new console-message handler and overwriting the cleanup function in consoleListeners — leaking the previous handler.

Either always clean up the previous listener before re-attaching, or skip setupConsoleCapture when the ID hasn't changed:

Proposed fix
 	register(paneId: string, webContentsId: number): void {
-		// Clean up previous console listener if re-registering with a new webContentsId
-		const prevId = this.paneWebContentsIds.get(paneId);
-		if (prevId != null && prevId !== webContentsId) {
-			const cleanup = this.consoleListeners.get(paneId);
-			if (cleanup) {
-				cleanup();
-				this.consoleListeners.delete(paneId);
-			}
+		// Always clean up previous console listener before re-registering
+		const cleanup = this.consoleListeners.get(paneId);
+		if (cleanup) {
+			cleanup();
+			this.consoleListeners.delete(paneId);
 		}
 		this.paneWebContentsIds.set(paneId, webContentsId);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop/src/main/lib/browser/browser-manager.ts` around lines 30 - 51,
The register() method can leak console listeners when called with the same
webContentsId because setupConsoleCapture(paneId, wc) is called unconditionally;
modify register so it always removes any existing listener for paneId before
attaching a new one: lookup this.consoleListeners.get(paneId), call the
cleanup() and this.consoleListeners.delete(paneId) if present (regardless of
prevId === webContentsId), then set this.paneWebContentsIds.set(paneId,
webContentsId), obtain wc via webContents.fromId and call
setupConsoleCapture(paneId, wc) as before; this ensures old handlers are removed
and prevents leaks tied to paneId/webContentsId re-registration.

Comment on lines +125 to +148
const webviewTargets = targets.filter(
(t) => t.type === "page" || t.type === "webview",
);

// Strategy 1: Exact URL match
let target = webviewTargets.find((t) => t.url === targetUrl);

// Strategy 2: Match ignoring trailing slash / fragment differences
if (!target && targetUrl) {
const normalize = (u: string) =>
u.replace(/\/?(#.*)?$/, "").toLowerCase();
const normalizedTarget = normalize(targetUrl);
target = webviewTargets.find(
(t) => normalize(t.url) === normalizedTarget,
);
}

// Strategy 3: If only one webview target exists, use it
if (!target) {
const webviewOnly = webviewTargets.filter((t) => t.type === "webview");
if (webviewOnly.length === 1) {
target = webviewOnly[0];
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Strategy 3 fallback may match the wrong webview when multiple browser panes are open.

If the URL-based strategies fail (e.g., a redirect changed the URL after wc.getURL() was captured) and there happens to be exactly one type: "webview" target among all panes, this fallback returns it — even if it belongs to a different pane. This is a narrow race but could surface DevTools for the wrong page.

Consider also matching by webContentsId from the target's id field or comparing against the known webContentsId from paneWebContentsIds as a more reliable fallback.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop/src/main/lib/browser/browser-manager.ts` around lines 125 - 148,
The Strategy 3 fallback (the block that sets target when webviewOnly.length ===
1 using webviewTargets/webviewOnly and targetUrl) can pick a webview from a
different pane; update this fallback to prefer a webview whose target.id or
target.webContentsId matches a known pane webContents id (compare target.id or
target.webContentsId against paneWebContentsIds) before returning the single
webview, and only fall back to the lone webview if no matching webContentsId is
found; use the existing symbols webviewTargets, targetUrl, webviewOnly,
target.id/target.webContentsId and paneWebContentsIds to implement the
comparison.

Comment on lines +43 to +54
function sanitizeUrl(url: string): string {
if (/^https?:\/\//i.test(url) || url.startsWith("about:")) {
return url;
}
if (url.startsWith("localhost") || url.startsWith("127.0.0.1")) {
return `http://${url}`;
}
if (url.includes(".")) {
return `https://${url}`;
}
return `https://www.google.com/search?q=${encodeURIComponent(url)}`;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Duplicate sanitizeUrl — same function exists in browser-manager.ts (main process).

This is a copy of the same function from apps/desktop/src/main/lib/browser/browser-manager.ts (lines 12–23). Consider extracting it into a shared utility under src/shared/ or src/lib/ so both main and renderer processes import the same implementation. This avoids divergence as one copy gets updated but the other doesn't.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/BrowserPane/hooks/usePersistentWebview/usePersistentWebview.ts`
around lines 43 - 54, The sanitizeUrl implementation is duplicated (sanitizeUrl
in usePersistentWebview.ts and the same function in browser-manager.ts); extract
this logic into a single shared utility module (e.g., src/shared/sanitizeUrl or
src/lib/urlUtils) that exports sanitizeUrl, then remove the local copies and
update usePersistentWebview.ts and browser-manager.ts to import and use the
shared sanitizeUrl; ensure exports are typed the same and adjust imports, run
build/tests to verify no breakage.

@saddlepaddle
saddlepaddle merged commit 6eb9bf6 into main Feb 17, 2026
15 checks passed
Kitenite added a commit that referenced this pull request Feb 18, 2026
The persistent webview refactor (#1535) introduced two issues that
prevented the browser pane from loading/rendering images:

1. Missing display styling on programmatically-created webview element.
   The old JSX-rendered <webview> had `display: flex; flex: 1` but the
   new createElement approach only set width/height, causing the custom
   element to default to `display: inline` where dimensions may not
   apply correctly.

2. Restrictive Content Security Policy. The renderer CSP lacked explicit
   `frame-src` (falling back to `default-src 'self'`) which could block
   the webview from loading external content. Also added `http:` and
   `blob:` to `img-src` for full image source compatibility.
Kitenite added a commit that referenced this pull request Feb 19, 2026
The persistent webview refactor (#1535) introduced two issues that
prevented the browser pane from loading/rendering images:

1. Missing display styling on programmatically-created webview element.
   The old JSX-rendered <webview> had `display: flex; flex: 1` but the
   new createElement approach only set width/height, causing the custom
   element to default to `display: inline` where dimensions may not
   apply correctly.

2. Restrictive Content Security Policy. The renderer CSP lacked explicit
   `frame-src` (falling back to `default-src 'self'`) which could block
   the webview from loading external content. Also added `http:` and
   `blob:` to `img-src` for full image source compatibility.
@Kitenite
Kitenite deleted the browser-use branch February 27, 2026 09:29

This branch was previously deployed

1 inactive deployment
preview — b7342f4f Deployed Feb 17, 2026 by saddlepaddle via Deploy Docs #2037
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant