Repository navigation
refactor(desktop): Make browser tabs persistent - #1535
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughCentralizes 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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
🧹 Preview Cleanup CompleteThe following preview resources have been cleaned up:
Thank you for your contribution! 🎉 |
There was a problem hiding this comment.
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: UnstableonEditingChangereference will cause redundant notifications.If the parent doesn't wrap
onEditingChangeinuseCallback, every parent render creates a new function reference, re-triggering this effect and callingonEditingChange(isEditing)even whenisEditinghasn't changed.Since the project is on React 19.2, you can use
useEffectEventto 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.dirnameresolves 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 thepackage.jsonbinentry 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.errorCodebeing present whentype === "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:anddata:URIs by falling through to the Google search orhttps://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.
| 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)}`; | ||
| } |
There was a problem hiding this comment.
sanitizeUrl doesn't handle non-http(s) schemes and has edge cases with the dot heuristic.
- URLs with valid schemes like
file://,data:, or custom app protocols will gethttps://prepended. url.includes(".")on line 19 will match search-like inputs containing dots (e.g.,"node v22.1"→https://node v22.1).localhost.example.comwould match thestartsWith("localhost")check and gethttp://instead ofhttps://.
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.
| 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.
| 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); | ||
| }; |
There was a problem hiding this comment.
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.
| 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.
ee04920 to
d94169b
Compare
d94169b to
87a4e3b
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (4)
apps/desktop/src/main/lib/browser/browser-manager.ts (1)
64-68:unregisterAllshould also remove emitter listeners to prevent leaks.
unregistercleans up console listeners and map entries, but event listeners registered on theBrowserManageremitter 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, staleinitialUrlRefcould cause issues ifinitialUrlprop changed.
initialUrlRefis captured once (line 72) and never updated. If the component is remounted with a differentinitialUrlfor the samepaneId(e.g., an existing webview being reclaimed), the newinitialUrlis ignored since the webview already exists. This is likely intentional (the webview preserves its own state), but worth confirming that thecurrentUrlpassed fromBrowserPaneis 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: DuplicatesanitizeUrlimplementation across main and renderer processes.This is an exact copy of the
sanitizeUrlinbrowser-manager.ts. Consider extracting it into a shared module (e.g., undershared/) 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:handlePageFaviconUpdatedtriggersupsertHistoryon 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. IfupsertHistoryis not idempotent or debounced, this could generate unnecessary IPC calls. Consider debouncing or only callingupsertHistorywhen 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.
87a4e3b to
d25763b
Compare
…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)
d25763b to
b7342f4
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (3)
packages/desktop-mcp/src/bin.ts (1)
7-9: Hardcoded relative path to.envis fragile.The
"../../../.env"path is coupled to the exact depth of this file within the monorepo. Ifdesktop-mcpis 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 rootpackage.jsonor 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 alsostyle={{ flex: 1 }}. Since the parent isflex flex-1,flex: 1alone would suffice, orw-full h-fullalone. 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.
webviewRegistryandregisteredWebContentsIdsare module-scopedMaps. 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 animport.meta.hot?.disposehandler 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.
| 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); | ||
| } |
There was a problem hiding this comment.
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.
| 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]; | ||
| } | ||
| } |
There was a problem hiding this comment.
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.
| 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)}`; | ||
| } |
There was a problem hiding this comment.
🛠️ 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.
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.
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.
Summary
WebContentsView(native OS overlay that always renders above DOM) back to<webview>tags with persistent DOM reparentingbrowser-managerfrom full lifecycle owner to a lightweight paneId→webContentsId registrycreate/destroy/setBounds/setVisibilityproceduresusePersistentWebviewhook replacesuseBrowserNavigationwith direct webview DOM managementBugs fixed
capturePage()screenshotsallowpopups—target="_blank"links silently failed without this webview attributepartitionas property — must be set viasetAttribute, not property assignmentsanitizeUrlin navigate() — agent-triggered raw URLs (e.g. "google.com") weren't sanitizedSettoMap<paneId, webContentsId>to detect ID changes after DOM reparenting<webview>targets havetype: "webview", not"page"updateBrowserUrl/navigateBrowserHistorynow propagate name to tab viaderiveTabNameisDestroyed()safety —getWebContentsnow checkswc.isDestroyed()before returningTest plan
navigate/screenshot/evaluateJSon hidden browser tabSummary by CodeRabbit
New Features
Bug Fixes
Refactor