From 8d5b57f97721ad623c03bec9e8e9074eab0ef438 Mon Sep 17 00:00:00 2001 From: Yuhan Lei Date: Mon, 8 Jun 2026 00:42:31 +0800 Subject: [PATCH 1/8] feat(app): embedded browser tab (WebContentsView) Add a desktop-only "Browser" tab to the session right panel: one app-owned WebContentsView on a persistent partition, driven by a navigation toolbar (back / forward / reload-or-stop, an editable two-tone address bar, and an overflow menu for open-in-system-browser / copy-link / clear-data) plus the prototype's empty, loading, loaded, and clear-data-confirm states. The page lives in the main process and survives tab switches; the renderer owns the DOM chrome and reports the content rect each animation frame while visible, so main sizes/shows the native overlay and hides it on tab switch, panel collapse, or when an app modal / the tab's own menu would paint over it. Security: the view loads only http/https (validated in main), runs on its own partition with no preload, sandboxed and context-isolated, denies all permission requests, and hands non-web schemes to the system browser. The feature is gated on the Electron platform via canUseBrowser(platform) and is absent on web. Part of #1186. Automation (a narrow CDP bridge) and HTML-artifact preview are deliberately out of scope for this PR. --- .../command-palette-default-items.test.ts | 2 + .../command-palette-default-items.ts | 2 +- .../command-palette-search-items.ts | 1 + packages/app/src/context/platform.tsx | 50 ++++ packages/app/src/desktop-api.ts | 4 + packages/app/src/i18n/en.ts | 16 ++ packages/app/src/i18n/zh.ts | 16 ++ .../pages/session/browser/browser-panel.tsx | 269 ++++++++++++++++++ .../app/src/pages/session/browser/url.test.ts | 41 +++ packages/app/src/pages/session/browser/url.ts | 37 +++ .../pages/session/browser/view-state.test.ts | 32 +++ .../src/pages/session/browser/view-state.ts | 34 +++ .../pages/session/right-panel-tab-strip.tsx | 3 + .../app/src/pages/session/right-panel-tabs.ts | 13 +- .../src/pages/session/session-side-panel.tsx | 21 +- .../pages/session/use-session-commands.tsx | 15 + .../src/main/browser/controller.ts | 156 ++++++++++ .../src/main/browser/logic.test.ts | 73 +++++ .../src/main/browser/logic.ts | 64 +++++ .../src/main/browser/options.test.ts | 19 ++ .../src/main/browser/options.ts | 24 ++ packages/desktop-electron/src/main/index.ts | 2 + .../desktop-electron/src/main/ipc/browser.ts | 51 ++++ .../desktop-electron/src/preload/index.ts | 18 ++ .../desktop-electron/src/preload/types.ts | 2 + .../desktop-electron/src/renderer/index.tsx | 4 + 26 files changed, 965 insertions(+), 4 deletions(-) create mode 100644 packages/app/src/pages/session/browser/browser-panel.tsx create mode 100644 packages/app/src/pages/session/browser/url.test.ts create mode 100644 packages/app/src/pages/session/browser/url.ts create mode 100644 packages/app/src/pages/session/browser/view-state.test.ts create mode 100644 packages/app/src/pages/session/browser/view-state.ts create mode 100644 packages/desktop-electron/src/main/browser/controller.ts create mode 100644 packages/desktop-electron/src/main/browser/logic.test.ts create mode 100644 packages/desktop-electron/src/main/browser/logic.ts create mode 100644 packages/desktop-electron/src/main/browser/options.test.ts create mode 100644 packages/desktop-electron/src/main/browser/options.ts create mode 100644 packages/desktop-electron/src/main/ipc/browser.ts diff --git a/packages/app/src/components/command-palette/command-palette-default-items.test.ts b/packages/app/src/components/command-palette/command-palette-default-items.test.ts index e334a0a13..dc1ed7bad 100644 --- a/packages/app/src/components/command-palette/command-palette-default-items.test.ts +++ b/packages/app/src/components/command-palette/command-palette-default-items.test.ts @@ -33,6 +33,7 @@ describe("buildCommandPaletteDefaultGroups", () => { command("panel.toggle"), command("terminal.toggle"), command("review.toggle"), + command("browser.toggle"), command("model.choose"), command("mcp.toggle"), command("permissions.autoaccept"), @@ -54,6 +55,7 @@ describe("buildCommandPaletteDefaultGroups", () => { "panel.toggle", "terminal.toggle", "review.toggle", + "browser.toggle", "model.choose", "mcp.toggle", "permissions.autoaccept", diff --git a/packages/app/src/components/command-palette/command-palette-default-items.ts b/packages/app/src/components/command-palette/command-palette-default-items.ts index 510836a66..fcec36c31 100644 --- a/packages/app/src/components/command-palette/command-palette-default-items.ts +++ b/packages/app/src/components/command-palette/command-palette-default-items.ts @@ -26,7 +26,7 @@ const SUGGESTED_PREFIX = "suggested." const DEFAULT_GROUPS: readonly CommandPaletteDefaultGroup[] = [ { id: "suggested", commandIDs: ["session.new", "project.open", "file.open", "settings.open"] }, { id: "navigation", commandIDs: ["session.previous", "session.next", "input.focus"] }, - { id: "panels", commandIDs: ["sidebar.toggle", "panel.toggle", "terminal.toggle", "review.toggle"] }, + { id: "panels", commandIDs: ["sidebar.toggle", "panel.toggle", "terminal.toggle", "review.toggle", "browser.toggle"] }, { id: "configure", commandIDs: ["model.choose", "mcp.toggle", "permissions.autoaccept"] }, ] diff --git a/packages/app/src/components/command-palette/command-palette-search-items.ts b/packages/app/src/components/command-palette/command-palette-search-items.ts index b05be80f0..dbab321a9 100644 --- a/packages/app/src/components/command-palette/command-palette-search-items.ts +++ b/packages/app/src/components/command-palette/command-palette-search-items.ts @@ -14,6 +14,7 @@ const COMMON_COMMAND_IDS = [ "session.next", "terminal.toggle", "review.toggle", + "browser.toggle", ] as const type SessionTabsAccessor = Accessor<{ diff --git a/packages/app/src/context/platform.tsx b/packages/app/src/context/platform.tsx index e700ffabf..cfd7e1158 100644 --- a/packages/app/src/context/platform.tsx +++ b/packages/app/src/context/platform.tsx @@ -64,6 +64,49 @@ export type RendererDiagnosticInput = { export type RendererDiagnosticsExportResult = { ok: true; path: string } | { ok: false; error: string } +/** A viewport rect in CSS pixels (the renderer's coordinate space). */ +export type BrowserViewRect = { x: number; y: number; width: number; height: number } + +/** Desired presentation of the embedded browser overlay, sent as one unit so + * visibility and bounds never race. `rect` is ignored when `visible` is false. */ +export type BrowserViewLayout = { visible: boolean; rect: BrowserViewRect } + +/** Snapshot of the embedded browser pushed from the main process on every + * navigation/loading change. `hasPage` is false before any successful load, + * which keeps the DOM empty state showing and the native view hidden. */ +export type BrowserState = { + url: string + title: string + canGoBack: boolean + canGoForward: boolean + loading: boolean + favicon: string | null + secure: boolean + hasPage: boolean +} + +/** + * Control surface for the embedded browser (a single app-owned WebContentsView + * with a persistent partition). Desktop/Electron only — undefined on web, where + * there is no native view to drive. Gate usage with `canUseBrowser`. + */ +export type BrowserBridge = { + navigate(url: string): Promise + goBack(): Promise + goForward(): Promise + reload(): Promise + stop(): Promise + /** Report desired visibility + bounds (CSS px). The main process converts to + * device-independent pixels using the window's zoom factor. */ + setView(layout: BrowserViewLayout): Promise + /** Sign out of every site: clear cookies, storage, and cache. */ + clearData(): Promise + /** Read the current state once (used to seed a freshly mounted panel). */ + getState(): Promise + /** Subscribe to state pushes; returns an unsubscribe function. */ + onState(cb: (state: BrowserState) => void): () => void +} + export type Platform = { /** Platform discriminator */ platform: "web" | "desktop" @@ -185,6 +228,9 @@ export type Platform = { /** Read image from clipboard (desktop only) */ readClipboardImage?(): Promise + + /** Embedded browser control surface (desktop only). Gate with `canUseBrowser`. */ + browser?: BrowserBridge } export type DisplayBackend = "auto" | "wayland" @@ -237,6 +283,10 @@ export function canUseNativeFilePicker(platform: Pick) { + return !!platform.browser +} + export const { use: usePlatform, provider: PlatformProvider } = createSimpleContext({ name: "Platform", init: (props: { value: Platform }) => { diff --git a/packages/app/src/desktop-api.ts b/packages/app/src/desktop-api.ts index 2338cbe10..f3d89af32 100644 --- a/packages/app/src/desktop-api.ts +++ b/packages/app/src/desktop-api.ts @@ -1,5 +1,9 @@ export { buildDesktopContext, desktopWindowTitle, type DesktopContext } from "./utils/desktop-context" export type { + BrowserBridge, + BrowserState, + BrowserViewLayout, + BrowserViewRect, RendererDiagnosticInput, RendererDiagnosticsExportResult, ReportProblemInput, diff --git a/packages/app/src/i18n/en.ts b/packages/app/src/i18n/en.ts index a0b86fe1c..087b25524 100644 --- a/packages/app/src/i18n/en.ts +++ b/packages/app/src/i18n/en.ts @@ -55,6 +55,7 @@ export const dict = { "command.panel.toggle": "Toggle right panel", "command.panel.toggle.description": "Open or close the right utility panel (⌥⌘B)", "command.review.toggle": "Toggle review", + "command.browser.toggle": "Toggle browser", "session.panel.files": "Files", "session.panel.addTab": "Add tab", "session.panel.changes": "Changes", @@ -588,6 +589,21 @@ export const dict = { "session.tab.session": "Session", "session.tab.review": "Review", "session.tab.context": "Context", + "session.tab.browser": "Browser", + "browser.address.placeholder": "Enter a URL or paste a link", + "browser.empty.title": "Nothing open yet", + "browser.empty.description": "Enter a URL above, or let the agent open one. Sites you sign in to stay signed in next time.", + "browser.action.back": "Back", + "browser.action.forward": "Forward", + "browser.action.reload": "Reload", + "browser.action.stop": "Stop", + "browser.action.more": "More", + "browser.action.openExternal": "Open in system browser", + "browser.action.copyLink": "Copy link", + "browser.action.clearData": "Clear browsing data", + "browser.clearData.title": "Clear browsing data?", + "browser.clearData.description": "This signs you out of every site and clears cookies and cache. It can't be undone.", + "browser.clearData.confirm": "Clear", "session.panel.reviewAndFiles": "Review and files", "session.review.filesChanged": "{{count}} Files Changed", "session.review.change.one": "Change", diff --git a/packages/app/src/i18n/zh.ts b/packages/app/src/i18n/zh.ts index 00c38723b..314d8545b 100644 --- a/packages/app/src/i18n/zh.ts +++ b/packages/app/src/i18n/zh.ts @@ -69,6 +69,7 @@ export const dict = { "command.panel.toggle.description": "打开或关闭右侧工具面板(⌥⌘B)", "command.review.toggle": "切换审查", + "command.browser.toggle": "切换浏览器", "session.panel.files": "文件", "session.panel.addTab": "添加标签页", "session.panel.changes": "变更", @@ -555,6 +556,21 @@ export const dict = { "session.tab.session": "会话", "session.tab.review": "审查", "session.tab.context": "上下文", + "session.tab.browser": "浏览器", + "browser.address.placeholder": "输入网址,或粘贴链接", + "browser.empty.title": "还没有打开网页", + "browser.empty.description": "在上面输入网址,或让 agent 替你打开。登录后的网站会保持登录,下次免登录。", + "browser.action.back": "后退", + "browser.action.forward": "前进", + "browser.action.reload": "刷新", + "browser.action.stop": "停止", + "browser.action.more": "更多", + "browser.action.openExternal": "在系统浏览器打开", + "browser.action.copyLink": "复制链接", + "browser.action.clearData": "清除浏览数据", + "browser.clearData.title": "清除浏览数据?", + "browser.clearData.description": "会退出所有已登录的网站,清空 cookie 和缓存。此操作无法撤销。", + "browser.clearData.confirm": "清除", "session.panel.reviewAndFiles": "审查和文件", "session.review.filesChanged": "{{count}} 个文件变更", "session.review.change.one": "更改", diff --git a/packages/app/src/pages/session/browser/browser-panel.tsx b/packages/app/src/pages/session/browser/browser-panel.tsx new file mode 100644 index 000000000..1fef7d289 --- /dev/null +++ b/packages/app/src/pages/session/browser/browser-panel.tsx @@ -0,0 +1,269 @@ +import { createEffect, createMemo, createSignal, onCleanup, onMount, Show } from "solid-js" +import { Button } from "@opencode-ai/ui/button" +import { Dialog } from "@opencode-ai/ui/dialog" +import { DropdownMenu } from "@opencode-ai/ui/dropdown-menu" +import { Icon } from "@opencode-ai/ui/icon" +import { IconButton } from "@opencode-ai/ui/icon-button" +import { useDialog } from "@opencode-ai/ui/context/dialog" +import { useLanguage } from "@/context/language" +import { usePlatform } from "@/context/platform" +import type { BrowserBridge, BrowserState, BrowserViewRect } from "@/context/platform" +import { formatAddress, normalizeAddressInput } from "./url" +import { rectsEqual, shouldShowBrowserView } from "./view-state" + +const HIDDEN_RECT: BrowserViewRect = { x: 0, y: 0, width: 0, height: 0 } + +/** + * The embedded browser tab body: navigation toolbar, editable address bar, + * overflow menu, and the content region the native WebContentsView is painted + * over. The page itself lives in the main process (it survives tab switches); + * this component owns the DOM chrome and reports the content rect so main can + * size/show the overlay. + */ +export function BrowserPanel(props: { + bridge: BrowserBridge + active: () => boolean + panelOpen: () => boolean +}) { + const language = useLanguage() + const dialog = useDialog() + const platform = usePlatform() + const bridge = props.bridge + + const [state, setState] = createSignal(null) + const [editing, setEditing] = createSignal(false) + const [draft, setDraft] = createSignal("") + const [menuOpen, setMenuOpen] = createSignal(false) + const [rect, setRect] = createSignal(null) + + let host: HTMLDivElement | undefined + let input: HTMLInputElement | undefined + + // Subscribe first, then seed once — and only if no push has arrived yet, so a + // navigation landing mid-flight isn't clobbered by the older getState snapshot. + onCleanup(bridge.onState(setState)) + onMount(() => { + void bridge.getState().then((s) => s && setState((prev) => prev ?? s)) + }) + + const url = () => state()?.url ?? "" + const hasPage = () => state()?.hasPage ?? false + const loading = () => state()?.loading ?? false + const secure = () => state()?.secure ?? false + const address = createMemo(() => formatAddress(url())) + + // Hide the native overlay whenever an app modal or this tab's own menu is open, + // since the view would otherwise paint over them. + const suppressed = () => !!dialog.active || menuOpen() + const shouldShow = createMemo(() => + shouldShowBrowserView({ + panelOpen: props.panelOpen(), + active: props.active(), + hasPage: hasPage(), + suppressed: suppressed(), + }), + ) + + // Push visibility + bounds to main as one unit so they never race. + createEffect(() => { + if (!shouldShow()) { + void bridge.setView({ visible: false, rect: HIDDEN_RECT }) + return + } + const r = rect() + if (r) void bridge.setView({ visible: true, rect: r }) + }) + + // While visible, track the content rect every frame: a native overlay must + // follow position changes (window resize moving the right-aligned panel, the + // open/close slide, drag-resize) that a ResizeObserver can't observe. The + // diff keeps this from sending IPC unless the device-pixel rect actually moved. + createEffect(() => { + if (!shouldShow()) return + let raf = 0 + const measure = () => { + if (host) { + const b = host.getBoundingClientRect() + const next = { x: b.x, y: b.y, width: b.width, height: b.height } + setRect((prev) => (rectsEqual(prev, next) ? prev : next)) + } + raf = requestAnimationFrame(measure) + } + raf = requestAnimationFrame(measure) + onCleanup(() => cancelAnimationFrame(raf)) + }) + + onCleanup(() => void bridge.setView({ visible: false, rect: HIDDEN_RECT })) + + const beginEdit = () => { + setDraft(url()) + setEditing(true) + requestAnimationFrame(() => { + input?.focus() + input?.select() + }) + } + + const submit = () => { + const target = normalizeAddressInput(draft()) + setEditing(false) + if (target) void bridge.navigate(target) + } + + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === "Enter") { + event.preventDefault() + submit() + } else if (event.key === "Escape") { + event.preventDefault() + setEditing(false) + input?.blur() + } + } + + const confirmClearData = () => { + dialog.show(() => ( + + + + + } + /> + )) + } + + return ( +
+ {/* Navigation toolbar */} +
+ bridge.goBack()} + /> + bridge.goForward()} + /> + bridge.reload()} + /> + } + > + bridge.stop()} + /> + + + {/* Address bar: two-tone display, swapped for an input while editing */} + + + + + {language.t("browser.address.placeholder")}} + > + + {address().host} + {address().path} + + + + } + > + setDraft(e.currentTarget.value)} + onKeyDown={onKeyDown} + onBlur={() => setEditing(false)} + /> + + + + + + + platform.openLink(url())}> + + {language.t("browser.action.openExternal")} + + void navigator.clipboard?.writeText(url())}> + + {language.t("browser.action.copyLink")} + + + + + {language.t("browser.action.clearData")} + + + + + + +
+ +
+ + {/* Content region: the native WebContentsView is painted over this rect. + When there is no page, the view stays hidden and the empty state shows. */} +
+ +
+
{language.t("browser.empty.title")}
+
{language.t("browser.empty.description")}
+
+
+
+
+ ) +} diff --git a/packages/app/src/pages/session/browser/url.test.ts b/packages/app/src/pages/session/browser/url.test.ts new file mode 100644 index 000000000..3a7b0051e --- /dev/null +++ b/packages/app/src/pages/session/browser/url.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, test } from "bun:test" +import { formatAddress, normalizeAddressInput } from "./url" + +describe("normalizeAddressInput", () => { + test("returns null for empty / whitespace-only input", () => { + expect(normalizeAddressInput("")).toBeNull() + expect(normalizeAddressInput(" ")).toBeNull() + }) + + test("prefixes https:// for bare hosts and trims", () => { + expect(normalizeAddressInput("example.com")).toBe("https://example.com") + expect(normalizeAddressInput(" example.com/docs ")).toBe("https://example.com/docs") + }) + + test("passes through explicit http/https schemes unchanged (case-insensitive)", () => { + expect(normalizeAddressInput("https://a.com/x?q=1")).toBe("https://a.com/x?q=1") + expect(normalizeAddressInput("http://a.com")).toBe("http://a.com") + expect(normalizeAddressInput("HTTPS://A.com")).toBe("HTTPS://A.com") + }) + + test("treats host:port as a host, not a scheme", () => { + expect(normalizeAddressInput("localhost:3000")).toBe("https://localhost:3000") + expect(normalizeAddressInput("192.168.0.1:8080/p?q=1")).toBe("https://192.168.0.1:8080/p?q=1") + }) + + test("passes through other schemes for the main process to validate/reject", () => { + expect(normalizeAddressInput("ftp://files.example.com")).toBe("ftp://files.example.com") + }) +}) + +describe("formatAddress", () => { + test("splits host and path, strips www and a lone slash", () => { + expect(formatAddress("https://www.lumen.so/feed")).toEqual({ host: "lumen.so", path: "/feed" }) + expect(formatAddress("https://lumen.so/")).toEqual({ host: "lumen.so", path: "" }) + expect(formatAddress("https://lumen.so/a?b=1#c")).toEqual({ host: "lumen.so", path: "/a?b=1#c" }) + }) + + test("falls back to the raw string when it does not parse", () => { + expect(formatAddress("not a url")).toEqual({ host: "not a url", path: "" }) + }) +}) diff --git a/packages/app/src/pages/session/browser/url.ts b/packages/app/src/pages/session/browser/url.ts new file mode 100644 index 000000000..b7320b144 --- /dev/null +++ b/packages/app/src/pages/session/browser/url.ts @@ -0,0 +1,37 @@ +/** + * Address-bar input → navigable URL string. + * + * The embedded browser is a content viewer, not a search box: v1 only resolves + * URLs (no search-engine fallback, which would be a product decision about which + * engine). Anything already carrying a `scheme://` is passed through untouched — + * the main process validates the scheme before loading, so this stays purely + * about shaping the string. Bareword/host input gets `https://` so the common + * case ("example.com") just works. Returns null for empty input (no navigation). + */ +const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i + +export function normalizeAddressInput(raw: string): string | null { + const trimmed = raw.trim() + if (!trimmed) return null + // `host:port` (e.g. localhost:3000) has no `//`, so it is NOT treated as a + // scheme and correctly gets the https prefix below. + if (HAS_SCHEME.test(trimmed)) return trimmed + return `https://${trimmed}` +} + +/** + * Split a loaded URL into host + remainder for the address bar's two-tone + * display (host emphasized, path muted). Falls back to the raw string when it + * does not parse as a URL. `www.` is stripped and a lone `/` path is dropped to + * keep the common case clean. + */ +export function formatAddress(url: string): { host: string; path: string } { + try { + const parsed = new URL(url) + const host = parsed.host.replace(/^www\./, "") + const rest = `${parsed.pathname}${parsed.search}${parsed.hash}` + return { host, path: rest === "/" ? "" : rest } + } catch { + return { host: url, path: "" } + } +} diff --git a/packages/app/src/pages/session/browser/view-state.test.ts b/packages/app/src/pages/session/browser/view-state.test.ts new file mode 100644 index 000000000..0cada7c97 --- /dev/null +++ b/packages/app/src/pages/session/browser/view-state.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, test } from "bun:test" +import { rectsEqual, shouldShowBrowserView } from "./view-state" + +describe("shouldShowBrowserView", () => { + const base = { panelOpen: true, active: true, hasPage: true, suppressed: false } + + test("shows only when open, active, has a page, and not suppressed", () => { + expect(shouldShowBrowserView(base)).toBe(true) + }) + + test("hides when any precondition fails", () => { + expect(shouldShowBrowserView({ ...base, panelOpen: false })).toBe(false) + expect(shouldShowBrowserView({ ...base, active: false })).toBe(false) + expect(shouldShowBrowserView({ ...base, hasPage: false })).toBe(false) + expect(shouldShowBrowserView({ ...base, suppressed: true })).toBe(false) + }) +}) + +describe("rectsEqual", () => { + test("treats null pairs as equal and null/value as unequal", () => { + expect(rectsEqual(null, null)).toBe(true) + expect(rectsEqual(null, { x: 0, y: 0, width: 1, height: 1 })).toBe(false) + expect(rectsEqual({ x: 0, y: 0, width: 1, height: 1 }, null)).toBe(false) + }) + + test("ignores sub-pixel jitter but catches device-pixel changes", () => { + expect(rectsEqual({ x: 10.1, y: 20.2, width: 30.4, height: 40 }, { x: 10, y: 20, width: 30, height: 40 })).toBe( + true, + ) + expect(rectsEqual({ x: 10, y: 20, width: 30, height: 40 }, { x: 11, y: 20, width: 30, height: 40 })).toBe(false) + }) +}) diff --git a/packages/app/src/pages/session/browser/view-state.ts b/packages/app/src/pages/session/browser/view-state.ts new file mode 100644 index 000000000..7b36e3365 --- /dev/null +++ b/packages/app/src/pages/session/browser/view-state.ts @@ -0,0 +1,34 @@ +import type { BrowserViewRect } from "@/context/platform" + +/** + * Whether the native WebContentsView overlay should be shown over the panel's + * content region. It is a native layer painted on top of the DOM, so it must be + * hidden whenever something should sit above it: + * - panel collapsed or this tab not active → nothing to overlay, + * - no page loaded yet → the DOM empty state shows instead, + * - an app modal / the browser's own menu is open → it would paint over them. + */ +export function shouldShowBrowserView(input: { + panelOpen: boolean + active: boolean + hasPage: boolean + suppressed: boolean +}): boolean { + return input.panelOpen && input.active && input.hasPage && !input.suppressed +} + +/** + * Compare two viewport rects at device-pixel resolution. The renderer measures + * the host every animation frame while visible; this gate keeps sub-pixel jitter + * from spamming the bounds IPC, since the main process rounds to integers anyway. + */ +export function rectsEqual(a: BrowserViewRect | null, b: BrowserViewRect | null): boolean { + if (a === b) return true + if (!a || !b) return false + return ( + Math.round(a.x) === Math.round(b.x) && + Math.round(a.y) === Math.round(b.y) && + Math.round(a.width) === Math.round(b.width) && + Math.round(a.height) === Math.round(b.height) + ) +} diff --git a/packages/app/src/pages/session/right-panel-tab-strip.tsx b/packages/app/src/pages/session/right-panel-tab-strip.tsx index 6cb75f135..699de4e18 100644 --- a/packages/app/src/pages/session/right-panel-tab-strip.tsx +++ b/packages/app/src/pages/session/right-panel-tab-strip.tsx @@ -37,6 +37,9 @@ function RightPanelShellIcon(props: { icon: ShellTabIcon }) { + + + ) } diff --git a/packages/app/src/pages/session/right-panel-tabs.ts b/packages/app/src/pages/session/right-panel-tabs.ts index 319b33435..68148589b 100644 --- a/packages/app/src/pages/session/right-panel-tabs.ts +++ b/packages/app/src/pages/session/right-panel-tabs.ts @@ -14,7 +14,7 @@ * slot is dropped via migrateLegacyRightPanelTab / coerceLegacySidePanelTab. */ -export type RightPanelStaticTab = "status" | "review" | "context" +export type RightPanelStaticTab = "status" | "review" | "context" | "browser" export type RightPanelTerminalTab = `terminal:${string}` export type RightPanelTab = RightPanelStaticTab | RightPanelTerminalTab @@ -22,9 +22,10 @@ export const RIGHT_PANEL_TAB_VALUES: readonly RightPanelStaticTab[] = [ "status", "review", "context", + "browser", ] as const -export type RightPanelShellIconName = "status" | "review" | "terminal" +export type RightPanelShellIconName = "status" | "review" | "terminal" | "browser" export type ShellTabIcon = | { kind: "icon"; name: RightPanelShellIconName } @@ -34,6 +35,7 @@ export type RightPanelTabLabelKey = | "status.popover.trigger" | "session.tab.review" | "session.tab.context" + | "session.tab.browser" export interface RightPanelTabMeta { icon: ShellTabIcon @@ -56,6 +58,13 @@ export const RIGHT_PANEL_TAB_META: Record` tab values. Imported by helpers diff --git a/packages/app/src/pages/session/session-side-panel.tsx b/packages/app/src/pages/session/session-side-panel.tsx index 6ad1ee3cd..b2813a4bc 100644 --- a/packages/app/src/pages/session/session-side-panel.tsx +++ b/packages/app/src/pages/session/session-side-panel.tsx @@ -14,6 +14,7 @@ import { useCommand } from "@/context/command" import { useFile, type SelectedLineRange } from "@/context/file" import { useLanguage } from "@/context/language" import { MAX_RIGHT_PANEL_WIDTH, MIN_RIGHT_PANEL_WIDTH, useLayout } from "@/context/layout" +import { canUseBrowser, usePlatform } from "@/context/platform" import { useTerminal } from "@/context/terminal" import type { TerminalTabID } from "@/context/terminal-types" import type { FilesTabEntry } from "@/pages/session/files-tab-state" @@ -30,6 +31,7 @@ import { } from "@/pages/session/helpers" import { setSessionHandoff } from "@/pages/session/handoff" +import { BrowserPanel } from "@/pages/session/browser/browser-panel" import { RightPanelReviewBody } from "@/pages/session/right-panel-review-body" import { RightPanelTabStrip } from "@/pages/session/right-panel-tab-strip" import { @@ -67,6 +69,7 @@ export function SessionSidePanel(props: { const command = useCommand() const dialog = useDialog() const terminal = useTerminal() + const platform = usePlatform() const { layoutRouteKey, params, tabs, view } = useSessionLayout() const isDesktop = createMediaQuery("(min-width: 768px)") @@ -137,6 +140,8 @@ export function SessionSidePanel(props: { const shellTabs = createMemo(() => { const staticTabs = view() .sidePanel.openTabs() + // Browser is desktop/Electron only; drop a persisted chip on web. + .filter((value) => value !== "browser" || canUseBrowser(platform)) .map((value) => { const meta = RIGHT_PANEL_TAB_META[value] return { @@ -161,7 +166,9 @@ export function SessionSidePanel(props: { const closableMissingTabs = createMemo(() => { const open = new Set(view().sidePanel.openTabs()) - return RIGHT_PANEL_TAB_VALUES.filter((tab) => tab !== "status" && !open.has(tab)).map((value) => { + return RIGHT_PANEL_TAB_VALUES.filter( + (tab) => tab !== "status" && !open.has(tab) && (tab !== "browser" || canUseBrowser(platform)), + ).map((value) => { const meta = RIGHT_PANEL_TAB_META[value] const iconName: RightPanelShellIconName = meta.icon.kind === "icon" ? meta.icon.name : meta.icon.fallbackIcon const keybind = meta.commandId ? command.keybind(meta.commandId) : undefined @@ -425,6 +432,18 @@ export function SessionSidePanel(props: { + + + {(bridge) => ( + + sidePanelTab() === "browser"} + panelOpen={open} + /> + + )} +
diff --git a/packages/app/src/pages/session/use-session-commands.tsx b/packages/app/src/pages/session/use-session-commands.tsx index 7369a2d8b..577306280 100644 --- a/packages/app/src/pages/session/use-session-commands.tsx +++ b/packages/app/src/pages/session/use-session-commands.tsx @@ -8,6 +8,7 @@ import { useLanguage } from "@/context/language" import { useLayout } from "@/context/layout" import { useLocal } from "@/context/local" import { usePermission } from "@/context/permission" +import { canUseBrowser, usePlatform } from "@/context/platform" import { usePrompt } from "@/context/prompt" import { useSDK } from "@/context/sdk" import { useSync } from "@/context/sync" @@ -52,6 +53,7 @@ export const useSessionCommands = (actions: SessionCommandContext) => { const sync = useSync() const terminal = useTerminal() const layout = useLayout() + const platform = usePlatform() const navigate = useNavigate() const { params, tabs, view } = useSessionLayout() const isDesktop = createMediaQuery("(min-width: 768px)") @@ -442,6 +444,19 @@ export const useSessionCommands = (actions: SessionCommandContext) => { keybind: "mod+shift+r", onSelect: () => view().sidePanel.toggleTab("review"), }), + // Embedded browser is desktop/Electron only (WebContentsView); like + // terminal it has no host on web or narrow layouts, so don't register the + // command or its keybind there. Reactive, so it re-registers across 768px. + ...(isDesktop() && canUseBrowser(platform) + ? [ + viewCommand({ + id: "browser.toggle", + title: language.t("command.browser.toggle"), + keybind: "mod+shift+b", + onSelect: () => view().sidePanel.toggleTab("browser"), + }), + ] + : []), viewCommand({ id: "panel.toggle", title: language.t("command.panel.toggle"), diff --git a/packages/desktop-electron/src/main/browser/controller.ts b/packages/desktop-electron/src/main/browser/controller.ts new file mode 100644 index 000000000..e887dc1c6 --- /dev/null +++ b/packages/desktop-electron/src/main/browser/controller.ts @@ -0,0 +1,156 @@ +import { WebContentsView, shell, type BrowserWindow } from "electron" +import type { BrowserState, BrowserViewLayout } from "@opencode-ai/app/desktop-api" +import { browserViewWebPreferences } from "./options" +import { computeViewBounds, deriveBrowserState, parseNavigable } from "./logic" + +export const BROWSER_STATE_CHANNEL = "browser:state" + +const NON_WEB_SCHEME = /^[a-z][a-z0-9+.-]*:/i + +/** + * Owns one embedded browser per window: a WebContentsView painted over the + * panel's content region. The view is a native layer above the DOM, so the + * renderer drives its bounds/visibility via setView; navigation state is pushed + * back over BROWSER_STATE_CHANNEL. Created lazily on first use, destroyed with + * the window. + */ +export class BrowserViewController { + private readonly view: WebContentsView + private rect: BrowserViewLayout["rect"] | null = null + private visible = false + private favicon: string | null = null + private destroyed = false + + constructor(private readonly win: BrowserWindow) { + this.view = new WebContentsView({ webPreferences: browserViewWebPreferences() }) + this.view.setVisible(false) + win.contentView.addChildView(this.view) + this.wireEvents() + } + + private get wc() { + return this.view.webContents + } + + private wireEvents() { + const wc = this.wc + wc.on("did-start-loading", () => this.emitState()) + wc.on("did-stop-loading", () => this.emitState()) + wc.on("did-navigate", () => { + this.favicon = null + this.emitState() + }) + wc.on("did-navigate-in-page", () => this.emitState()) + wc.on("page-title-updated", () => this.emitState()) + wc.on("page-favicon-updated", (_event, favicons: string[]) => { + this.favicon = favicons[0] ?? null + this.emitState() + }) + wc.on("did-fail-load", () => this.emitState()) + + // Single-view browser: keep http(s) "open in new window" links in-place and + // hand any other scheme to the system browser. Never spawn a child window. + wc.setWindowOpenHandler(({ url }) => { + const navigable = parseNavigable(url) + if (navigable) void this.loadInternal(navigable) + else this.openExternal(url) + return { action: "deny" } + }) + + // Block link navigations to non-web schemes (file://, etc.); route real + // external schemes to the system browser instead of failing silently. + wc.on("will-navigate", (event, url) => { + if (parseNavigable(url)) return + event.preventDefault() + this.openExternal(url) + }) + + // Deny every permission request by default — a v1 content viewer should not + // silently grant camera/mic/geolocation/etc. (the permission model for + // agent-driven use is tracked separately in #1186 PR2). + wc.session.setPermissionRequestHandler((_wc, _permission, callback) => callback(false)) + } + + private openExternal(url: string) { + if (NON_WEB_SCHEME.test(url) && !url.startsWith("about:")) void shell.openExternal(url).catch(() => {}) + } + + private async loadInternal(url: string) { + // loadURL rejects on aborted/failed loads (e.g. a superseding navigation); + // the did-fail-load handler already surfaces errors, so swallow here. + try { + await this.wc.loadURL(url) + } catch { + /* surfaced via did-fail-load */ + } + } + + state(): BrowserState { + const wc = this.wc + return deriveBrowserState({ + url: wc.getURL(), + title: wc.getTitle(), + canGoBack: wc.navigationHistory.canGoBack(), + canGoForward: wc.navigationHistory.canGoForward(), + loading: wc.isLoading(), + favicon: this.favicon, + }) + } + + private emitState() { + if (this.destroyed || this.win.isDestroyed()) return + this.win.webContents.send(BROWSER_STATE_CHANNEL, this.state()) + } + + async navigate(input: string) { + const url = parseNavigable(input) + if (!url) return + await this.loadInternal(url) + } + + goBack() { + if (this.wc.navigationHistory.canGoBack()) this.wc.navigationHistory.goBack() + } + + goForward() { + if (this.wc.navigationHistory.canGoForward()) this.wc.navigationHistory.goForward() + } + + reload() { + this.wc.reload() + } + + stop() { + this.wc.stop() + } + + setView(layout: BrowserViewLayout) { + this.visible = layout.visible + this.rect = layout.rect + this.applyLayout() + } + + private applyLayout() { + if (this.destroyed || this.win.isDestroyed()) return + if (!this.visible || !this.rect) { + this.view.setVisible(false) + return + } + this.view.setBounds(computeViewBounds(this.rect, this.win.webContents.zoomFactor)) + this.view.setVisible(true) + } + + async clearData() { + await this.wc.session.clearStorageData() + await this.wc.session.clearCache() + // Reload so the page reflects the signed-out state immediately. + if (!this.wc.isDestroyed() && this.state().hasPage) this.wc.reload() + } + + destroy() { + if (this.destroyed) return + this.destroyed = true + if (!this.win.isDestroyed()) this.win.contentView.removeChildView(this.view) + if (!this.wc.isDestroyed()) this.wc.close() + } +} diff --git a/packages/desktop-electron/src/main/browser/logic.test.ts b/packages/desktop-electron/src/main/browser/logic.test.ts new file mode 100644 index 000000000..4315b84ea --- /dev/null +++ b/packages/desktop-electron/src/main/browser/logic.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, test } from "bun:test" +import { computeViewBounds, deriveBrowserState, parseNavigable, type BrowserStateSnapshot } from "./logic" + +describe("parseNavigable", () => { + test("accepts http and https and normalizes", () => { + expect(parseNavigable("https://a.com")).toBe("https://a.com/") + expect(parseNavigable("http://a.com/x?q=1")).toBe("http://a.com/x?q=1") + }) + + test("rejects non-web schemes and garbage", () => { + expect(parseNavigable("file:///etc/passwd")).toBeNull() + expect(parseNavigable("javascript:alert(1)")).toBeNull() + expect(parseNavigable("about:blank")).toBeNull() + expect(parseNavigable("ftp://files.example.com")).toBeNull() + expect(parseNavigable("not a url")).toBeNull() + expect(parseNavigable("")).toBeNull() + }) +}) + +describe("computeViewBounds", () => { + test("rounds and passes through at zoom 1", () => { + expect(computeViewBounds({ x: 10.4, y: 20.6, width: 300.5, height: 400.2 }, 1)).toEqual({ + x: 10, + y: 21, + width: 301, + height: 400, + }) + }) + + test("scales by the zoom factor", () => { + expect(computeViewBounds({ x: 10, y: 20, width: 100, height: 200 }, 1.5)).toEqual({ + x: 15, + y: 30, + width: 150, + height: 300, + }) + }) + + test("guards a non-positive zoom and clamps negative sizes", () => { + expect(computeViewBounds({ x: 0, y: 0, width: 50, height: 50 }, 0)).toEqual({ x: 0, y: 0, width: 50, height: 50 }) + expect(computeViewBounds({ x: 0, y: 0, width: -5, height: -5 }, 1)).toEqual({ x: 0, y: 0, width: 0, height: 0 }) + }) +}) + +describe("deriveBrowserState", () => { + const snap = (over: Partial): BrowserStateSnapshot => ({ + url: "", + title: "", + canGoBack: false, + canGoForward: false, + loading: false, + favicon: null, + ...over, + }) + + test("flags hasPage false for empty and about: URLs", () => { + expect(deriveBrowserState(snap({ url: "" })).hasPage).toBe(false) + expect(deriveBrowserState(snap({ url: "about:blank" })).hasPage).toBe(false) + expect(deriveBrowserState(snap({ url: "https://a.com/" })).hasPage).toBe(true) + }) + + test("derives secure from the https scheme", () => { + expect(deriveBrowserState(snap({ url: "https://a.com/" })).secure).toBe(true) + expect(deriveBrowserState(snap({ url: "http://a.com/" })).secure).toBe(false) + }) + + test("passes navigation flags through", () => { + const state = deriveBrowserState( + snap({ url: "https://a.com/", title: "A", canGoBack: true, canGoForward: false, loading: true, favicon: "f" }), + ) + expect(state).toMatchObject({ title: "A", canGoBack: true, canGoForward: false, loading: true, favicon: "f" }) + }) +}) diff --git a/packages/desktop-electron/src/main/browser/logic.ts b/packages/desktop-electron/src/main/browser/logic.ts new file mode 100644 index 000000000..9ab58e742 --- /dev/null +++ b/packages/desktop-electron/src/main/browser/logic.ts @@ -0,0 +1,64 @@ +import type { BrowserState } from "@opencode-ai/app/desktop-api" + +/** + * Validate an address before loading it into the embedded view. Only http/https + * are navigable: file://, javascript:, and other schemes are rejected so a typed + * address or an in-page link can never reach the local filesystem or privileged + * surfaces. Returns the parsed (normalized) URL string, or null if not allowed. + */ +export function parseNavigable(input: string): string | null { + let url: URL + try { + url = new URL(input) + } catch { + return null + } + if (url.protocol === "http:" || url.protocol === "https:") return url.toString() + return null +} + +/** + * Convert a CSS-pixel viewport rect (reported by the renderer) into the + * device-independent pixel bounds a WebContentsView expects. The renderer is + * zoom-agnostic; the window's zoom factor is applied here as the single source + * of truth. Negative sizes are clamped to 0 (setBounds rejects negatives). + */ +export function computeViewBounds( + rect: { x: number; y: number; width: number; height: number }, + zoomFactor: number, +): { x: number; y: number; width: number; height: number } { + const z = zoomFactor > 0 ? zoomFactor : 1 + return { + x: Math.round(rect.x * z), + y: Math.round(rect.y * z), + width: Math.max(0, Math.round(rect.width * z)), + height: Math.max(0, Math.round(rect.height * z)), + } +} + +export type BrowserStateSnapshot = { + url: string + title: string + canGoBack: boolean + canGoForward: boolean + loading: boolean + favicon: string | null +} + +/** + * Derive the renderer-facing state from a raw webContents snapshot. `hasPage` is + * false until a real page is loaded (empty or about: URL), which keeps the DOM + * empty state visible and the native overlay hidden; `secure` reflects https. + */ +export function deriveBrowserState(snapshot: BrowserStateSnapshot): BrowserState { + return { + url: snapshot.url, + title: snapshot.title, + canGoBack: snapshot.canGoBack, + canGoForward: snapshot.canGoForward, + loading: snapshot.loading, + favicon: snapshot.favicon, + secure: /^https:\/\//i.test(snapshot.url), + hasPage: snapshot.url !== "" && !snapshot.url.startsWith("about:"), + } +} diff --git a/packages/desktop-electron/src/main/browser/options.test.ts b/packages/desktop-electron/src/main/browser/options.test.ts new file mode 100644 index 000000000..f1a37ebff --- /dev/null +++ b/packages/desktop-electron/src/main/browser/options.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, test } from "bun:test" +import { BROWSER_PARTITION, browserViewWebPreferences } from "./options" + +describe("embedded browser security", () => { + test("uses a locked-down, preload-free, sandboxed view on a persistent partition", () => { + const prefs = browserViewWebPreferences() + + expect(prefs).toMatchObject({ + sandbox: true, + contextIsolation: true, + nodeIntegration: false, + webSecurity: true, + }) + // The embedded page must never receive the app's IPC preload bridge. + expect(prefs.preload).toBeUndefined() + expect(prefs.partition).toBe(BROWSER_PARTITION) + expect(BROWSER_PARTITION.startsWith("persist:")).toBe(true) + }) +}) diff --git a/packages/desktop-electron/src/main/browser/options.ts b/packages/desktop-electron/src/main/browser/options.ts new file mode 100644 index 000000000..06019137b --- /dev/null +++ b/packages/desktop-electron/src/main/browser/options.ts @@ -0,0 +1,24 @@ +import type { WebPreferences } from "electron" + +/** + * Single app-owned persistent partition: one browsing session shared by every + * window, surviving restarts. `persist:` keeps cookies/storage on disk so logins + * stick; clear-data wipes it. Multi-profile is intentionally out of scope (#1186). + */ +export const BROWSER_PARTITION = "persist:pawwork-browser" + +/** + * WebPreferences for the embedded browser's WebContentsView. It loads arbitrary + * external sites, so it is locked down and deliberately distinct from the app + * renderer (window-options.ts): no preload — the page must never receive the + * app's IPC bridge — plus sandbox, context isolation, no Node, web security on. + */ +export function browserViewWebPreferences(): WebPreferences { + return { + partition: BROWSER_PARTITION, + sandbox: true, + contextIsolation: true, + nodeIntegration: false, + webSecurity: true, + } +} diff --git a/packages/desktop-electron/src/main/index.ts b/packages/desktop-electron/src/main/index.ts index dd13783ef..21a6813f8 100644 --- a/packages/desktop-electron/src/main/index.ts +++ b/packages/desktop-electron/src/main/index.ts @@ -76,6 +76,7 @@ import { createDesktopContextStore } from "./desktop-context-store" import { createFeedbackHandler, feedbackDialogLabels } from "./feedback" import { registerIpcHandlers, sendDeepLinks, sendMenuCommand, sendSqliteMigrationProgress } from "./ipc" import { registerAboutIpc, triggerAbout } from "./ipc/about" +import { registerBrowserIpc } from "./ipc/browser" import { filePath, initLogging, tail } from "./logging" import { parseMarkdown } from "./markdown" import { createMenu } from "./menu" @@ -652,6 +653,7 @@ registerIpcHandlers({ }) registerAboutIpc() +registerBrowserIpc() function killSidecar() { if (!server) return diff --git a/packages/desktop-electron/src/main/ipc/browser.ts b/packages/desktop-electron/src/main/ipc/browser.ts new file mode 100644 index 000000000..a6b17c68e --- /dev/null +++ b/packages/desktop-electron/src/main/ipc/browser.ts @@ -0,0 +1,51 @@ +import { BrowserWindow, ipcMain, type IpcMainInvokeEvent } from "electron" +import type { BrowserViewLayout } from "@opencode-ai/app/desktop-api" +import { BrowserViewController } from "../browser/controller" + +/** + * Wires the embedded-browser IPC. One controller per window, created lazily and + * keyed by window id so each window drives its own WebContentsView, and torn + * down when the window closes. Channels mirror the BrowserBridge in the app's + * platform contract. + */ +export function registerBrowserIpc() { + const controllers = new Map() + + const windowFor = (event: IpcMainInvokeEvent) => BrowserWindow.fromWebContents(event.sender) + + const existing = (event: IpcMainInvokeEvent) => { + const win = windowFor(event) + return win ? controllers.get(win.id) : undefined + } + + // Create on first real use (navigate, or a visible set-view) so windows that + // never open the browser pay nothing. + const ensure = (event: IpcMainInvokeEvent) => { + const win = windowFor(event) + if (!win) return undefined + let controller = controllers.get(win.id) + if (!controller) { + controller = new BrowserViewController(win) + controllers.set(win.id, controller) + win.once("closed", () => { + controllers.get(win.id)?.destroy() + controllers.delete(win.id) + }) + } + return controller + } + + ipcMain.handle("browser:navigate", (event, url: string) => ensure(event)?.navigate(url)) + ipcMain.handle("browser:back", (event) => existing(event)?.goBack()) + ipcMain.handle("browser:forward", (event) => existing(event)?.goForward()) + ipcMain.handle("browser:reload", (event) => existing(event)?.reload()) + ipcMain.handle("browser:stop", (event) => existing(event)?.stop()) + ipcMain.handle("browser:set-view", (event, layout: BrowserViewLayout) => { + // Only spin up a view when there is something to show; hiding a view that + // was never created is a no-op. + const controller = layout.visible ? ensure(event) : existing(event) + controller?.setView(layout) + }) + ipcMain.handle("browser:clear-data", (event) => existing(event)?.clearData()) + ipcMain.handle("browser:get-state", (event) => existing(event)?.state() ?? null) +} diff --git a/packages/desktop-electron/src/preload/index.ts b/packages/desktop-electron/src/preload/index.ts index e545f6679..8a356c75a 100644 --- a/packages/desktop-electron/src/preload/index.ts +++ b/packages/desktop-electron/src/preload/index.ts @@ -1,11 +1,28 @@ import { contextBridge, ipcRenderer } from "electron" import { buildDesktopContext } from "@opencode-ai/app/desktop-api" +import type { BrowserState } from "@opencode-ai/app/desktop-api" import type { DesktopContext, ElectronAPI, InitStep, SqliteMigrationProgress } from "./types" import { getRuntimeFlags } from "./runtime-flags" const runtimeFlags = getRuntimeFlags(process.env) const invokeSetDesktopContext = (context: DesktopContext) => ipcRenderer.invoke("set-desktop-context", context) +const browser: ElectronAPI["browser"] = { + navigate: (url) => ipcRenderer.invoke("browser:navigate", url), + goBack: () => ipcRenderer.invoke("browser:back"), + goForward: () => ipcRenderer.invoke("browser:forward"), + reload: () => ipcRenderer.invoke("browser:reload"), + stop: () => ipcRenderer.invoke("browser:stop"), + setView: (layout) => ipcRenderer.invoke("browser:set-view", layout), + clearData: () => ipcRenderer.invoke("browser:clear-data"), + getState: () => ipcRenderer.invoke("browser:get-state"), + onState: (cb) => { + const handler = (_: unknown, state: BrowserState) => cb(state) + ipcRenderer.on("browser:state", handler) + return () => ipcRenderer.removeListener("browser:state", handler) + }, +} + const api: ElectronAPI = { ciSmokeEnabled: runtimeFlags.ciSmokeEnabled, killSidecar: () => ipcRenderer.invoke("kill-sidecar"), @@ -99,6 +116,7 @@ const api: ElectronAPI = { }, flashFrame: () => ipcRenderer.invoke("flash-frame"), setBadgeCount: (count: number) => ipcRenderer.invoke("set-badge-count", count), + browser, } contextBridge.exposeInMainWorld("api", api) diff --git a/packages/desktop-electron/src/preload/types.ts b/packages/desktop-electron/src/preload/types.ts index e3e717971..d00df1a63 100644 --- a/packages/desktop-electron/src/preload/types.ts +++ b/packages/desktop-electron/src/preload/types.ts @@ -1,4 +1,5 @@ import type { + BrowserBridge, DesktopContext, RendererDiagnosticInput, RendererDiagnosticsExportResult, @@ -125,4 +126,5 @@ export type ElectronAPI = { onAboutOpen: (handler: () => void) => () => void flashFrame: () => Promise setBadgeCount: (count: number) => Promise + browser: BrowserBridge } diff --git a/packages/desktop-electron/src/renderer/index.tsx b/packages/desktop-electron/src/renderer/index.tsx index 8a99ee779..55b46576d 100644 --- a/packages/desktop-electron/src/renderer/index.tsx +++ b/packages/desktop-electron/src/renderer/index.tsx @@ -334,6 +334,10 @@ const createPlatform = (): Platform => { type: "image/png", }) }, + + // Embedded browser: a thin passthrough to the locked-down WebContentsView + // bridge. Present only on desktop, which is what `canUseBrowser` keys off. + browser: window.api.browser, } } From 531fd6349a52de53ca310f16fccc57804865fbab Mon Sep 17 00:00:00 2001 From: Yuhan Lei Date: Mon, 8 Jun 2026 00:59:08 +0800 Subject: [PATCH 2/8] fix(app): harden embedded browser external-scheme and clear-data handling Codex review (#1204): - [P1] openExternal now hands only an allow-list (mailto:/tel:) to the OS via the new safeExternalUrl helper; file:, javascript:, and custom app protocols from page-provided links/window.open are dropped so a hostile page can't launch local files or registered handlers. - [P2] clear-data wipes the persistent partition session directly instead of needing a live controller, so it works when the tab is opened fresh after a restart; any live views then reload to reflect the signed-out state. --- .../src/main/browser/controller.ts | 17 ++++++++--------- .../src/main/browser/logic.test.ts | 18 +++++++++++++++++- .../desktop-electron/src/main/browser/logic.ts | 15 +++++++++++++++ .../desktop-electron/src/main/ipc/browser.ts | 14 ++++++++++++-- 4 files changed, 52 insertions(+), 12 deletions(-) diff --git a/packages/desktop-electron/src/main/browser/controller.ts b/packages/desktop-electron/src/main/browser/controller.ts index e887dc1c6..e72892ebc 100644 --- a/packages/desktop-electron/src/main/browser/controller.ts +++ b/packages/desktop-electron/src/main/browser/controller.ts @@ -1,12 +1,10 @@ import { WebContentsView, shell, type BrowserWindow } from "electron" import type { BrowserState, BrowserViewLayout } from "@opencode-ai/app/desktop-api" import { browserViewWebPreferences } from "./options" -import { computeViewBounds, deriveBrowserState, parseNavigable } from "./logic" +import { computeViewBounds, deriveBrowserState, parseNavigable, safeExternalUrl } from "./logic" export const BROWSER_STATE_CHANNEL = "browser:state" -const NON_WEB_SCHEME = /^[a-z][a-z0-9+.-]*:/i - /** * Owns one embedded browser per window: a WebContentsView painted over the * panel's content region. The view is a native layer above the DOM, so the @@ -72,7 +70,8 @@ export class BrowserViewController { } private openExternal(url: string) { - if (NON_WEB_SCHEME.test(url) && !url.startsWith("about:")) void shell.openExternal(url).catch(() => {}) + const safe = safeExternalUrl(url) + if (safe) void shell.openExternal(safe).catch(() => {}) } private async loadInternal(url: string) { @@ -140,11 +139,11 @@ export class BrowserViewController { this.view.setVisible(true) } - async clearData() { - await this.wc.session.clearStorageData() - await this.wc.session.clearCache() - // Reload so the page reflects the signed-out state immediately. - if (!this.wc.isDestroyed() && this.state().hasPage) this.wc.reload() + // Reflect a partition-wide data clear: reload so the page shows its + // signed-out state immediately. No-op when no real page is loaded. + reloadIfLoaded() { + if (this.destroyed || this.wc.isDestroyed()) return + if (this.state().hasPage) this.wc.reload() } destroy() { diff --git a/packages/desktop-electron/src/main/browser/logic.test.ts b/packages/desktop-electron/src/main/browser/logic.test.ts index 4315b84ea..0beb6b112 100644 --- a/packages/desktop-electron/src/main/browser/logic.test.ts +++ b/packages/desktop-electron/src/main/browser/logic.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test" -import { computeViewBounds, deriveBrowserState, parseNavigable, type BrowserStateSnapshot } from "./logic" +import { computeViewBounds, deriveBrowserState, parseNavigable, safeExternalUrl, type BrowserStateSnapshot } from "./logic" describe("parseNavigable", () => { test("accepts http and https and normalizes", () => { @@ -17,6 +17,22 @@ describe("parseNavigable", () => { }) }) +describe("safeExternalUrl", () => { + test("allows mailto and tel (case-insensitive)", () => { + expect(safeExternalUrl("mailto:a@b.com")).toBe("mailto:a@b.com") + expect(safeExternalUrl("tel:+15551234")).toBe("tel:+15551234") + expect(safeExternalUrl("MAILTO:a@b.com")).toBe("MAILTO:a@b.com") + }) + + test("drops file, custom app, javascript, and schemeless inputs", () => { + expect(safeExternalUrl("file:///etc/passwd")).toBeNull() + expect(safeExternalUrl("javascript:alert(1)")).toBeNull() + expect(safeExternalUrl("slack://open?team=T1")).toBeNull() + expect(safeExternalUrl("example.com")).toBeNull() + expect(safeExternalUrl("")).toBeNull() + }) +}) + describe("computeViewBounds", () => { test("rounds and passes through at zoom 1", () => { expect(computeViewBounds({ x: 10.4, y: 20.6, width: 300.5, height: 400.2 }, 1)).toEqual({ diff --git a/packages/desktop-electron/src/main/browser/logic.ts b/packages/desktop-electron/src/main/browser/logic.ts index 9ab58e742..b589270c6 100644 --- a/packages/desktop-electron/src/main/browser/logic.ts +++ b/packages/desktop-electron/src/main/browser/logic.ts @@ -17,6 +17,21 @@ export function parseNavigable(input: string): string | null { return null } +// Page-provided non-web links are handed to the OS only for this tight set of +// schemes. Everything else (file:, javascript:, custom app protocols) is dropped +// so a hostile page can't launch local files or arbitrary registered handlers. +const EXTERNAL_SCHEMES = new Set(["mailto:", "tel:"]) + +/** + * The page-provided URL to hand to the system handler, or null to drop it. Only + * a small allow-list of safe schemes escapes; navigable http/https links are + * handled in-place by parseNavigable and never reach here. + */ +export function safeExternalUrl(url: string): string | null { + const scheme = url.slice(0, url.indexOf(":") + 1).toLowerCase() + return EXTERNAL_SCHEMES.has(scheme) ? url : null +} + /** * Convert a CSS-pixel viewport rect (reported by the renderer) into the * device-independent pixel bounds a WebContentsView expects. The renderer is diff --git a/packages/desktop-electron/src/main/ipc/browser.ts b/packages/desktop-electron/src/main/ipc/browser.ts index a6b17c68e..f6a7ab441 100644 --- a/packages/desktop-electron/src/main/ipc/browser.ts +++ b/packages/desktop-electron/src/main/ipc/browser.ts @@ -1,6 +1,7 @@ -import { BrowserWindow, ipcMain, type IpcMainInvokeEvent } from "electron" +import { BrowserWindow, ipcMain, session, type IpcMainInvokeEvent } from "electron" import type { BrowserViewLayout } from "@opencode-ai/app/desktop-api" import { BrowserViewController } from "../browser/controller" +import { BROWSER_PARTITION } from "../browser/options" /** * Wires the embedded-browser IPC. One controller per window, created lazily and @@ -46,6 +47,15 @@ export function registerBrowserIpc() { const controller = layout.visible ? ensure(event) : existing(event) controller?.setView(layout) }) - ipcMain.handle("browser:clear-data", (event) => existing(event)?.clearData()) + // Browsing data lives in the shared persistent partition, not in any one view, + // so clear the session directly — this works even before a view exists (e.g. + // opening the tab fresh after restart). Then reload any live views so they + // reflect the signed-out state immediately. + ipcMain.handle("browser:clear-data", async () => { + const partition = session.fromPartition(BROWSER_PARTITION) + await partition.clearStorageData() + await partition.clearCache() + for (const controller of controllers.values()) controller.reloadIfLoaded() + }) ipcMain.handle("browser:get-state", (event) => existing(event)?.state() ?? null) } From a48b7c603b686833dc6376169380ec39508896d1 Mon Sep 17 00:00:00 2001 From: Yuhan Lei Date: Mon, 8 Jun 2026 01:04:51 +0800 Subject: [PATCH 3/8] fix(app): drop a persisted browser tab when the platform lacks it CodeRabbit (#1204): a session persisted with the browser tab active can be restored where canUseBrowser is false (the feature flag-disabled or rolled back). Its chip was already filtered out, but the active "browser" selection left the panel on a tab whose never mounts (blank body). Mirror the existing dangling-terminal guard: close the unsupported persisted tab so the selection falls back to a real one. --- .../app/src/pages/session/session-side-panel.tsx | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/packages/app/src/pages/session/session-side-panel.tsx b/packages/app/src/pages/session/session-side-panel.tsx index b2813a4bc..2196c89b7 100644 --- a/packages/app/src/pages/session/session-side-panel.tsx +++ b/packages/app/src/pages/session/session-side-panel.tsx @@ -212,6 +212,19 @@ export function SessionSidePanel(props: { view().sidePanel.closeTab(tab) } }) + // Stale browser selector guard (sibling to the dangling-terminal guard + // above): browser is desktop/Electron only, so a session persisted with the + // tab open can be restored where the platform lacks it — the feature + // flag-disabled or rolled back. Its chip is already filtered out, but a + // persisted active "browser" tab would leave the panel on a value whose + // never mounts (blank body). Drop it so the selection falls + // back to a real tab. + createEffect(() => { + if (canUseBrowser(platform)) return + if (!view().sidePanel.openTabs().includes("browser")) return + view().sidePanel.closeTab("browser") + }) + const showAllFiles = () => { if (view().sidePanel.explorer.tab() !== "changes") return view().sidePanel.explorer.setTab("all") From 61aeff17923a4d57d5135b2a02fdb7e700354269 Mon Sep 17 00:00:00 2001 From: Yuhan Lei Date: Mon, 8 Jun 2026 15:37:27 +0800 Subject: [PATCH 4/8] fix(app): suppress embedded browser overlay under shell surface takeovers The native WebContentsView is a window-level layer that DOM CSS can't cover. A settings/automations/skills takeover keeps the session mounted (CSS-hidden via `invisible`, not unmounted, to preserve its state), so the overlay kept painting through the takeover. Feed `mainSurfaceOpen` into the visibility gate as a first-class `coveredBySurface` input so the overlay hides whenever a surface covers the session. Found during manual QA of the browser tab; deeper surface-architecture rework tracked in #1209. --- .../app/src/pages/session/browser/browser-panel.tsx | 5 +++++ .../app/src/pages/session/browser/view-state.test.ts | 12 ++++++++++-- packages/app/src/pages/session/browser/view-state.ts | 10 ++++++++-- 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/packages/app/src/pages/session/browser/browser-panel.tsx b/packages/app/src/pages/session/browser/browser-panel.tsx index 1fef7d289..ad30cdf99 100644 --- a/packages/app/src/pages/session/browser/browser-panel.tsx +++ b/packages/app/src/pages/session/browser/browser-panel.tsx @@ -7,6 +7,7 @@ import { IconButton } from "@opencode-ai/ui/icon-button" import { useDialog } from "@opencode-ai/ui/context/dialog" import { useLanguage } from "@/context/language" import { usePlatform } from "@/context/platform" +import { useShellSurface } from "@/context/shell-surface" import type { BrowserBridge, BrowserState, BrowserViewRect } from "@/context/platform" import { formatAddress, normalizeAddressInput } from "./url" import { rectsEqual, shouldShowBrowserView } from "./view-state" @@ -28,6 +29,7 @@ export function BrowserPanel(props: { const language = useLanguage() const dialog = useDialog() const platform = usePlatform() + const shell = useShellSurface() const bridge = props.bridge const [state, setState] = createSignal(null) @@ -61,6 +63,9 @@ export function BrowserPanel(props: { active: props.active(), hasPage: hasPage(), suppressed: suppressed(), + // A settings / automations / skills takeover keeps the session mounted but + // hidden; the native overlay ignores that CSS and would bleed through. + coveredBySurface: shell.mainSurfaceOpen(), }), ) diff --git a/packages/app/src/pages/session/browser/view-state.test.ts b/packages/app/src/pages/session/browser/view-state.test.ts index 0cada7c97..683464c97 100644 --- a/packages/app/src/pages/session/browser/view-state.test.ts +++ b/packages/app/src/pages/session/browser/view-state.test.ts @@ -2,9 +2,9 @@ import { describe, expect, test } from "bun:test" import { rectsEqual, shouldShowBrowserView } from "./view-state" describe("shouldShowBrowserView", () => { - const base = { panelOpen: true, active: true, hasPage: true, suppressed: false } + const base = { panelOpen: true, active: true, hasPage: true, suppressed: false, coveredBySurface: false } - test("shows only when open, active, has a page, and not suppressed", () => { + test("shows only when open, active, has a page, not suppressed, and not covered by a surface", () => { expect(shouldShowBrowserView(base)).toBe(true) }) @@ -13,6 +13,14 @@ describe("shouldShowBrowserView", () => { expect(shouldShowBrowserView({ ...base, active: false })).toBe(false) expect(shouldShowBrowserView({ ...base, hasPage: false })).toBe(false) expect(shouldShowBrowserView({ ...base, suppressed: true })).toBe(false) + expect(shouldShowBrowserView({ ...base, coveredBySurface: true })).toBe(false) + }) + + test("hides while a full-surface takeover (settings / automations / skills) covers the session", () => { + // The session DOM stays mounted under a takeover (CSS-hidden, not unmounted), + // so without this gate the native overlay would paint through settings / + // automations / skills. Regression guard for that bleed-through. + expect(shouldShowBrowserView({ ...base, coveredBySurface: true })).toBe(false) }) }) diff --git a/packages/app/src/pages/session/browser/view-state.ts b/packages/app/src/pages/session/browser/view-state.ts index 7b36e3365..bdc3bbb2a 100644 --- a/packages/app/src/pages/session/browser/view-state.ts +++ b/packages/app/src/pages/session/browser/view-state.ts @@ -6,15 +6,21 @@ import type { BrowserViewRect } from "@/context/platform" * hidden whenever something should sit above it: * - panel collapsed or this tab not active → nothing to overlay, * - no page loaded yet → the DOM empty state shows instead, - * - an app modal / the browser's own menu is open → it would paint over them. + * - suppressed: an app modal / the browser's own menu is open → it would paint + * over them, + * - coveredBySurface: a full-region takeover (settings / automations / skills) + * covers the session. The session DOM stays mounted (CSS-hidden, not + * unmounted, to preserve its state), but a native layer ignores CSS, so it + * must be hidden explicitly or it bleeds through the takeover. */ export function shouldShowBrowserView(input: { panelOpen: boolean active: boolean hasPage: boolean suppressed: boolean + coveredBySurface: boolean }): boolean { - return input.panelOpen && input.active && input.hasPage && !input.suppressed + return input.panelOpen && input.active && input.hasPage && !input.suppressed && !input.coveredBySurface } /** From 86e74cbd9017a088d5088009eb25ea00f1de80d0 Mon Sep 17 00:00:00 2001 From: Yuhan Lei Date: Mon, 8 Jun 2026 15:44:45 +0800 Subject: [PATCH 5/8] fix(app): drop premature "agent can open it" hint from browser empty state PR1's embedded browser is human-driven only; agent-driven navigation is PR2. The empty-state copy promised an ability that does not exist yet and misled users into asking the agent to open pages. Updated zh and en. --- packages/app/src/i18n/en.ts | 2 +- packages/app/src/i18n/zh.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/app/src/i18n/en.ts b/packages/app/src/i18n/en.ts index 087b25524..05c69c43d 100644 --- a/packages/app/src/i18n/en.ts +++ b/packages/app/src/i18n/en.ts @@ -592,7 +592,7 @@ export const dict = { "session.tab.browser": "Browser", "browser.address.placeholder": "Enter a URL or paste a link", "browser.empty.title": "Nothing open yet", - "browser.empty.description": "Enter a URL above, or let the agent open one. Sites you sign in to stay signed in next time.", + "browser.empty.description": "Enter a URL above to start browsing. Sites you sign in to stay signed in next time.", "browser.action.back": "Back", "browser.action.forward": "Forward", "browser.action.reload": "Reload", diff --git a/packages/app/src/i18n/zh.ts b/packages/app/src/i18n/zh.ts index 314d8545b..7b464cd89 100644 --- a/packages/app/src/i18n/zh.ts +++ b/packages/app/src/i18n/zh.ts @@ -559,7 +559,7 @@ export const dict = { "session.tab.browser": "浏览器", "browser.address.placeholder": "输入网址,或粘贴链接", "browser.empty.title": "还没有打开网页", - "browser.empty.description": "在上面输入网址,或让 agent 替你打开。登录后的网站会保持登录,下次免登录。", + "browser.empty.description": "在上面输入网址开始浏览。登录后的网站会保持登录,下次免登录。", "browser.action.back": "后退", "browser.action.forward": "前进", "browser.action.reload": "刷新", From e0d4b5b5f069439b99d4db83dbf883f53f39b257 Mon Sep 17 00:00:00 2001 From: Yuhan Lei Date: Mon, 8 Jun 2026 16:00:48 +0800 Subject: [PATCH 6/8] fix(app): suppress browser overlay while the add-tab menu is open The titlebar add-tab "+" menu opens downward over the embedded browser's content region. The browser paints a native WebContentsView there, and a native layer ignores DOM stacking, so the menu's lower items were occluded by the loaded page once a tab was active. Lift the menu's open state into SessionSidePanel and thread it to BrowserPanel so the native overlay is suppressed while the menu is up, mirroring how the browser's own overflow menu and app modals already suppress it. --- .../pages/session/browser/browser-panel.tsx | 11 +++++++--- .../pages/session/right-panel-tab-strip.tsx | 6 ++++- .../pages/session/session-side-panel.test.tsx | 22 +++++++++++++++++++ .../src/pages/session/session-side-panel.tsx | 6 +++++ 4 files changed, 41 insertions(+), 4 deletions(-) diff --git a/packages/app/src/pages/session/browser/browser-panel.tsx b/packages/app/src/pages/session/browser/browser-panel.tsx index ad30cdf99..45ec08bcf 100644 --- a/packages/app/src/pages/session/browser/browser-panel.tsx +++ b/packages/app/src/pages/session/browser/browser-panel.tsx @@ -25,6 +25,9 @@ export function BrowserPanel(props: { bridge: BrowserBridge active: () => boolean panelOpen: () => boolean + // True while a right-panel chrome menu (the titlebar add-tab "+" menu) is open. + // It lives in a sibling component but its dropdown overlaps this content rect. + panelChromeMenuOpen: () => boolean }) { const language = useLanguage() const dialog = useDialog() @@ -54,9 +57,11 @@ export function BrowserPanel(props: { const secure = () => state()?.secure ?? false const address = createMemo(() => formatAddress(url())) - // Hide the native overlay whenever an app modal or this tab's own menu is open, - // since the view would otherwise paint over them. - const suppressed = () => !!dialog.active || menuOpen() + // Hide the native overlay whenever something must paint above it: an app modal, + // this tab's own overflow menu, or a right-panel chrome menu (the titlebar + // add-tab "+" menu opens downward over this content region). The view is a + // native layer, so DOM stacking can't lift those above it — it must be hidden. + const suppressed = () => !!dialog.active || menuOpen() || props.panelChromeMenuOpen() const shouldShow = createMemo(() => shouldShowBrowserView({ panelOpen: props.panelOpen(), diff --git a/packages/app/src/pages/session/right-panel-tab-strip.tsx b/packages/app/src/pages/session/right-panel-tab-strip.tsx index 699de4e18..103dbe65c 100644 --- a/packages/app/src/pages/session/right-panel-tab-strip.tsx +++ b/packages/app/src/pages/session/right-panel-tab-strip.tsx @@ -63,6 +63,10 @@ export function RightPanelTabStrip(props: { }[] openFilePicker: (onOpenFile?: () => void) => void showAllFiles: () => void + // Reported so the embedded browser can hide its native overlay while this + // menu is open — the dropdown opens down over the browser content region and + // a native layer ignores DOM stacking, so it would otherwise be occluded. + onMenuOpenChange: (open: boolean) => void }) { const language = useLanguage() const command = useCommand() @@ -139,7 +143,7 @@ export function RightPanelTabStrip(props: { the chip strip reads left-justified and `+` lives at the end of the rail (matching docs/design/ui_kits/desktop/RightPanel.jsx). */}
- + { expect(source).toContain(" { + test("add-tab menu open state is lifted and threaded to the strip and browser panel", async () => { + const source = await fs.readFile(SOURCE_PATH, "utf8") + expect(source).toContain("setAddTabMenuOpen") + expect(source).toContain("onMenuOpenChange={setAddTabMenuOpen}") + expect(source).toContain("panelChromeMenuOpen={addTabMenuOpen}") + }) + + test("the strip's add-tab menu reports its open state via onOpenChange", async () => { + const stripSource = await fs.readFile(path.join(__dirname, "right-panel-tab-strip.tsx"), "utf8") + expect(stripSource).toContain("onOpenChange={props.onMenuOpenChange}") + }) +}) diff --git a/packages/app/src/pages/session/session-side-panel.tsx b/packages/app/src/pages/session/session-side-panel.tsx index 2196c89b7..418a0eed6 100644 --- a/packages/app/src/pages/session/session-side-panel.tsx +++ b/packages/app/src/pages/session/session-side-panel.tsx @@ -88,6 +88,10 @@ export function SessionSidePanel(props: { onMount(() => { setTabsPortalMount(document.getElementById("pawwork-titlebar-tabs") ?? undefined) }) + // The titlebar add-tab "+" menu lives in RightPanelTabStrip but its dropdown + // overlaps the embedded browser's content region. Lift its open state here so + // the sibling BrowserPanel can hide its native overlay while the menu is up. + const [addTabMenuOpen, setAddTabMenuOpen] = createSignal(false) let bodyUnmountTimer: number | undefined const clearBodyUnmountTimer = () => { @@ -397,6 +401,7 @@ export function SessionSidePanel(props: { closableMissingTabs={closableMissingTabs} openFilePicker={openFilePicker} showAllFiles={showAllFiles} + onMenuOpenChange={setAddTabMenuOpen} /> @@ -453,6 +458,7 @@ export function SessionSidePanel(props: { bridge={bridge()} active={() => sidePanelTab() === "browser"} panelOpen={open} + panelChromeMenuOpen={addTabMenuOpen} /> )} From 72cc410f17517749785bc61a98515f646273da92 Mon Sep 17 00:00:00 2001 From: Yuhan Lei Date: Mon, 8 Jun 2026 16:08:14 +0800 Subject: [PATCH 7/8] fix(app): default loopback hosts to http in the browser address bar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A bare address with no scheme always got https, so an HTTP-only local dev server typed as "localhost:3000" failed to load on first navigation. Pick the scheme from the host: loopback hosts (localhost, *.localhost, 127.0.0.0/8, ::1, 0.0.0.0) default to http since they only ever route to the local machine; everything else — including private LAN IPs, whose network may be hostile — keeps the https default, and the user can type http:// to opt in. --- .../app/src/pages/session/browser/url.test.ts | 18 +++++++++- packages/app/src/pages/session/browser/url.ts | 36 ++++++++++++++++--- 2 files changed, 48 insertions(+), 6 deletions(-) diff --git a/packages/app/src/pages/session/browser/url.test.ts b/packages/app/src/pages/session/browser/url.test.ts index 3a7b0051e..7013d6ea4 100644 --- a/packages/app/src/pages/session/browser/url.test.ts +++ b/packages/app/src/pages/session/browser/url.test.ts @@ -19,10 +19,26 @@ describe("normalizeAddressInput", () => { }) test("treats host:port as a host, not a scheme", () => { - expect(normalizeAddressInput("localhost:3000")).toBe("https://localhost:3000") + // No `//`, so host:port is a host (not a scheme) and gets a scheme prefixed. expect(normalizeAddressInput("192.168.0.1:8080/p?q=1")).toBe("https://192.168.0.1:8080/p?q=1") }) + test("defaults loopback hosts to http so local dev servers just work", () => { + expect(normalizeAddressInput("localhost:3000")).toBe("http://localhost:3000") + expect(normalizeAddressInput("127.0.0.1:8080/p?q=1")).toBe("http://127.0.0.1:8080/p?q=1") + expect(normalizeAddressInput("api.localhost")).toBe("http://api.localhost") + expect(normalizeAddressInput("[::1]:5173")).toBe("http://[::1]:5173") + expect(normalizeAddressInput("0.0.0.0:5173")).toBe("http://0.0.0.0:5173") + }) + + test("keeps https for non-loopback hosts, including private LAN IPs", () => { + // Private LAN may sit on a hostile shared network, so a bare host keeps the + // https default; the user can type http:// to opt into plaintext. + expect(normalizeAddressInput("192.168.0.1:8080")).toBe("https://192.168.0.1:8080") + expect(normalizeAddressInput("10.0.0.5:3000")).toBe("https://10.0.0.5:3000") + expect(normalizeAddressInput("myserver:8080")).toBe("https://myserver:8080") + }) + test("passes through other schemes for the main process to validate/reject", () => { expect(normalizeAddressInput("ftp://files.example.com")).toBe("ftp://files.example.com") }) diff --git a/packages/app/src/pages/session/browser/url.ts b/packages/app/src/pages/session/browser/url.ts index b7320b144..907450ac1 100644 --- a/packages/app/src/pages/session/browser/url.ts +++ b/packages/app/src/pages/session/browser/url.ts @@ -5,18 +5,44 @@ * URLs (no search-engine fallback, which would be a product decision about which * engine). Anything already carrying a `scheme://` is passed through untouched — * the main process validates the scheme before loading, so this stays purely - * about shaping the string. Bareword/host input gets `https://` so the common - * case ("example.com") just works. Returns null for empty input (no navigation). + * about shaping the string. Bareword/host input gets a scheme: `http://` for + * loopback hosts (so a local dev server like "localhost:3000" just works) and + * `https://` for everything else. Returns null for empty input (no navigation). */ const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i +const LOOPBACK_IPV4 = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/ + +/** + * Loopback hosts only ever route to the local machine, so plaintext http has no + * MITM surface — and local dev servers are overwhelmingly http. Private LAN + * addresses are intentionally excluded: their network may be hostile, so they + * keep the https default and the user opts into plaintext by typing http://. + */ +function isLoopbackHost(host: string): boolean { + const h = host.toLowerCase() + return ( + h === "localhost" || + h.endsWith(".localhost") || + h === "0.0.0.0" || + h === "[::1]" || + LOOPBACK_IPV4.test(h) + ) +} export function normalizeAddressInput(raw: string): string | null { const trimmed = raw.trim() if (!trimmed) return null - // `host:port` (e.g. localhost:3000) has no `//`, so it is NOT treated as a - // scheme and correctly gets the https prefix below. + // Anything with a `scheme://` is passed through for the main process to validate. if (HAS_SCHEME.test(trimmed)) return trimmed - return `https://${trimmed}` + // Bareword host[:port][/path]. Parse with a throwaway scheme to read the bare + // hostname (drops the port/path, normalizes IPv6) and pick the scheme from it. + let host = trimmed + try { + host = new URL(`http://${trimmed}`).hostname + } catch { + // Unparseable as a host — fall through with the raw string and the https default. + } + return `${isLoopbackHost(host) ? "http" : "https"}://${trimmed}` } /** From 12d15cba32c63f0900c3af8903d6243fb65eb142 Mon Sep 17 00:00:00 2001 From: Yuhan Lei Date: Mon, 8 Jun 2026 16:13:55 +0800 Subject: [PATCH 8/8] fix(electron): reload the browser after clear-data during the first load reloadIfLoaded() only reloaded when hasPage was true, but hasPage stays false until the first navigation commits. If browser:clear-data ran while that first load was in flight, the request already sent with pre-clear cookies could land as stale signed-in content and never get the reload this path promises. Treat an in-flight load as live: reload now when a page is loaded, otherwise defer one reload until did-stop-loading when the first navigation is still in flight. The decision is extracted as the pure clearDataReloadAction for tests. --- .../src/main/browser/controller.ts | 18 ++++++++++--- .../src/main/browser/logic.test.ts | 26 ++++++++++++++++++- .../src/main/browser/logic.ts | 17 ++++++++++++ 3 files changed, 56 insertions(+), 5 deletions(-) diff --git a/packages/desktop-electron/src/main/browser/controller.ts b/packages/desktop-electron/src/main/browser/controller.ts index e72892ebc..68eac934f 100644 --- a/packages/desktop-electron/src/main/browser/controller.ts +++ b/packages/desktop-electron/src/main/browser/controller.ts @@ -1,7 +1,7 @@ import { WebContentsView, shell, type BrowserWindow } from "electron" import type { BrowserState, BrowserViewLayout } from "@opencode-ai/app/desktop-api" import { browserViewWebPreferences } from "./options" -import { computeViewBounds, deriveBrowserState, parseNavigable, safeExternalUrl } from "./logic" +import { clearDataReloadAction, computeViewBounds, deriveBrowserState, parseNavigable, safeExternalUrl } from "./logic" export const BROWSER_STATE_CHANNEL = "browser:state" @@ -139,11 +139,21 @@ export class BrowserViewController { this.view.setVisible(true) } - // Reflect a partition-wide data clear: reload so the page shows its - // signed-out state immediately. No-op when no real page is loaded. + // Reflect a partition-wide data clear: reload so the page shows its signed-out + // state immediately. A first navigation still in flight was sent with the + // pre-clear cookies, so defer one reload until it commits — otherwise it lands + // as stale signed-in content with no follow-up. No-op when idle with no page. reloadIfLoaded() { if (this.destroyed || this.wc.isDestroyed()) return - if (this.state().hasPage) this.wc.reload() + const action = clearDataReloadAction({ hasPage: this.state().hasPage, loading: this.wc.isLoading() }) + if (action === "now") { + this.wc.reload() + } else if (action === "defer") { + this.wc.once("did-stop-loading", () => { + if (this.destroyed || this.wc.isDestroyed()) return + this.wc.reload() + }) + } } destroy() { diff --git a/packages/desktop-electron/src/main/browser/logic.test.ts b/packages/desktop-electron/src/main/browser/logic.test.ts index 0beb6b112..b212e8c57 100644 --- a/packages/desktop-electron/src/main/browser/logic.test.ts +++ b/packages/desktop-electron/src/main/browser/logic.test.ts @@ -1,5 +1,12 @@ import { describe, expect, test } from "bun:test" -import { computeViewBounds, deriveBrowserState, parseNavigable, safeExternalUrl, type BrowserStateSnapshot } from "./logic" +import { + clearDataReloadAction, + computeViewBounds, + deriveBrowserState, + parseNavigable, + safeExternalUrl, + type BrowserStateSnapshot, +} from "./logic" describe("parseNavigable", () => { test("accepts http and https and normalizes", () => { @@ -87,3 +94,20 @@ describe("deriveBrowserState", () => { expect(state).toMatchObject({ title: "A", canGoBack: true, canGoForward: false, loading: true, favicon: "f" }) }) }) + +describe("clearDataReloadAction", () => { + test("reloads immediately when a page is loaded", () => { + expect(clearDataReloadAction({ hasPage: true, loading: false })).toBe("now") + expect(clearDataReloadAction({ hasPage: true, loading: true })).toBe("now") + }) + + test("defers one reload when the first navigation is still in flight", () => { + // hasPage stays false until the first load commits; the in-flight request + // carries the pre-clear cookies, so it must reload once it settles. + expect(clearDataReloadAction({ hasPage: false, loading: true })).toBe("defer") + }) + + test("does nothing when idle with no page", () => { + expect(clearDataReloadAction({ hasPage: false, loading: false })).toBe("none") + }) +}) diff --git a/packages/desktop-electron/src/main/browser/logic.ts b/packages/desktop-electron/src/main/browser/logic.ts index b589270c6..cc0e17eed 100644 --- a/packages/desktop-electron/src/main/browser/logic.ts +++ b/packages/desktop-electron/src/main/browser/logic.ts @@ -60,6 +60,23 @@ export type BrowserStateSnapshot = { favicon: string | null } +export type ClearDataReloadAction = "now" | "defer" | "none" + +/** + * After a partition-wide data clear, decide how the embedded view should refresh + * so it reflects the cleared (signed-out) cookies: + * - "now": a page is loaded → reload it immediately. + * - "defer": the first navigation is still in flight (no committed page yet, so + * hasPage is false) → it was sent with the pre-clear cookies, so reload once + * it settles instead of leaving stale signed-in content with no follow-up. + * - "none": nothing is loaded or loading → nothing to refresh. + */ +export function clearDataReloadAction(snapshot: { hasPage: boolean; loading: boolean }): ClearDataReloadAction { + if (snapshot.hasPage) return "now" + if (snapshot.loading) return "defer" + return "none" +} + /** * Derive the renderer-facing state from a raw webContents snapshot. `hasPage` is * false until a real page is loaded (empty or about: URL), which keeps the DOM