From 9c451291244a1a246ca978077bed7ea126e21b17 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 13:54:05 -0700 Subject: [PATCH 01/15] feat: add the cef engine family for the opt-in Blink engine --- src/common/engine-id.ts | 9 ++++++--- tests/unit/cli/engine-index.test.ts | 10 ++++++---- tests/unit/common/engine-id.test.ts | 17 +++++++++++++++++ 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/src/common/engine-id.ts b/src/common/engine-id.ts index be78199..5adb7a0 100644 --- a/src/common/engine-id.ts +++ b/src/common/engine-id.ts @@ -5,8 +5,11 @@ import { InvalidArgumentError } from './errors'; import { compareVersions } from './manifest'; import type { Arch } from './platform'; -/** Which web-engine family a build belongs to (`webkit` covers WinCairo + macOS; D044). */ -export type EngineFamily = 'webkitgtk' | 'webkit'; +/** + * `webkit` covers WinCairo + macOS (D044). `cef` is the opt-in Blink engine (D048): its `api` + * is the CEF version and its `upstream` the Chromium version. + */ +export type EngineFamily = 'webkitgtk' | 'webkit' | 'cef'; export type EngineOs = 'linux' | 'macos' | 'windows'; @@ -26,7 +29,7 @@ export type EngineRef = { /** The reserved sentinel meaning "use the OS WebView" (the default). */ export const SYSTEM_ENGINE = 'system'; -const ENGINE_FAMILIES: ReadonlySet = new Set(['webkitgtk', 'webkit']); +const ENGINE_FAMILIES: ReadonlySet = new Set(['webkitgtk', 'webkit', 'cef']); const ENGINE_OSES: ReadonlySet = new Set(['linux', 'macos', 'windows']); const ENGINE_ARCHES: ReadonlySet = new Set(['x64', 'arm64']); diff --git a/tests/unit/cli/engine-index.test.ts b/tests/unit/cli/engine-index.test.ts index a78e71d..073a01e 100644 --- a/tests/unit/cli/engine-index.test.ts +++ b/tests/unit/cli/engine-index.test.ts @@ -10,7 +10,7 @@ import { } from '../../../src/cli/engine-index'; const ID = 'webkit-2-2.53.3-bunmaska1-windows-x64'; -const CEF_ID = 'cef-154-154.0.8037.58-bunmaska1-macos-arm64'; +const FUTURE_ID = 'servo-1-0.1.0-bunmaska1-macos-arm64'; describe('engineFeedIndexUrl', () => { test('maps a feed base to /index.json (official by default, trailing slash ok)', () => { @@ -50,7 +50,7 @@ describe('parseEngineIndex', () => { test('skips entries this client cannot parse, so a newer engine family never breaks it', () => { const entries = parseEngineIndex( - JSON.stringify({ version: 1, engines: [{ id: CEF_ID }, { id: ID }, { id: 'nope' }] }), + JSON.stringify({ version: 1, engines: [{ id: FUTURE_ID }, { id: ID }, { id: 'nope' }] }), ); expect(entries.map((e) => e.id)).toEqual([ID]); }); @@ -117,9 +117,11 @@ describe('mergeEngineIndex', () => { }); test('keeps entries this client cannot parse', () => { - const existing = buildEngineIndex([{ id: CEF_ID, hash: 'blink' }]); + const existing = buildEngineIndex([{ id: FUTURE_ID, hash: 'servo' }]); const json = mergeEngineIndex(existing, { id: ID, hash: 'new' }); - expect(JSON.parse(json).engines.map((e: { id: string }) => e.id)).toEqual([CEF_ID, ID].sort()); + expect(JSON.parse(json).engines.map((e: { id: string }) => e.id)).toEqual( + [FUTURE_ID, ID].sort(), + ); }); test('refuses to republish an id already in the index (ids are immutable)', () => { diff --git a/tests/unit/common/engine-id.test.ts b/tests/unit/common/engine-id.test.ts index c4be49a..1207fb1 100644 --- a/tests/unit/common/engine-id.test.ts +++ b/tests/unit/common/engine-id.test.ts @@ -26,6 +26,17 @@ describe('parseEngineId', () => { expect(parsed.os).toBe('windows'); }); + test('parses a Blink engine with the CEF version as api and Chromium as upstream (D048)', () => { + expect(parseEngineId('cef-154.0.28-154.0.8037.58-bunmaska1-macos-arm64')).toEqual({ + engine: 'cef', + api: '154.0.28', + upstream: '154.0.8037.58', + rev: 'bunmaska1', + os: 'macos', + arch: 'arm64', + }); + }); + test('rejects the retired webview2 family', () => { expect(() => parseEngineId('webview2-fixed-126.0.2592-bunmaska1-windows-x64')).toThrow( BunmaskaError, @@ -78,6 +89,12 @@ describe('compareEngineIds', () => { expect(compareEngineIds(r1, r2)).toBe(-1); }); + test('orders Blink engines by Chromium version, not by CEF version', () => { + const older = 'cef-999.0.0-153.0.1.1-bunmaska1-macos-arm64'; + const newer = 'cef-154.0.28-154.0.8037.58-bunmaska1-macos-arm64'; + expect(compareEngineIds(older, newer)).toBe(-1); + }); + test('sorts a list ascending', () => { const sorted = [b, a].sort(compareEngineIds); expect(sorted).toEqual([a, b]); From ccd6506e0bbc9e551ccff142cdfc6651ffc0eed5 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 13:54:25 -0700 Subject: [PATCH 02/15] feat: report the pinned engine family and read BUNMASKA_ENGINE_ID --- src/main/engine/resolve.ts | 18 +++++++++++++++--- tests/unit/main/engine-resolve.test.ts | 18 ++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/main/engine/resolve.ts b/src/main/engine/resolve.ts index f3a1c2e..83e2b65 100644 --- a/src/main/engine/resolve.ts +++ b/src/main/engine/resolve.ts @@ -2,7 +2,12 @@ import { existsSync, readFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; -import { type EngineRef, isSystemEngine, parseEngineId } from '../../common/engine-id'; +import { + type EngineFamily, + type EngineRef, + isSystemEngine, + parseEngineId, +} from '../../common/engine-id'; import { isBunCli } from '../../common/preload-bundle'; import { type Arch, currentArch, currentPlatform, type Platform } from '../../common/platform'; import { @@ -16,6 +21,8 @@ import { /** The resolved engine decision for the current process. */ export type EngineResolution = { readonly mode: 'system' | 'pinned'; + /** The pinned engine's family (store pins only); `cef` selects the Blink backend (D048). */ + readonly family?: EngineFamily; /** The pinned engine's `lib/` dir (absolute). Absent in system mode. */ readonly libDir?: string; /** The resolved engine-id (store pins only; absent for an explicit-dir pin/system). */ @@ -73,7 +80,12 @@ export const resolveEngineWith = (deps: ResolveDeps = {}): EngineResolution => { } const readBakedId = deps.readBakedId ?? (() => defaultReadBakedId(env)); - const id = env['BUNMASKA_WEBKIT_ID']?.trim() || readBakedId()?.trim() || 'system'; + // BUNMASKA_ENGINE_ID is the family-neutral name; BUNMASKA_WEBKIT_ID stays as its alias. + const id = + env['BUNMASKA_ENGINE_ID']?.trim() || + env['BUNMASKA_WEBKIT_ID']?.trim() || + readBakedId()?.trim() || + 'system'; if (isSystemEngine(id)) { return { mode: 'system', warnings: [] }; @@ -113,7 +125,7 @@ export const resolveEngineWith = (deps: ResolveDeps = {}): EngineResolution => { ], }; } - return { mode: 'pinned', libDir: join(dir, 'lib'), id, root, warnings: [] }; + return { mode: 'pinned', family: ref.engine, libDir: join(dir, 'lib'), id, root, warnings: [] }; }; const cache: { value: EngineResolution | undefined } = { value: undefined }; diff --git a/tests/unit/main/engine-resolve.test.ts b/tests/unit/main/engine-resolve.test.ts index 60452b6..25dd787 100644 --- a/tests/unit/main/engine-resolve.test.ts +++ b/tests/unit/main/engine-resolve.test.ts @@ -85,6 +85,24 @@ describe('resolveEngineWith', () => { expect(warnings.join(' ')).not.toMatch(/system WebKit/); }); + test('a Blink store pin reports the cef family', () => { + const cef = 'cef-154.0.28-154.0.8037.58-bunmaska1-macos-arm64'; + const r = resolve({ + env: { BUNMASKA_ENGINE_ID: cef }, + host: { os: 'macos', arch: 'arm64' }, + }); + expect(r.mode).toBe('pinned'); + expect(r.family).toBe('cef'); + expect(slash(r.libDir ?? '')).toBe(`${ROOT}/${cef}/lib`); + }); + + test('BUNMASKA_ENGINE_ID wins over its BUNMASKA_WEBKIT_ID alias', () => { + const other = 'webkitgtk-6.0-2.46.0-bunmaska1-linux-x64'; + const r = resolve({ env: { BUNMASKA_ENGINE_ID: other, BUNMASKA_WEBKIT_ID: ID } }); + expect(r.id).toBe(other); + expect(r.family).toBe('webkitgtk'); + }); + test('store-resolved pinned carries the engine id + root (for refcount linking)', () => { const r = resolve({ env: {}, readBakedId: () => ID }); expect(r.id).toBe(ID); From 5bc697a08ff6e40655170816c353d3fa20984ada Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 13:57:59 -0700 Subject: [PATCH 03/15] feat: let an engine drive the macOS pump and host its window view --- src/main/platform/macos/cocoa-backend.ts | 417 ++++++++++-------- tests/integration/macos/cocoa-backend.test.ts | 60 ++- 2 files changed, 290 insertions(+), 187 deletions(-) diff --git a/src/main/platform/macos/cocoa-backend.ts b/src/main/platform/macos/cocoa-backend.ts index 278c5ff..fecf6b1 100644 --- a/src/main/platform/macos/cocoa-backend.ts +++ b/src/main/platform/macos/cocoa-backend.ts @@ -542,7 +542,7 @@ class MacOSWebContents implements NativeWebContents { class MacOSWindow implements NativeWindow { #window: Handle; - readonly #contents: MacOSWebContents; + readonly #contents: NativeWebContents; readonly #teardown: () => void; readonly #releaseNative: () => void; #tornDown = false; @@ -554,7 +554,7 @@ class MacOSWindow implements NativeWindow { constructor( window: Handle, - contents: MacOSWebContents, + contents: NativeWebContents, teardown: () => void, releaseNative: () => void, ) { @@ -828,7 +828,223 @@ class MacOSWindow implements NativeWindow { } } +/** The view a {@link createMacOSWindow} shell hosts, and how to take it down. */ +export type MacOSViewHost = { + readonly contents: NativeWebContents; + /** Runs once AppKit committed to the close, before `closed`. */ + readonly teardown: () => void; + /** Frees the view's natives a tick after the close, before the window's own release. */ + readonly release: () => void; +}; + +/** Builds the view inside a new NSWindow; `emit` surfaces window events such as `ready-to-show`. */ +export type MacOSViewAttacher = ( + window: Handle, + options: NativeWindowOptions, + emit: (type: WindowEventType) => void, +) => MacOSViewHost; + +const attachWebKitView: MacOSViewAttacher = (window, options, emit) => { + const rt = cocoa(); + const frame: readonly [number, number, number, number] = [0, 0, options.width, options.height]; + + const configuration = rt.msgSend( + rt.msgSend(rt.classes.get('WKWebViewConfiguration'), rt.selectors.get('alloc')), + rt.selectors.get('init'), + ); + + enableDeveloperExtras(rt.msgSend(configuration, rt.selectors.get('preferences'))); + + registerCustomSchemes(configuration, options.protocol); + + // The handlers exist before the web view, so they reach its contents late-bound. + let contents: MacOSWebContents | undefined; + const userContentController = rt.msgSend( + configuration, + rt.selectors.get('userContentController'), + ); + + // The bridge and preload run in an isolated world, invisible to page scripts. + const isolatedWorld = getContentWorld(PRELOAD_WORLD_NAME); + + const handler = createScriptMessageHandler((envelopeJson) => + contents?.deliverRendererEnvelope(envelopeJson), + ); + // Only the isolated world can reach this handler. + msgSendPtr3( + userContentController, + rt.selectors.get('addScriptMessageHandler:contentWorld:name:'), + handler.handle, + isolatedWorld, + nsString(IPC_HANDLER_NAME), + ); + + // executeJavaScript's return channel (D022b). pageWorld() is interned by WebKit, + // so teardown gets the same handle without a retain here. + const execHandler = createScriptMessageHandler((json) => contents?.deliverExecResult(json)); + msgSendPtr3( + userContentController, + rt.selectors.get('addScriptMessageHandler:contentWorld:name:'), + execHandler.handle, + pageWorld(), + nsString(EXEC_HANDLER_NAME), + ); + + // The page world's DOMContentLoaded surfaces Electron's dom-ready. + const domReadyHandler = createScriptMessageHandler(() => + contents?.deliverNavigation({ type: 'dom-ready' }), + ); + msgSendPtr3( + userContentController, + rt.selectors.get('addScriptMessageHandler:contentWorld:name:'), + domReadyHandler.handle, + pageWorld(), + nsString(DOM_READY_HANDLER_NAME), + ); + + const addUserScript = (source: string, world: Handle): void => { + const userScript = msgSendPtrI64U8Ptr( + rt.msgSend(rt.classes.get('WKUserScript'), rt.selectors.get('alloc')), + rt.selectors.get('initWithSource:injectionTime:forMainFrameOnly:inContentWorld:'), + nsString(source), + WK_INJECTION_TIME_AT_DOCUMENT_START, + FOR_MAIN_FRAME_ONLY, + world, + ); + msgSendPtr(userContentController, rt.selectors.get('addUserScript:'), userScript); + rt.msgSend(userScript, rt.selectors.get('release')); + }; + + const scripts = injectedScripts({ + preloadScript: options.preloadScript, + frame: options.frame, + domReadyWorld: 'page', + }); + for (const source of scripts.isolated) { + addUserScript(source, isolatedWorld); + } + for (const source of scripts.page) { + addUserScript(source, pageWorld()); + } + + const webview = msgSendInitWithFrameConfig( + rt.msgSend(rt.classes.get('WKWebView'), rt.selectors.get('alloc')), + rt.selectors.get('initWithFrame:configuration:'), + frame, + configuration, + ); + // The web view copies the configuration; the copy shares its user content controller. + rt.msgSend(configuration, rt.selectors.get('release')); + contents = new MacOSWebContents(webview, isolatedWorld); + + let readyToShowEmitted = false; + const navigationDelegate = createNavigationDelegate((event) => { + contents?.deliverNavigation(event); + if (event.type === 'did-finish-load' && !readyToShowEmitted) { + readyToShowEmitted = true; + emit('ready-to-show'); + } + }); + msgSendPtr(webview, rt.selectors.get('setNavigationDelegate:'), navigationDelegate.handle); + + // window.open and target=_blank go to the JS handler; nil means no child view. + const uiDelegate = createUIDelegate((url) => contents?.deliverWindowOpen(url)); + msgSendPtr(webview, rt.selectors.get('setUIDelegate:'), uiDelegate.handle); + + msgSendPtr(window, rt.selectors.get('setContentView:'), webview); + + const teardown = (): void => { + msgSendPtrPtr( + userContentController, + rt.selectors.get('removeScriptMessageHandlerForName:contentWorld:'), + nsString(IPC_HANDLER_NAME), + isolatedWorld, + ); + handler.dispose(); + msgSendPtrPtr( + userContentController, + rt.selectors.get('removeScriptMessageHandlerForName:contentWorld:'), + nsString(EXEC_HANDLER_NAME), + pageWorld(), + ); + execHandler.dispose(); + msgSendPtrPtr( + userContentController, + rt.selectors.get('removeScriptMessageHandlerForName:contentWorld:'), + nsString(DOM_READY_HANDLER_NAME), + pageWorld(), + ); + domReadyHandler.dispose(); + contents?.rejectPendingExecs(); + }; + + return { + contents, + teardown, + release: () => { + navigationDelegate.destroy(); + uiDelegate.destroy(); + cocoa().msgSend(webview, rt.selectors.get('release')); + }, + }; +}; + +/** An NSWindow (style, placement, delegate, close choreography) around the view `attach` builds. */ +export const createMacOSWindow = ( + options: NativeWindowOptions, + attach: MacOSViewAttacher, +): NativeWindow => { + const rt = cocoa(); + const windowClass = + options.frame === false ? ensureFramelessWindowClass() : rt.classes.get('NSWindow'); + const window = msgSendInitWithContentRect( + rt.msgSend(windowClass, rt.selectors.get('alloc')), + rt.selectors.get('initWithContentRect:styleMask:backing:defer:'), + [0, 0, options.width, options.height], + BigInt(computeWindowStyleMask(styleFromOptions(options))), + NS_BACKING_STORE_BUFFERED, + false, + ); + + // releasedWhenClosed:YES (the default) frees the window under our handle on + // close; releaseNative balances our +1 instead. + msgSendU8(window, rt.selectors.get('setReleasedWhenClosed:'), 0); + // Electron's default placement. + rt.msgSend(window, rt.selectors.get('center')); + + // Assigned below; the view's and the delegate's closures only run on later native callbacks. + let nativeWindow: MacOSWindow; + const view = attach(window, options, (type) => nativeWindow.emitEvent(type)); + msgSendPtr(window, rt.selectors.get('setTitle:'), nsString(options.title)); + + // Detach the delegate before releasing, so no late notification fires. + const releaseNative = (): void => { + msgSendPtr(window, rt.selectors.get('setDelegate:'), 0n); + view.release(); + windowDelegate.destroy(); + cocoa().msgSend(window, rt.selectors.get('release')); + }; + + nativeWindow = new MacOSWindow(window, view.contents, view.teardown, releaseNative); + + const windowDelegate = createWindowDelegate({ + shouldClose: () => nativeWindow.shouldClose(), + willClose: () => nativeWindow.willClose(), + event: (type) => nativeWindow.emitEvent(type), + }); + msgSendPtr(window, rt.selectors.get('setDelegate:'), windowDelegate.handle); + + if (options.fullscreen === true) { + nativeWindow.setFullScreen(true); + } + if (options.show) { + nativeWindow.show(); + } + return nativeWindow; +}; + class MacOSApplication implements NativeApplication { + readonly #onDrain: (() => void) | undefined; #started = false; #app: Handle = 0n; #appDelegate: Handle = 0n; @@ -844,6 +1060,10 @@ class MacOSApplication implements NativeApplication { #distantPast: Handle = 0n; #eventPumpMode: Handle = 0n; + constructor(onDrain?: () => void) { + this.#onDrain = onDrain; + } + start(): void { if (this.#started) { return; @@ -873,7 +1093,12 @@ class MacOSApplication implements NativeApplication { this.#distantPast = rt.msgSend(rt.classes.get('NSDate'), rt.selectors.get('distantPast')); this.#eventPumpMode = rt.msgSend(nsString('kCFRunLoopDefaultMode'), rt.selectors.get('retain')); - this.#pump = new AdaptiveBlockingPump(createMacOSDrain(() => this.#pumpAppEvents())); + this.#pump = new AdaptiveBlockingPump( + createMacOSDrain(() => { + this.#pumpAppEvents(); + this.#onDrain?.(); + }), + ); this.#pump.start(); this.#started = true; log.info('application started'); @@ -946,186 +1171,7 @@ class MacOSApplication implements NativeApplication { } createWindow(options: NativeWindowOptions): NativeWindow { - const rt = cocoa(); - const frame: readonly [number, number, number, number] = [0, 0, options.width, options.height]; - - const windowClass = - options.frame === false ? ensureFramelessWindowClass() : rt.classes.get('NSWindow'); - const window = msgSendInitWithContentRect( - rt.msgSend(windowClass, rt.selectors.get('alloc')), - rt.selectors.get('initWithContentRect:styleMask:backing:defer:'), - frame, - BigInt(computeWindowStyleMask(styleFromOptions(options))), - NS_BACKING_STORE_BUFFERED, - false, - ); - - // releasedWhenClosed:YES (the default) frees the window under our handle on - // close; releaseNative balances our +1 instead. - msgSendU8(window, rt.selectors.get('setReleasedWhenClosed:'), 0); - // Electron's default placement. - rt.msgSend(window, rt.selectors.get('center')); - - const configuration = rt.msgSend( - rt.msgSend(rt.classes.get('WKWebViewConfiguration'), rt.selectors.get('alloc')), - rt.selectors.get('init'), - ); - - enableDeveloperExtras(rt.msgSend(configuration, rt.selectors.get('preferences'))); - - registerCustomSchemes(configuration, options.protocol); - - // The handlers exist before the web view, so they reach its contents late-bound. - let contents: MacOSWebContents | undefined; - const userContentController = rt.msgSend( - configuration, - rt.selectors.get('userContentController'), - ); - - // The bridge and preload run in an isolated world, invisible to page scripts. - const isolatedWorld = getContentWorld(PRELOAD_WORLD_NAME); - - const handler = createScriptMessageHandler((envelopeJson) => - contents?.deliverRendererEnvelope(envelopeJson), - ); - // Only the isolated world can reach this handler. - msgSendPtr3( - userContentController, - rt.selectors.get('addScriptMessageHandler:contentWorld:name:'), - handler.handle, - isolatedWorld, - nsString(IPC_HANDLER_NAME), - ); - - // executeJavaScript's return channel (D022b). pageWorld() is interned by WebKit, - // so teardown gets the same handle without a retain here. - const execHandler = createScriptMessageHandler((json) => contents?.deliverExecResult(json)); - msgSendPtr3( - userContentController, - rt.selectors.get('addScriptMessageHandler:contentWorld:name:'), - execHandler.handle, - pageWorld(), - nsString(EXEC_HANDLER_NAME), - ); - - // The page world's DOMContentLoaded surfaces Electron's dom-ready. - const domReadyHandler = createScriptMessageHandler(() => - contents?.deliverNavigation({ type: 'dom-ready' }), - ); - msgSendPtr3( - userContentController, - rt.selectors.get('addScriptMessageHandler:contentWorld:name:'), - domReadyHandler.handle, - pageWorld(), - nsString(DOM_READY_HANDLER_NAME), - ); - - const addUserScript = (source: string, world: Handle): void => { - const userScript = msgSendPtrI64U8Ptr( - rt.msgSend(rt.classes.get('WKUserScript'), rt.selectors.get('alloc')), - rt.selectors.get('initWithSource:injectionTime:forMainFrameOnly:inContentWorld:'), - nsString(source), - WK_INJECTION_TIME_AT_DOCUMENT_START, - FOR_MAIN_FRAME_ONLY, - world, - ); - msgSendPtr(userContentController, rt.selectors.get('addUserScript:'), userScript); - rt.msgSend(userScript, rt.selectors.get('release')); - }; - - const scripts = injectedScripts({ - preloadScript: options.preloadScript, - frame: options.frame, - domReadyWorld: 'page', - }); - for (const source of scripts.isolated) { - addUserScript(source, isolatedWorld); - } - for (const source of scripts.page) { - addUserScript(source, pageWorld()); - } - - const webview = msgSendInitWithFrameConfig( - rt.msgSend(rt.classes.get('WKWebView'), rt.selectors.get('alloc')), - rt.selectors.get('initWithFrame:configuration:'), - frame, - configuration, - ); - // The web view copies the configuration; the copy shares its user content controller. - rt.msgSend(configuration, rt.selectors.get('release')); - contents = new MacOSWebContents(webview, isolatedWorld); - - // Assigned below; the delegate closures only run on later native callbacks. - let nativeWindow: MacOSWindow; - - let readyToShowEmitted = false; - const navigationDelegate = createNavigationDelegate((event) => { - contents?.deliverNavigation(event); - if (event.type === 'did-finish-load' && !readyToShowEmitted) { - readyToShowEmitted = true; - nativeWindow.emitEvent('ready-to-show'); - } - }); - msgSendPtr(webview, rt.selectors.get('setNavigationDelegate:'), navigationDelegate.handle); - - // window.open and target=_blank go to the JS handler; nil means no child view. - const uiDelegate = createUIDelegate((url) => contents?.deliverWindowOpen(url)); - msgSendPtr(webview, rt.selectors.get('setUIDelegate:'), uiDelegate.handle); - - msgSendPtr(window, rt.selectors.get('setContentView:'), webview); - msgSendPtr(window, rt.selectors.get('setTitle:'), nsString(options.title)); - - const teardown = (): void => { - msgSendPtrPtr( - userContentController, - rt.selectors.get('removeScriptMessageHandlerForName:contentWorld:'), - nsString(IPC_HANDLER_NAME), - isolatedWorld, - ); - handler.dispose(); - msgSendPtrPtr( - userContentController, - rt.selectors.get('removeScriptMessageHandlerForName:contentWorld:'), - nsString(EXEC_HANDLER_NAME), - pageWorld(), - ); - execHandler.dispose(); - msgSendPtrPtr( - userContentController, - rt.selectors.get('removeScriptMessageHandlerForName:contentWorld:'), - nsString(DOM_READY_HANDLER_NAME), - pageWorld(), - ); - domReadyHandler.dispose(); - contents?.rejectPendingExecs(); - }; - - // Detach the delegate before releasing, so no late notification fires. - const releaseNative = (): void => { - msgSendPtr(window, rt.selectors.get('setDelegate:'), 0n); - navigationDelegate.destroy(); - uiDelegate.destroy(); - windowDelegate.destroy(); - cocoa().msgSend(webview, rt.selectors.get('release')); - cocoa().msgSend(window, rt.selectors.get('release')); - }; - - nativeWindow = new MacOSWindow(window, contents, teardown, releaseNative); - - const windowDelegate = createWindowDelegate({ - shouldClose: () => nativeWindow.shouldClose(), - willClose: () => nativeWindow.willClose(), - event: (type) => nativeWindow.emitEvent(type), - }); - msgSendPtr(window, rt.selectors.get('setDelegate:'), windowDelegate.handle); - - if (options.fullscreen === true) { - nativeWindow.setFullScreen(true); - } - if (options.show) { - nativeWindow.show(); - } - return nativeWindow; + return createMacOSWindow(options, attachWebKitView); } quit(): void { @@ -1135,5 +1181,6 @@ class MacOSApplication implements NativeApplication { } } -/** Create the macOS native application backend. Call `start()` before use. */ -export const createMacOSApplication = (): NativeApplication => new MacOSApplication(); +/** Call `start()` before use. `onDrain` runs every pump tick, for an engine with its own loop. */ +export const createMacOSApplication = (onDrain?: () => void): NativeApplication => + new MacOSApplication(onDrain); diff --git a/tests/integration/macos/cocoa-backend.test.ts b/tests/integration/macos/cocoa-backend.test.ts index 91e6d98..a060fd0 100644 --- a/tests/integration/macos/cocoa-backend.test.ts +++ b/tests/integration/macos/cocoa-backend.test.ts @@ -3,7 +3,10 @@ import { dlopen, FFIType, ptr } from 'bun:ffi'; import { currentPlatform } from '../../../src/common/platform'; import { protocol } from '../../../src/main/api/protocol'; import { decodeEnvelope, encodeEnvelope } from '../../../src/main/ipc/ipc-protocol'; -import { createMacOSApplication } from '../../../src/main/platform/macos/cocoa-backend'; +import { + createMacOSApplication, + createMacOSWindow, +} from '../../../src/main/platform/macos/cocoa-backend'; import { retainedBlockCount } from '../../../src/main/platform/macos/cocoa-block'; import { nsString, nsStringToString } from '../../../src/main/platform/macos/cocoa-foundation'; import { @@ -20,7 +23,11 @@ import { LIBOBJC_PATH, setNativeErrorReporterForTesting, } from '../../../src/main/platform/macos/objc'; -import type { NativeWindow } from '../../../src/main/platform/native'; +import type { + NativeWebContents, + NativeWindow, + WindowEventType, +} from '../../../src/main/platform/native'; const delay = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); @@ -119,6 +126,55 @@ onMac('MacOSApplication', () => { app.quit(); } }); + + test('an engine drain hook runs on the pump', async () => { + let ticks = 0; + const app = createMacOSApplication(() => { + ticks += 1; + }); + app.start(); + try { + await delay(100); + expect(ticks).toBeGreaterThan(0); + } finally { + app.quit(); + } + }); +}); + +onMac('createMacOSWindow with a hosted view', () => { + test('the view gets the new window, its events and a teardown before its release', async () => { + const app = createMacOSApplication(); + app.start(); + try { + const calls: string[] = []; + const contents = {} as NativeWebContents; + let hostWindow = 0n; + let emit: (type: WindowEventType) => void = () => undefined; + const win = createMacOSWindow( + { width: 320, height: 240, title: 'hosted', show: false }, + (window, _options, emitEvent) => { + hostWindow = window; + emit = emitEvent; + return { + contents, + teardown: () => calls.push('teardown'), + release: () => calls.push('release'), + }; + }, + ); + expect(win.webContents).toBe(contents); + expect(nsWindowTitled('hosted')).toBe(hostWindow); + win.onWindowEvent('ready-to-show', () => calls.push('ready-to-show')); + emit('ready-to-show'); + win.onClosed(() => calls.push('closed')); + win.close(); + await delay(50); + expect(calls).toEqual(['ready-to-show', 'teardown', 'closed', 'release']); + } finally { + app.quit(); + } + }); }); onMac('MacOSWindow + WebContents end-to-end', () => { From 66deafe714a7b94ae41ef56dbb38b74dc605253c Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 13:58:24 -0700 Subject: [PATCH 04/15] feat: hand userData to a backend that keeps its own engine profile --- src/main/bootstrap.ts | 1 + src/main/platform/native.ts | 2 ++ tests/unit/main/bootstrap.test.ts | 15 +++++++++++++++ 3 files changed, 18 insertions(+) diff --git a/src/main/bootstrap.ts b/src/main/bootstrap.ts index 0915a1a..63a5b15 100644 --- a/src/main/bootstrap.ts +++ b/src/main/bootstrap.ts @@ -58,6 +58,7 @@ export const ensureNativeStarted = (): void => { native.onQuitRequest?.(() => { setTimeout(() => app.quit(), 0); }); + native.setUserDataPath?.(app.getPath('userData')); try { native.start(); } catch (error) { diff --git a/src/main/platform/native.ts b/src/main/platform/native.ts index ab02cfe..acc9cb9 100644 --- a/src/main/platform/native.ts +++ b/src/main/platform/native.ts @@ -230,4 +230,6 @@ export interface NativeApplication { readonly appKit?: NativeAppKit; /** macOS and Linux. */ showAboutPanel?(): void; + /** Blink keeps its profile here (`app.getPath('userData')`); set before {@link start}. */ + setUserDataPath?(path: string): void; } diff --git a/tests/unit/main/bootstrap.test.ts b/tests/unit/main/bootstrap.test.ts index 7588876..cd7e4da 100644 --- a/tests/unit/main/bootstrap.test.ts +++ b/tests/unit/main/bootstrap.test.ts @@ -138,6 +138,21 @@ describe('bootstrap native wiring', () => { }, ); + test('hands userData to a backend with its own profile before starting it', () => { + const { native } = makeNative(); + const calls: string[] = []; + resetBootstrapForTesting(); + setNativeAppForTesting({ + ...native, + setUserDataPath: (path) => calls.push(`userData ${path}`), + start: () => { + calls.push('start'); + }, + }); + ensureNativeStarted(); + expect(calls).toEqual([`userData ${app.getPath('userData')}`, 'start']); + }); + test('retries the native start after a failed one', () => { const { native } = makeNative(); let starts = 0; From 6b2ba42f77bd818b7a9671a6ab39ebf26ace6386 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 14:03:16 -0700 Subject: [PATCH 05/15] feat: add the opt-in Blink backend over CEF on macOS --- biome.json | 24 ++ src/main/api/web-contents.ts | 2 +- src/main/platform/cef/cef-backend.ts | 149 +++++++ src/main/platform/cef/cef-client.ts | 228 ++++++++++ src/main/platform/cef/cef-devtools.ts | 96 +++++ src/main/platform/cef/cef-ffi.ts | 205 +++++++++ src/main/platform/cef/cef-glue.ts | 117 +++++ src/main/platform/cef/cef-input.ts | 91 ++++ src/main/platform/cef/cef-runtime.ts | 359 ++++++++++++++++ src/main/platform/cef/cef-web-contents.ts | 404 ++++++++++++++++++ src/main/platform/index.ts | 47 +- src/main/platform/native.ts | 2 +- .../main/platform/cef/cef-devtools.test.ts | 63 +++ tests/unit/main/platform/cef/cef-ffi.test.ts | 19 + .../unit/main/platform/cef/cef-input.test.ts | 45 ++ .../platform/cef/cef-web-contents.test.ts | 19 + tests/unit/main/platform/index.test.ts | 66 ++- 17 files changed, 1928 insertions(+), 8 deletions(-) create mode 100644 src/main/platform/cef/cef-backend.ts create mode 100644 src/main/platform/cef/cef-client.ts create mode 100644 src/main/platform/cef/cef-devtools.ts create mode 100644 src/main/platform/cef/cef-ffi.ts create mode 100644 src/main/platform/cef/cef-glue.ts create mode 100644 src/main/platform/cef/cef-input.ts create mode 100644 src/main/platform/cef/cef-runtime.ts create mode 100644 src/main/platform/cef/cef-web-contents.ts create mode 100644 tests/unit/main/platform/cef/cef-devtools.test.ts create mode 100644 tests/unit/main/platform/cef/cef-ffi.test.ts create mode 100644 tests/unit/main/platform/cef/cef-input.test.ts create mode 100644 tests/unit/main/platform/cef/cef-web-contents.test.ts diff --git a/biome.json b/biome.json index f716a7c..bf404d5 100644 --- a/biome.json +++ b/biome.json @@ -165,6 +165,30 @@ } } }, + { + "includes": ["src/main/platform/cef/**"], + "linter": { + "rules": { + "style": { + "noRestrictedImports": { + "level": "error", + "options": { + "patterns": [ + { + "group": ["../api/**", "../../api/**", "**/bootstrap", "**/native-app"], + "message": "D024: platform/ never imports api/; contracts live in platform/services.ts and native.ts." + }, + { + "group": ["**/linux/**", "**/windows/**"], + "message": "D024: the Blink backend reuses only the macOS window code (D048); share the rest through a platform/ root file." + } + ] + } + } + } + } + } + }, { "includes": ["src/main/platform/windows/**"], "linter": { diff --git a/src/main/api/web-contents.ts b/src/main/api/web-contents.ts index 45a6b2f..83a1ca2 100644 --- a/src/main/api/web-contents.ts +++ b/src/main/api/web-contents.ts @@ -246,7 +246,7 @@ export class WebContents extends EventEmitter { return this.#userAgent; } - /** Delivers an `isTrusted` event through the engine; Windows only, macOS and Linux throw. */ + /** An `isTrusted` event via the engine: Windows and Blink; WebKit on macOS and Linux throws. */ sendInputEvent(event: NativeInputEvent): void { // Validate at the boundary (Electron throws on a bad event): an unknown type // must not silently no-op, and non-finite coordinates must not coerce to a diff --git a/src/main/platform/cef/cef-backend.ts b/src/main/platform/cef/cef-backend.ts new file mode 100644 index 0000000..1658e8c --- /dev/null +++ b/src/main/platform/cef/cef-backend.ts @@ -0,0 +1,149 @@ +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import { UnsupportedPlatformError } from '../../../common/errors'; +import { createLogger } from '../../../common/logger'; +import { currentPlatform } from '../../../common/platform'; +import { createMacOSApplication, createMacOSWindow } from '../macos/cocoa-backend'; +import { withAutoreleasePool } from '../macos/cocoa-run-loop'; +import { cocoa } from '../macos/cocoa-runtime'; +import type { NativeAppKit, NativeApplication, NativeWindow, NativeWindowOptions } from '../native'; +import { loadCef } from './cef-ffi'; +import { + cefLibraryPath, + createCefBrowser, + doCefWork, + flushCookies, + initializeCef, + installCefApplicationClass, +} from './cef-runtime'; +import { CefWebContents } from './cef-web-contents'; + +const log = createLogger('cef-backend'); + +const QUIT_CLOSE_TIMEOUT_MS = 2_000; +const FLUSH_GRACE_MS = 200; + +/** + * The opt-in Blink engine (D048): CEF browsers inside the macOS backend's own NSWindows, + * so every window, menu, tray, dialog and app operation is the OS backend's and only the + * web contents are Chromium. + */ +class CefApplication implements NativeApplication { + readonly #libDir: string; + readonly #host: NativeApplication; + readonly #live = new Set(); + #readyCallbacks: Array<() => void> = []; + #userDataPath = join(homedir(), '.bunmaska', 'blink-profile'); + #cefRunning = false; + #started = false; + readonly appKit?: NativeAppKit; + + constructor(libDir: string) { + this.#libDir = libDir; + this.#host = createMacOSApplication(() => { + if (this.#cefRunning) { + doCefWork(); + } + }); + if (this.#host.appKit !== undefined) { + this.appKit = this.#host.appKit; + } + } + + setUserDataPath(path: string): void { + this.#userDataPath = path; + } + + start(): void { + if (this.#started) { + return; + } + this.#started = true; + loadCef(cefLibraryPath(this.#libDir)); + installCefApplicationClass(); + this.#host.start(); + initializeCef({ libDir: this.#libDir, userDataPath: this.#userDataPath }); + this.#cefRunning = true; + const callbacks = this.#readyCallbacks; + this.#readyCallbacks = []; + for (const callback of callbacks) { + callback(); + } + } + + onReady(callback: () => void): void { + if (this.#cefRunning) { + callback(); + } else { + this.#readyCallbacks.push(callback); + } + } + + onActivate(callback: (hasVisibleWindows: boolean) => void): void { + this.#host.onActivate?.(callback); + } + + onOpenUrl(callback: (url: string) => void): void { + this.#host.onOpenUrl?.(callback); + } + + onOpenFile(callback: (path: string) => void): void { + this.#host.onOpenFile?.(callback); + } + + onQuitRequest(callback: () => void): void { + this.#host.onQuitRequest?.(callback); + } + + showAboutPanel(): void { + this.#host.showAboutPanel?.(); + } + + createWindow(options: NativeWindowOptions): NativeWindow { + const schemes = options.protocol?.schemes ?? []; + if (schemes.length > 0) { + // ponytail: needs the phase 2 native scheme-handler bridge in the glue (D048). + log.warn( + `protocol.handle schemes are not served by the Blink engine yet: ${schemes.join(', ')}`, + ); + } + return withAutoreleasePool(() => + createMacOSWindow(options, (window, _options, emit) => { + const rt = cocoa(); + const contentView = rt.msgSend(window, rt.selectors.get('contentView')); + const browser = createCefBrowser(contentView, options.width, options.height); + const contents = new CefWebContents(browser, options, () => emit('ready-to-show')); + this.#live.add(contents); + void contents.closed.then(() => this.#live.delete(contents)); + // do_close returns 1: the browser is destroyed when CEF's host view deallocs with the + // window, which needs the drain's rolling autorelease pool. + return { contents, teardown: () => contents.close(), release: () => undefined }; + }), + ); + } + + /** Close every browser and flush cookies while the pump still runs, then stop it. */ + async quit(): Promise { + if (this.#cefRunning) { + const closing = [...this.#live].map((contents) => { + contents.close(); + return contents.closed; + }); + await Promise.race([Promise.all(closing), Bun.sleep(QUIT_CLOSE_TIMEOUT_MS)]); + flushCookies(); + await Bun.sleep(FLUSH_GRACE_MS); + // ponytail: no cef_shutdown - it blocks forever on a Mach wait under the Bun pump, so the + // helpers exit with us and DOM storage can lose its last few seconds; fix with a symbolized CEF. + this.#cefRunning = false; + } + await this.#host.quit(); + } +} + +/** The Blink backend over the CEF engine in `libDir` (an installed engine's `lib/`). macOS only. */ +export const createCefApplication = (libDir: string): NativeApplication => { + if (currentPlatform() !== 'macos') { + throw new UnsupportedPlatformError('The Blink (cef) engine runs on macOS only so far'); + } + return new CefApplication(libDir); +}; diff --git a/src/main/platform/cef/cef-client.ts b/src/main/platform/cef/cef-client.ts new file mode 100644 index 0000000..7b91d1f --- /dev/null +++ b/src/main/platform/cef/cef-client.ts @@ -0,0 +1,228 @@ +import { FFIType, JSCallback, type Pointer, toArrayBuffer } from 'bun:ffi'; +import { createLogger } from '../../../common/logger'; +import { + allocImmortal, + BROWSER, + CLIENT, + callMethod, + DEVTOOLS_OBSERVER, + DISPLAY, + FRAME, + LIFE_SPAN, + LOAD, + readCefString, + release, + retainForever, + SIZE, + setPtr, + toAddress, +} from './cef-ffi'; +import { cefGlue } from './cef-glue'; + +const log = createLogger('cef-client'); + +/** What one browser's owner wants to hear. Every callback runs on the UI (= Bun main) thread. */ +export type BrowserListener = { + readonly onLoadingStateChange: (isLoading: boolean) => void; + readonly onMainFrameLoadEnd: (httpStatus: number) => void; + readonly onMainFrameLoadError: (code: number, text: string, url: string) => void; + readonly onTitleChange: (title: string) => void; + readonly onBeforePopup: (url: string) => void; + readonly onDevToolsMessage: (text: string) => void; + readonly onBeforeClose: () => void; +}; + +const listeners = new Map(); + +/** Route a browser's callbacks to `listener` until {@link unregisterBrowser}. */ +export const registerBrowser = (id: number, listener: BrowserListener): void => { + listeners.set(id, listener); +}; + +export const unregisterBrowser = (id: number): void => { + listeners.delete(id); +}; + +/** The listener for a callback's `browser` argument; releases the reference CEF passed. */ +const listenerFor = (browser: number): BrowserListener | undefined => { + const id = Number(callMethod(browser, BROWSER.getIdentifier, [], FFIType.i32)); + release(browser); + return listeners.get(id); +}; + +const isMainFrame = (frame: number): boolean => { + const main = Number(callMethod(frame, FRAME.isMain, [], FFIType.i32)) === 1; + release(frame); + return main; +}; + +/** A UI-thread JSCallback that never lets a JS exception unwind into CEF. */ +const uiCallback = ( + name: string, + args: readonly FFIType[], + returns: FFIType, + body: (...values: number[]) => number | undefined, +): number => { + const fallback = returns === FFIType.void ? undefined : 0; + const callback = new JSCallback( + (...raw: unknown[]) => { + try { + return body(...raw.map(toAddress)) ?? fallback; + } catch (error) { + log.error(`${name} threw`, error); + return fallback; + } + }, + { args: [...args], returns }, + ); + retainForever(callback); + return toAddress(callback.ptr); +}; + +const P = FFIType.ptr; + +const buildClient = (): Pointer => { + const glue = cefGlue(); + const handler = (size: number) => { + const struct = allocImmortal(size); + glue.initBase(struct.at, size); + return struct; + }; + + const lifeSpan = handler(SIZE.lifeSpanHandler); + setPtr( + lifeSpan.buf, + LIFE_SPAN.onBeforePopup, + uiCallback( + 'on_before_popup', + [P, P, P, FFIType.i32, P, P, FFIType.i32, FFIType.i32, P, P, P, P, P, P], + FFIType.i32, + (_self, browser, frame, _id, url) => { + release(frame); + listenerFor(browser)?.onBeforePopup(readCefString(url)); + return 1; + }, + ), + ); + setPtr( + lifeSpan.buf, + LIFE_SPAN.doClose, + uiCallback('do_close', [P, P], FFIType.i32, (_self, browser) => { + release(browser); + return 1; + }), + ); + setPtr( + lifeSpan.buf, + LIFE_SPAN.onBeforeClose, + uiCallback('on_before_close', [P, P], FFIType.void, (_self, browser) => { + listenerFor(browser)?.onBeforeClose(); + return undefined; + }), + ); + + const load = handler(SIZE.loadHandler); + setPtr( + load.buf, + LOAD.onLoadingStateChange, + uiCallback( + 'on_loading_state_change', + [P, P, FFIType.i32, FFIType.i32, FFIType.i32], + FFIType.void, + (_self, browser, isLoading) => { + listenerFor(browser)?.onLoadingStateChange(isLoading === 1); + return undefined; + }, + ), + ); + setPtr( + load.buf, + LOAD.onLoadEnd, + uiCallback( + 'on_load_end', + [P, P, P, FFIType.i32], + FFIType.void, + (_self, browser, frame, status) => { + const main = isMainFrame(frame); + const listener = listenerFor(browser); + if (main) { + listener?.onMainFrameLoadEnd(status); + } + return undefined; + }, + ), + ); + setPtr( + load.buf, + LOAD.onLoadError, + uiCallback( + 'on_load_error', + [P, P, P, FFIType.i32, P, P], + FFIType.void, + (_self, browser, frame, code, text, url) => { + const main = isMainFrame(frame); + const listener = listenerFor(browser); + if (main) { + listener?.onMainFrameLoadError(code, readCefString(text), readCefString(url)); + } + return undefined; + }, + ), + ); + + const display = handler(SIZE.displayHandler); + setPtr( + display.buf, + DISPLAY.onTitleChange, + uiCallback('on_title_change', [P, P, P], FFIType.void, (_self, browser, title) => { + listenerFor(browser)?.onTitleChange(readCefString(title)); + return undefined; + }), + ); + + const client = allocImmortal(SIZE.client + 3 * 8); + glue.initBase(client.at, SIZE.client); + setPtr(client.buf, CLIENT.getDisplayHandler, glue.slotGetter(0)); + setPtr(client.buf, CLIENT.getLifeSpanHandler, glue.slotGetter(1)); + setPtr(client.buf, CLIENT.getLoadHandler, glue.slotGetter(2)); + setPtr(client.buf, SIZE.client, display.at); + setPtr(client.buf, SIZE.client + 8, lifeSpan.at); + setPtr(client.buf, SIZE.client + 16, load.at); + return client.at; +}; + +const buildObserver = (): Pointer => { + const observer = allocImmortal(SIZE.devToolsObserver); + cefGlue().initBase(observer.at, SIZE.devToolsObserver); + const decoder = new TextDecoder(); + setPtr( + observer.buf, + DEVTOOLS_OBSERVER.onDevToolsMessage, + uiCallback( + 'on_dev_tools_message', + [P, P, P, FFIType.u64], + FFIType.i32, + (_self, browser, message, size) => { + const text = decoder.decode(toArrayBuffer(message as Pointer, 0, size)); + listenerFor(browser)?.onDevToolsMessage(text); + return 1; + }, + ), + ); + return observer.at; +}; + +let client: Pointer | undefined; +let observer: Pointer | undefined; + +/** The one immortal `cef_client_t` every bunmaska browser shares. */ +export const sharedClient = (): Pointer => { + client ??= buildClient(); + return client; +}; + +/** The one immortal DevTools message observer every browser registers. */ +export const sharedDevToolsObserver = (): Pointer => { + observer ??= buildObserver(); + return observer; +}; diff --git a/src/main/platform/cef/cef-devtools.ts b/src/main/platform/cef/cef-devtools.ts new file mode 100644 index 0000000..32c122a --- /dev/null +++ b/src/main/platform/cef/cef-devtools.ts @@ -0,0 +1,96 @@ +import { BunmaskaError } from '../../../common/errors'; + +export type CdpParams = Readonly>; +type Pending = { + readonly resolve: (result: CdpParams) => void; + readonly reject: (error: Error) => void; +}; + +/** + * One Chrome DevTools Protocol session over CEF's in-process DevTools channel + * (`send_dev_tools_message` out, the message observer in). Transport-agnostic so + * the routing is testable without CEF. + */ +export class CdpSession { + readonly #send: (json: string) => boolean; + readonly #pending = new Map(); + readonly #listeners = new Map void>>(); + #nextId = 1; + #closedReason: string | undefined; + + constructor(send: (json: string) => boolean) { + this.#send = send; + } + + /** Invoke a method; resolves with its `result`, rejects on a protocol error. */ + call(method: string, params: CdpParams = {}): Promise { + if (this.#closedReason !== undefined) { + return Promise.reject(new BunmaskaError(`CDP ${method}: ${this.#closedReason}`)); + } + const id = this.#nextId; + this.#nextId += 1; + return new Promise((resolve, reject) => { + this.#pending.set(id, { resolve, reject }); + if (!this.#send(JSON.stringify({ id, method, params }))) { + this.#pending.delete(id); + reject(new BunmaskaError(`CDP ${method}: the DevTools channel refused the message`)); + } + }); + } + + /** Subscribe to a protocol event (`Runtime.bindingCalled`, ...). */ + on(method: string, listener: (params: CdpParams) => void): void { + const list = this.#listeners.get(method) ?? []; + list.push(listener); + this.#listeners.set(method, list); + } + + /** Feed one raw message from the observer. Malformed input is dropped. */ + receive(text: string): void { + let message: unknown; + try { + message = JSON.parse(text); + } catch { + return; + } + if (message === null || typeof message !== 'object') { + return; + } + const record = message as Record; + const id = record['id']; + if (typeof id === 'number') { + const slot = this.#pending.get(id); + if (slot === undefined) { + return; + } + this.#pending.delete(id); + const error = record['error']; + if (error !== undefined) { + const detail = (error as Record)['message']; + slot.reject( + new BunmaskaError(`CDP error: ${typeof detail === 'string' ? detail : 'unknown'}`), + ); + } else { + slot.resolve((record['result'] as CdpParams | undefined) ?? {}); + } + return; + } + const method = record['method']; + if (typeof method === 'string') { + const params = (record['params'] as CdpParams | undefined) ?? {}; + for (const listener of this.#listeners.get(method) ?? []) { + listener(params); + } + } + } + + /** Reject every in-flight call and refuse new ones (the browser is gone). */ + close(reason: string): void { + this.#closedReason = reason; + const pending = [...this.#pending.values()]; + this.#pending.clear(); + for (const slot of pending) { + slot.reject(new BunmaskaError(`CDP: ${reason}`)); + } + } +} diff --git a/src/main/platform/cef/cef-ffi.ts b/src/main/platform/cef/cef-ffi.ts new file mode 100644 index 0000000..81defd4 --- /dev/null +++ b/src/main/platform/cef/cef-ffi.ts @@ -0,0 +1,205 @@ +import { CFunction, FFIType, type Pointer, ptr, read, toArrayBuffer } from 'bun:ffi'; +import { dlopen } from '../dlopen'; + +/** + * CEF's C API, pinned to one API version. Every struct below is LP64 + * (macOS/Linux) at CEF_API_VERSION 15400, measured with + * `clang -DCEF_API_VERSION=15400 -Xclang -fdump-record-layouts` against the CEF + * headers. A struct's leading `size` is how CEF tells versions apart, so the + * numbers must match the version passed to `cef_api_hash`, never a newer header. + */ +export const CEF_API_VERSION = 15400; + +export const SIZE = { + settings: 448, + browserSettings: 264, + windowInfo: 96, + app: 80, + browserProcessHandler: 96, + client: 192, + lifeSpanHandler: 88, + loadHandler: 72, + displayHandler: 144, + devToolsObserver: 80, + mainArgs: 16, +} as const; + +export const SETTINGS = { + noSandbox: 8, + browserSubprocessPath: 16, + frameworkDirPath: 40, + mainBundlePath: 64, + multiThreadedMessageLoop: 88, + externalMessagePump: 92, + cachePath: 104, + rootCachePath: 128, + persistSessionCookies: 152, + logSeverity: 256, +} as const; + +export const WINDOW_INFO = { bounds: 32, parentView: 56, runtimeStyle: 88 } as const; +export const RUNTIME_STYLE_ALLOY = 2; +export const LOG_SEVERITY_ERROR = 4; + +export const APP = { onBeforeCommandLineProcessing: 40, getBrowserProcessHandler: 64 } as const; +export const COMMAND_LINE = { + getSwitchValue: 136, + appendSwitch: 152, + appendSwitchWithValue: 160, +} as const; +export const BROWSER_PROCESS_HANDLER = { onContextInitialized: 48, onScheduleMessagePumpWork: 72 }; +export const CLIENT = { getDisplayHandler: 72, getLifeSpanHandler: 144, getLoadHandler: 152 }; +export const LIFE_SPAN = { onBeforePopup: 40, onAfterCreated: 64, doClose: 72, onBeforeClose: 80 }; +export const LOAD = { onLoadingStateChange: 40, onLoadEnd: 56, onLoadError: 64 } as const; +export const DISPLAY = { onAddressChange: 40, onTitleChange: 48 } as const; +export const DEVTOOLS_OBSERVER = { onDevToolsMessage: 40 } as const; +export const BASE = { release: 16 } as const; +export const BROWSER = { + getHost: 48, + canGoBack: 56, + goBack: 64, + canGoForward: 72, + goForward: 80, + reload: 96, + reloadIgnoreCache: 104, + stopLoad: 112, + getIdentifier: 120, +} as const; +export const HOST = { + closeBrowser: 48, + setFocus: 72, + setZoomLevel: 160, + showDevTools: 224, + closeDevTools: 232, + sendDevToolsMessage: 248, + addDevToolsMessageObserver: 264, +} as const; +export const FRAME = { isMain: 160 } as const; +export const COOKIE_MANAGER = { flushStore: 72 } as const; +export const PREFERENCE_MANAGER = { setPreference: 72 } as const; +export const VALUE = { setString: 184 } as const; + +const openCef = (path: string) => + dlopen(path, { + cef_api_hash: { args: [FFIType.i32, FFIType.i32], returns: FFIType.ptr }, + cef_initialize: { + args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr], + returns: FFIType.i32, + }, + cef_do_message_loop_work: { args: [], returns: FFIType.void }, + cef_cookie_manager_get_global_manager: { args: [FFIType.ptr], returns: FFIType.ptr }, + cef_preference_manager_get_global: { args: [], returns: FFIType.ptr }, + cef_value_create: { args: [], returns: FFIType.ptr }, + cef_string_userfree_utf16_free: { args: [FFIType.ptr], returns: FFIType.void }, + cef_browser_host_create_browser_sync: { + args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr], + returns: FFIType.ptr, + }, + }); + +export type CefLibrary = ReturnType; + +let library: CefLibrary | undefined; + +/** Open libcef once per process; a second call must name the same path. */ +export const loadCef = (path: string): CefLibrary => { + library ??= openCef(path); + return library; +}; + +/** The already-opened libcef. Throws before {@link loadCef}. */ +export const cefLibrary = (): CefLibrary => { + if (library === undefined) { + throw new Error('CEF used before loadCef()'); + } + return library; +}; + +/** Structs CEF keeps pointers to live for the whole process (see cef-glue). */ +const immortal: unknown[] = []; + +/** A zeroed buffer that is never freed, and its address. */ +export const allocImmortal = (size: number): { readonly buf: Buffer; readonly at: Pointer } => { + const buf = Buffer.alloc(size); + immortal.push(buf); + return { buf, at: addressOf(buf) }; +}; + +/** Keep a JSCallback (or anything CEF points into) alive for the process. */ +export const retainForever = (value: unknown): void => { + immortal.push(value); +}; + +export const addressOf = (buf: Uint8Array): Pointer => ptr(buf); + +export const setPtr = (buf: Buffer, offset: number, value: number | bigint): void => { + buf.writeBigUInt64LE(BigInt(value), offset); +}; + +/** + * Write a `cef_string_t` (UTF-16 `{str, length, dtor}`) into `buf`. The text + * lives in `keep`, which must outlive the CEF call that copies it. + */ +export const writeCefString = ( + buf: Buffer, + offset: number, + value: string, + keep: unknown[], +): void => { + const data = Buffer.from(`${value}\0`, 'utf16le'); + keep.push(data); + setPtr(buf, offset, ptr(data)); + setPtr(buf, offset + 8, value.length); + setPtr(buf, offset + 16, 0); +}; + +const utf16 = new TextDecoder('utf-16le'); + +/** Read a borrowed `const cef_string_t*` (NULL reads as `''`). */ +export const readCefString = (at: number): string => { + if (at === 0) { + return ''; + } + const str = read.ptr(at as Pointer, 0); + const length = Number(read.u64(at as Pointer, 8)); + if (str === 0 || length === 0) { + return ''; + } + return utf16.decode(toArrayBuffer(str as Pointer, 0, length * 2)); +}; + +type FFITypeValue = (typeof FFIType)[keyof typeof FFIType]; +const methods = new Map unknown>(); + +/** + * Call method `offset` of the CEF object at `self` (`self->method(self, ...)`). + * CFunctions are cached per function pointer + signature, so a vtable shared + * by every browser costs one wrapper. + */ +export const callMethod = ( + self: number, + offset: number, + args: readonly FFITypeValue[], + returns: FFITypeValue, + ...values: unknown[] +): unknown => { + const fn = read.ptr(self as Pointer, offset); + const key = `${fn}|${args.join(',')}|${returns}`; + let method = methods.get(key); + if (method === undefined) { + const created = CFunction({ ptr: fn as Pointer, args: [FFIType.ptr, ...args], returns }); + method = created as unknown as (...args: unknown[]) => unknown; + methods.set(key, method); + } + return method(self, ...values); +}; + +/** Drop the reference CEF handed us with an argument or return value. */ +export const release = (object: number): void => { + if (object !== 0) { + callMethod(object, BASE.release, [], FFIType.i32); + } +}; + +/** Coerce a pointer-ish FFI value (number, bigint or null) to a number. */ +export const toAddress = (value: unknown): number => Number(value ?? 0); diff --git a/src/main/platform/cef/cef-glue.ts b/src/main/platform/cef/cef-glue.ts new file mode 100644 index 0000000..1607c73 --- /dev/null +++ b/src/main/platform/cef/cef-glue.ts @@ -0,0 +1,117 @@ +import { cc, FFIType, type Pointer } from 'bun:ffi'; +import { createHash } from 'node:crypto'; +import { mkdirSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +/** + * The C half of the CEF client, compiled in-process by Bun's TinyCC (`cc`, D048): no + * prebuilt binary ships in the package. CEF calls refcounting, some getters + * (`get_browser_process_handler` "on multiple threads") and the pump scheduler from + * threads a synchronous JSCallback must never run on, so those are C. Every object + * bunmaska hands CEF is immortal: refcounting is a no-op, and a getter returns the + * pointer stored in a trailing slot found via the struct's own `size`. + * + * The scheduler wakes the macOS drain with a signaled version-0 run-loop source, never + * CFRunLoopStop: a stop that lands while Bun runs JS (outside CFRunLoopRunInMode) is + * dropped by the next run, and the work then waits for the pump's idle timeout. + */ +const GLUE_SOURCE = `#include +typedef struct { uint64_t size; void* add_ref; void* release; void* has_one_ref; void* has_at_least_one_ref; } bm_base; +static void bm_add_ref(void* s) { (void)s; } +static int bm_release(void* s) { (void)s; return 0; } +static int bm_has_one_ref(void* s) { (void)s; return 0; } +static int bm_has_at_least_one_ref(void* s) { (void)s; return 1; } +void bm_init_base(void* p, uint64_t size) { + bm_base* b = (bm_base*)p; + b->size = size; + b->add_ref = (void*)bm_add_ref; + b->release = (void*)bm_release; + b->has_one_ref = (void*)bm_has_one_ref; + b->has_at_least_one_ref = (void*)bm_has_at_least_one_ref; +} +#define BM_SLOT(i) static void* bm_slot##i(void* s) { return *(void**)((char*)s + ((bm_base*)s)->size + 8 * (i)); } +BM_SLOT(0) BM_SLOT(1) BM_SLOT(2) BM_SLOT(3) BM_SLOT(4) BM_SLOT(5) BM_SLOT(6) BM_SLOT(7) +void* bm_slot_getter(int i) { + switch (i) { + case 0: return (void*)bm_slot0; case 1: return (void*)bm_slot1; + case 2: return (void*)bm_slot2; case 3: return (void*)bm_slot3; + case 4: return (void*)bm_slot4; case 5: return (void*)bm_slot5; + case 6: return (void*)bm_slot6; default: return (void*)bm_slot7; + } +} +typedef struct { + int64_t version; void* info; void* retain; void* release; void* copy_description; + void* equal; void* hash; void* schedule; void* cancel; void* perform; +} bm_source_context; +extern void* CFRunLoopGetMain(void); +extern void CFRunLoopWakeUp(void* rl); +extern double CFAbsoluteTimeGetCurrent(void); +extern void* CFRunLoopSourceCreate(void* allocator, int64_t order, bm_source_context* context); +extern void CFRunLoopSourceSignal(void* source); +extern void CFRunLoopAddSource(void* rl, void* source, void* mode); +extern void* CFRunLoopTimerCreate(void* a, double fire, double interval, uint64_t flags, int64_t order, void* cb, void* ctx); +extern void CFRunLoopTimerSetNextFireDate(void* timer, double fire); +extern void CFRunLoopAddTimer(void* rl, void* timer, void* mode); +extern void* kCFRunLoopCommonModes; +static void* bm_source = 0; +static void* bm_timer = 0; +static void bm_perform(void* info) { (void)info; } +static void bm_wake(void) { CFRunLoopSourceSignal(bm_source); CFRunLoopWakeUp(CFRunLoopGetMain()); } +static void bm_fire(void* timer, void* info) { (void)timer; (void)info; bm_wake(); } +void bm_pump_init(void) { + bm_source_context context = {0}; + context.perform = (void*)bm_perform; + bm_source = CFRunLoopSourceCreate(0, 0, &context); + CFRunLoopAddSource(CFRunLoopGetMain(), bm_source, kCFRunLoopCommonModes); + bm_timer = CFRunLoopTimerCreate(0, CFAbsoluteTimeGetCurrent() + 1e9, 1e9, 0, 0, (void*)bm_fire, 0); + CFRunLoopAddTimer(CFRunLoopGetMain(), bm_timer, kCFRunLoopCommonModes); +} +static void bm_schedule(void* self, int64_t delay_ms) { + (void)self; + if (delay_ms <= 0) { bm_wake(); return; } + CFRunLoopTimerSetNextFireDate(bm_timer, CFAbsoluteTimeGetCurrent() + (double)delay_ms / 1000.0); +} +void* bm_schedule_fn(void) { return (void*)bm_schedule; } +`; + +const SYMBOLS = { + bm_init_base: { args: [FFIType.ptr, FFIType.u64], returns: FFIType.void }, + bm_slot_getter: { args: [FFIType.i32], returns: FFIType.ptr }, + bm_pump_init: { args: [], returns: FFIType.void }, + bm_schedule_fn: { args: [], returns: FFIType.ptr }, +} as const; + +export type CefGlue = { + /** Fill a CEF struct's `cef_base_ref_counted_t` header as an immortal object. */ + readonly initBase: (struct: Pointer, size: number) => void; + /** A getter returning trailing slot `index` of whatever struct it is installed in. */ + readonly slotGetter: (index: number) => number; + /** Add the wakeup source and timer to the main run loop; main thread, before `cef_initialize`. */ + readonly pumpInit: () => void; + /** `on_schedule_message_pump_work`: wakes the adaptive pump from any thread. */ + readonly scheduleFn: () => number; +}; + +let cached: CefGlue | undefined; + +/** Compile the glue once per process (TinyCC needs a source file on disk). */ +export const cefGlue = (): CefGlue => { + if (cached !== undefined) { + return cached; + } + const hash = createHash('sha256').update(GLUE_SOURCE).digest('hex').slice(0, 16); + const dir = join(tmpdir(), 'bunmaska-cef'); + mkdirSync(dir, { recursive: true }); + const source = join(dir, `glue-${hash}.c`); + writeFileSync(source, GLUE_SOURCE); + const lib = cc({ source, symbols: SYMBOLS }); + const toNumber = (value: unknown): number => Number(value ?? 0); + cached = { + initBase: (struct, size) => lib.symbols.bm_init_base(struct, BigInt(size)), + slotGetter: (index) => toNumber(lib.symbols.bm_slot_getter(index)), + pumpInit: () => lib.symbols.bm_pump_init(), + scheduleFn: () => toNumber(lib.symbols.bm_schedule_fn()), + }; + return cached; +}; diff --git a/src/main/platform/cef/cef-input.ts b/src/main/platform/cef/cef-input.ts new file mode 100644 index 0000000..30aab10 --- /dev/null +++ b/src/main/platform/cef/cef-input.ts @@ -0,0 +1,91 @@ +import { InvalidArgumentError } from '../../../common/errors'; +import type { NativeInputEvent } from '../native'; + +/** Electron key names -> DOM `key` + Windows virtual-key code (CDP wants both). */ +const NAMED_KEYS = new Map([ + ['Backspace', ['Backspace', 0x08]], + ['Tab', ['Tab', 0x09]], + ['Enter', ['Enter', 0x0d]], + ['Return', ['Enter', 0x0d]], + ['Escape', ['Escape', 0x1b]], + ['Space', [' ', 0x20]], + ['PageUp', ['PageUp', 0x21]], + ['PageDown', ['PageDown', 0x22]], + ['End', ['End', 0x23]], + ['Home', ['Home', 0x24]], + ['Left', ['ArrowLeft', 0x25]], + ['Up', ['ArrowUp', 0x26]], + ['Right', ['ArrowRight', 0x27]], + ['Down', ['ArrowDown', 0x28]], + ['Delete', ['Delete', 0x2e]], +]); + +const TEXT_OF_NAMED = new Map([ + ['Enter', '\r'], + ['Tab', '\t'], + [' ', ' '], +]); + +/** A CDP `Input.*` call equivalent to one Electron input event. */ +export type CdpInput = { + readonly method: 'Input.dispatchMouseEvent' | 'Input.dispatchKeyEvent'; + readonly params: Readonly>; +}; + +const resolveKey = (keyCode: string): readonly [string, number] => { + const named = NAMED_KEYS.get(keyCode); + if (named !== undefined) { + return named; + } + if ([...keyCode].length === 1) { + return [keyCode, keyCode.toUpperCase().charCodeAt(0)]; + } + throw new InvalidArgumentError(`sendInputEvent: unsupported keyCode ${JSON.stringify(keyCode)}`); +}; + +/** + * Map an Electron input event to CDP. `keyDown` is a raw key press (no text), + * `char` types, `keyUp` releases, matching Electron's keyDown/char/keyUp recipe. + */ +export const toCdpInput = (event: NativeInputEvent): CdpInput => { + switch (event.type) { + case 'mouseDown': + case 'mouseUp': + case 'mouseMove': + return { + method: 'Input.dispatchMouseEvent', + params: { + type: + event.type === 'mouseDown' + ? 'mousePressed' + : event.type === 'mouseUp' + ? 'mouseReleased' + : 'mouseMoved', + x: event.x, + y: event.y, + button: event.type === 'mouseMove' ? 'none' : (event.button ?? 'left'), + clickCount: event.type === 'mouseMove' ? 0 : 1, + }, + }; + case 'keyDown': + case 'keyUp': { + const [key, code] = resolveKey(event.keyCode); + return { + method: 'Input.dispatchKeyEvent', + params: { + type: event.type === 'keyDown' ? 'rawKeyDown' : 'keyUp', + key, + windowsVirtualKeyCode: code, + }, + }; + } + case 'char': { + const [key, code] = resolveKey(event.keyCode); + const text = TEXT_OF_NAMED.get(key) ?? ([...key].length === 1 ? key : ''); + return { + method: 'Input.dispatchKeyEvent', + params: { type: 'char', key, text, unmodifiedText: text, windowsVirtualKeyCode: code }, + }; + } + } +}; diff --git a/src/main/platform/cef/cef-runtime.ts b/src/main/platform/cef/cef-runtime.ts new file mode 100644 index 0000000..538a5d9 --- /dev/null +++ b/src/main/platform/cef/cef-runtime.ts @@ -0,0 +1,359 @@ +import { FFIType, JSCallback, type Pointer, ptr } from 'bun:ffi'; +import { mkdirSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { BunmaskaError } from '../../../common/errors'; +import { cstr } from '../cstr'; +import { dlopen } from '../dlopen'; +import { cocoa } from '../macos/cocoa-runtime'; +import { defineObjcClass } from '../macos/cocoa-runtime-class'; +import { type Handle, LIBOBJC_PATH, macOSLibraryAccessor } from '../macos/objc'; +import { sharedClient } from './cef-client'; +import { + APP, + allocImmortal, + BROWSER_PROCESS_HANDLER, + CEF_API_VERSION, + COMMAND_LINE, + COOKIE_MANAGER, + callMethod, + cefLibrary, + LOG_SEVERITY_ERROR, + PREFERENCE_MANAGER, + RUNTIME_STYLE_ALLOY, + readCefString, + release, + retainForever, + SETTINGS, + SIZE, + setPtr, + toAddress, + VALUE, + WINDOW_INFO, + writeCefString, +} from './cef-ffi'; +import { cefGlue } from './cef-glue'; + +/** Where a CEF engine keeps its framework and generic helper apps (the engine's `lib/`). */ +export const cefFrameworkPath = (libDir: string): string => + join(libDir, 'Chromium Embedded Framework.framework'); +export const cefLibraryPath = (libDir: string): string => + join(cefFrameworkPath(libDir), 'Chromium Embedded Framework'); +export const cefHelperPath = (libDir: string): string => + join(libDir, 'bunmaska Helper.app', 'Contents', 'MacOS', 'bunmaska Helper'); + +const objcExtras = macOSLibraryAccessor('objc super + protocols', () => + dlopen(LIBOBJC_PATH, { + objc_msgSendSuper: { args: [FFIType.ptr, FFIType.u64, FFIType.u64], returns: FFIType.void }, + objc_getProtocol: { args: [FFIType.cstring], returns: FFIType.u64 }, + class_addProtocol: { args: [FFIType.u64, FFIType.u64], returns: FFIType.u8 }, + }), +); + +let handlingSendEvent = false; + +/** + * Chromium requires NSApp to be an NSApplication subclass answering + * `isHandlingSendEvent` (CrAppControlProtocol), created before anything calls + * `+sharedApplication`; `sendEvent:` brackets every dispatch with the flag. + * Must run after the CEF framework is loaded (it registers the protocols). + */ +export const installCefApplicationClass = (): void => { + const rt = cocoa(); + const objc = objcExtras(); + const superclass = rt.classes.get('NSApplication'); + const sendEventSelector = rt.selectors.get('sendEvent:'); + const objcSuper = Buffer.alloc(16); + retainForever(objcSuper); + const cls = defineObjcClass('BunmaskaCefApplication', 'NSApplication', [ + { + selector: 'isHandlingSendEvent', + typeEncoding: 'c@:', + args: [], + returns: 'bool', + impl: () => (handlingSendEvent ? 1 : 0), + }, + { + selector: 'setHandlingSendEvent:', + typeEncoding: 'v@:c', + args: ['bool'], + impl: (_self, _cmd, flag) => { + handlingSendEvent = flag !== 0n; + }, + }, + { + selector: 'sendEvent:', + typeEncoding: 'v@:@', + args: ['object'], + impl: (self, _cmd, event) => { + const previous = handlingSendEvent; + handlingSendEvent = true; + try { + objcSuper.writeBigUInt64LE(self, 0); + objcSuper.writeBigUInt64LE(superclass, 8); + objc.symbols.objc_msgSendSuper(ptr(objcSuper), sendEventSelector, event ?? 0n); + } finally { + handlingSendEvent = previous; + } + }, + }, + ]); + for (const name of ['CrAppProtocol', 'CrAppControlProtocol']) { + const protocol = objc.symbols.objc_getProtocol(cstr(name)); + if (protocol !== 0n) { + objc.symbols.class_addProtocol(cls, protocol); + } + } + rt.msgSend(cls, rt.selectors.get('sharedApplication')); +}; + +/** + * An unbundled process (`bun main.ts`) has no main bundle, and Chromium derives + * the Mach rendezvous service name from it in the parent AND (via + * `--main-bundle-path`) in every helper; without one they never meet. A packaged + * .app already is one. + */ +const mainBundlePath = (): string => { + if (process.execPath.includes('.app/Contents/MacOS/')) { + return ''; + } + const bundle = join(tmpdir(), 'bunmaska-cef', 'DevHost.app'); + mkdirSync(join(bundle, 'Contents'), { recursive: true }); + writeFileSync( + join(bundle, 'Contents', 'Info.plist'), + ` + + +CFBundleIdentifierorg.bunmaska.devhost +CFBundleNamebunmaska +CFBundlePackageTypeAPPL + +`, + ); + return bundle; +}; + +/** + * Browser-process switches asking Chrome's layer (which CEF always boots) to stay off + * the network on its own. + */ +const CHROMIUM_SWITCHES = [ + 'disable-background-networking', + 'disable-component-update', + 'disable-sync', + 'disable-default-apps', + 'disable-domain-reliability', + 'disable-client-side-phishing-detection', + 'no-first-run', + 'no-default-browser-check', + // Chromium keeps its cookie key in a Keychain item every CEF app shares ("Chromium + // Safe Storage"); another app's item makes ours prompt, and every HTTP load waits on it. + 'use-mock-keychain', +] as const; + +/** + * Chrome features that still call Google with the switches above (measured on CEF 154): + * the AI Mode eligibility check (www.google.com/async/folae), network time + * (clients2.google.com/time), the default search engine preconnect (www.google.com) and + * Autofill's form-signature queries (content-autofill.googleapis.com, on any page with a form). + */ +const DISABLED_FEATURES = [ + 'AimEnabled', + 'NetworkTimeServiceQuerying', + 'PreconnectToSearch', + 'AutofillServerCommunication', +]; + +/** A `cef_string_t*` for `value`; `keep` must outlive the call it is passed to. */ +const cefString = (value: string, keep: unknown[]): Pointer => { + const buf = Buffer.alloc(24); + writeCefString(buf, 0, value, keep); + keep.push(buf); + return ptr(buf); +}; + +const appendChromiumSwitches = (commandLine: number, userDataPath: string): void => { + const keep: unknown[] = []; + const call = (method: number, returns: FFIType, ...values: string[]): unknown => + callMethod( + commandLine, + method, + values.map(() => FFIType.ptr), + returns, + ...values.map((value) => cefString(value, keep)), + ); + const append = (name: string, value: string): void => { + call(COMMAND_LINE.appendSwitchWithValue, FFIType.void, name, value); + }; + for (const name of CHROMIUM_SWITCHES) { + call(COMMAND_LINE.appendSwitch, FFIType.void, name); + } + // CEF has already disabled features of its own here, and a second value replaces them. + const cefDisabled = toAddress(call(COMMAND_LINE.getSwitchValue, FFIType.ptr, 'disable-features')); + append( + 'disable-features', + [readCefString(cefDisabled), ...DISABLED_FEATURES].filter(Boolean).join(','), + ); + if (cefDisabled !== 0) { + cefLibrary().symbols.cef_string_userfree_utf16_free(cefDisabled as Pointer); + } + // The on-device AI model manifest registers with the component updater and downloads on + // every launch, --disable-component-update or not; an empty local override skips it. + const manifest = join(userDataPath, 'bunmaska-model-manifest.json'); + writeFileSync(manifest, '{}'); + append('optimization-guide-manifest-override', manifest); + // Chrome POSTs accounts.google.com/ListAccounts at every launch and no switch, feature or + // pref stops it (CEF issue #4276); an unresolvable URL fails it before any DNS or socket. + append('gaia-config-contents', '{"urls":{"list_accounts_url":{"url":"data:,"}}}'); +}; + +/** Set a Local State preference. UI thread, after the context is initialized. */ +const setGlobalPreference = (name: string, value: string): void => { + const lib = cefLibrary().symbols; + const keep: unknown[] = []; + const cefValue = toAddress(lib.cef_value_create()); + callMethod(cefValue, VALUE.setString, [FFIType.ptr], FFIType.i32, cefString(value, keep)); + const manager = toAddress(lib.cef_preference_manager_get_global()); + const error = Buffer.alloc(24); + // set_preference takes over our reference to the value. + callMethod( + manager, + PREFERENCE_MANAGER.setPreference, + [FFIType.ptr, FFIType.ptr, FFIType.ptr], + FFIType.i32, + cefString(name, keep), + cefValue, + ptr(error), + ); + release(manager); +}; + +export type CefInitOptions = { + /** The CEF engine's `lib/` (framework + helper apps). */ + readonly libDir: string; + /** The app's `userData`: Chromium's profile (cookies, storage, caches) lives here. */ + readonly userDataPath: string; +}; + +/** + * `cef_initialize` with the external message pump: CEF asks for work through + * the glue's scheduler, which wakes the adaptive pump that calls + * {@link doCefWork}. The UI thread is therefore the Bun main thread. + */ +export const initializeCef = (options: CefInitOptions): void => { + const lib = cefLibrary(); + const glue = cefGlue(); + lib.symbols.cef_api_hash(CEF_API_VERSION, 0); + + let contextInitialized = false; + const onContextInitialized = new JSCallback( + () => { + contextInitialized = true; + // Chrome's default "automatic" secure DNS upgrades lookups to the system resolver's + // DoH endpoint and probes it; plain system DNS like any other app instead. + setGlobalPreference('dns_over_https.mode', 'off'); + }, + { args: [FFIType.ptr], returns: FFIType.void }, + ); + retainForever(onContextInitialized); + const handler = allocImmortal(SIZE.browserProcessHandler); + glue.initBase(handler.at, SIZE.browserProcessHandler); + setPtr( + handler.buf, + BROWSER_PROCESS_HANDLER.onContextInitialized, + toAddress(onContextInitialized.ptr), + ); + setPtr(handler.buf, BROWSER_PROCESS_HANDLER.onScheduleMessagePumpWork, glue.scheduleFn()); + + const onCommandLine = new JSCallback( + (_self: unknown, processType: unknown, commandLine: unknown) => { + if (readCefString(toAddress(processType)) === '') { + appendChromiumSwitches(toAddress(commandLine), options.userDataPath); + } + release(toAddress(commandLine)); + }, + { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.void }, + ); + retainForever(onCommandLine); + const app = allocImmortal(SIZE.app + 8); + glue.initBase(app.at, SIZE.app); + setPtr(app.buf, APP.onBeforeCommandLineProcessing, toAddress(onCommandLine.ptr)); + setPtr(app.buf, APP.getBrowserProcessHandler, glue.slotGetter(0)); + setPtr(app.buf, SIZE.app, handler.at); + + const keep: unknown[] = []; + const argv0 = cstr('bunmaska'); + const argv = Buffer.alloc(8); + setPtr(argv, 0, ptr(argv0)); + const mainArgs = Buffer.alloc(SIZE.mainArgs); + mainArgs.writeInt32LE(1, 0); + setPtr(mainArgs, 8, ptr(argv)); + + mkdirSync(options.userDataPath, { recursive: true }); + const settings = Buffer.alloc(SIZE.settings); + setPtr(settings, 0, SIZE.settings); + settings.writeInt32LE(1, SETTINGS.noSandbox); + writeCefString(settings, SETTINGS.browserSubprocessPath, cefHelperPath(options.libDir), keep); + writeCefString(settings, SETTINGS.frameworkDirPath, cefFrameworkPath(options.libDir), keep); + writeCefString(settings, SETTINGS.mainBundlePath, mainBundlePath(), keep); + settings.writeInt32LE(1, SETTINGS.externalMessagePump); + writeCefString(settings, SETTINGS.rootCachePath, options.userDataPath, keep); + writeCefString(settings, SETTINGS.cachePath, options.userDataPath, keep); + settings.writeInt32LE(LOG_SEVERITY_ERROR, SETTINGS.logSeverity); + glue.pumpInit(); + const ok = lib.symbols.cef_initialize(ptr(mainArgs), ptr(settings), app.at, null); + if (ok !== 1 || !contextInitialized) { + throw new BunmaskaError( + `Blink engine: cef_initialize failed (result ${ok}); is another instance of this app running with the same userData?`, + { code: 'ERR_BLINK_INIT' }, + ); + } +}; + +/** Run the work CEF scheduled; called on every pump tick. */ +export const doCefWork = (): void => { + cefLibrary().symbols.cef_do_message_loop_work(); +}; + +/** Ask Chromium to write its cookie store to disk now (async, fire-and-forget). */ +export const flushCookies = (): void => { + const manager = toAddress(cefLibrary().symbols.cef_cookie_manager_get_global_manager(null)); + if (manager !== 0) { + callMethod(manager, COOKIE_MANAGER.flushStore, [FFIType.ptr], FFIType.i32, null); + release(manager); + } +}; + +/** + * A windowed Alloy-style browser as a child of `parentView` (an NSView), starting + * on about:blank so the DevTools session can be armed before the app's first load. + */ +export const createCefBrowser = (parentView: Handle, width: number, height: number): number => { + const keep: unknown[] = []; + const windowInfo = Buffer.alloc(SIZE.windowInfo); + setPtr(windowInfo, 0, SIZE.windowInfo); + windowInfo.writeInt32LE(width, WINDOW_INFO.bounds + 8); + windowInfo.writeInt32LE(height, WINDOW_INFO.bounds + 12); + setPtr(windowInfo, WINDOW_INFO.parentView, parentView); + windowInfo.writeInt32LE(RUNTIME_STYLE_ALLOY, WINDOW_INFO.runtimeStyle); + const browserSettings = Buffer.alloc(SIZE.browserSettings); + setPtr(browserSettings, 0, SIZE.browserSettings); + const url = Buffer.alloc(24); + writeCefString(url, 0, 'about:blank', keep); + const browser = toAddress( + cefLibrary().symbols.cef_browser_host_create_browser_sync( + ptr(windowInfo), + sharedClient(), + ptr(url), + ptr(browserSettings), + null, + null, + ), + ); + if (browser === 0) { + throw new BunmaskaError('Blink engine: CEF refused to create a browser', { + code: 'ERR_BLINK_BROWSER', + }); + } + return browser; +}; diff --git a/src/main/platform/cef/cef-web-contents.ts b/src/main/platform/cef/cef-web-contents.ts new file mode 100644 index 0000000..f6a06e3 --- /dev/null +++ b/src/main/platform/cef/cef-web-contents.ts @@ -0,0 +1,404 @@ +import { FFIType, ptr } from 'bun:ffi'; +import { createLogger } from '../../../common/logger'; +import type { + NativeInputEvent, + NativeNavigationEvent, + NativeWebContents, + NativeWindowOptions, +} from '../native'; +import { + dispatchScript, + IPC_HANDLER_NAME, + injectedScripts, + PRELOAD_WORLD_NAME, +} from '../web-scripts'; +import { + registerBrowser, + sharedClient, + sharedDevToolsObserver, + unregisterBrowser, +} from './cef-client'; +import { type CdpParams, CdpSession } from './cef-devtools'; +import { BROWSER, callMethod, HOST, release, SIZE, setPtr, toAddress } from './cef-ffi'; +import { toCdpInput } from './cef-input'; + +const log = createLogger('cef-web-contents'); + +const BINDING = '__bunmaskaPost'; +const ZOOM_STEP = 1.2; + +/** + * Chromium has no WKScriptMessageHandler: the isolated world gets a CDP binding instead, + * behind the `webkit.messageHandlers` shape the shared bootstrap captures, so it runs first. + */ +const BINDING_SHIM = `(function(){var g=globalThis;g.webkit={messageHandlers:{${IPC_HANDLER_NAME}:{postMessage:function(s){g.${BINDING}(s);}}}};})();`; + +/** One source per world. `dom-ready` comes from CDP, so the shared notifier finds no handler. */ +const documentSources = (options: NativeWindowOptions): { isolated: string; page: string } => { + const scripts = injectedScripts({ + preloadScript: options.preloadScript, + frame: options.frame, + domReadyWorld: 'page', + }); + return { + isolated: [BINDING_SHIM, ...scripts.isolated].join('\n;\n'), + page: scripts.page.join('\n;\n'), + }; +}; + +/** `data:` URL for {@link CefWebContents.loadHTML}; a base URL becomes a `` element. */ +export const htmlDataUrl = (html: string, baseUrl?: string): string => { + const base = + baseUrl !== undefined && baseUrl.length > 0 + ? `` + : ''; + return `data:text/html;charset=utf-8;base64,${Buffer.from(base + html).toString('base64')}`; +}; + +/** A Chromium page in a CEF browser, driven over the in-process DevTools protocol. */ +export class CefWebContents implements NativeWebContents { + readonly #browser: number; + readonly #host: number; + readonly #session: CdpSession; + readonly #ready: Promise; + readonly #closed: Promise; + readonly #registration: number; + readonly #queuedEnvelopes: string[] = []; + #mainFrameId = ''; + #mainIsolatedContext = 0; + #title = ''; + #url = ''; + #alive = true; + #closing = false; + #navigated = false; + #firstLoad = true; + #onEnvelope: ((json: string) => void) | undefined; + #onNavigation: ((event: NativeNavigationEvent) => void) | undefined; + #onWindowOpen: ((url: string) => void) | undefined; + + constructor(browser: number, options: NativeWindowOptions, onFirstLoad: () => void) { + this.#browser = browser; + this.#host = toAddress(callMethod(browser, BROWSER.getHost, [], FFIType.ptr)); + this.#session = new CdpSession((json) => { + const bytes = Buffer.from(json); + return ( + Number( + callMethod( + this.#host, + HOST.sendDevToolsMessage, + [FFIType.ptr, FFIType.u64], + FFIType.i32, + ptr(bytes), + bytes.length, + ), + ) === 1 + ); + }); + let resolveClosed: () => void = () => undefined; + this.#closed = new Promise((resolve) => { + resolveClosed = resolve; + }); + const id = Number(callMethod(browser, BROWSER.getIdentifier, [], FFIType.i32)); + registerBrowser(id, { + onLoadingStateChange: () => undefined, + onMainFrameLoadEnd: () => undefined, + onMainFrameLoadError: (code, text) => { + this.#emit({ type: 'did-fail-load', errorCode: code, errorDescription: text }); + }, + onTitleChange: (title) => { + this.#title = title; + }, + onBeforePopup: (url) => this.#onWindowOpen?.(url), + onDevToolsMessage: (text) => this.#session.receive(text), + onBeforeClose: () => { + this.#alive = false; + this.#session.close('the browser closed'); + unregisterBrowser(id); + release(this.#registration); + release(this.#host); + release(this.#browser); + resolveClosed(); + }, + }); + this.#registration = toAddress( + callMethod( + this.#host, + HOST.addDevToolsMessageObserver, + [FFIType.ptr], + FFIType.ptr, + sharedDevToolsObserver(), + ), + ); + this.#listen(onFirstLoad); + const sources = documentSources(options); + this.#ready = Promise.all([ + this.#session.call('Runtime.enable'), + this.#session.call('Page.enable'), + this.#session.call('Runtime.addBinding', { + name: BINDING, + executionContextName: PRELOAD_WORLD_NAME, + }), + this.#session.call('Page.addScriptToEvaluateOnNewDocument', { + source: sources.isolated, + worldName: PRELOAD_WORLD_NAME, + }), + this.#session.call('Page.addScriptToEvaluateOnNewDocument', { source: sources.page }), + this.#session.call('Page.getFrameTree').then((tree) => { + const frame = (tree['frameTree'] as { frame?: { id?: unknown } } | undefined)?.frame; + this.#mainFrameId = typeof frame?.id === 'string' ? frame.id : ''; + }), + ]).then(() => undefined); + this.#ready.catch((error: unknown) => log.error('DevTools setup failed', error)); + } + + /** Resolves once CEF destroyed the browser (after {@link close}). */ + get closed(): Promise { + return this.#closed; + } + + #listen(onFirstLoad: () => void): void { + const isMain = (params: CdpParams): boolean => params['frameId'] === this.#mainFrameId; + this.#session.on('Page.frameStartedLoading', (p) => { + if (isMain(p)) { + this.#emit({ type: 'did-start-loading' }); + } + }); + this.#session.on('Page.frameNavigated', (p) => { + const frame = p['frame'] as + | { parentId?: unknown; url?: unknown; urlFragment?: unknown } + | undefined; + if (frame !== undefined && frame.parentId === undefined) { + this.#url = `${String(frame.url ?? '')}${String(frame.urlFragment ?? '')}`; + this.#emit({ type: 'did-navigate' }); + } + }); + this.#session.on('Page.domContentEventFired', () => this.#emit({ type: 'dom-ready' })); + this.#session.on('Page.loadEventFired', () => { + this.#emit({ type: 'did-finish-load' }); + if (this.#navigated && this.#firstLoad) { + this.#firstLoad = false; + onFirstLoad(); + } + }); + this.#session.on('Page.frameStoppedLoading', (p) => { + if (isMain(p)) { + this.#emit({ type: 'did-stop-loading' }); + } + }); + this.#session.on('Runtime.executionContextCreated', (p) => { + const context = p['context'] as { id: number; name: string; auxData?: { frameId?: string } }; + if (context.name === PRELOAD_WORLD_NAME && context.auxData?.frameId === this.#mainFrameId) { + this.#mainIsolatedContext = context.id; + this.#flushEnvelopes(); + } + }); + this.#session.on('Runtime.executionContextDestroyed', (p) => { + if (p['executionContextId'] === this.#mainIsolatedContext) { + this.#mainIsolatedContext = 0; + } + }); + this.#session.on('Runtime.executionContextsCleared', () => { + this.#mainIsolatedContext = 0; + }); + // CDP injects into every frame, but the preload is main-frame only: iframes never reach IPC. + this.#session.on('Runtime.bindingCalled', (p) => { + const context = p['executionContextId']; + if (p['name'] === BINDING && context !== 0 && context === this.#mainIsolatedContext) { + this.#onEnvelope?.(String(p['payload'])); + } + }); + } + + /** Nothing before the app's first load (the internal about:blank) is reported. */ + #emit(event: NativeNavigationEvent): void { + if (this.#navigated) { + this.#onNavigation?.(event); + } + } + + #call(method: string, params: CdpParams = {}): Promise { + return this.#ready.then(() => this.#session.call(method, params)); + } + + #fireAndForget(method: string, params: CdpParams): void { + this.#call(method, params).catch((error: unknown) => log.warn(`${method} failed`, error)); + } + + #flushEnvelopes(): void { + while (this.#mainIsolatedContext !== 0 && this.#queuedEnvelopes.length > 0) { + const json = this.#queuedEnvelopes.shift() ?? ''; + this.#fireAndForget('Runtime.evaluate', { + expression: dispatchScript(json), + contextId: this.#mainIsolatedContext, + }); + } + } + + loadURL(url: string): void { + this.#navigated = true; + this.#fireAndForget('Page.navigate', { url }); + } + + loadHTML(html: string, baseUrl?: string): void { + this.loadURL(htmlDataUrl(html, baseUrl)); + } + + getURL(): string { + return this.#url; + } + + getTitle(): string { + return this.#title; + } + + #browserCall(offset: number): void { + if (this.#alive) { + callMethod(this.#browser, offset, [], FFIType.void); + } + } + + reload(): void { + this.#browserCall(BROWSER.reload); + } + + reloadIgnoringCache(): void { + this.#browserCall(BROWSER.reloadIgnoreCache); + } + + stop(): void { + this.#browserCall(BROWSER.stopLoad); + } + + goBack(): void { + this.#browserCall(BROWSER.goBack); + } + + goForward(): void { + this.#browserCall(BROWSER.goForward); + } + + canGoBack(): boolean { + return ( + this.#alive && Number(callMethod(this.#browser, BROWSER.canGoBack, [], FFIType.i32)) === 1 + ); + } + + canGoForward(): boolean { + return ( + this.#alive && Number(callMethod(this.#browser, BROWSER.canGoForward, [], FFIType.i32)) === 1 + ); + } + + async executeJavaScript(code: string): Promise { + if (this.#closing) { + throw new Error('executeJavaScript failed: web contents destroyed'); + } + let response: CdpParams; + try { + response = await this.#call('Runtime.evaluate', { + expression: code, + awaitPromise: true, + returnByValue: true, + userGesture: true, + }); + } catch (error) { + // As on WebKit: an exec cut off by the close must not become an unhandled rejection. + if (this.#closing) { + return undefined; + } + throw error; + } + const details = response['exceptionDetails'] as + | { text?: string; exception?: { description?: string } } + | undefined; + if (details !== undefined) { + throw new Error(details.exception?.description ?? details.text ?? 'executeJavaScript failed'); + } + return (response['result'] as { value?: unknown } | undefined)?.value; + } + + async printToPDF(): Promise { + const response = await this.#call('Page.printToPDF'); + return new Uint8Array(Buffer.from(String(response['data']), 'base64')); + } + + async capturePage(): Promise { + const response = await this.#call('Page.captureScreenshot', { format: 'png' }); + return new Uint8Array(Buffer.from(String(response['data']), 'base64')); + } + + openDevTools(): void { + if (!this.#alive) { + return; + } + const windowInfo = Buffer.alloc(SIZE.windowInfo); + setPtr(windowInfo, 0, SIZE.windowInfo); + const settings = Buffer.alloc(SIZE.browserSettings); + setPtr(settings, 0, SIZE.browserSettings); + callMethod( + this.#host, + HOST.showDevTools, + [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr], + FFIType.void, + ptr(windowInfo), + sharedClient(), + ptr(settings), + null, + ); + } + + closeDevTools(): void { + if (this.#alive) { + callMethod(this.#host, HOST.closeDevTools, [], FFIType.void); + } + } + + setZoomFactor(factor: number): void { + if (this.#alive && factor > 0) { + callMethod( + this.#host, + HOST.setZoomLevel, + [FFIType.f64], + FFIType.void, + Math.log(factor) / Math.log(ZOOM_STEP), + ); + } + } + + setUserAgent(userAgent: string): void { + this.#fireAndForget('Emulation.setUserAgentOverride', { userAgent }); + } + + sendInputEvent(event: NativeInputEvent): void { + const input = toCdpInput(event); + this.#fireAndForget(input.method, input.params); + } + + sendEnvelopeToRenderer(envelopeJson: string): void { + if (!this.#alive) { + return; + } + this.#queuedEnvelopes.push(envelopeJson); + this.#flushEnvelopes(); + } + + onRendererEnvelope(callback: (envelopeJson: string) => void): void { + this.#onEnvelope = callback; + } + + onNavigation(callback: (event: NativeNavigationEvent) => void): void { + this.#onNavigation = callback; + } + + setWindowOpenHandler(callback: (url: string) => void): void { + this.#onWindowOpen = callback; + } + + /** Force-close the browser (no unload handlers); {@link closed} settles after. */ + close(): void { + this.#closing = true; + if (this.#alive) { + callMethod(this.#host, HOST.closeBrowser, [FFIType.i32], FFIType.void, 1); + } + } +} diff --git a/src/main/platform/index.ts b/src/main/platform/index.ts index 7f83708..8fb3412 100644 --- a/src/main/platform/index.ts +++ b/src/main/platform/index.ts @@ -1,5 +1,7 @@ import { UnsupportedPlatformError } from '../../common/errors'; import { currentPlatform, type Platform } from '../../common/platform'; +import { type EngineResolution, prepareEngineForLoad, resolveEngine } from '../engine/resolve'; +import { createCefApplication } from './cef/cef-backend'; import { gdkNativeImageBackend } from './linux/gdk-native-image'; import { gdkScreenBackend } from './linux/gdk-screen'; import { linuxClipboardBackend } from './linux/gtk-clipboard'; @@ -32,7 +34,7 @@ import * as cocoaShell from './macos/cocoa-shell'; import { macosTrayBackend } from './macos/cocoa-tray'; import { clearStorageData as macosClearStorageData } from './macos/cocoa-website-data'; import type { NativeApplication } from './native'; -import type { PlatformServices } from './services'; +import type { PlatformServices, SessionBackend } from './services'; import { createWindowsApplication } from './windows/windows-backend'; import { windowsClipboardBackend } from './windows/windows-clipboard'; import { windowsDialogBackend } from './windows/windows-dialog'; @@ -49,9 +51,25 @@ import { windowsSessionBackend } from './windows/windows-session'; import { windowsShellBackend } from './windows/windows-shell'; import { windowsTrayBackend } from './windows/windows-tray'; -/** Every backend's FFI loaders are lazy, so importing another OS's backend opens no library. */ -export const createNativeApplication = (): NativeApplication => { +/** + * Every backend's FFI loaders are lazy, so importing another OS's backend opens no library. + * A pinned `cef` engine picks the Blink backend (D048); it exists on macOS only. + */ +export const createNativeApplication = ( + engine: EngineResolution = resolveEngine(), +): NativeApplication => { const platform = currentPlatform(); + if (platform === 'macos') { + prepareEngineForLoad(engine, (text) => process.stderr.write(text)); + } + if (engine.family === 'cef') { + if (platform !== 'macos' || engine.libDir === undefined) { + throw new UnsupportedPlatformError( + `The Blink engine ${engine.id ?? ''} runs on macOS only so far; unpin it on ${platform}.`, + ); + } + return createCefApplication(engine.libDir); + } switch (platform) { case 'macos': return createMacOSApplication(); @@ -147,6 +165,27 @@ const SERVICES: Record = { }, }; +const blinkGap = (what: string): Promise => + Promise.reject(new UnsupportedPlatformError(`${what} is not wired for the Blink engine yet`)); + +// ponytail: session acts on WKWebsiteDataStore, so Blink rejects; wire cef_cookie_manager + CDP Storage. +const BLINK_SESSION: SessionBackend = { + clearStorageData: () => blinkGap('session.clearStorageData'), + getCookies: () => blinkGap('session.cookies.get'), + setCookie: () => blinkGap('session.cookies.set'), + removeCookie: () => blinkGap('session.cookies.remove'), +}; + +/** macOS services under the Blink engine: only the ones that act on the web engine differ. */ +const BLINK_ON_MACOS: PlatformServices = { ...SERVICES.macos, session: BLINK_SESSION }; + +const currentServices = (): PlatformServices => { + const platform = currentPlatform(); + return platform === 'macos' && resolveEngine().family === 'cef' + ? BLINK_ON_MACOS + : SERVICES[platform]; +}; + /** The current OS's `key` service, resolved on every `get()`, with a test override. */ export const service = ( key: K, @@ -156,7 +195,7 @@ export const service = ( } => { let override: PlatformServices[K] | undefined; return { - get: () => override ?? SERVICES[currentPlatform()][key], + get: () => override ?? currentServices()[key], setForTesting: (fake) => { override = fake; }, diff --git a/src/main/platform/native.ts b/src/main/platform/native.ts index acc9cb9..5b9bfe5 100644 --- a/src/main/platform/native.ts +++ b/src/main/platform/native.ts @@ -113,7 +113,7 @@ export interface NativeWebContents { setUserAgent(userAgent: string): void; /** * Delivered through the engine's input path, so the page sees `isTrusted === true`, which a - * script-dispatched event cannot fake. Windows only; macOS and Linux throw. + * script-dispatched event cannot fake. Windows and Blink; WebKit on macOS and Linux throws. */ sendInputEvent(event: NativeInputEvent): void; /** Delivers a raw JSON envelope to the renderer's bridge. */ diff --git a/tests/unit/main/platform/cef/cef-devtools.test.ts b/tests/unit/main/platform/cef/cef-devtools.test.ts new file mode 100644 index 0000000..9343380 --- /dev/null +++ b/tests/unit/main/platform/cef/cef-devtools.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, test } from 'bun:test'; +import { CdpSession } from '../../../../../src/main/platform/cef/cef-devtools'; + +const session = (accept = true) => { + const sent: Array<{ id: number; method: string; params: unknown }> = []; + const cdp = new CdpSession((json) => { + sent.push(JSON.parse(json)); + return accept; + }); + return { cdp, sent }; +}; + +describe('CdpSession', () => { + test('resolves a call with the result of the matching response id', async () => { + const { cdp, sent } = session(); + const first = cdp.call('Runtime.evaluate', { expression: '1' }); + const second = cdp.call('Page.enable'); + cdp.receive(JSON.stringify({ id: sent[1]?.id, result: { second: true } })); + cdp.receive(JSON.stringify({ id: sent[0]?.id, result: { value: 1 } })); + expect(await first).toEqual({ value: 1 }); + expect(await second).toEqual({ second: true }); + expect(sent.map((m) => m.method)).toEqual(['Runtime.evaluate', 'Page.enable']); + }); + + test('rejects a call whose response carries a protocol error', async () => { + const { cdp, sent } = session(); + const call = cdp.call('Page.navigate', { url: 'x' }); + cdp.receive(JSON.stringify({ id: sent[0]?.id, error: { message: 'Invalid URL' } })); + await expect(call).rejects.toThrow('Invalid URL'); + }); + + test('rejects immediately when the channel refuses the message', async () => { + const { cdp } = session(false); + await expect(cdp.call('Page.enable')).rejects.toThrow('refused'); + }); + + test('delivers events to every listener of that method, in order', () => { + const { cdp } = session(); + const seen: string[] = []; + cdp.on('Runtime.bindingCalled', (p) => seen.push(`a:${String(p['payload'])}`)); + cdp.on('Runtime.bindingCalled', (p) => seen.push(`b:${String(p['payload'])}`)); + cdp.on('Page.loadEventFired', () => seen.push('load')); + cdp.receive(JSON.stringify({ method: 'Runtime.bindingCalled', params: { payload: 'x' } })); + expect(seen).toEqual(['a:x', 'b:x']); + }); + + test('drops malformed messages and responses nobody is waiting for', () => { + const { cdp } = session(); + expect(() => { + cdp.receive('not json'); + cdp.receive('null'); + cdp.receive(JSON.stringify({ id: 999, result: {} })); + }).not.toThrow(); + }); + + test('close rejects in-flight calls and refuses new ones', async () => { + const { cdp } = session(); + const inFlight = cdp.call('Runtime.evaluate'); + cdp.close('the browser closed'); + await expect(inFlight).rejects.toThrow('the browser closed'); + await expect(cdp.call('Page.enable')).rejects.toThrow('the browser closed'); + }); +}); diff --git a/tests/unit/main/platform/cef/cef-ffi.test.ts b/tests/unit/main/platform/cef/cef-ffi.test.ts new file mode 100644 index 0000000..918c0e8 --- /dev/null +++ b/tests/unit/main/platform/cef/cef-ffi.test.ts @@ -0,0 +1,19 @@ +import { ptr } from 'bun:ffi'; +import { describe, expect, test } from 'bun:test'; +import { readCefString, writeCefString } from '../../../../../src/main/platform/cef/cef-ffi'; + +describe('cef_string_t', () => { + test('a written string reads back, surrogate pairs included, with no destructor', () => { + const keep: unknown[] = []; + const struct = Buffer.alloc(24); + writeCefString(struct, 0, 'Blink 😀', keep); + expect(struct.readBigUInt64LE(8)).toBe(8n); + expect(struct.readBigUInt64LE(16)).toBe(0n); + expect(readCefString(Number(ptr(struct)))).toBe('Blink 😀'); + }); + + test('NULL and empty strings read as empty', () => { + expect(readCefString(0)).toBe(''); + expect(readCefString(Number(ptr(Buffer.alloc(24))))).toBe(''); + }); +}); diff --git a/tests/unit/main/platform/cef/cef-input.test.ts b/tests/unit/main/platform/cef/cef-input.test.ts new file mode 100644 index 0000000..c9aefdb --- /dev/null +++ b/tests/unit/main/platform/cef/cef-input.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, test } from 'bun:test'; +import { InvalidArgumentError } from '../../../../../src/common/errors'; +import { toCdpInput } from '../../../../../src/main/platform/cef/cef-input'; + +describe('toCdpInput', () => { + test('a mouse press is a single left-button click by default', () => { + expect(toCdpInput({ type: 'mouseDown', x: 3, y: 4 })).toEqual({ + method: 'Input.dispatchMouseEvent', + params: { type: 'mousePressed', x: 3, y: 4, button: 'left', clickCount: 1 }, + }); + }); + + test('a mouse move carries no button and no click', () => { + const input = toCdpInput({ type: 'mouseMove', x: 1, y: 2, button: 'right' }); + expect(input.params).toMatchObject({ type: 'mouseMoved', button: 'none', clickCount: 0 }); + }); + + test('keyDown is a raw key press that types nothing', () => { + expect(toCdpInput({ type: 'keyDown', keyCode: 'a' }).params).toEqual({ + type: 'rawKeyDown', + key: 'a', + windowsVirtualKeyCode: 65, + }); + }); + + test('char types the character, including control keys and astral symbols', () => { + expect(toCdpInput({ type: 'char', keyCode: 'Enter' }).params).toMatchObject({ + key: 'Enter', + text: '\r', + }); + expect(toCdpInput({ type: 'char', keyCode: 'Space' }).params).toMatchObject({ + key: ' ', + text: ' ', + }); + expect(toCdpInput({ type: 'char', keyCode: '😀' }).params).toMatchObject({ text: '😀' }); + expect(toCdpInput({ type: 'char', keyCode: 'Up' }).params).toMatchObject({ + key: 'ArrowUp', + text: '', + }); + }); + + test('an unknown named key is rejected, not silently dropped', () => { + expect(() => toCdpInput({ type: 'keyUp', keyCode: 'F99' })).toThrow(InvalidArgumentError); + }); +}); diff --git a/tests/unit/main/platform/cef/cef-web-contents.test.ts b/tests/unit/main/platform/cef/cef-web-contents.test.ts new file mode 100644 index 0000000..43797a2 --- /dev/null +++ b/tests/unit/main/platform/cef/cef-web-contents.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, test } from 'bun:test'; +import { htmlDataUrl } from '../../../../../src/main/platform/cef/cef-web-contents'; + +const decode = (url: string): string => + Buffer.from(url.slice(url.indexOf(',') + 1), 'base64').toString('utf8'); + +describe('htmlDataUrl', () => { + test('encodes the markup as a UTF-8 base64 data URL', () => { + const url = htmlDataUrl('

héllo

'); + expect(url.startsWith('data:text/html;charset=utf-8;base64,')).toBe(true); + expect(decode(url)).toBe('

héllo

'); + }); + + test('a base URL becomes an escaped element ahead of the markup', () => { + expect(decode(htmlDataUrl('

x

', 'file:///a "b"&c/'))).toBe( + '

x

', + ); + }); +}); diff --git a/tests/unit/main/platform/index.test.ts b/tests/unit/main/platform/index.test.ts index 504d0be..7fe8430 100644 --- a/tests/unit/main/platform/index.test.ts +++ b/tests/unit/main/platform/index.test.ts @@ -1,6 +1,15 @@ -import { afterEach, describe, expect, it } from 'bun:test'; +import { afterEach, describe, expect, it, test } from 'bun:test'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import { UnsupportedPlatformError } from '../../../../src/common/errors'; -import { createNativeApplication } from '../../../../src/main/platform/index'; +import { currentArch } from '../../../../src/common/platform'; +import { + type EngineResolution, + resetEnginePreparation, + resetEngineResolution, +} from '../../../../src/main/engine/resolve'; +import { createNativeApplication, service } from '../../../../src/main/platform/index'; /** * Dispatcher routing tests. @@ -54,3 +63,56 @@ describe('createNativeApplication dispatcher', () => { expect(() => createNativeApplication()).toThrow(UnsupportedPlatformError); }); }); + +const ENGINE_ENV = ['BUNMASKA_ENGINES_PATH', 'BUNMASKA_ENGINE_ID'] as const; + +describe('the Blink (cef) engine pin', () => { + const cefPin: EngineResolution = { + mode: 'pinned', + family: 'cef', + libDir: '/store/cef-154.0.28-154.0.8037.58-bunmaska1-macos-arm64/lib', + warnings: [], + }; + + afterEach(() => { + resetEnginePreparation(); + }); + + test('picks the Blink backend on macOS without loading the engine', () => { + setPlatform('darwin'); + const app = createNativeApplication(cefPin); + expect(typeof app.setUserDataPath).toBe('function'); + }); + + test('fails loudly off macOS instead of loading it', () => { + setPlatform('linux'); + expect(() => createNativeApplication(cefPin)).toThrow(UnsupportedPlatformError); + }); + + test('session rejects on macOS rather than acting on the WebKit store', async () => { + const root = mkdtempSync(join(tmpdir(), 'bunmaska-blink-')); + const id = `cef-154.0.28-154.0.8037.58-bunmaska1-macos-${currentArch()}`; + mkdirSync(join(root, id), { recursive: true }); + writeFileSync(join(root, id, 'INSTALLATION_COMPLETE'), ''); + const saved = new Map(ENGINE_ENV.map((key) => [key, process.env[key]])); + process.env['BUNMASKA_ENGINES_PATH'] = root; + process.env['BUNMASKA_ENGINE_ID'] = id; + setPlatform('darwin'); + resetEngineResolution(); + try { + await expect(service('session').get().getCookies({})).rejects.toThrow( + 'not wired for the Blink engine', + ); + } finally { + for (const [key, value] of saved) { + if (value === undefined) { + delete process.env[key]; + } else { + process.env[key] = value; + } + } + resetEngineResolution(); + rmSync(root, { recursive: true, force: true }); + } + }); +}); From 9840a078575c77e18134f1a9796c010b8e6f523b Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 14:03:50 -0700 Subject: [PATCH 06/15] build: add the CEF engine builder and its generic helper --- .../tools/engine/build-cef-engine.test.ts | 56 ++++++ tools/engine/build-cef-engine.ts | 178 ++++++++++++++++++ tools/engine/cef-helper.c | 62 ++++++ 3 files changed, 296 insertions(+) create mode 100644 tests/unit/tools/engine/build-cef-engine.test.ts create mode 100644 tools/engine/build-cef-engine.ts create mode 100644 tools/engine/cef-helper.c diff --git a/tests/unit/tools/engine/build-cef-engine.test.ts b/tests/unit/tools/engine/build-cef-engine.test.ts new file mode 100644 index 0000000..533f057 --- /dev/null +++ b/tests/unit/tools/engine/build-cef-engine.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, test } from 'bun:test'; +import { cefEngineId, pickCefBuild } from '../../../../tools/engine/build-cef-engine'; + +const version = (cef: string, chromium: string, channel: string) => ({ + cef_version: `${cef}+gabc+chromium-${chromium}`, + chromium_version: chromium, + channel, + files: [ + { type: 'standard', name: `std-${cef}`, sha1: 'aaa' }, + { type: 'minimal', name: `min-${cef}`, sha1: `sha-${cef}` }, + ], +}); + +const index = { + macosarm64: { + versions: [ + version('155.0.1', '155.0.1.1', 'beta'), + version('154.0.28', '154.0.8037.58', 'stable'), + version('153.0.9', '153.0.1.9', 'stable'), + ], + }, +}; + +describe('pickCefBuild', () => { + test('takes the newest stable minimal build by default', () => { + expect(pickCefBuild(index, 'macosarm64')).toEqual({ + cefVersion: '154.0.28+gabc+chromium-154.0.8037.58', + chromiumVersion: '154.0.8037.58', + file: 'min-154.0.28', + sha1: 'sha-154.0.28', + }); + }); + + test('a wanted CEF version matches on the full version, not a prefix of it', () => { + expect(pickCefBuild(index, 'macosarm64', '153.0.9').file).toBe('min-153.0.9'); + expect(() => pickCefBuild(index, 'macosarm64', '153.0')).toThrow('no CEF minimal build'); + }); + + test('an unknown platform fails loudly', () => { + expect(() => pickCefBuild(index, 'linux64')).toThrow('no CEF minimal build for linux64'); + }); +}); + +describe('cefEngineId', () => { + test('drops the CEF build hash and keeps the Chromium version as upstream', () => { + const build = pickCefBuild(index, 'macosarm64'); + expect(cefEngineId(build, 'macos', 'arm64')).toBe( + 'cef-154.0.28-154.0.8037.58-bunmaska1-macos-arm64', + ); + }); + + test('refuses an index entry that would mint a malformed id', () => { + const build = { ...pickCefBuild(index, 'macosarm64'), chromiumVersion: '154-beta' }; + expect(() => cefEngineId(build, 'macos', 'arm64')).toThrow('engine-id'); + }); +}); diff --git a/tools/engine/build-cef-engine.ts b/tools/engine/build-cef-engine.ts new file mode 100644 index 0000000..f381c14 --- /dev/null +++ b/tools/engine/build-cef-engine.ts @@ -0,0 +1,178 @@ +/** + * Build a store-shaped Blink engine (lib/ + engine.json) from an official CEF + * "minimal" distribution, verified against the SHA-1 in the CEF build index: + * + * bun tools/engine/build-cef-engine.ts [cefVersion] + * + * then `bunmaska engine install /`. macOS only so far; the helper + * is compiled with the host clang. + */ +import { createHash } from 'node:crypto'; +import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { parseEngineId } from '../../src/common/engine-id'; +import { currentArch, currentPlatform } from '../../src/common/platform'; +import { CEF_API_VERSION } from '../../src/main/platform/cef/cef-ffi'; + +const INDEX_URL = 'https://cef-builds.spotifycdn.com/index.json'; +const HELPER_VARIANTS = ['', ' (Renderer)', ' (GPU)', ' (Plugin)', ' (Alerts)'] as const; + +export type CefBuild = { + readonly cefVersion: string; + readonly chromiumVersion: string; + readonly file: string; + readonly sha1: string; +}; + +type IndexFile = { type?: unknown; name?: unknown; sha1?: unknown }; +type IndexVersion = { + cef_version?: unknown; + chromium_version?: unknown; + channel?: unknown; + files?: IndexFile[]; +}; + +/** The newest stable minimal build for `platformKey`, or the one whose CEF version starts with `wanted`. */ +export const pickCefBuild = (index: unknown, platformKey: string, wanted?: string): CefBuild => { + const versions = ((index as Record)[ + platformKey + ]?.versions ?? []) as IndexVersion[]; + for (const v of versions) { + const cef = String(v.cef_version ?? ''); + const matches = wanted === undefined ? v.channel === 'stable' : cef.startsWith(`${wanted}+`); + const minimal = v.files?.find((f) => f.type === 'minimal'); + if (matches && minimal !== undefined) { + return { + cefVersion: cef, + chromiumVersion: String(v.chromium_version ?? ''), + file: String(minimal.name), + sha1: String(minimal.sha1), + }; + } + } + throw new Error(`no CEF minimal build for ${platformKey}${wanted ? ` ${wanted}` : ''}`); +}; + +/** `154.0.28+g564dd6c+chromium-154.0.8037.58` -> `cef-154.0.28-154.0.8037.58-bunmaska1-macos-arm64`. */ +export const cefEngineId = ( + build: CefBuild, + os: 'macos' | 'linux' | 'windows', + arch: 'x64' | 'arm64', +): string => { + const id = `cef-${build.cefVersion.split('+')[0]}-${build.chromiumVersion}-bunmaska1-${os}-${arch}`; + parseEngineId(id); + return id; +}; + +const run = (cmd: string[]): void => { + const proc = Bun.spawnSync(cmd, { stdout: 'inherit', stderr: 'inherit' }); + if (proc.exitCode !== 0) { + throw new Error(`${cmd[0]} exited ${proc.exitCode}`); + } +}; + +const helperPlist = (name: string): string => ` + + +CFBundleExecutable${name} +CFBundleIdentifierorg.bunmaska.engine.helper +CFBundleName${name} +CFBundlePackageTypeAPPL +LSUIElement1 + +`; + +const main = async (): Promise => { + const [outDir, wanted] = process.argv.slice(2); + if (outDir === undefined) { + process.stderr.write('usage: bun tools/engine/build-cef-engine.ts [cefVersion]\n'); + process.exit(2); + } + if (currentPlatform() !== 'macos') { + throw new Error('build-cef-engine: only macOS engines are wired so far'); + } + const arch = currentArch(); + const index: unknown = await (await fetch(INDEX_URL)).json(); + const build = pickCefBuild(index, arch === 'arm64' ? 'macosarm64' : 'macosx64', wanted); + const id = cefEngineId(build, 'macos', arch); + const cache = join(outDir, '.cache'); + mkdirSync(cache, { recursive: true }); + + const archive = join(cache, build.file); + if (!existsSync(archive)) { + process.stdout.write(`downloading ${build.file}\n`); + const response = await fetch( + `https://cef-builds.spotifycdn.com/${encodeURIComponent(build.file)}`, + ); + if (!response.ok) { + throw new Error(`download failed: HTTP ${response.status}`); + } + writeFileSync(archive, new Uint8Array(await response.arrayBuffer())); + } + const sha1 = createHash('sha1').update(readFileSync(archive)).digest('hex'); + if (sha1 !== build.sha1) { + rmSync(archive); + throw new Error(`sha1 mismatch for ${build.file}: got ${sha1}, index says ${build.sha1}`); + } + + const extracted = join(cache, `extract-${build.cefVersion.split('+')[0]}`); + rmSync(extracted, { recursive: true, force: true }); + mkdirSync(extracted, { recursive: true }); + run(['tar', '-xjf', archive, '-C', extracted, '--strip-components=1']); + + const engine = join(outDir, id); + const lib = join(engine, 'lib'); + rmSync(engine, { recursive: true, force: true }); + mkdirSync(lib, { recursive: true }); + run([ + 'ditto', + join(extracted, 'Release', 'Chromium Embedded Framework.framework'), + join(lib, 'Chromium Embedded Framework.framework'), + ]); + + const helperBinary = join(cache, 'bunmaska-helper'); + run([ + 'clang', + '-std=c17', + '-pedantic', + '-O2', + '-Wall', + '-Wextra', + '-Werror', + `-DBM_CEF_API_VERSION=${CEF_API_VERSION}`, + '-o', + helperBinary, + join(import.meta.dir, 'cef-helper.c'), + ]); + for (const variant of HELPER_VARIANTS) { + const name = `bunmaska Helper${variant}`; + const contents = join(lib, `${name}.app`, 'Contents'); + mkdirSync(join(contents, 'MacOS'), { recursive: true }); + cpSync(helperBinary, join(contents, 'MacOS', name)); + writeFileSync(join(contents, 'Info.plist'), helperPlist(name)); + } + + cpSync(join(extracted, 'LICENSE.txt'), join(engine, 'LICENSE.txt')); + cpSync(join(extracted, 'CREDITS.html'), join(engine, 'CREDITS.html')); + writeFileSync( + join(engine, 'engine.json'), + `${JSON.stringify( + { + id, + soname: 'Chromium Embedded Framework.framework/Chromium Embedded Framework', + cef: build.cefVersion, + chromium: build.chromiumVersion, + source: build.file, + sha1: build.sha1, + }, + null, + 2, + )}\n`, + ); + rmSync(extracted, { recursive: true, force: true }); + process.stdout.write(`built ${engine}\ninstall with: bunmaska engine install ${engine}\n`); +}; + +if (import.meta.main) { + await main(); +} diff --git a/tools/engine/cef-helper.c b/tools/engine/cef-helper.c new file mode 100644 index 0000000..eee8efe --- /dev/null +++ b/tools/engine/cef-helper.c @@ -0,0 +1,62 @@ +/* The generic CEF subprocess (renderer, GPU, utility) shipped inside a Blink + * engine. It loads the framework next to its own .app and hands the process to + * CEF; every app on the machine shares it. Build: see build-cef-engine.ts. */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef BM_CEF_API_VERSION +#error "build with -DBM_CEF_API_VERSION=" +#endif + +typedef struct { + int argc; + char** argv; +} cef_main_args_t; +typedef const char* (*api_hash_fn)(int, int); +typedef int (*execute_fn)(const cef_main_args_t*, void*, void*); + +/* A child can outlive a SIGKILLed app while holding its stdio; exit with the parent pid. */ +static void* exit_with_parent(void* arg) { + pid_t parent = (pid_t)(intptr_t)arg; + int kq = kqueue(); + struct kevent change; + EV_SET(&change, parent, EVFILT_PROC, EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, NULL); + struct kevent event; + if (kq >= 0 && kevent(kq, &change, 1, &event, 1, NULL) > 0) _exit(0); + return NULL; +} + +/* / Helper.app/Contents/MacOS/: four levels up is . */ +int main(int argc, char** argv) { + pthread_t watcher; + if (pthread_create(&watcher, NULL, exit_with_parent, (void*)(intptr_t)getppid()) == 0) { + pthread_detach(watcher); + } + char exe[PATH_MAX], lib[PATH_MAX], path[PATH_MAX * 2]; + uint32_t size = sizeof exe; + if (_NSGetExecutablePath(exe, &size) != 0 || realpath(exe, lib) == NULL) return 70; + for (int i = 0; i < 4; i++) { + char* slash = strrchr(lib, '/'); + if (slash == NULL) return 71; + *slash = '\0'; + } + snprintf(path, sizeof path, "%s/Chromium Embedded Framework.framework/Chromium Embedded Framework", lib); + void* handle = dlopen(path, RTLD_LAZY | RTLD_LOCAL | RTLD_FIRST); + if (handle == NULL) { + fprintf(stderr, "bunmaska helper: %s\n", dlerror()); + return 72; + } + api_hash_fn api_hash = (api_hash_fn)dlsym(handle, "cef_api_hash"); + execute_fn execute = (execute_fn)dlsym(handle, "cef_execute_process"); + if (api_hash == NULL || execute == NULL) return 73; + api_hash(BM_CEF_API_VERSION, 0); + cef_main_args_t args = {argc, argv}; + return execute(&args, NULL, NULL); +} From eca016090673cad23f97816fd2fe2d639af75683 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 14:34:32 -0700 Subject: [PATCH 07/15] fix: keep the Blink profile out of userData's single-instance lock --- src/main/platform/cef/cef-runtime.ts | 22 +++++++++++++------ .../main/platform/cef/cef-runtime.test.ts | 11 ++++++++++ 2 files changed, 26 insertions(+), 7 deletions(-) create mode 100644 tests/unit/main/platform/cef/cef-runtime.test.ts diff --git a/src/main/platform/cef/cef-runtime.ts b/src/main/platform/cef/cef-runtime.ts index 538a5d9..e465186 100644 --- a/src/main/platform/cef/cef-runtime.ts +++ b/src/main/platform/cef/cef-runtime.ts @@ -172,7 +172,7 @@ const cefString = (value: string, keep: unknown[]): Pointer => { return ptr(buf); }; -const appendChromiumSwitches = (commandLine: number, userDataPath: string): void => { +const appendChromiumSwitches = (commandLine: number, profile: string): void => { const keep: unknown[] = []; const call = (method: number, returns: FFIType, ...values: string[]): unknown => callMethod( @@ -199,7 +199,7 @@ const appendChromiumSwitches = (commandLine: number, userDataPath: string): void } // The on-device AI model manifest registers with the component updater and downloads on // every launch, --disable-component-update or not; an empty local override skips it. - const manifest = join(userDataPath, 'bunmaska-model-manifest.json'); + const manifest = join(profile, 'bunmaska-model-manifest.json'); writeFileSync(manifest, '{}'); append('optimization-guide-manifest-override', manifest); // Chrome POSTs accounts.google.com/ListAccounts at every launch and no switch, feature or @@ -231,10 +231,17 @@ const setGlobalPreference = (name: string, value: string): void => { export type CefInitOptions = { /** The CEF engine's `lib/` (framework + helper apps). */ readonly libDir: string; - /** The app's `userData`: Chromium's profile (cookies, storage, caches) lives here. */ + /** The app's `userData`; Chromium's profile lives in {@link cefProfilePath} inside it. */ readonly userDataPath: string; }; +/** + * Chromium's profile dir, never `userData` itself: its process-singleton files are named + * SingletonLock/SingletonSocket, like requestSingleInstanceLock's, and sharing the names + * stalls cef_initialize ~20s on our socket, then Chromium takes over our lock. + */ +export const cefProfilePath = (userDataPath: string): string => join(userDataPath, 'Blink'); + /** * `cef_initialize` with the external message pump: CEF asks for work through * the glue's scheduler, which wakes the adaptive pump that calls @@ -243,6 +250,7 @@ export type CefInitOptions = { export const initializeCef = (options: CefInitOptions): void => { const lib = cefLibrary(); const glue = cefGlue(); + const profile = cefProfilePath(options.userDataPath); lib.symbols.cef_api_hash(CEF_API_VERSION, 0); let contextInitialized = false; @@ -268,7 +276,7 @@ export const initializeCef = (options: CefInitOptions): void => { const onCommandLine = new JSCallback( (_self: unknown, processType: unknown, commandLine: unknown) => { if (readCefString(toAddress(processType)) === '') { - appendChromiumSwitches(toAddress(commandLine), options.userDataPath); + appendChromiumSwitches(toAddress(commandLine), profile); } release(toAddress(commandLine)); }, @@ -289,7 +297,7 @@ export const initializeCef = (options: CefInitOptions): void => { mainArgs.writeInt32LE(1, 0); setPtr(mainArgs, 8, ptr(argv)); - mkdirSync(options.userDataPath, { recursive: true }); + mkdirSync(profile, { recursive: true }); const settings = Buffer.alloc(SIZE.settings); setPtr(settings, 0, SIZE.settings); settings.writeInt32LE(1, SETTINGS.noSandbox); @@ -297,8 +305,8 @@ export const initializeCef = (options: CefInitOptions): void => { writeCefString(settings, SETTINGS.frameworkDirPath, cefFrameworkPath(options.libDir), keep); writeCefString(settings, SETTINGS.mainBundlePath, mainBundlePath(), keep); settings.writeInt32LE(1, SETTINGS.externalMessagePump); - writeCefString(settings, SETTINGS.rootCachePath, options.userDataPath, keep); - writeCefString(settings, SETTINGS.cachePath, options.userDataPath, keep); + writeCefString(settings, SETTINGS.rootCachePath, profile, keep); + writeCefString(settings, SETTINGS.cachePath, profile, keep); settings.writeInt32LE(LOG_SEVERITY_ERROR, SETTINGS.logSeverity); glue.pumpInit(); const ok = lib.symbols.cef_initialize(ptr(mainArgs), ptr(settings), app.at, null); diff --git a/tests/unit/main/platform/cef/cef-runtime.test.ts b/tests/unit/main/platform/cef/cef-runtime.test.ts new file mode 100644 index 0000000..f0852b5 --- /dev/null +++ b/tests/unit/main/platform/cef/cef-runtime.test.ts @@ -0,0 +1,11 @@ +import { describe, expect, test } from 'bun:test'; +import { dirname, join } from 'node:path'; +import { cefProfilePath } from '../../../../../src/main/platform/cef/cef-runtime'; + +describe('cefProfilePath', () => { + test("is not userData, where requestSingleInstanceLock keeps Chromium's lock file names", () => { + const userData = join('/Users', 'me', 'Library', 'Application Support', 'Demo'); + expect(cefProfilePath(userData)).not.toBe(userData); + expect(dirname(cefProfilePath(userData))).toBe(userData); + }); +}); From 06e02c63776b250f43d83b27632738498de9f766 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 14:43:53 -0700 Subject: [PATCH 08/15] fix: stop a Blink relaunch from opening a Chrome browser window --- src/main/platform/cef/cef-ffi.ts | 6 +++++- src/main/platform/cef/cef-runtime.ts | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/main/platform/cef/cef-ffi.ts b/src/main/platform/cef/cef-ffi.ts index 81defd4..e1f7f63 100644 --- a/src/main/platform/cef/cef-ffi.ts +++ b/src/main/platform/cef/cef-ffi.ts @@ -47,7 +47,11 @@ export const COMMAND_LINE = { appendSwitch: 152, appendSwitchWithValue: 160, } as const; -export const BROWSER_PROCESS_HANDLER = { onContextInitialized: 48, onScheduleMessagePumpWork: 72 }; +export const BROWSER_PROCESS_HANDLER = { + onContextInitialized: 48, + onAlreadyRunningAppRelaunch: 64, + onScheduleMessagePumpWork: 72, +}; export const CLIENT = { getDisplayHandler: 72, getLifeSpanHandler: 144, getLoadHandler: 152 }; export const LIFE_SPAN = { onBeforePopup: 40, onAfterCreated: 64, doClose: 72, onBeforeClose: 80 }; export const LOAD = { onLoadingStateChange: 40, onLoadEnd: 56, onLoadError: 64 } as const; diff --git a/src/main/platform/cef/cef-runtime.ts b/src/main/platform/cef/cef-runtime.ts index e465186..92a61c3 100644 --- a/src/main/platform/cef/cef-runtime.ts +++ b/src/main/platform/cef/cef-runtime.ts @@ -272,6 +272,21 @@ export const initializeCef = (options: CefInitOptions): void => { toAddress(onContextInitialized.ptr), ); setPtr(handler.buf, BROWSER_PROCESS_HANDLER.onScheduleMessagePumpWork, glue.scheduleFn()); + // Another process launched on this profile: unhandled (0 or NULL), Chrome opens its own + // tabbed browser window here, outside every bunmaska policy. UI thread. + const onRelaunch = new JSCallback( + (_self: unknown, commandLine: unknown) => { + release(toAddress(commandLine)); + return 1; + }, + { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.i32 }, + ); + retainForever(onRelaunch); + setPtr( + handler.buf, + BROWSER_PROCESS_HANDLER.onAlreadyRunningAppRelaunch, + toAddress(onRelaunch.ptr), + ); const onCommandLine = new JSCallback( (_self: unknown, processType: unknown, commandLine: unknown) => { From 3aaa03d1c01f04604ea1ffbd047352a449681273 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 14:35:13 -0700 Subject: [PATCH 09/15] fix: swap an early plain NSApp to the Blink application class --- src/main/platform/cef/cef-runtime.ts | 14 +++++++--- .../macos/cef-application-class.test.ts | 28 +++++++++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) create mode 100644 tests/integration/macos/cef-application-class.test.ts diff --git a/src/main/platform/cef/cef-runtime.ts b/src/main/platform/cef/cef-runtime.ts index 92a61c3..c66d1ec 100644 --- a/src/main/platform/cef/cef-runtime.ts +++ b/src/main/platform/cef/cef-runtime.ts @@ -47,6 +47,8 @@ const objcExtras = macOSLibraryAccessor('objc super + protocols', () => objc_msgSendSuper: { args: [FFIType.ptr, FFIType.u64, FFIType.u64], returns: FFIType.void }, objc_getProtocol: { args: [FFIType.cstring], returns: FFIType.u64 }, class_addProtocol: { args: [FFIType.u64, FFIType.u64], returns: FFIType.u8 }, + object_getClass: { args: [FFIType.u64], returns: FFIType.u64 }, + object_setClass: { args: [FFIType.u64, FFIType.u64], returns: FFIType.u64 }, }), ); @@ -54,9 +56,8 @@ let handlingSendEvent = false; /** * Chromium requires NSApp to be an NSApplication subclass answering - * `isHandlingSendEvent` (CrAppControlProtocol), created before anything calls - * `+sharedApplication`; `sendEvent:` brackets every dispatch with the flag. - * Must run after the CEF framework is loaded (it registers the protocols). + * `isHandlingSendEvent` (CrAppControlProtocol); `sendEvent:` brackets every dispatch + * with the flag. Must run after the CEF framework is loaded (it registers the protocols). */ export const installCefApplicationClass = (): void => { const rt = cocoa(); @@ -104,7 +105,12 @@ export const installCefApplicationClass = (): void => { objc.symbols.class_addProtocol(cls, protocol); } } - rt.msgSend(cls, rt.selectors.get('sharedApplication')); + const app = rt.msgSend(cls, rt.selectors.get('sharedApplication')); + // An AppKit call before ready (nativeTheme.themeSource, Menu.setApplicationMenu) already + // made a plain NSApp, which Chromium aborts on; the subclass adds no ivars, so swap in place. + if (objc.symbols.object_getClass(app) === superclass) { + objc.symbols.object_setClass(app, cls); + } }; /** diff --git a/tests/integration/macos/cef-application-class.test.ts b/tests/integration/macos/cef-application-class.test.ts new file mode 100644 index 0000000..0bd4380 --- /dev/null +++ b/tests/integration/macos/cef-application-class.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, test } from 'bun:test'; +import { join } from 'node:path'; +import { currentPlatform } from '../../../src/common/platform'; + +const PLATFORM = join(import.meta.dir, '../../../src/main/platform'); + +if (currentPlatform() === 'macos') { + describe('installCefApplicationClass', () => { + test('turns an NSApp an early AppKit call already made into the CEF subclass', () => { + // A fresh process: this suite already has a plain NSApp, and the swap must not leak into it. + const script = `import { dlopen } from 'bun:ffi'; +import { cocoa } from ${JSON.stringify(`${PLATFORM}/macos/cocoa-runtime.ts`)}; +import { installCefApplicationClass } from ${JSON.stringify(`${PLATFORM}/cef/cef-runtime.ts`)}; +const rt = cocoa(); +const nsApp = () => rt.msgSend(rt.classes.get('NSApplication'), rt.selectors.get('sharedApplication')); +nsApp(); +installCefApplicationClass(); +const objc = dlopen('libobjc.A.dylib', { object_getClassName: { args: ['u64'], returns: 'cstring' } }); +console.log(objc.symbols.object_getClassName(nsApp()));`; + const proc = Bun.spawnSync([process.execPath, '-e', script], { + stdout: 'pipe', + stderr: 'pipe', + }); + expect(proc.stderr.toString()).toBe(''); + expect(proc.stdout.toString().trim()).toBe('BunmaskaCefApplication'); + }); + }); +} From ccd7e62ea0607ca1427645ed0165119f91dfdb61 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 14:35:38 -0700 Subject: [PATCH 10/15] fix: rethrow a failed Blink start instead of never firing ready --- src/main/platform/cef/cef-backend.ts | 18 ++++++++++--- .../main/platform/cef/cef-backend.test.ts | 26 +++++++++++++++++++ 2 files changed, 40 insertions(+), 4 deletions(-) create mode 100644 tests/unit/main/platform/cef/cef-backend.test.ts diff --git a/src/main/platform/cef/cef-backend.ts b/src/main/platform/cef/cef-backend.ts index 1658e8c..5d4ef10 100644 --- a/src/main/platform/cef/cef-backend.ts +++ b/src/main/platform/cef/cef-backend.ts @@ -36,6 +36,7 @@ class CefApplication implements NativeApplication { #userDataPath = join(homedir(), '.bunmaska', 'blink-profile'); #cefRunning = false; #started = false; + #startError: unknown; readonly appKit?: NativeAppKit; constructor(libDir: string) { @@ -54,15 +55,24 @@ class CefApplication implements NativeApplication { this.#userDataPath = path; } + /** A failed start rethrows its error forever: cef_initialize cannot run twice in a process. */ start(): void { + if (this.#startError !== undefined) { + throw this.#startError; + } if (this.#started) { return; } this.#started = true; - loadCef(cefLibraryPath(this.#libDir)); - installCefApplicationClass(); - this.#host.start(); - initializeCef({ libDir: this.#libDir, userDataPath: this.#userDataPath }); + try { + loadCef(cefLibraryPath(this.#libDir)); + installCefApplicationClass(); + this.#host.start(); + initializeCef({ libDir: this.#libDir, userDataPath: this.#userDataPath }); + } catch (error) { + this.#startError = error; + throw error; + } this.#cefRunning = true; const callbacks = this.#readyCallbacks; this.#readyCallbacks = []; diff --git a/tests/unit/main/platform/cef/cef-backend.test.ts b/tests/unit/main/platform/cef/cef-backend.test.ts new file mode 100644 index 0000000..fc45f52 --- /dev/null +++ b/tests/unit/main/platform/cef/cef-backend.test.ts @@ -0,0 +1,26 @@ +import { afterEach, describe, expect, test } from 'bun:test'; +import { createCefApplication } from '../../../../../src/main/platform/cef/cef-backend'; + +const original = Object.getOwnPropertyDescriptor(process, 'platform'); + +afterEach(() => { + if (original) { + Object.defineProperty(process, 'platform', original); + } +}); + +describe('CefApplication.start', () => { + test('a failed start fails every later start the same way instead of passing silently', () => { + // Constructing the backend opens nothing; start() then fails at the missing framework. + Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }); + const app = createCefApplication('/nonexistent-bunmaska-cef-engine/lib'); + let first: unknown; + try { + app.start(); + } catch (error) { + first = error; + } + expect(first).toBeDefined(); + expect(() => app.start()).toThrow(first as Error); + }); +}); From 594eb95f6518816c9be755790ede2dbaf47f4608 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 14:36:23 -0700 Subject: [PATCH 11/15] fix: refuse a CEF build that lacks the pinned API version --- src/main/platform/cef/cef-runtime.ts | 8 ++++++- .../tools/engine/build-cef-engine.test.ts | 15 ++++++++---- tools/engine/build-cef-engine.ts | 24 +++++++++++++++---- tools/engine/cef-helper.c | 2 +- 4 files changed, 38 insertions(+), 11 deletions(-) diff --git a/src/main/platform/cef/cef-runtime.ts b/src/main/platform/cef/cef-runtime.ts index c66d1ec..b2ecf0a 100644 --- a/src/main/platform/cef/cef-runtime.ts +++ b/src/main/platform/cef/cef-runtime.ts @@ -257,7 +257,13 @@ export const initializeCef = (options: CefInitOptions): void => { const lib = cefLibrary(); const glue = cefGlue(); const profile = cefProfilePath(options.userDataPath); - lib.symbols.cef_api_hash(CEF_API_VERSION, 0); + // NULL = this CEF build lacks the API version; every CEF call after it is a FATAL abort. + if (toAddress(lib.symbols.cef_api_hash(CEF_API_VERSION, 0)) === 0) { + throw new BunmaskaError( + `Blink engine: this CEF build does not support API ${CEF_API_VERSION}; install a CEF ${CEF_API_VERSION / 100} engine`, + { code: 'ERR_BLINK_INIT' }, + ); + } let contextInitialized = false; const onContextInitialized = new JSCallback( diff --git a/tests/unit/tools/engine/build-cef-engine.test.ts b/tests/unit/tools/engine/build-cef-engine.test.ts index 533f057..c9e8093 100644 --- a/tests/unit/tools/engine/build-cef-engine.test.ts +++ b/tests/unit/tools/engine/build-cef-engine.test.ts @@ -11,18 +11,21 @@ const version = (cef: string, chromium: string, channel: string) => ({ ], }); +// Publish order, as the CEF index lists it: an older branch's stable patch can come first. const index = { macosarm64: { versions: [ version('155.0.1', '155.0.1.1', 'beta'), + version('150.0.21', '150.0.7871.21', 'stable'), + version('154.0.9', '154.0.8037.9', 'stable'), version('154.0.28', '154.0.8037.58', 'stable'), - version('153.0.9', '153.0.1.9', 'stable'), + version('154.0.26', '154.0.8037.50', 'stable'), ], }, }; describe('pickCefBuild', () => { - test('takes the newest stable minimal build by default', () => { + test('takes the highest stable build of the CEF branch the FFI pins, not the first listed', () => { expect(pickCefBuild(index, 'macosarm64')).toEqual({ cefVersion: '154.0.28+gabc+chromium-154.0.8037.58', chromiumVersion: '154.0.8037.58', @@ -32,8 +35,12 @@ describe('pickCefBuild', () => { }); test('a wanted CEF version matches on the full version, not a prefix of it', () => { - expect(pickCefBuild(index, 'macosarm64', '153.0.9').file).toBe('min-153.0.9'); - expect(() => pickCefBuild(index, 'macosarm64', '153.0')).toThrow('no CEF minimal build'); + expect(pickCefBuild(index, 'macosarm64', '154.0.9').file).toBe('min-154.0.9'); + expect(() => pickCefBuild(index, 'macosarm64', '154.0')).toThrow('no CEF minimal build'); + }); + + test('a wanted version from another CEF branch is refused', () => { + expect(() => pickCefBuild(index, 'macosarm64', '150.0.21')).toThrow('on CEF 154'); }); test('an unknown platform fails loudly', () => { diff --git a/tools/engine/build-cef-engine.ts b/tools/engine/build-cef-engine.ts index f381c14..16e9a2d 100644 --- a/tools/engine/build-cef-engine.ts +++ b/tools/engine/build-cef-engine.ts @@ -11,6 +11,7 @@ import { createHash } from 'node:crypto'; import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { parseEngineId } from '../../src/common/engine-id'; +import { compareVersions } from '../../src/common/manifest'; import { currentArch, currentPlatform } from '../../src/common/platform'; import { CEF_API_VERSION } from '../../src/main/platform/cef/cef-ffi'; @@ -32,25 +33,38 @@ type IndexVersion = { files?: IndexFile[]; }; -/** The newest stable minimal build for `platformKey`, or the one whose CEF version starts with `wanted`. */ +/** The FFI's struct offsets are measured on this CEF branch only (see cef-ffi.ts). */ +const CEF_MAJOR = String(CEF_API_VERSION / 100); + +/** + * The highest stable minimal build of {@link CEF_MAJOR} for `platformKey`, or the one whose + * CEF version is `wanted`. The index is in publish order, so an older branch's patch can lead. + */ export const pickCefBuild = (index: unknown, platformKey: string, wanted?: string): CefBuild => { const versions = ((index as Record)[ platformKey ]?.versions ?? []) as IndexVersion[]; + const builds: CefBuild[] = []; for (const v of versions) { const cef = String(v.cef_version ?? ''); const matches = wanted === undefined ? v.channel === 'stable' : cef.startsWith(`${wanted}+`); const minimal = v.files?.find((f) => f.type === 'minimal'); - if (matches && minimal !== undefined) { - return { + if (matches && minimal !== undefined && cef.split('.')[0] === CEF_MAJOR) { + builds.push({ cefVersion: cef, chromiumVersion: String(v.chromium_version ?? ''), file: String(minimal.name), sha1: String(minimal.sha1), - }; + }); } } - throw new Error(`no CEF minimal build for ${platformKey}${wanted ? ` ${wanted}` : ''}`); + const newest = builds.sort((a, b) => compareVersions(b.cefVersion, a.cefVersion))[0]; + if (newest === undefined) { + throw new Error( + `no CEF minimal build for ${platformKey}${wanted ? ` ${wanted}` : ''} on CEF ${CEF_MAJOR}`, + ); + } + return newest; }; /** `154.0.28+g564dd6c+chromium-154.0.8037.58` -> `cef-154.0.28-154.0.8037.58-bunmaska1-macos-arm64`. */ diff --git a/tools/engine/cef-helper.c b/tools/engine/cef-helper.c index eee8efe..4604e68 100644 --- a/tools/engine/cef-helper.c +++ b/tools/engine/cef-helper.c @@ -56,7 +56,7 @@ int main(int argc, char** argv) { api_hash_fn api_hash = (api_hash_fn)dlsym(handle, "cef_api_hash"); execute_fn execute = (execute_fn)dlsym(handle, "cef_execute_process"); if (api_hash == NULL || execute == NULL) return 73; - api_hash(BM_CEF_API_VERSION, 0); + if (api_hash(BM_CEF_API_VERSION, 0) == NULL) return 74; cef_main_args_t args = {argc, argv}; return execute(&args, NULL, NULL); } From dcddf7ff0f28b0706708e4f5b1913631b453d9a9 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 14:37:24 -0700 Subject: [PATCH 12/15] fix: write the CEF glue and dev bundle into private temp dirs --- src/main/platform/cef/cef-glue.ts | 38 +++++++++------- src/main/platform/cef/cef-runtime.ts | 11 +++-- .../macos/cef-scratch-files.test.ts | 44 +++++++++++++++++++ 3 files changed, 72 insertions(+), 21 deletions(-) create mode 100644 tests/integration/macos/cef-scratch-files.test.ts diff --git a/src/main/platform/cef/cef-glue.ts b/src/main/platform/cef/cef-glue.ts index 1607c73..8f06182 100644 --- a/src/main/platform/cef/cef-glue.ts +++ b/src/main/platform/cef/cef-glue.ts @@ -1,6 +1,5 @@ import { cc, FFIType, type Pointer } from 'bun:ffi'; -import { createHash } from 'node:crypto'; -import { mkdirSync, writeFileSync } from 'node:fs'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -95,23 +94,28 @@ export type CefGlue = { let cached: CefGlue | undefined; -/** Compile the glue once per process (TinyCC needs a source file on disk). */ +/** + * Compile the glue once per process. TinyCC reads a file, written into a private mkdtemp + * dir: a shared fixed path lets another user (TMPDIR unset = /tmp) swap in their own C. + */ export const cefGlue = (): CefGlue => { if (cached !== undefined) { return cached; } - const hash = createHash('sha256').update(GLUE_SOURCE).digest('hex').slice(0, 16); - const dir = join(tmpdir(), 'bunmaska-cef'); - mkdirSync(dir, { recursive: true }); - const source = join(dir, `glue-${hash}.c`); - writeFileSync(source, GLUE_SOURCE); - const lib = cc({ source, symbols: SYMBOLS }); - const toNumber = (value: unknown): number => Number(value ?? 0); - cached = { - initBase: (struct, size) => lib.symbols.bm_init_base(struct, BigInt(size)), - slotGetter: (index) => toNumber(lib.symbols.bm_slot_getter(index)), - pumpInit: () => lib.symbols.bm_pump_init(), - scheduleFn: () => toNumber(lib.symbols.bm_schedule_fn()), - }; - return cached; + const dir = mkdtempSync(join(tmpdir(), 'bunmaska-cef-')); + try { + const source = join(dir, 'glue.c'); + writeFileSync(source, GLUE_SOURCE, { flag: 'wx' }); + const lib = cc({ source, symbols: SYMBOLS }); + const toNumber = (value: unknown): number => Number(value ?? 0); + cached = { + initBase: (struct, size) => lib.symbols.bm_init_base(struct, BigInt(size)), + slotGetter: (index) => toNumber(lib.symbols.bm_slot_getter(index)), + pumpInit: () => lib.symbols.bm_pump_init(), + scheduleFn: () => toNumber(lib.symbols.bm_schedule_fn()), + }; + return cached; + } finally { + rmSync(dir, { recursive: true, force: true }); + } }; diff --git a/src/main/platform/cef/cef-runtime.ts b/src/main/platform/cef/cef-runtime.ts index b2ecf0a..8874087 100644 --- a/src/main/platform/cef/cef-runtime.ts +++ b/src/main/platform/cef/cef-runtime.ts @@ -1,5 +1,5 @@ import { FFIType, JSCallback, type Pointer, ptr } from 'bun:ffi'; -import { mkdirSync, writeFileSync } from 'node:fs'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { BunmaskaError } from '../../../common/errors'; @@ -117,13 +117,16 @@ export const installCefApplicationClass = (): void => { * An unbundled process (`bun main.ts`) has no main bundle, and Chromium derives * the Mach rendezvous service name from it in the parent AND (via * `--main-bundle-path`) in every helper; without one they never meet. A packaged - * .app already is one. + * .app already is one. The stub lives in a private per-process dir: helpers read it + * whenever they spawn, so a shared one rewritten by another launch can be caught empty. */ -const mainBundlePath = (): string => { +export const mainBundlePath = (): string => { if (process.execPath.includes('.app/Contents/MacOS/')) { return ''; } - const bundle = join(tmpdir(), 'bunmaska-cef', 'DevHost.app'); + const dir = mkdtempSync(join(tmpdir(), 'bunmaska-cef-')); + process.once('exit', () => rmSync(dir, { recursive: true, force: true })); + const bundle = join(dir, 'DevHost.app'); mkdirSync(join(bundle, 'Contents'), { recursive: true }); writeFileSync( join(bundle, 'Contents', 'Info.plist'), diff --git a/tests/integration/macos/cef-scratch-files.test.ts b/tests/integration/macos/cef-scratch-files.test.ts new file mode 100644 index 0000000..eaeec07 --- /dev/null +++ b/tests/integration/macos/cef-scratch-files.test.ts @@ -0,0 +1,44 @@ +import { dlopen } from 'bun:ffi'; +import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; +import { mkdtempSync, readdirSync, rmSync, statSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { currentPlatform } from '../../../src/common/platform'; +import { cefGlue } from '../../../src/main/platform/cef/cef-glue'; +import { mainBundlePath } from '../../../src/main/platform/cef/cef-runtime'; + +if (currentPlatform() === 'macos') { + describe('CEF scratch files', () => { + const saved = process.env['TMPDIR']; + let tmp = ''; + + beforeEach(() => { + tmp = mkdtempSync(join(tmpdir(), 'bunmaska-cef-test-')); + process.env['TMPDIR'] = tmp; + }); + + afterEach(() => { + if (saved === undefined) { + delete process.env['TMPDIR']; + } else { + process.env['TMPDIR'] = saved; + } + rmSync(tmp, { recursive: true, force: true }); + }); + + test('the glue compiles from a private dir and leaves no shared file behind', () => { + // TinyCC resolves the glue's CoreFoundation externs against the loaded images. + dlopen('/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation', { + CFRunLoopGetMain: { args: [], returns: 'ptr' }, + }); + expect(cefGlue().slotGetter(0)).not.toBe(0); + expect(readdirSync(tmp).filter((name) => name.startsWith('bunmaska'))).toEqual([]); + }); + + test('every launch gets its own dev bundle, in a dir no other user can open', () => { + const first = mainBundlePath(); + expect(mainBundlePath()).not.toBe(first); + expect(statSync(dirname(first)).mode & 0o077).toBe(0); + }); + }); +} From b5894c69027eea4b0799e7e4e296bf1afb8a71ae Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 14:37:36 -0700 Subject: [PATCH 13/15] fix: stop punctuation keyDown from aliasing Delete and arrow keys --- src/main/platform/cef/cef-input.ts | 3 ++- tests/unit/main/platform/cef/cef-input.test.ts | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/main/platform/cef/cef-input.ts b/src/main/platform/cef/cef-input.ts index 30aab10..caa4eb3 100644 --- a/src/main/platform/cef/cef-input.ts +++ b/src/main/platform/cef/cef-input.ts @@ -38,7 +38,8 @@ const resolveKey = (keyCode: string): readonly [string, number] => { return named; } if ([...keyCode].length === 1) { - return [keyCode, keyCode.toUpperCase().charCodeAt(0)]; + // Only A-Z/0-9 share a code point with their VK: '.' as 0x2E is VK_DELETE and edits text. + return [keyCode, /^[A-Za-z0-9]$/.test(keyCode) ? keyCode.toUpperCase().charCodeAt(0) : 0]; } throw new InvalidArgumentError(`sendInputEvent: unsupported keyCode ${JSON.stringify(keyCode)}`); }; diff --git a/tests/unit/main/platform/cef/cef-input.test.ts b/tests/unit/main/platform/cef/cef-input.test.ts index c9aefdb..38f2d2b 100644 --- a/tests/unit/main/platform/cef/cef-input.test.ts +++ b/tests/unit/main/platform/cef/cef-input.test.ts @@ -23,6 +23,19 @@ describe('toCdpInput', () => { }); }); + test('punctuation is never sent as the key its code point aliases (Delete, Left)', () => { + for (const keyCode of ['.', '%', '!', '-', '(', 'é']) { + expect(toCdpInput({ type: 'keyDown', keyCode }).params).toEqual({ + type: 'rawKeyDown', + key: keyCode, + windowsVirtualKeyCode: 0, + }); + } + expect(toCdpInput({ type: 'keyDown', keyCode: '7' }).params).toMatchObject({ + windowsVirtualKeyCode: 0x37, + }); + }); + test('char types the character, including control keys and astral symbols', () => { expect(toCdpInput({ type: 'char', keyCode: 'Enter' }).params).toMatchObject({ key: 'Enter', From 1dc1c93c06d5a4c59f13ad898d5eb09693b3fc8b Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 14:38:12 -0700 Subject: [PATCH 14/15] fix: refuse a macOS build pinned to the Blink engine --- src/cli/index.ts | 10 ++++++++++ tests/unit/cli/dispatch-run.test.ts | 31 +++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/src/cli/index.ts b/src/cli/index.ts index 513d4fa..4a945e8 100755 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -9,6 +9,7 @@ import { configChannel, rendererOutDir, } from '../common/config-schema'; +import { parseEngineId } from '../common/engine-id'; import { type Arch, currentArch, currentPlatform, type Platform } from '../common/platform'; import { BUNMASKA_VERSION } from '../common/version'; import { buildLinuxApp, resolveBuildEngineId } from './build-linux'; @@ -243,6 +244,15 @@ const runBuild = async ( ); return 1; } + const macPin = resolveBuildEngineId(config.engine?.webkit, { os: 'macos', arch: currentArch() }); + if (target === 'macos' && macPin !== 'system' && parseEngineId(macPin).engine === 'cef') { + // ponytail: packaged Blink waits on helper signing + the entitlements audit (D048 phase 2). + err( + `bunmaska build: the Blink engine ${macPin} runs under dev and run only so far; the .app ` + + 'would ship the system WebKit instead. Remove the pin to build.', + ); + return 1; + } const macOnly: readonly [string, boolean, string][] = [ ['--sign', command.options.sign !== undefined, 'codesign'], ['--notarize', command.options.notarize === true, 'notarytool'], diff --git a/tests/unit/cli/dispatch-run.test.ts b/tests/unit/cli/dispatch-run.test.ts index d1f8fe5..16b1fe8 100644 --- a/tests/unit/cli/dispatch-run.test.ts +++ b/tests/unit/cli/dispatch-run.test.ts @@ -59,3 +59,34 @@ describe('dispatch run forwards the engine pin', () => { expect(env).toEqual({}); }); }); + +describe('dispatch build on macOS', () => { + test.skipIf(currentPlatform() !== 'macos')( + 'refuses a Blink pin that the .app would silently drop for the system WebKit', + async () => { + dir = mkdtempSync(join(tmpdir(), 'bunmaska-dispatch-build-')); + const pin = `cef-154.0.28-154.0.8037.58-bunmaska1-macos-${currentArch()}`; + writeFileSync( + join(dir, 'bunmaska.config.ts'), + `export default { engine: { webkit: '${pin}' } };\n`, + ); + process.chdir(dir); + let built = false; + let code: number | undefined; + const streams = await captureStdio(async () => { + code = await dispatch( + { kind: 'build', entry: 'app.ts', options: { target: 'macos' } }, + { + buildMac: async () => { + built = true; + return '/tmp/Demo.app'; + }, + }, + ); + }); + expect(code).toBe(1); + expect(built).toBe(false); + expect(streams.err.join('')).toContain(`the Blink engine ${pin} runs under dev and run only`); + }, + ); +}); From 20f0b0262c8af830210dc4d4b8aa8d0ac84aa41e Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 14:38:26 -0700 Subject: [PATCH 15/15] fix: forward the project engine pin as BUNMASKA_ENGINE_ID too --- src/cli/index.ts | 9 +++++++-- tests/unit/cli/dispatch-run.test.ts | 4 ++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/cli/index.ts b/src/cli/index.ts index 4a945e8..e5b1c33 100755 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -219,10 +219,15 @@ const resolveProjectEngine = ( return { engineId, embed: config.engine?.embed === true }; }; -/** dev and run must forward the pin, or on Windows the app launches with no engine. */ +/** + * dev and run must forward the pin, or on Windows the app launches with no engine. Both + * names: an inherited BUNMASKA_ENGINE_ID would otherwise outrank the alias. + */ const launchEngineEnv = (config: BunmaskaConfig, command: string): Record => { const { engineId } = resolveProjectEngine(config, command); - return engineId === 'system' ? {} : { BUNMASKA_WEBKIT_ID: engineId }; + return engineId === 'system' + ? {} + : { BUNMASKA_ENGINE_ID: engineId, BUNMASKA_WEBKIT_ID: engineId }; }; const runBuild = async ( diff --git a/tests/unit/cli/dispatch-run.test.ts b/tests/unit/cli/dispatch-run.test.ts index 16b1fe8..029636e 100644 --- a/tests/unit/cli/dispatch-run.test.ts +++ b/tests/unit/cli/dispatch-run.test.ts @@ -42,9 +42,9 @@ const runWithPin = async ( }; describe('dispatch run forwards the engine pin', () => { - test('a full engine id reaches the app as BUNMASKA_WEBKIT_ID', async () => { + test('a full engine id reaches the app under both names, so an inherited one never wins', async () => { const { env } = await runWithPin(ID); - expect(env).toEqual({ BUNMASKA_WEBKIT_ID: ID }); + expect(env).toEqual({ BUNMASKA_ENGINE_ID: ID, BUNMASKA_WEBKIT_ID: ID }); }); test('a bare version warns and launches on the system WebKit', async () => {