mirror of
https://github.com/stablyai/orca.git
synced 2026-11-18 20:06:10 +00:00
fix(browser): start a browser profile's extensions with its first page, not at launch (#42683)
* fix(browser): start a profile's extensions with its first page, not at launch Every local browser profile attached its enabled extensions at startup, so each profile's service workers ran even with no tab open. A profile now starts its extensions when it gets its first page or when Settings acts on it, and that page's first load waits (up to 3 s) until they have loaded. * fix(browser): keep extension startup out of import cycles
This commit is contained in:
@@ -19,6 +19,7 @@ import { AgentBrowserBridgeQueue } from '../command-queue/agent-browser-bridge-q
|
||||
import { assertRemoteCliPageAccess } from '../../routing/input-ownership/remote-cli-page-admission'
|
||||
import { agentBrowserSnapshotArgs } from '../protocol/agent-browser-snapshot-arguments'
|
||||
import { getBrowserPasskeyRequest } from '../../webauthn/browser-passkey-requests'
|
||||
import { whenBrowserExtensionsReadyForPage } from '../../extensions/profile-sessions/browser-extension-page-start'
|
||||
|
||||
export abstract class AgentBrowserBridgeCoreCommands extends AgentBrowserBridgeQueue {
|
||||
async snapshot(
|
||||
@@ -97,6 +98,8 @@ export abstract class AgentBrowserBridgeCoreCommands extends AgentBrowserBridgeQ
|
||||
if (!navigationUrl) {
|
||||
throw new BrowserError('invalid_argument', `Unsupported browser URL: ${url}`)
|
||||
}
|
||||
// A new tab's profile may still be starting its extensions; its first page waits for them.
|
||||
await whenBrowserExtensionsReadyForPage(wc)
|
||||
const navigationState: { preventUnloadEvent: Electron.Event | null } = {
|
||||
preventUnloadEvent: null
|
||||
}
|
||||
|
||||
@@ -71,7 +71,8 @@ class MockBrowserWindow {
|
||||
vi.mock('electron', () => ({ BrowserWindow: mocks.BrowserWindow }))
|
||||
vi.mock('../sessions/profiles/browser-session-registry', () => ({
|
||||
browserSessionRegistry: {
|
||||
getDefaultProfile: vi.fn(() => ({ id: 'default', partition: 'persist:orca-browser' }))
|
||||
getDefaultProfile: vi.fn(() => ({ id: 'default', partition: 'persist:orca-browser' })),
|
||||
attachExtensions: vi.fn()
|
||||
}
|
||||
}))
|
||||
|
||||
|
||||
@@ -9,6 +9,10 @@ import type { BrowserManager } from '../guest-lifecycle/manager/browser-manager'
|
||||
import type { AgentBrowserBridge } from '../agent-browser/agent-browser-bridge'
|
||||
import { browserSessionRegistry } from '../sessions/profiles/browser-session-registry'
|
||||
import { installBrowserJavaScriptDialogs } from '../guest-lifecycle/prompts/browser-javascript-dialogs'
|
||||
import {
|
||||
loadPageWhenReady,
|
||||
whenBrowserExtensionsStartFor
|
||||
} from '../extensions/profile-sessions/browser-extension-page-start'
|
||||
import type { ServeBrowserPageState } from '../../runtime/browser/headless/serve-browser-tab-layout'
|
||||
|
||||
// orca serve has no renderer for webviews; hidden offscreen BrowserWindows host its pages.
|
||||
@@ -46,6 +50,11 @@ export class OffscreenBrowserBackend implements BrowserBackend {
|
||||
? browserSessionRegistry.getProfile(params.profileId)
|
||||
: browserSessionRegistry.getDefaultProfile()
|
||||
const partition = profile?.partition ?? ORCA_BROWSER_PARTITION
|
||||
if (profile) {
|
||||
// A server page starts its profile's extensions, as a desktop tab does.
|
||||
browserSessionRegistry.attachExtensions(profile.id)
|
||||
}
|
||||
const extensionsReady = profile ? whenBrowserExtensionsStartFor(profile.id) : null
|
||||
|
||||
const win = new BrowserWindow({
|
||||
show: false,
|
||||
@@ -112,7 +121,10 @@ export class OffscreenBrowserBackend implements BrowserBackend {
|
||||
}
|
||||
|
||||
const url = params.url || 'about:blank'
|
||||
void this.loadUrl(win, url).catch((error) => {
|
||||
const loaded = extensionsReady
|
||||
? loadPageWhenReady(win.webContents, extensionsReady, () => this.loadUrl(win, url))
|
||||
: this.loadUrl(win, url)
|
||||
void loaded.catch((error) => {
|
||||
console.warn(
|
||||
'[offscreen-browser] page load failed:',
|
||||
error instanceof Error ? error.message : String(error)
|
||||
|
||||
@@ -159,6 +159,7 @@ it('clears Google paths/partitions and preserves other sites across a graceful E
|
||||
unused as retireFailedBrowserSessionProfile, unused as cancelBrowserWebAuthnAccountRequestsForSession,
|
||||
unused as retireDeletedBrowserSessionProfile,
|
||||
unused as attachBrowserExtensionsToProfileSession,
|
||||
unused as getBrowserExtensionSessionForProfile, unused as isBrowserExtensionSupportEnabled,
|
||||
unused as getCanonicalUserDataPath, unused as markBrowserIdentityMigrationNoticePending,
|
||||
unused as forgetBrowserProfileOwnedStores };
|
||||
`
|
||||
|
||||
@@ -19,7 +19,8 @@ import {
|
||||
loadBrowserExtensionFolderIntoProfile,
|
||||
loadBrowserExtensionIntoProfile,
|
||||
unloadBrowserExtensionEverywhere,
|
||||
unloadBrowserExtensionFromProfile
|
||||
unloadBrowserExtensionFromProfile,
|
||||
whenBrowserExtensionProfileLoaded
|
||||
} from './profile-sessions/browser-extension-session-loader'
|
||||
import { clearBrowserExtensionSessionData } from './profile-storage/browser-extension-data-removal'
|
||||
import {
|
||||
@@ -109,6 +110,7 @@ export function setBrowserExtensionEnabled(
|
||||
if (!installed) {
|
||||
throw new Error('Extension is not installed')
|
||||
}
|
||||
browserSessionRegistry.attachExtensions(browserProfileId)
|
||||
await loadBrowserExtensionIntoProfile(browserProfileId, installed)
|
||||
browserSessionRegistry.updateEnabledExtensionIds((byProfile) =>
|
||||
withExtensionEnabled(byProfile, browserProfileId, extensionId, true)
|
||||
@@ -230,6 +232,7 @@ export function addUnpackedBrowserExtension(
|
||||
}
|
||||
let loaded: Electron.Extension
|
||||
try {
|
||||
browserSessionRegistry.attachExtensions(browserProfileId)
|
||||
loaded = await loadBrowserExtensionFolderIntoProfile(
|
||||
browserProfileId,
|
||||
extensionId,
|
||||
@@ -260,6 +263,8 @@ export function openBrowserExtensionOptions(
|
||||
extensionId: string
|
||||
): Promise<BrowserExtensionActionResult> {
|
||||
return settle(async () => {
|
||||
browserSessionRegistry.attachExtensions(browserProfileId)
|
||||
await whenBrowserExtensionProfileLoaded(browserProfileId)
|
||||
const extension =
|
||||
getBrowserExtensionSessionForProfile(browserProfileId)?.extensions.getExtension(extensionId)
|
||||
if (!extension) {
|
||||
|
||||
@@ -11,10 +11,7 @@ import {
|
||||
setBrowserExtensionSupportEnabled
|
||||
} from './browser-extension-support'
|
||||
import { browserSessionRegistry } from '../sessions/profiles/browser-session-registry'
|
||||
import {
|
||||
attachBrowserExtensionsToProfileSession,
|
||||
detachBrowserExtensionsFromAllProfileSessions
|
||||
} from './profile-sessions/browser-extension-session-loader'
|
||||
import { detachBrowserExtensionsFromAllProfileSessions } from './profile-sessions/browser-extension-session-loader'
|
||||
import { notifyBrowserExtensionActionsChanged } from './actions/browser-extension-action-registry'
|
||||
import { registerBrowserExtensionNamespaces } from './register-browser-extension-namespaces'
|
||||
import { observeBrowserExtensionTabLifecycle } from './tabs-and-windows/browser-extension-tab-lifecycle'
|
||||
@@ -57,7 +54,7 @@ export function initializeBrowserExtensionSupport(options: {
|
||||
|
||||
/**
|
||||
* The extensions setting changed while Orca runs. Off unloads every profile's extensions and
|
||||
* keeps their data; on loads them into every open profile, as a launch would.
|
||||
* keeps their data; on loads them into each profile that has a page open.
|
||||
*/
|
||||
export function switchBrowserExtensionSupport(enabled: boolean): Promise<void> {
|
||||
// Why chained: an unload still in flight must finish before a load reuses the same sessions.
|
||||
@@ -69,14 +66,14 @@ export function switchBrowserExtensionSupport(enabled: boolean): Promise<void> {
|
||||
setBrowserExtensionSupportEnabled(enabled)
|
||||
if (enabled) {
|
||||
installBrowserExtensionSupport()
|
||||
for (const profile of browserSessionRegistry.listProfiles()) {
|
||||
attachBrowserExtensionsToProfileSession(
|
||||
profile,
|
||||
browserSessionRegistry.getEnabledExtensionIds(profile.id)
|
||||
)
|
||||
// Why: pages already open, server pages included, were created before extensions ran.
|
||||
for (const contents of webContents.getAllWebContents()) {
|
||||
const profileId = browserSessionRegistry.profileIdForSession(contents.session)
|
||||
if (profileId) {
|
||||
browserSessionRegistry.attachExtensions(profileId)
|
||||
}
|
||||
observeExtensionContents(contents)
|
||||
}
|
||||
// Why: tabs already open were created before their session ran extensions.
|
||||
webContents.getAllWebContents().forEach(observeExtensionContents)
|
||||
} else {
|
||||
await detachBrowserExtensionsFromAllProfileSessions()
|
||||
}
|
||||
@@ -97,7 +94,9 @@ function installBrowserExtensionSupport(): void {
|
||||
return
|
||||
}
|
||||
initialized = true
|
||||
setSavedBrowserTabsSource(savedBrowserTabs)
|
||||
setSavedBrowserTabsSource(savedBrowserTabs, (profileId) =>
|
||||
browserSessionRegistry.resolveKnownPartition(profileId)
|
||||
)
|
||||
registerBrowserExtensionNamespaces()
|
||||
installBrowserExtensionApiHost()
|
||||
installBrowserExtensionSessionServices()
|
||||
|
||||
@@ -260,11 +260,12 @@ export async function prepareBrowserExtensionDirectory(
|
||||
options: { refresh?: boolean } = {}
|
||||
): Promise<PreparedBrowserExtensionDirectory> {
|
||||
const key = resolve(extension.path)
|
||||
let running = pending.get(key)
|
||||
const copied = copiedThisRun.get(key)
|
||||
if (copied && !options.refresh) {
|
||||
// Why not while a copy runs: a profile starting mid-Reload must load the finished copy.
|
||||
if (copied && !options.refresh && !running) {
|
||||
return copied
|
||||
}
|
||||
let running = pending.get(key)
|
||||
if (!running) {
|
||||
running = prepare(extension)
|
||||
pending.set(key, running)
|
||||
|
||||
@@ -36,6 +36,7 @@ vi.mock('../../sessions/profiles/browser-session-registry', () => ({
|
||||
browserSessionRegistry: {
|
||||
listProfiles: () => [{ id: 'default' }, { id: 'work' }],
|
||||
getProfile: (id: string) => ({ id }),
|
||||
attachExtensions: () => {},
|
||||
getEnabledExtensionIds: (profileId: string) => state.enabled[profileId] ?? [],
|
||||
updateEnabledExtensionIds: (
|
||||
update: (value: Record<string, string[]>) => Record<string, string[]>
|
||||
|
||||
@@ -158,6 +158,7 @@ export async function commitStagedWebStoreExtension(
|
||||
await reloadBrowserExtensionWhereEnabled(record)
|
||||
}
|
||||
if (enableInProfileId) {
|
||||
browserSessionRegistry.attachExtensions(enableInProfileId)
|
||||
await loadBrowserExtensionIntoProfile(enableInProfileId, record)
|
||||
browserSessionRegistry.updateEnabledExtensionIds((byProfile) =>
|
||||
withExtensionEnabled(byProfile, enableInProfileId, extensionId, true)
|
||||
|
||||
+1
@@ -26,6 +26,7 @@ vi.mock('../../guest-lifecycle/manager/browser-manager', () => ({ browserManager
|
||||
vi.mock('../../sessions/profiles/browser-session-registry', () => ({
|
||||
browserSessionRegistry: {
|
||||
getProfile: () => ({ label: 'Work' }),
|
||||
attachExtensions: () => {},
|
||||
getEnabledExtensionIds: () => [],
|
||||
updateEnabledExtensionIds: vi.fn()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { app } from 'electron'
|
||||
import { getBrowserExtensionProfileIdForSession } from '../api-runtime/browser-extension-api-host'
|
||||
import {
|
||||
isBrowserExtensionProfileLoading,
|
||||
whenBrowserExtensionProfileLoaded
|
||||
} from './browser-extension-session-loader'
|
||||
|
||||
// Why bounded: a slow extension must not keep the page from loading.
|
||||
const FIRST_LOAD_WAIT_MS = 3_000
|
||||
|
||||
/**
|
||||
* What a page opening in this profile must wait for before its first load, or null when its
|
||||
* extensions are not loading. Waiting registers content scripts before the page commits, and
|
||||
* keeps its request out of flight while a webRequest extension loads, which Electron would
|
||||
* leave hanging. Callers start the profile's extensions first (registry.attachExtensions).
|
||||
*/
|
||||
export function whenBrowserExtensionsStartFor(profileId: string): Promise<void> | null {
|
||||
return whileExtensionsStart(profileId)
|
||||
}
|
||||
|
||||
/** For a load into an existing page: the same wait, when its profile's extensions are still starting. */
|
||||
export function whenBrowserExtensionsReadyForPage(
|
||||
contents: Electron.WebContents
|
||||
): Promise<void> | null {
|
||||
const profileId = getBrowserExtensionProfileIdForSession(contents.session)
|
||||
return profileId ? whileExtensionsStart(profileId) : null
|
||||
}
|
||||
|
||||
const startWaits = new Map<string, Promise<void>>()
|
||||
|
||||
// One bounded wait per starting profile, so a later caller never extends the deadline.
|
||||
function whileExtensionsStart(profileId: string): Promise<void> | null {
|
||||
if (!isBrowserExtensionProfileLoading(profileId)) {
|
||||
return null
|
||||
}
|
||||
const running = startWaits.get(profileId)
|
||||
if (running) {
|
||||
return running
|
||||
}
|
||||
let timer: NodeJS.Timeout | undefined
|
||||
const wait = Promise.race([
|
||||
whenBrowserExtensionProfileLoaded(profileId),
|
||||
new Promise<void>((resolve) => {
|
||||
timer = setTimeout(resolve, FIRST_LOAD_WAIT_MS)
|
||||
})
|
||||
]).finally(() => {
|
||||
clearTimeout(timer)
|
||||
startWaits.delete(profileId)
|
||||
})
|
||||
startWaits.set(profileId, wait)
|
||||
return wait
|
||||
}
|
||||
|
||||
const heldFirstLoads = new WeakSet<Electron.WebContents>()
|
||||
|
||||
/** Its first load is held for its profile's extensions, so it counts as loading already. */
|
||||
export function isBrowserPageFirstLoadHeld(contents: Electron.WebContents): boolean {
|
||||
return heldFirstLoads.has(contents)
|
||||
}
|
||||
|
||||
/** Loads `load` once `ready` settles, unless the page was navigated elsewhere meanwhile. */
|
||||
export function loadPageWhenReady(
|
||||
contents: Electron.WebContents,
|
||||
ready: Promise<unknown>,
|
||||
load: () => Promise<void>
|
||||
): Promise<void> {
|
||||
heldFirstLoads.add(contents)
|
||||
let navigated = false
|
||||
const noteNavigation = (): void => {
|
||||
navigated = true
|
||||
heldFirstLoads.delete(contents)
|
||||
}
|
||||
contents.once('did-start-navigation', noteNavigation)
|
||||
return ready.then(() => {
|
||||
heldFirstLoads.delete(contents)
|
||||
contents.off('did-start-navigation', noteNavigation)
|
||||
return navigated || contents.isDestroyed() ? undefined : load()
|
||||
})
|
||||
}
|
||||
|
||||
/** will-attach-webview for a tab in a local profile: its first load waits for the profile's extensions. */
|
||||
export function holdWebviewFirstLoadForExtensions(
|
||||
embedder: Electron.WebContents,
|
||||
profileId: string,
|
||||
params: Record<string, string>
|
||||
): void {
|
||||
const ready = whileExtensionsStart(profileId)
|
||||
const src = params.src
|
||||
if (!ready || !src) {
|
||||
return
|
||||
}
|
||||
// Electron loads params.src when the guest attaches; without it the guest waits blank.
|
||||
delete params.src
|
||||
// Why: Electron creates the guest synchronously right after will-attach-webview.
|
||||
const claim = (_event: Electron.Event, guest: Electron.WebContents): void => {
|
||||
app.off('web-contents-created', claim)
|
||||
// Why after attach too: the <webview> only hears the guest's navigation events once attached.
|
||||
void loadPageWhenReady(guest, Promise.all([whenAttached(embedder, guest), ready]), () =>
|
||||
guest.loadURL(src)
|
||||
).catch(() => {})
|
||||
}
|
||||
app.on('web-contents-created', claim)
|
||||
queueMicrotask(() => app.off('web-contents-created', claim))
|
||||
}
|
||||
|
||||
const attachWaiters = new WeakMap<Electron.WebContents, () => void>()
|
||||
const watchedEmbedders = new WeakSet<Electron.WebContents>()
|
||||
|
||||
function whenAttached(embedder: Electron.WebContents, guest: Electron.WebContents): Promise<void> {
|
||||
if (!watchedEmbedders.has(embedder)) {
|
||||
watchedEmbedders.add(embedder)
|
||||
embedder.on('did-attach-webview', (_event, attached) => attachWaiters.get(attached)?.())
|
||||
}
|
||||
return new Promise<void>((resolve) => {
|
||||
const done = (): void => {
|
||||
attachWaiters.delete(guest)
|
||||
guest.off('destroyed', done)
|
||||
resolve()
|
||||
}
|
||||
attachWaiters.set(guest, done)
|
||||
guest.once('destroyed', done)
|
||||
})
|
||||
}
|
||||
@@ -36,8 +36,10 @@ import {
|
||||
type ProfileSessionState = {
|
||||
profile: BrowserSessionProfile
|
||||
session: Electron.Session
|
||||
/** Startup's sweep and loads; later loads wait for it. */
|
||||
/** The attach's sweep and loads; later loads wait for it. */
|
||||
loading: Promise<void>
|
||||
/** Until `loading` settles, when the attach had extensions to load. */
|
||||
loadingExtensions: boolean
|
||||
loads: BrowserExtensionProfileLoads
|
||||
}
|
||||
|
||||
@@ -122,8 +124,19 @@ export function attachBrowserExtensionsToProfileSession(
|
||||
console.warn('[browser-extensions] Could not initialize extension storage:', error)
|
||||
throw error
|
||||
})
|
||||
void loading.catch(() => {})
|
||||
stateByProfileId.set(profile.id, { profile, session: sess, loading, loads })
|
||||
const state: ProfileSessionState = {
|
||||
profile,
|
||||
session: sess,
|
||||
loading,
|
||||
loadingExtensions: enabledExtensionIds.length > 0,
|
||||
loads
|
||||
}
|
||||
void loading
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
state.loadingExtensions = false
|
||||
})
|
||||
stateByProfileId.set(profile.id, state)
|
||||
}
|
||||
|
||||
/** Unloads a profile session's extensions and Orca's wiring; its saved extension data stays. */
|
||||
@@ -173,21 +186,14 @@ export async function detachBrowserExtensionsFromAllProfileSessions(): Promise<v
|
||||
await Promise.all(states.map(unloadProfileSession))
|
||||
}
|
||||
|
||||
/** One profile session's startup loads, restore hooks included. */
|
||||
/** One profile session's attach-time loads, restore hooks included. */
|
||||
export function whenBrowserExtensionProfileLoaded(profileId: string): Promise<void> {
|
||||
return stateByProfileId.get(profileId)?.loading.catch(() => {}) ?? Promise.resolve()
|
||||
}
|
||||
|
||||
/** Startup waits briefly so restored tabs get content scripts; a slow load never blocks launch. */
|
||||
export async function whenBrowserExtensionSessionsLoaded(timeoutMs: number): Promise<void> {
|
||||
let timer: NodeJS.Timeout | undefined
|
||||
await Promise.race([
|
||||
Promise.all([...stateByProfileId.values()].map((state) => state.loading.catch(() => {}))),
|
||||
new Promise<void>((resolve) => {
|
||||
timer = setTimeout(resolve, timeoutMs)
|
||||
})
|
||||
])
|
||||
clearTimeout(timer)
|
||||
/** Whether the profile's enabled extensions are still loading after its attach. */
|
||||
export function isBrowserExtensionProfileLoading(profileId: string): boolean {
|
||||
return stateByProfileId.get(profileId)?.loadingExtensions ?? false
|
||||
}
|
||||
|
||||
export function getBrowserExtensionSessionForProfile(profileId: string): Electron.Session | null {
|
||||
|
||||
+11
-10
@@ -4,14 +4,13 @@ import { createServer } from 'node:http'
|
||||
import '../../../../shared/constants'
|
||||
import { ORCA_BROWSER_PARTITION } from '../../../../shared/browser/browser-session-partition'
|
||||
import { applyBackgroundActivationPolicy } from '../../../window/activation/foreground-activation-policy'
|
||||
import { initializeBrowserProcessUserAgent } from '../../identity/browser-process-user-agent'
|
||||
import { browserManager } from '../../guest-lifecycle/manager/browser-manager'
|
||||
import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry'
|
||||
import { initializeBrowserExtensionSupport } from '../browser-extension-startup'
|
||||
import { BROWSER_EXTENSION_API_CUSTOM_SCHEME } from '../api-runtime/browser-extension-api-scheme'
|
||||
import {
|
||||
attachBrowserExtensionsToProfileSession,
|
||||
whenBrowserExtensionSessionsLoaded
|
||||
} from '../profile-sessions/browser-extension-session-loader'
|
||||
import { attachBrowserExtensionsToProfileSession } from '../profile-sessions/browser-extension-session-loader'
|
||||
import { holdWebviewFirstLoadForExtensions } from '../profile-sessions/browser-extension-page-start'
|
||||
import { addUnpackedBrowserExtension } from '../browser-extension-management'
|
||||
import { closeBrowserExtensionProfileDocumentStores } from './browser-extension-profile-document-store'
|
||||
import { buildBrowserExtensionPageContextMenu } from '../context-menus/browser-extension-context-menu-host'
|
||||
@@ -36,6 +35,8 @@ const fixtureExtensionDirectory = extensionDirectory
|
||||
|
||||
// Orca's preflight registers this before ready; the worker shim calls main through it.
|
||||
protocol.registerSchemesAsPrivileged([BROWSER_EXTENSION_API_CUSTOM_SCHEME])
|
||||
// Orca sets this before ready; the tab's guest policies read it as its first load starts.
|
||||
initializeBrowserProcessUserAgent('clean')
|
||||
|
||||
const presentationCalls: string[] = []
|
||||
for (const method of ['show', 'showInactive', 'focus', 'moveTop'] as const) {
|
||||
@@ -101,6 +102,11 @@ async function openTab(url: string): Promise<Electron.WebContents> {
|
||||
webPreferences: { contextIsolation: true, sandbox: true, webviewTag: true }
|
||||
})
|
||||
trackBrowserExtensionMainWindow(host)
|
||||
// What Orca's main window does when a tab attaches in a browser profile.
|
||||
host.webContents.on('will-attach-webview', (_event, _webPreferences, params) => {
|
||||
browserSessionRegistry.attachExtensions('default')
|
||||
holdWebviewFirstLoadForExtensions(host.webContents, 'default', params)
|
||||
})
|
||||
const attached = new Promise<Electron.WebContents>((resolve) => {
|
||||
host.webContents.once('did-attach-webview', (_event, guest) => {
|
||||
guest.on('console-message', (details) => capture(details.message))
|
||||
@@ -145,12 +151,7 @@ async function run(): Promise<void> {
|
||||
return
|
||||
}
|
||||
|
||||
// Second launch: what a restart does, then the first page load.
|
||||
attachBrowserExtensionsToProfileSession(
|
||||
profile,
|
||||
browserSessionRegistry.getEnabledExtensionIds(profile.id)
|
||||
)
|
||||
await whenBrowserExtensionSessionsLoaded(5_000)
|
||||
// Second launch: the profile's extensions start with its first page, which must still get them.
|
||||
const guest = await openTab(pageUrl)
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the builder reads only the fields given here.
|
||||
const params = {
|
||||
|
||||
+31
-10
@@ -85,7 +85,8 @@ vi.mock('../profile-sessions/browser-extension-session-loader', () => {
|
||||
getBrowserExtensionProfileForPartition: (partition: string) =>
|
||||
profile(partition.replace('persist:', '')),
|
||||
getBrowserExtensionSessionForProfile: (id: string) =>
|
||||
id === 'default' || id === 'work' ? mocks.sessions[id] : null
|
||||
id === 'default' || id === 'work' ? mocks.sessions[id] : null,
|
||||
isBrowserExtensionProfileLoading: () => false
|
||||
}
|
||||
})
|
||||
vi.mock('./browser-extension-window-model', () => ({
|
||||
@@ -256,16 +257,21 @@ beforeEach(() => {
|
||||
page('streamed', 'bt-ssh', { remoteBrowserPageId: 'runtime-page' })
|
||||
])
|
||||
}
|
||||
discardedTabs.setSavedBrowserTabsSource({
|
||||
getWorkspaceSessionHostIds: () => ['local', 'ssh:box'],
|
||||
getWorkspaceSession: (hostId) => (hostId === 'ssh:box' ? saved.ssh : saved.local),
|
||||
onWorkspaceSessionWritten: (listener) => {
|
||||
writeListener = listener
|
||||
return () => {
|
||||
writeListener = null
|
||||
discardedTabs.setSavedBrowserTabsSource(
|
||||
{
|
||||
getWorkspaceSessionHostIds: () => ['local', 'ssh:box'],
|
||||
getWorkspaceSession: (hostId) => (hostId === 'ssh:box' ? saved.ssh : saved.local),
|
||||
onWorkspaceSessionWritten: (listener) => {
|
||||
writeListener = listener
|
||||
return () => {
|
||||
writeListener = null
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
},
|
||||
(id) =>
|
||||
// 'idle' is a profile whose extensions have not started: it has no extension session.
|
||||
id && !(id in mocks.sessions) && id !== 'idle' ? null : `persist:${id ?? 'default'}`
|
||||
)
|
||||
discardedTabs.forgetBrowserPageGuestsGone()
|
||||
// Retire ids an earlier test handed out, so each test starts with none listed.
|
||||
for (const pageId of ['live', 'cold', 'doc', 'notes', 'job', 'remote', 'streamed']) {
|
||||
@@ -310,6 +316,21 @@ describe('restored browser pages without a guest are discarded tabs', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it("lists no page of a profile whose extensions have not started, not even to Default's", async () => {
|
||||
saved.local.browserTabsByWorktree = {
|
||||
...saved.local.browserTabsByWorktree,
|
||||
'wt-2': [tab('bt-idle', { sessionProfileId: 'idle' })]
|
||||
}
|
||||
saved.local.browserPagesByWorkspace = {
|
||||
...saved.local.browserPagesByWorkspace,
|
||||
'bt-idle': [page('idle', 'bt-idle')]
|
||||
}
|
||||
writeListener?.('local')
|
||||
const urls = (await query({ discarded: true })).map((entry) => entry.url)
|
||||
expect(urls).toContain('https://cold.test/')
|
||||
expect(urls).not.toContain('https://idle.test/')
|
||||
})
|
||||
|
||||
it('does not list a closed page until the session save drops it, nor an evicted one after', async () => {
|
||||
const live = mocks.guests.get(11)
|
||||
if (!(live instanceof EventEmitter)) {
|
||||
|
||||
@@ -5,7 +5,6 @@ import type { BrowserPage, BrowserWorkspace } from '../../../../shared/browser-w
|
||||
import { browserManager } from '../../guest-lifecycle/manager/browser-manager'
|
||||
import { emitBrowserExtensionEvent } from '../api-runtime/browser-extension-api-host'
|
||||
import {
|
||||
getBrowserExtensionProfile,
|
||||
getBrowserExtensionProfileForPartition,
|
||||
getBrowserExtensionSessionForProfile
|
||||
} from '../profile-sessions/browser-extension-session-loader'
|
||||
@@ -39,17 +38,18 @@ export type DiscardedBrowserTab = {
|
||||
/** Far past webContents ids (they count up from 1), still a 32-bit int like Chrome's tab ids. */
|
||||
export const FIRST_DISCARDED_BROWSER_TAB_ID = 1_000_000_000
|
||||
|
||||
type PartitionResolver = (profileId: string | null | undefined) => string | null
|
||||
|
||||
let source: SavedBrowserTabsSource | null = null
|
||||
let resolveKnownPartition: PartitionResolver = () => null
|
||||
let stopWatchingWrites: (() => void) | null = null
|
||||
let nextTabId = FIRST_DISCARDED_BROWSER_TAB_ID
|
||||
const assignedByPageId = new Map<string, { tabId: number; session: Electron.Session }>()
|
||||
|
||||
/** The extension session a tab's guest would load in, as the renderer picks its partition. */
|
||||
function extensionSessionFor(tab: BrowserWorkspace): Electron.Session | null {
|
||||
const profile = tab.sessionPartition
|
||||
? getBrowserExtensionProfileForPartition(tab.sessionPartition)
|
||||
: (getBrowserExtensionProfile(tab.sessionProfileId ?? 'default') ??
|
||||
getBrowserExtensionProfile('default'))
|
||||
const partition = tab.sessionPartition || resolveKnownPartition(tab.sessionProfileId)
|
||||
const profile = partition ? getBrowserExtensionProfileForPartition(partition) : null
|
||||
return profile ? getBrowserExtensionSessionForProfile(profile.id) : null
|
||||
}
|
||||
|
||||
@@ -130,9 +130,14 @@ export function emitDiscardedBrowserTabRemoved(tab: {
|
||||
}
|
||||
|
||||
/** Main's copy of the renderer's saved browser tabs; read on every listing, so never stale for long. */
|
||||
export function setSavedBrowserTabsSource(next: SavedBrowserTabsSource | null): void {
|
||||
/** `resolvePartition` is the session registry's: a saved tab's profile id to its partition. */
|
||||
export function setSavedBrowserTabsSource(
|
||||
next: SavedBrowserTabsSource | null,
|
||||
resolvePartition: PartitionResolver
|
||||
): void {
|
||||
stopWatchingWrites?.()
|
||||
source = next
|
||||
resolveKnownPartition = resolvePartition
|
||||
stopWatchingWrites =
|
||||
next?.onWorkspaceSessionWritten((hostId) => {
|
||||
if (unloadedPageIds.size === 0 && assignedByPageId.size === 0) {
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
takeDiscardedBrowserTabId
|
||||
} from './browser-extension-discarded-tabs'
|
||||
import { isBrowserExtensionSupportEnabled } from '../browser-extension-support'
|
||||
import { whenBrowserExtensionsReadyForPage } from '../profile-sessions/browser-extension-page-start'
|
||||
import {
|
||||
canExtensionSeeTabUrl,
|
||||
describeBrowserExtensionTab,
|
||||
@@ -99,6 +100,21 @@ export function announceRegisteredBrowserExtensionTab(
|
||||
if (!isBrowserExtensionSupportEnabled() || !contents || contents.isDestroyed()) {
|
||||
return
|
||||
}
|
||||
// A profile's first tab registers before its extensions have loaded to hear about it.
|
||||
const starting = whenBrowserExtensionsReadyForPage(contents)
|
||||
if (starting) {
|
||||
void starting.then(() => {
|
||||
if (isBrowserExtensionSupportEnabled() && !contents.isDestroyed()) {
|
||||
announceRegisteredTab(contents, browserPageId)
|
||||
}
|
||||
})
|
||||
} else {
|
||||
announceRegisteredTab(contents, browserPageId)
|
||||
}
|
||||
}
|
||||
|
||||
function announceRegisteredTab(contents: Electron.WebContents, browserPageId: string): void {
|
||||
const webContentsId = contents.id
|
||||
pageIdByTabId.set(webContentsId, browserPageId)
|
||||
const discarded = takeDiscardedBrowserTabId(browserPageId)
|
||||
const replaces = discarded?.session === contents.session
|
||||
|
||||
@@ -12,7 +12,6 @@ import { removeBrowserExtension } from '../browser-extension-management'
|
||||
import { readBrowserExtensionIconDataUrl } from '../installation/browser-extension-manifest'
|
||||
import { samePermissionSummary } from '../permissions/browser-extension-permission-summary'
|
||||
import type { BrowserExtensionAccessLists as BrowserExtensionPermissionSummary } from '../../../../shared/browser/extensions/browser-extension-permission-warnings'
|
||||
import { getBrowserExtensionSessionForProfile } from '../profile-sessions/browser-extension-session-loader'
|
||||
import { isBrowserExtensionSupportEnabled } from '../browser-extension-support'
|
||||
import {
|
||||
downloadWebStoreCrx,
|
||||
@@ -143,7 +142,7 @@ export async function installBrowserExtensionFromWebStore(
|
||||
error: 'Paste a Chrome Web Store link or a 32-letter extension ID'
|
||||
}
|
||||
}
|
||||
if (!getBrowserExtensionSessionForProfile(profileId)) {
|
||||
if (!browserSessionRegistry.getProfile(profileId)) {
|
||||
return { status: 'failed', error: 'Browser profile is not available for extensions' }
|
||||
}
|
||||
const existing = getBrowserExtensionInstallStore().get(extensionId)
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { BrowserLoadError } from '../../../../shared/browser-workspace-type
|
||||
import type { BrowserGuestMetadata } from '../../../../shared/browser/guest-lifecycle/browser-guest-metadata'
|
||||
import { readGuestNavigationState } from './browser-guest-navigation-state'
|
||||
import { isChromiumInternalErrorUrl } from '../manager/navigation/browser-main-frame-navigation'
|
||||
import { isBrowserPageFirstLoadHeld } from '../../extensions/profile-sessions/browser-extension-page-start'
|
||||
|
||||
const projections = new WeakMap<
|
||||
Electron.WebContents,
|
||||
@@ -38,7 +39,7 @@ export function installBrowserGuestMetadata({
|
||||
let navigationRevision = 0
|
||||
let committedUrl = isChromiumInternalErrorUrl(guest.getURL()) ? '' : guest.getURL()
|
||||
let title = committedUrl ? guest.getTitle() : ''
|
||||
let loading = guest.isLoadingMainFrame()
|
||||
let loading = guest.isLoadingMainFrame() || isBrowserPageFirstLoadHeld(guest)
|
||||
let previous: BrowserGuestMetadata | null = null
|
||||
const read = (kind: BrowserGuestMetadata['kind'] = 'snapshot'): BrowserGuestMetadata | null => {
|
||||
const browserPageId = resolveOwner()
|
||||
@@ -163,7 +164,7 @@ export function installBrowserGuestMetadata({
|
||||
if (guest.isDestroyed()) {
|
||||
return null
|
||||
}
|
||||
loading = guest.isLoadingMainFrame()
|
||||
loading = guest.isLoadingMainFrame() || isBrowserPageFirstLoadHeld(guest)
|
||||
return publish()
|
||||
},
|
||||
publish: () => {
|
||||
|
||||
@@ -225,7 +225,7 @@ describe('BrowserSessionRegistry', () => {
|
||||
expect(isValidPersistedBrowserSessionProfile(first, DEFAULT_LOCAL_ORCA_PROFILE_ID)).toBe(true)
|
||||
|
||||
expect(await deleteManagedBrowserProfile(owner)).toBe(true)
|
||||
expect(browserSessionRegistry.isAllowedPartition(first.partition)).toBe(false)
|
||||
expect(browserSessionRegistry.profileIdForPartition(first.partition)).toBeNull()
|
||||
expect(browserSessionRegistry.getProfile(repoProfile.id)).not.toBeNull()
|
||||
// A workspace recreated at the same path must not land on the deleted, retired session.
|
||||
const recreated = await ensureManagedBrowserProfile(owner, 'Workspace: feature')
|
||||
|
||||
@@ -37,7 +37,11 @@ import {
|
||||
import { getCanonicalUserDataPath } from '../../../persistence/loading-store/user-data-path'
|
||||
import { markBrowserIdentityMigrationNoticePending } from '../../identity/mode/browser-identity-mode-store'
|
||||
import { forgetBrowserProfileOwnedStores } from './browser-profile-owned-stores'
|
||||
import { attachBrowserExtensionsToProfileSession } from '../../extensions/profile-sessions/browser-extension-session-loader'
|
||||
import {
|
||||
attachBrowserExtensionsToProfileSession,
|
||||
getBrowserExtensionSessionForProfile
|
||||
} from '../../extensions/profile-sessions/browser-extension-session-loader'
|
||||
import { isBrowserExtensionSupportEnabled } from '../../extensions/browser-extension-support'
|
||||
|
||||
type ExtensionIdListKey = 'enabledExtensionIdsByProfileId' | 'pinnedExtensionIdsByProfileId'
|
||||
type ExtensionIdListUpdate = (byProfile: Record<string, string[]>) => Record<string, string[]>
|
||||
@@ -129,7 +133,7 @@ class BrowserSessionRegistry {
|
||||
}
|
||||
}
|
||||
if (meta.profiles.length > 0) {
|
||||
this.hydrateFromPersisted(meta.profiles, meta.enabledExtensionIdsByProfileId)
|
||||
this.hydrateFromPersisted(meta.profiles)
|
||||
}
|
||||
|
||||
// Hydration skips the default profile, so install its policies separately.
|
||||
@@ -137,16 +141,23 @@ class BrowserSessionRegistry {
|
||||
void installBrowserSessionPartitionPolicies(defaultProfile).catch(() => {
|
||||
console.warn('[proxy] Failed to apply proxy to browser partition', defaultProfile.partition)
|
||||
})
|
||||
this.attachExtensions(defaultProfile, meta.enabledExtensionIdsByProfileId.default ?? [])
|
||||
}
|
||||
|
||||
// Why here and not in the partition installer: that installer also serves route, SSH and
|
||||
// doc-preview partitions, and release 1 runs extensions only in local browser profiles.
|
||||
private attachExtensions(
|
||||
profile: BrowserSessionProfile,
|
||||
enabledExtensionIds = this.getEnabledExtensionIds(profile.id)
|
||||
): void {
|
||||
attachBrowserExtensionsToProfileSession(profile, enabledExtensionIds)
|
||||
/**
|
||||
* Starts a profile's extensions once it has a page or Settings acts on them, never at launch:
|
||||
* each running profile wakes its extensions' service workers. Only local browser profiles
|
||||
* run extensions, so route, SSH and doc-preview partitions never come through here.
|
||||
*/
|
||||
attachExtensions(profileId: string): void {
|
||||
const profile = this.profiles.get(profileId)
|
||||
// Why these first: the enabled list is read from disk, and this runs for every new tab.
|
||||
if (
|
||||
profile &&
|
||||
isBrowserExtensionSupportEnabled() &&
|
||||
!getBrowserExtensionSessionForProfile(profileId)
|
||||
) {
|
||||
attachBrowserExtensionsToProfileSession(profile, this.getEnabledExtensionIds(profileId))
|
||||
}
|
||||
}
|
||||
|
||||
getEnabledExtensionIds(profileId: string): string[] {
|
||||
@@ -204,8 +215,9 @@ class BrowserSessionRegistry {
|
||||
)
|
||||
}
|
||||
|
||||
isAllowedPartition(partition: string): boolean {
|
||||
return this.listProfiles().some((p) => p.partition === partition)
|
||||
/** The local browser profile a partition belongs to; tabs attach only in these. */
|
||||
profileIdForPartition(partition: string): string | null {
|
||||
return this.listProfiles().find((p) => p.partition === partition)?.id ?? null
|
||||
}
|
||||
|
||||
resolvePartition(profileId: string | null | undefined): string {
|
||||
@@ -260,7 +272,6 @@ class BrowserSessionRegistry {
|
||||
}
|
||||
this.profiles.set(id, profile)
|
||||
this.persistProfiles()
|
||||
this.attachExtensions(profile)
|
||||
this.onProfilesChanged?.()
|
||||
return profile
|
||||
}
|
||||
@@ -324,10 +335,7 @@ class BrowserSessionRegistry {
|
||||
}
|
||||
}
|
||||
|
||||
hydrateFromPersisted(
|
||||
profiles: BrowserSessionProfile[],
|
||||
enabledExtensionIdsByProfileId = this.loadPersistedMeta().enabledExtensionIdsByProfileId
|
||||
): void {
|
||||
hydrateFromPersisted(profiles: BrowserSessionProfile[]): void {
|
||||
for (const profile of profiles) {
|
||||
if (!isValidPersistedBrowserSessionProfile(profile, this.activeOrcaProfileId)) {
|
||||
continue
|
||||
@@ -337,7 +345,6 @@ class BrowserSessionRegistry {
|
||||
void installBrowserSessionPartitionPolicies(profile).catch(() => {
|
||||
console.warn('[proxy] Failed to apply proxy to browser partition', profile.partition)
|
||||
})
|
||||
this.attachExtensions(profile, enabledExtensionIdsByProfileId[profile.id] ?? [])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,7 +49,6 @@ import {
|
||||
initializeBrowserExtensionSupport,
|
||||
switchBrowserExtensionSupport
|
||||
} from '../browser/extensions/browser-extension-startup'
|
||||
import { whenBrowserExtensionSessionsLoaded } from '../browser/extensions/profile-sessions/browser-extension-session-loader'
|
||||
import { browserSessionRegistry } from '../browser/sessions/profiles/browser-session-registry'
|
||||
import { logStartupMilestone } from './diagnostics/startup-diagnostics'
|
||||
import { writeHttp1CompatibilityMarker } from './network-compatibility/http1-compatibility-marker'
|
||||
@@ -324,6 +323,4 @@ export async function initializeReadyFoundation(): Promise<void> {
|
||||
} catch {
|
||||
console.warn('[proxy] Failed to apply network proxy settings to browser sessions')
|
||||
}
|
||||
// Why bounded: restored tabs should get content scripts, but a slow extension never blocks launch.
|
||||
await whenBrowserExtensionSessionsLoaded(3_000)
|
||||
}
|
||||
|
||||
@@ -28,6 +28,9 @@ import { registerHostFrameNavigationGuard } from './host-frame-navigation-guard'
|
||||
import { installPrivilegedWindowNavigationPolicy } from './privileged-window-navigation'
|
||||
import { parseChromeExtensionUrl } from '../../../shared/browser/extensions/browser-extension-url'
|
||||
import { getBrowserExtensionSessionForProfile } from '../../browser/extensions/profile-sessions/browser-extension-session-loader'
|
||||
import { isBrowserExtensionEnabledInProfile } from '../../browser/extensions/web-store/browser-extension-webstore-service'
|
||||
import { isBrowserExtensionSupportEnabled } from '../../browser/extensions/browser-extension-support'
|
||||
import { holdWebviewFirstLoadForExtensions } from '../../browser/extensions/profile-sessions/browser-extension-page-start'
|
||||
import { installBrowserJavaScriptDialogs } from '../../browser/guest-lifecycle/prompts/browser-javascript-dialogs'
|
||||
import { installNativeChatVisualGuestTheme } from '../../host/native-chat-visual-guest-theme'
|
||||
import {
|
||||
@@ -49,17 +52,20 @@ function isAdmissibleDocPreviewAttach(partition: string, src: string): boolean {
|
||||
|
||||
/**
|
||||
* Why its own rule: extension pages (options, tabs.create) are not typed URLs, so they attach only
|
||||
* in a local browser-profile partition whose session has that extension loaded — i.e. installed
|
||||
* and enabled for that profile. Route, SSH and doc-preview partitions never qualify.
|
||||
* in a local browser-profile partition with that extension installed and enabled. Route, SSH and
|
||||
* doc-preview partitions never qualify.
|
||||
*/
|
||||
function isAdmissibleExtensionPageAttach(partition: string, src: string): boolean {
|
||||
function isAdmissibleExtensionPageAttach(profileId: string | null, src: string): boolean {
|
||||
const extensionUrl = parseChromeExtensionUrl(src)
|
||||
if (!extensionUrl || !browserSessionRegistry.isAllowedPartition(partition)) {
|
||||
if (!extensionUrl || !profileId || !isBrowserExtensionSupportEnabled()) {
|
||||
return false
|
||||
}
|
||||
const profile = browserSessionRegistry.listProfiles().find((p) => p.partition === partition)
|
||||
const sess = profile ? getBrowserExtensionSessionForProfile(profile.id) : null
|
||||
return Boolean(sess?.extensions.getExtension(extensionUrl.extensionId))
|
||||
// Loaded covers one Settings is still turning on; enabled covers one its profile has yet to load.
|
||||
return Boolean(
|
||||
getBrowserExtensionSessionForProfile(profileId)?.extensions.getExtension(
|
||||
extensionUrl.extensionId
|
||||
) || isBrowserExtensionEnabledInProfile(profileId, extensionUrl.extensionId)
|
||||
)
|
||||
}
|
||||
|
||||
export function installMainWindowWebviewSecurity(mainWindow: BrowserWindow): void {
|
||||
@@ -103,12 +109,13 @@ export function installMainWindowWebviewSecurity(mainWindow: BrowserWindow): voi
|
||||
delete params.allowpopups
|
||||
return
|
||||
}
|
||||
const isProfilePartition = browserSessionRegistry.isAllowedPartition(partition)
|
||||
const profileId = browserSessionRegistry.profileIdForPartition(partition)
|
||||
const isProfilePartition = profileId !== null
|
||||
const isRoutePartition = browserRouteSessionRegistry.isAllowedPartition(partition)
|
||||
// Direct-SSH partitions exist only after proxy verification; renderer URLs need no main-side grants, like profile partitions.
|
||||
const isLocalSshPartition = isLocalSshBrowserPartition(partition)
|
||||
const isDocPreviewAttach = isAdmissibleDocPreviewAttach(partition, src)
|
||||
const isExtensionPageAttach = isAdmissibleExtensionPageAttach(partition, src)
|
||||
const isExtensionPageAttach = isAdmissibleExtensionPageAttach(profileId, src)
|
||||
|
||||
// Require an allowlisted src/partition; renderer mistakes must not grant preload/Node authority.
|
||||
if (
|
||||
@@ -142,6 +149,11 @@ export function installMainWindowWebviewSecurity(mainWindow: BrowserWindow): voi
|
||||
Object.assign(webPreferences, ORCA_BROWSER_GUEST_WEB_PREFERENCES)
|
||||
// Preserve only the registry-validated partition so isolated profiles keep their storage.
|
||||
webPreferences.partition = partition
|
||||
if (profileId) {
|
||||
// A profile starts its extensions with its first tab, not at launch.
|
||||
browserSessionRegistry.attachExtensions(profileId)
|
||||
holdWebviewFirstLoadForExtensions(mainWindow.webContents, profileId, params)
|
||||
}
|
||||
})
|
||||
|
||||
mainWindow.webContents.on('did-attach-webview', (_event, guest) => {
|
||||
|
||||
Reference in New Issue
Block a user