Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions packages/app/src/context/platform.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import { createSimpleContext } from "@opencode-ai/ui/context"
import type { AsyncStorage, SyncStorage } from "@solid-primitives/storage"
import type { Accessor } from "solid-js"
Expand Down Expand Up @@ -63,8 +63,8 @@
export type BrowserTarget = string

/**
* Control surface for the embedded browser (one app-owned WebContentsView per
* conversation, all sharing a persistent partition). Every call names its
* Control surface for the embedded browser (one app-owned WebContentsView and
* persistent browser profile per conversation). Every call names its
* target conversation; main validates the target against what the calling
* window is showing. Desktop/Electron only — undefined on web, where there is
* no native view to drive. Gate usage with `canUseBrowser`.
Expand All @@ -87,10 +87,10 @@
adoptDraft(sessionID: string): Promise<{ adopted: boolean; hasPage: boolean }>
/** Destroy the target's page outright (view, history, renderer process) via
* the same chain as session delete/archive. WYSIWYG counterpart of the
* browser tab's ×. Cookies/storage survive in the shared partition. */
* browser tab's ×. Cookies/storage survive in the conversation's profile. */
closePage(target: BrowserTarget): Promise<void>
/** Sign out of every site: clear cookies, storage, and cache (all targets —
* the partition is shared). */
/** Sign out of every site across all conversation profiles: clear cookies,
* storage, and cache. */
clearData(): Promise<void>
/** Step or reset the embedded page zoom for this conversation's view. */
zoom(target: BrowserTarget, action: "in" | "out" | "reset"): Promise<void>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,30 @@
import { join } from "node:path"
import { app, session } from "electron"
import { BrowserViewController } from "./controller"
import { BrowserControllerRegistry } from "./registry"
import { BrowserProfileRegistry } from "./profile-registry"
import { BrowserProfileSessions } from "./profile-sessions"
import { getStore } from "../store"
import { PAWWORK_RUNTIME } from "../runtime-namespace"

const PROFILE_MAP_KEY = "profiles"

export const browserProfiles = new BrowserProfileRegistry({
read: () => getStore(PAWWORK_RUNTIME.browserProfilesStore).get(PROFILE_MAP_KEY),
write: (profiles) => getStore(PAWWORK_RUNTIME.browserProfilesStore).set(PROFILE_MAP_KEY, profiles),
})

export const browserProfileSessions = new BrowserProfileSessions({
rootPath: () => join(app.getPath("sessionData"), PAWWORK_RUNTIME.browserProfilesDirectory),
fromPath: (path) => session.fromPath(path),
})

/** Single main-process instance of the conversation-view registry (see registry.ts). */
export const browserControllers = new BrowserControllerRegistry((key: string) => new BrowserViewController(key))
export const browserControllers = new BrowserControllerRegistry((key: string) => {
const profileID = browserProfiles.profileFor(key)
return new BrowserViewController(
key,
browserProfileSessions.sessionFor(profileID),
(sessionID) => browserProfiles.adopt(sessionID, profileID),
)
})
37 changes: 21 additions & 16 deletions packages/desktop-electron/src/main/browser/controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { BrowserWindow, WebContentsView, session, shell } from "electron"
import { BrowserWindow, WebContentsView, shell, type Session } from "electron"
import type { BrowserState, BrowserViewLayout } from "@opencode-ai/app/desktop-api"
import { BROWSER_PARTITION, browserViewWebPreferences } from "./options"
import { browserViewWebPreferences } from "./options"
import { configurePartitionUserAgent } from "./user-agent"
import {
clampPageZoom,
Expand Down Expand Up @@ -29,17 +29,17 @@ export const BROWSER_DISPLAY_TAKEN_CHANNEL = "browser:display-taken"
*/
const DEFAULT_VIEW_BOUNDS = { x: 0, y: 0, width: 1280, height: 720 }

let partitionUserAgentConfigured = false
const configuredUserAgentSessions = new WeakSet<Session>()
/**
* Configure the browser partition's UA before the first view/request, exactly
* once: present the partition as the faithful Chrome it is (rewrite + rationale
* in user-agent.ts and the PR). Scoped to the browser partition; the app
* Configure the browser profile Session's UA before the first view/request,
* exactly once: present the profile as the faithful Chrome it is (rewrite +
* rationale in user-agent.ts and the PR). Scoped to the browser Session; the app
* renderer keeps its own UA.
*/
function ensureBrowserPartitionUserAgent() {
if (partitionUserAgentConfigured) return
partitionUserAgentConfigured = true
configurePartitionUserAgent(session.fromPartition(BROWSER_PARTITION), process.versions.chrome ?? "")
function ensureBrowserSessionUserAgent(profileSession: Session) {
if (configuredUserAgentSessions.has(profileSession)) return
configuredUserAgentSessions.add(profileSession)
configurePartitionUserAgent(profileSession, process.versions.chrome ?? "")
}

/**
Expand All @@ -60,18 +60,22 @@ export class BrowserViewController {
private throttlingBefore: boolean | null = null
/**
* Sole source of truth for this conversation's page zoom (1 = 100%).
* Chromium may also remember per-origin zoom in the shared partition; we
* Chromium may also remember per-origin zoom in this profile's partition; we
* reassert this value on navigate/display so the UI percent matches the page.
*/
private pageZoom = PAGE_ZOOM_DEFAULT
/** Suppress zoom-changed while we write setZoomFactor ourselves. */
private applyingPageZoom = false

constructor(private target: string) {
// Configure the partition UA before the view exists, so its very first
constructor(
private target: string,
profileSession: Session,
private readonly onRetarget: (target: string) => void = () => {},
) {
// Configure the profile UA before the view exists, so its very first
// request already carries the faithful Chrome UA.
ensureBrowserPartitionUserAgent()
this.view = new WebContentsView({ webPreferences: browserViewWebPreferences() })
ensureBrowserSessionUserAgent(profileSession)
this.view = new WebContentsView({ webPreferences: browserViewWebPreferences(profileSession) })
this.view.setVisible(false)
this.view.setBounds(DEFAULT_VIEW_BOUNDS)
this.wireEvents()
Expand All @@ -84,6 +88,7 @@ export class BrowserViewController {
/** Draft adoption rekeys the controller; state pushes follow the new owner. */
retarget(target: string) {
this.target = target
this.onRetarget(target)
}

private wireEvents() {
Expand All @@ -92,7 +97,7 @@ export class BrowserViewController {
wc.on("did-stop-loading", () => this.emitState())
wc.on("did-navigate", () => {
this.favicon = null
// HostZoomMap is origin-scoped in the shared partition; reassert so a new
// HostZoomMap is origin-scoped in the profile partition; reassert so a new
// host does not leave the page at 100% while state still shows the old %.
this.reassertPageZoom()
this.emitState()
Expand Down
16 changes: 9 additions & 7 deletions packages/desktop-electron/src/main/browser/options.test.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
import { describe, expect, test } from "bun:test"
import { BROWSER_PARTITION, browserViewWebPreferences } from "./options"
import type { Session } from "electron"
import { browserViewWebPreferences } from "./options"

describe("embedded browser security", () => {
test("uses a locked-down, preload-free, sandboxed view on a persistent partition", () => {
const prefs = browserViewWebPreferences()
test("uses the supplied profile session with locked-down web preferences", () => {
const profileSession = {} as Session
const preferences = browserViewWebPreferences(profileSession)

expect(prefs).toMatchObject({
expect(preferences).toMatchObject({
session: profileSession,
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)
expect(preferences.preload).toBeUndefined()
expect(preferences.partition).toBeUndefined()
})
})
14 changes: 5 additions & 9 deletions packages/desktop-electron/src/main/browser/options.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,17 @@
import type { WebPreferences } from "electron"
import type { Session, 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"
/** The pre-isolation shared profile, retained only so Clear Data can erase it. */
export const LEGACY_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 {
export function browserViewWebPreferences(profileSession: Session): WebPreferences {
return {
partition: BROWSER_PARTITION,
session: profileSession,
sandbox: true,
contextIsolation: true,
nodeIntegration: false,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { describe, expect, test } from "bun:test"
import { draftKey } from "./registry"
import { BrowserProfileRegistry, type BrowserProfileStorage } from "./profile-registry"

function memoryStorage(initial: unknown = {}) {
let value = initial
const storage: BrowserProfileStorage = {
read: () => value,
write: (profiles) => {
value = profiles
},
}
return { storage, value: () => value }
}

function ids(...values: string[]) {
let index = 0
return () => values[index++] ?? `profile-${index}`
}

describe("BrowserProfileRegistry", () => {
test("gives each session a stable persistent profile", () => {
const memory = memoryStorage()
const profiles = new BrowserProfileRegistry(memory.storage, ids("profile-a", "profile-b"))

expect(profiles.profileFor("ses_a")).toBe("profile-a")
expect(profiles.profileFor("ses_a")).toBe("profile-a")
expect(profiles.profileFor("ses_b")).toBe("profile-b")
expect(memory.value()).toEqual({ ses_a: "profile-a", ses_b: "profile-b" })

const restored = new BrowserProfileRegistry(memory.storage, ids("unused"))
expect(restored.profileFor("ses_a")).toBe("profile-a")
})

test("keeps draft profiles unique without persisting reusable draft owner keys", () => {
const memory = memoryStorage()
const profiles = new BrowserProfileRegistry(memory.storage, ids("draft-a", "draft-b"))

const firstDraft = profiles.profileFor(draftKey(1))
const secondDraft = profiles.profileFor(draftKey(2))
expect(firstDraft).toBe("draft-a")
expect(secondDraft).toBe("draft-b")
expect(memory.value()).toEqual({})
})

test("binds an adopted draft profile only to its new session", () => {
const memory = memoryStorage()
const profiles = new BrowserProfileRegistry(memory.storage, ids("draft-a"))

const firstDraft = profiles.profileFor(draftKey(1))
profiles.adopt("ses_new", firstDraft)
expect(profiles.profileFor("ses_new")).toBe("draft-a")
expect(memory.value()).toEqual({ ses_new: "draft-a" })
})

test("repairs duplicate stored profiles instead of restoring shared session state", () => {
const memory = memoryStorage({ ses_a: "shared", ses_b: "shared" })
const profiles = new BrowserProfileRegistry(memory.storage, ids("profile-b"))

expect(profiles.profileFor("ses_a")).toBe("shared")
expect(profiles.profileFor("ses_b")).toBe("profile-b")
expect(memory.value()).toEqual({ ses_a: "shared", ses_b: "profile-b" })
})
})
62 changes: 62 additions & 0 deletions packages/desktop-electron/src/main/browser/profile-registry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { randomUUID } from "node:crypto"
import { draftWindowID } from "./registry"

export type BrowserProfileStorage = {
read(): unknown
write(profiles: Record<string, string>): void
}

export class BrowserProfileRegistry {
private profiles: Record<string, string> | undefined

constructor(
private readonly storage: BrowserProfileStorage,
private readonly createID: () => string = randomUUID,
) {}

private readProfiles(): Record<string, string> {
if (this.profiles) return this.profiles
const stored = this.storage.read()
if (!stored || typeof stored !== "object" || Array.isArray(stored)) return (this.profiles = {})
const used = new Set<string>()
this.profiles = Object.fromEntries(
Object.entries(stored).filter(([ownerKey, profileID]) => {
if (
draftWindowID(ownerKey) !== null ||
typeof profileID !== "string" ||
profileID.length === 0 ||
used.has(profileID)
)
return false
used.add(profileID)
return true
}),
)
return this.profiles
}

private persist() {
this.storage.write({ ...this.readProfiles() })
}

profileFor(ownerKey: string): string {
// Home drafts are window-lifetime owners. Never persist by draft:<windowID>:
// that key is reused after adoption and would make the old conversation and
// the window's next draft share a Chromium session again.
if (draftWindowID(ownerKey) !== null) return this.createID()
const profiles = this.readProfiles()
const existing = profiles[ownerKey]
if (existing) return existing
const created = this.createID()
profiles[ownerKey] = created
this.persist()
return created
}

/** Persist a draft controller's immutable profile under its adopted session. */
adopt(sessionID: string, profileID: string) {
if (draftWindowID(sessionID) !== null || !sessionID || !profileID) return
this.readProfiles()[sessionID] = profileID
this.persist()
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
Loading