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..05c69c43d 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 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", + "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..7b464cd89 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": "在上面输入网址开始浏览。登录后的网站会保持登录,下次免登录。", + "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..45ec08bcf --- /dev/null +++ b/packages/app/src/pages/session/browser/browser-panel.tsx @@ -0,0 +1,279 @@ +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 { useShellSurface } from "@/context/shell-surface" +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 + // 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() + const platform = usePlatform() + const shell = useShellSurface() + 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 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(), + 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(), + }), + ) + + // 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..7013d6ea4 --- /dev/null +++ b/packages/app/src/pages/session/browser/url.test.ts @@ -0,0 +1,57 @@ +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", () => { + // 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") + }) +}) + +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..907450ac1 --- /dev/null +++ b/packages/app/src/pages/session/browser/url.ts @@ -0,0 +1,63 @@ +/** + * 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 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 + // Anything with a `scheme://` is passed through for the main process to validate. + if (HAS_SCHEME.test(trimmed)) return 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}` +} + +/** + * 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..683464c97 --- /dev/null +++ b/packages/app/src/pages/session/browser/view-state.test.ts @@ -0,0 +1,40 @@ +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, coveredBySurface: false } + + test("shows only when open, active, has a page, not suppressed, and not covered by a surface", () => { + 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) + 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) + }) +}) + +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..bdc3bbb2a --- /dev/null +++ b/packages/app/src/pages/session/browser/view-state.ts @@ -0,0 +1,40 @@ +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, + * - 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 && !input.coveredBySurface +} + +/** + * 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..103dbe65c 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 }) { + + + ) } @@ -60,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() @@ -136,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). */}
- + ` tab values. Imported by helpers diff --git a/packages/app/src/pages/session/session-side-panel.test.tsx b/packages/app/src/pages/session/session-side-panel.test.tsx index bb74b7d5d..c4ca7def0 100644 --- a/packages/app/src/pages/session/session-side-panel.test.tsx +++ b/packages/app/src/pages/session/session-side-panel.test.tsx @@ -234,3 +234,25 @@ describe("right-panel inactive-tab gating contract", () => { 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 6ad1ee3cd..418a0eed6 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)") @@ -85,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 = () => { @@ -137,6 +144,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 +170,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 @@ -205,6 +216,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") @@ -377,6 +401,7 @@ export function SessionSidePanel(props: { closableMissingTabs={closableMissingTabs} openFilePicker={openFilePicker} showAllFiles={showAllFiles} + onMenuOpenChange={setAddTabMenuOpen} /> @@ -425,6 +450,19 @@ export function SessionSidePanel(props: { + + + {(bridge) => ( + + sidePanelTab() === "browser"} + panelOpen={open} + panelChromeMenuOpen={addTabMenuOpen} + /> + + )} +
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..68eac934f --- /dev/null +++ b/packages/desktop-electron/src/main/browser/controller.ts @@ -0,0 +1,165 @@ +import { WebContentsView, shell, type BrowserWindow } from "electron" +import type { BrowserState, BrowserViewLayout } from "@opencode-ai/app/desktop-api" +import { browserViewWebPreferences } from "./options" +import { clearDataReloadAction, computeViewBounds, deriveBrowserState, parseNavigable, safeExternalUrl } from "./logic" + +export const BROWSER_STATE_CHANNEL = "browser:state" + +/** + * 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) { + const safe = safeExternalUrl(url) + if (safe) void shell.openExternal(safe).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) + } + + // 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 + 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() { + 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..b212e8c57 --- /dev/null +++ b/packages/desktop-electron/src/main/browser/logic.test.ts @@ -0,0 +1,113 @@ +import { describe, expect, test } from "bun:test" +import { + clearDataReloadAction, + computeViewBounds, + deriveBrowserState, + parseNavigable, + safeExternalUrl, + 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("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({ + 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" }) + }) +}) + +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 new file mode 100644 index 000000000..cc0e17eed --- /dev/null +++ b/packages/desktop-electron/src/main/browser/logic.ts @@ -0,0 +1,96 @@ +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 +} + +// 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 + * 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 +} + +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 + * 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..f6a7ab441 --- /dev/null +++ b/packages/desktop-electron/src/main/ipc/browser.ts @@ -0,0 +1,61 @@ +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 + * 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) + }) + // 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) +} 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, } }